问:
Fetching a list from a website using beautifulsoup in a dataframe column
I am trying to fetch the keywords from the article website. The website keywords look like this:

```<code>`This is the link:` `https://www.horizont.net/marketing/nachrichten/bgh-haendler-haftet-nicht-fuer-kundenbewertungen-auf-amazon-180980`
</code>```

I am using this to fetch the keywords:

```<code>   Article_Keyword = bs.find('div', {'class':'ListTags'}).get_text()
</code>```

and this is how what i am getting:

```<code>Themen Bundesgerichtshof Amazon Verband Sozialer Wettbewerb Kundenbewertung Tape dpa
</code>```

I need to get it by separating each keyword by comma. I can do it by RE but some keywords are with more than one word so i need that as one keyword.

is there any way to get each keyword by separating with comma?

答:
try this</p>

```<code>import requests
from bs4 import BeautifulSoup

url = 'https://www.horizont.net/marketing/nachrichten/bgh-haendler-haftet-nicht-fuer-kundenbewertungen-auf-amazon-180980'
page = requests.get(url)
soup1 = BeautifulSoup(page.content, "lxml")

Article_Keyword = soup1.find('div',{'class':'ListTags'}).find_all("a")
Article_Keyword = ", ".join([keyword.text.strip() for keyword in Article_Keyword])

print(Article_Keyword)
</code>```

Body:
I am trying to fetch the keywords from the article website. The website keywords look like this:

`This is the link:` `https://www.horizont.net/marketing/nachrichten/bgh-haendler-haftet-nicht-fuer-kundenbewertungen-auf-amazon-180980`

I am using this to fetch the keywords:

   Article_Keyword = bs.find('div', {'class':'ListTags'}).get_text()

and this is how what i am getting:

Themen Bundesgerichtshof Amazon Verband Sozialer Wettbewerb Kundenbewertung Tape dpa

I need to get it by separating each keyword by comma. I can do it by RE but some keywords are with more than one word so i need that as one keyword.

is there any way to get each keyword by separating with comma?

Body:
try this

import requests
from bs4 import BeautifulSoup

url = 'https://www.horizont.net/marketing/nachrichten/bgh-haendler-haftet-nicht-fuer-kundenbewertungen-auf-amazon-180980'
page = requests.get(url)
soup1 = BeautifulSoup(page.content, "lxml")

Article_Keyword = soup1.find('div',{'class':'ListTags'}).find_all("a")
Article_Keyword = ", ".join([keyword.text.strip() for keyword in Article_Keyword])

print(Article_Keyword)


来源: stackexchange

问:
Numpy Loading a File Showing All Zeros
I downloaded a npy file from Google, which is 96 MB. I am trying to load the file but I get all ZEROS as shown in the output below:

Using Python 3.6

```<code>>>> import numpy as np
>>> a = np.load("full_numpy_bitmap_cat.npy", allow_pickle=True)
>>> a = np.load("full_numpy_bitmap_cat.npy", allow_pickle=True, fix_imports=True)
>>> a
array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint8)
>>>
</code>```

What am I doing wrong?

答:
That's not because you see zeros when printing that everything is zeros. I downloaded the file, I have not only zeros.</p>

```<code>import numpy as npy
image = npy.load("full_numpy_bitmap_cat.npy")
print(" number of non-zeros", len(npy.nonzero(image)[0]) )
</code>```

ContentLicense: CC BY-SA 4.0

Title: Numpy Loading a File Showing All Zeros

Body:
I downloaded a npy file from Google, which is 96 MB. I am trying to load the file but I get all ZEROS as shown in the output below:

Using Python 3.6

>>> import numpy as np
>>> a = np.load("full_numpy_bitmap_cat.npy", allow_pickle=True)
>>> a = np.load("full_numpy_bitmap_cat.npy", allow_pickle=True, fix_imports=True)
>>> a
array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint8)
>>>

What am I doing wrong?

Body:
That's not because you see zeros when printing that everything is zeros. I downloaded the file, I have not only zeros.

import numpy as npy
image = npy.load("full_numpy_bitmap_cat.npy")
print(" number of non-zeros", len(npy.nonzero(image)[0]) )


答:
Thx Guys ,

solved with this method .

```<code>$datapolyline = array('polyline' => $items);
$encode = json_encode($datapolyline);
$hasil = str_replace(']"',']',str_replace('"[',"[",$encode));
</code>```

Title: How to create array this data

Body:
Please help me.

I want to create an array like this.

{
    "polyline": [
        [-5.40044378489256, 105.256219301373],
        [-5.40040246210992, 105.255722338334],
        [-5.40040673688054, 105.255641704425],
        [-5.40068350732327, 105.254918346182],
        [-5.40083421394229, 105.254701003432]
    ]
}

how implement in php array()?

Body:
Thx Guys ,

solved with this method .

$datapolyline = array('polyline' => $items);
$encode = json_encode($datapolyline);
$hasil = str_replace(']"',']',str_replace('"[',"[",$encode));


问:
Use Razor views as email templates inside a Web Forms app
I have an asp.net Web Forms application that needs to send emails.  I like the Razor syntax and as you can use Razor outside of MVC I thought I'd try and use that.  I've seen that you can programmatically pass a template string to razor but I'd like to keep my razor templates as separate .cshtml files.

Does anyone have any simple, idiot-proof advice as to how to do this?  I've tried to load them from file like this:

```<code>UserDetails userDetails = new UserDetails {Name = "Fred"};
string template = File.OpenText("Email/UserDetailsEmail.cshtml").ReadToEnd();
string messageText = Razor.Parse(template, userDetails);
</code>```

All to no avail.  There's an exception finding the file.  I'm using the razorengine dll.

I have everything else working, the smtp server etc, just not the views.

Any help appreciated.

答:
You need to get the full path to the file; relative paths will end up being relative to the wrong location.

Write

```<code>File.OpenText(Server.MapPath("~/Email/UserDetailsEmail.cshtml"))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an asp.net Web Forms application that needs to send emails.  I like the Razor syntax and as you can use Razor outside of MVC I thought I'd try and use that.  I've seen that you can programmatically pass a template string to razor but I'd like to keep my razor templates as separate .cshtml files.

Does anyone have any simple, idiot-proof advice as to how to do this?  I've tried to load them from file like this:

UserDetails userDetails = new UserDetails {Name = "Fred"};
string template = File.OpenText("Email/UserDetailsEmail.cshtml").ReadToEnd();
string messageText = Razor.Parse(template, userDetails);

All to no avail.  There's an exception finding the file.  I'm using the razorengine dll.

I have everything else working, the smtp server etc, just not the views.

Any help appreciated.

Body:
You need to get the full path to the file; relative paths will end up being relative to the wrong location.

Write

File.OpenText(Server.MapPath("~/Email/UserDetailsEmail.cshtml"))


问:
Replaces command for label in helm charts
I often see the following snippet in the helm charts:

```<code>  labels:
    app: {{ template "app.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
</code>```

Why is the replacement necessary? Are + signs bad?

答:
Replace - script and chart function
Replace() returns a string after replacing all occurrences of a given substring within the input string with another substring. The function is non-recursive and works from left to right.

Syntax:

Replace(text, from_str, to_str)
Return data type: string

Valid label values in pod configuration file must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between.

replace "+" "_" replaces plus characters with underscores. And that is how we avoid failures.

More information you can find here: replace-chart, syntax-pod-label.

Body:
I often see the following snippet in the helm charts:

  labels:
    app: {{ template "app.name" . }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}

Why is the replacement necessary? Are + signs bad?


问:
Reverse join in node js with mongoose
I have two documents

Users (_id, name)

  Dealer (user_id, address)

I Want to access dealer detail from users using aggregate. Is it possible?

I have tried following

User.aggregate([
       {
         $lookup: {
           from: "dealer",
           localField: "_id",
           foreignField: "user_id",
           as: "dealer_detail"
         }
       },
      {
        $project: {
          name: "$name",
          dealer_detail: "$dealer_detail"
        }
      }
    ]);```

But it is returning empty array for dealer_detail.

答:
Your code seems correct for accessing dealer details.
There might some possibility that can help you out.

1) Make sure your "from" field is same as you define in you model, there might case sensitive error.

2) In your dealer model "user_id" is type of "ObjectId". If it is in type String the aggregation wan't able to fetch the dealer details.

Title: Reverse join in node js with mongoose

Body:
I have two documents

Users (_id, name)

  Dealer (user_id, address)

I Want to access dealer detail from users using aggregate. Is it possible?

I have tried following

User.aggregate([
       {
         $lookup: {
           from: "dealer",
           localField: "_id",
           foreignField: "user_id",
           as: "dealer_detail"
         }
       },
      {
        $project: {
          name: "$name",
          dealer_detail: "$dealer_detail"
        }
      }
    ]);

But it is returning empty array for dealer_detail.


问:
Shared memory between NDK and SDK below API Level 26
Library written in c++ produces continuous stream of data and same has to be ported on different platforms. Now integrating the lib to android application, I am trying to create shared memory between NDK and SDK.

Below is working snippet,

Native code:

```<code>#include <jni.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <linux/ashmem.h>
#include <android/log.h>
#include <string>

char  *buffer;
constexpr size_t BufferSize=100;
extern "C" JNIEXPORT jobject JNICALL
Java_test_com_myapplication_MainActivity_getSharedBufferJNI(
        JNIEnv* env,
        jobject /* this */) {

    int fd = open("/dev/ashmem", O_RDWR);

    ioctl(fd, ASHMEM_SET_NAME, "shared_memory");
    ioctl(fd, ASHMEM_SET_SIZE, BufferSize);

    buffer = (char*) mmap(NULL, BufferSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    return (env->NewDirectByteBuffer(buffer, BufferSize));
}

extern "C" JNIEXPORT void JNICALL
Java_test_com_myapplication_MainActivity_TestBufferCopy(
        JNIEnv* env,
        jobject /* this */) {

   for(size_t i=0;i<BufferSize;i = i+2) {
       __android_log_print(ANDROID_LOG_INFO, "native_log", "Count %d value:%d", i,buffer[i]);
   }

   //pass `buffer` to dynamically loaded library to update share memory
   //

}
</code>```

SDK code:

```<code>//MainActivity.java
public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.

    static {
        System.loadLibrary("native-lib");
    }

    final int BufferSize = 100;
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ByteBuffer byteBuffer = getSharedBufferJNI();

        //update the command to shared memory here
        //byteBuffer updated with commands
        //Call JNI to inform update and get the response
        TestBufferCopy();
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native ByteBuffer getSharedBufferJNI();
    public native int TestBufferCopy();
}
</code>```

Question:

Accessing primitive arrays from Java to native is reference only if garbage collector supports pinning. Is it true for other way around ?

Is it guaranteed by android platform that ALWAYS reference is shared from NDK to SDK without redundant copy?

Is it the right way to share memory?

答:
You only need /dev/ashmem to share memory between processes. NDK and SDK (Java/Kotlin) work in same Linux process and have full access to same memory space.

The usual way to define memory that can be used both from C++ and Java is by creating a Direct ByteBuffer. You don't need JNI for that, Java API has ByteBuffer.allocateDirect(int capacity). If it's more natural for your logical flow to allocate the buffer on the C++ side, JNI has the NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) function that you used in your question.

Working with Direct ByteBuffer is very easy on the C++ side, but not so efficient on the JVM side. The reason is that this buffer is not backed by array, and the only API you have involves ByteBuffer.get() with typed variations (getting byte array, char, int, …). You have control of current position in the buffer, but working this way requires certain discipline: every get() operation updates the current position. Also, random access to this buffer is rather slow, because it involves calling both positioning and get APIs. Therefore, in some cases of non-trivial data structures, it may be easier to write your custom access code in C++ and have 'intelligent' getters called through JNI.

It's important not to forget to set ByteBuffer.order(ByteOrder.nativeOrder()). The order of a newly-created byte buffer is counterintuitively BIG_ENDIAN. This applies both to buffer created from Java and from C++.

If you can isolate the instances when C++ needs access to such shared memory, and don't really need it to be pinned all the time, it's worth to consider working with byte array. In Java, you have more efficient random access. On the NDK side, you will call GetByteArrayElements() or GetPrimitiveArrayCritical(). The latter is more efficient, but its use imposes restrictions on what Java functions you can call until the array is released. On Android, both methods don't involve memory allocation and copy (with no official guarantee, though). Even though C++ side uses the same memory as Java, your JNI code must call the appropriate Release…() function, and better do that as early as possible. It's a good practice to handle this Get/Release via RAII.

Body:
Library written in c++ produces continuous stream of data and same has to be ported on different platforms. Now integrating the lib to android application, I am trying to create shared memory between NDK and SDK.

Below is working snippet,

Native code:

#include <jni.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <linux/ashmem.h>
#include <android/log.h>
#include <string>

char  *buffer;
constexpr size_t BufferSize=100;
extern "C" JNIEXPORT jobject JNICALL
Java_test_com_myapplication_MainActivity_getSharedBufferJNI(
        JNIEnv* env,
        jobject /* this */) {

    int fd = open("/dev/ashmem", O_RDWR);

    ioctl(fd, ASHMEM_SET_NAME, "shared_memory");
    ioctl(fd, ASHMEM_SET_SIZE, BufferSize);

    buffer = (char*) mmap(NULL, BufferSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    return (env->NewDirectByteBuffer(buffer, BufferSize));
}

extern "C" JNIEXPORT void JNICALL
Java_test_com_myapplication_MainActivity_TestBufferCopy(
        JNIEnv* env,
        jobject /* this */) {

   for(size_t i=0;i<BufferSize;i = i+2) {
       __android_log_print(ANDROID_LOG_INFO, "native_log", "Count %d value:%d", i,buffer[i]);
   }

   //pass `buffer` to dynamically loaded library to update share memory
   //

}

SDK code:

//MainActivity.java
public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.

    static {
        System.loadLibrary("native-lib");
    }

    final int BufferSize = 100;
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ByteBuffer byteBuffer = getSharedBufferJNI();

        //update the command to shared memory here
        //byteBuffer updated with commands
        //Call JNI to inform update and get the response
        TestBufferCopy();
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native ByteBuffer getSharedBufferJNI();
    public native int TestBufferCopy();
}

Question:

Accessing primitive arrays from Java to native is reference only if garbage collector supports pinning. Is it true for other way around ?

Is it guaranteed by android platform that ALWAYS reference is shared from NDK to SDK without redundant copy?

Is it the right way to share memory?


问:
Can't Add A View to EF Data Model
I have a view that I am trying to add to my ADO.NET Entity Data Model. Every time I try to Update From Database, and check the view, it refreshes everything else, but does not add the view.
I get no error message or output, so I have no idea what is wrong with the view. Other views are no problem. Am I missing something, is there a way to turn error messages on?
Visual Studio 2008 sp1

Update: I found this link but the problem didn't solve with these solutions.
MSDN Forum

Update: The view that i can't add it will query from another view.

Update: Help

```<code>WITH cte AS (SELECT     dbo.TBL_Gharardad.PK_Shenase, dbo.TBL_Gharardad.FK_NoeKhedmat AS NoeKhedmatId,
                                                    dbo.TBL_NoeKhedmat.NoeKhedmat AS [نوع خدمت], dbo.TBL_Gharardad.OnvaneKhedmat AS [عنوان خدمت],
                                                    dbo.TBL_Gharardad.MahaleEraeieKhedmat AS [محل ارائه خدمت],
                                                    dbo.TBL_Gharardad.FK_NahveieTaieeneBarande AS NahveieTaeeneBararndeId,
                                                    dbo.TBL_NahveieTaieeneBarande.NahveieTaieeneBarande AS [نحوه تعيين برنده],
                                                    dbo.TBL_Gharardad.TarikheShorooeGharardad_Jalali AS [تاريخ شروع قرارداد],
                                                    dbo.TBL_Gharardad.TarikhePayaneGharardad_Jalali AS [تاريخ پايان قرارداد], dbo.TBL_Gharardad.FK_VahedeArz AS VahedeArzId,
                                                    dbo.TBL_VahedeArz.VahedeArz AS [واحد ارز], dbo.TBL_Gharardad.MablagheDariaftiKol AS [مبلغ دريافتي کل],
                                                    dbo.TBL_Gharardad.MablaghePardakhtieKol AS [مبلغ پرداختي کل], dbo.TBL_Gharardad.SahmeKarfarma AS [درصد مشارکت کارفرما],
                                                    100 - dbo.TBL_Gharardad.SahmeKarfarma AS [درصد مشارکت پيمانکار], dbo.TBL_Gharardad.TedadNirooyeMard AS [تعداد نيروي مرد],
                                                    dbo.TBL_Gharardad.TedadNirooyeZan AS [تعداد نيروي زن],
                                                    dbo.TBL_Gharardad.TedadNirooyeMard + dbo.TBL_Gharardad.TedadNirooyeZan AS [تعداد کل نيروها],
                                                    dbo.TBL_Gharardad.FK_TarafeGharardad AS TarafeGharardadId,
                                                    CASE TBL_TarafeGharardad.Hoghooghi WHEN 0 THEN ISNULL(TBL_TarafeGharardad.Naam, ' ')
                                                    + ' ' + ISNULL(TBL_TarafeGharardad.NaameKhanevadegi, ' ') ELSE TBL_TarafeGharardad.NameSherkat END AS [طرف قرارداد],
                                                    dbo.TBL_Gharardad.FK_VahedeVagozarKonande AS VahedeVagozarKonandeId,
                                                    dbo.TBL_VahedeVagozarKonande.VahedeVagozarKonande AS [واحد واگذار کننده], dbo.TBL_Gharardad.ShomareGharardad AS [شماره قرارداد],
                                                    dbo.TBL_Gharardad.TarikheGharardad_Jalali AS [تاريخ قرارداد],
                                                    CASE VaziateGharardad WHEN 0 THEN N'لغو شده' WHEN 1 THEN N'ثبت اوليه' WHEN 2 THEN N'فسخ' WHEN 3 THEN N'ثبت نهايي ' WHEN 4 THEN
                                                     N' جاري ' WHEN 5 THEN N'تمام شده ' WHEN 6 THEN N' متمم ' END AS [وضعيت قرارداد], dbo.TBL_NoeMoamele.NoeMoamele AS [نوع معامله]
                             FROM          dbo.TBL_Gharardad INNER JOIN
                                                    dbo.TBL_NoeKhedmat ON dbo.TBL_Gharardad.FK_NoeKhedmat = dbo.TBL_NoeKhedmat.PK_Id INNER JOIN
                                                    dbo.TBL_NahveieTaieeneBarande ON
                                                    dbo.TBL_Gharardad.FK_NahveieTaieeneBarande = dbo.TBL_NahveieTaieeneBarande.PK_Id INNER JOIN
                                                    dbo.TBL_VahedeArz ON dbo.TBL_Gharardad.FK_VahedeArz = dbo.TBL_VahedeArz.PK_Id INNER JOIN
                                                    dbo.TBL_TarafeGharardad ON dbo.TBL_Gharardad.FK_TarafeGharardad = dbo.TBL_TarafeGharardad.PK_Id INNER JOIN
                                                    dbo.TBL_VahedeVagozarKonande ON
                                                    dbo.TBL_Gharardad.FK_VahedeVagozarKonande = dbo.TBL_VahedeVagozarKonande.PK_Id INNER JOIN
                                                    dbo.TBL_NoeMoamele ON dbo.TBL_Gharardad.FK_NoeMoamele = dbo.TBL_NoeMoamele.PK_Id)
    SELECT     v_Gharardad.شناسه, v_Gharardad.NoeKhedmatId, v_Gharardad.[نوع خدمت], v_Gharardad.[عنوان خدمت], v_Gharardad.[محل ارائه خدمت],
                            v_Gharardad.NahveieTaeeneBararndeId, v_Gharardad.[نحوه تعيين برنده], v_Gharardad.[تاريخ شروع قرارداد], v_Gharardad.[تاريخ پايان قرارداد],
                            v_Gharardad.VahedeArzId, v_Gharardad.[واحد ارز], v_Gharardad.[مبلغ دريافتي کل], v_Gharardad.[مبلغ پرداختي کل], v_Gharardad.[درصد مشارکت کارفرما],
                            v_Gharardad.[درصد مشارکت پيمانکار], v_Gharardad.[تعداد نيروي مرد], v_Gharardad.[تعداد نيروي زن], v_Gharardad.[تعداد کل نيروها],
                            v_Gharardad.TarafeGharardadId, v_Gharardad.[طرف قرارداد], v_Gharardad.VahedeVagozarKonandeId, v_Gharardad.[واحد واگذار کننده],
                            v_Gharardad.[شماره قرارداد], v_Gharardad.[تاريخ قرارداد], v_Gharardad.[وضعيت قرارداد], v_Gharardad.[نوع معامله]
     FROM         dbo.TBL_Gharardad AS TBL_Gharardad_3 INNER JOIN
                            dbo.v_GharardadRecords AS v_Gharardad ON v_Gharardad.شناسه = TBL_Gharardad_3.PK_Shenase
     WHERE     (TBL_Gharardad_3.FK_GharardadeAsli IS NULL) AND (TBL_Gharardad_3.PK_Shenase NOT IN
                                (SELECT     FK_GharardadeAsli
                                   FROM         dbo.TBL_Gharardad AS TBL_Gharardad_2
                                   WHERE     (FK_GharardadeAsli IS NOT NULL)))
UNION
SELECT     sub.FK_GharardadeAsli AS شناسه, cte_2.NoeKhedmatId, cte_2.[نوع خدمت], cte_2.[عنوان خدمت], cte_2.[محل ارائه خدمت], cte_2.NahveieTaeeneBararndeId,
                      cte_2.[نحوه تعيين برنده], cte_2.[تاريخ شروع قرارداد], cte_2.[تاريخ پايان قرارداد], cte_2.VahedeArzId, cte_2.[واحد ارز], cte_2.[مبلغ دريافتي کل], cte_2.[مبلغ پرداختي کل],
                      cte_2.[درصد مشارکت کارفرما], cte_2.[درصد مشارکت پيمانکار], cte_2.[تعداد نيروي مرد], cte_2.[تعداد نيروي زن], cte_2.[تعداد کل نيروها], cte_2.TarafeGharardadId,
                      cte_2.[طرف قرارداد], cte_2.VahedeVagozarKonandeId, cte_2.[واحد واگذار کننده], cte_2.[شماره قرارداد], cte_2.[تاريخ قرارداد], cte_2.[وضعيت قرارداد],
                      cte_2.[نوع معامله]
FROM         dbo.v_GharardadRecords AS cte_2 INNER JOIN
                          (SELECT     FK_GharardadeAsli, MAX(PK_Shenase) AS PK_Shenase, MAX(TarikheSabt) AS TarikheSabt
                             FROM         dbo.TBL_Gharardad AS TBL_Gharardad_1
                             WHERE     (FK_GharardadeAsli IS NOT NULL)
                             GROUP BY FK_GharardadeAsli) AS sub ON sub.PK_Shenase = cte_2.شناسه
</code>```

答:
I have experienced this same behaviour when I try to add a view that doesn't select a primary key from another table. (Like Ladislav Mrnka has commented)

My strategy for solving this is to reduce the view to as simple as possible (1 column) and try and to get it added. Once you have it added to the model, slowly bring in more columns and refresh the model to make sure the view is still there. You can usually identify what section of the view is giving EDM problems.

Title: Can't Add A View to EF Data Model

Body:
I have a view that I am trying to add to my ADO.NET Entity Data Model. Every time I try to Update From Database, and check the view, it refreshes everything else, but does not add the view.
I get no error message or output, so I have no idea what is wrong with the view. Other views are no problem. Am I missing something, is there a way to turn error messages on?
Visual Studio 2008 sp1

Update: I found this link but the problem didn't solve with these solutions.
MSDN Forum

Update: The view that i can't add it will query from another view.

Update: Help

WITH cte AS (SELECT     dbo.TBL_Gharardad.PK_Shenase, dbo.TBL_Gharardad.FK_NoeKhedmat AS NoeKhedmatId,
                                                    dbo.TBL_NoeKhedmat.NoeKhedmat AS [نوع خدمت], dbo.TBL_Gharardad.OnvaneKhedmat AS [عنوان خدمت],
                                                    dbo.TBL_Gharardad.MahaleEraeieKhedmat AS [محل ارائه خدمت],
                                                    dbo.TBL_Gharardad.FK_NahveieTaieeneBarande AS NahveieTaeeneBararndeId,
                                                    dbo.TBL_NahveieTaieeneBarande.NahveieTaieeneBarande AS [نحوه تعيين برنده],
                                                    dbo.TBL_Gharardad.TarikheShorooeGharardad_Jalali AS [تاريخ شروع قرارداد],
                                                    dbo.TBL_Gharardad.TarikhePayaneGharardad_Jalali AS [تاريخ پايان قرارداد], dbo.TBL_Gharardad.FK_VahedeArz AS VahedeArzId,
                                                    dbo.TBL_VahedeArz.VahedeArz AS [واحد ارز], dbo.TBL_Gharardad.MablagheDariaftiKol AS [مبلغ دريافتي کل],
                                                    dbo.TBL_Gharardad.MablaghePardakhtieKol AS [مبلغ پرداختي کل], dbo.TBL_Gharardad.SahmeKarfarma AS [درصد مشارکت کارفرما],
                                                    100 - dbo.TBL_Gharardad.SahmeKarfarma AS [درصد مشارکت پيمانکار], dbo.TBL_Gharardad.TedadNirooyeMard AS [تعداد نيروي مرد],
                                                    dbo.TBL_Gharardad.TedadNirooyeZan AS [تعداد نيروي زن],
                                                    dbo.TBL_Gharardad.TedadNirooyeMard + dbo.TBL_Gharardad.TedadNirooyeZan AS [تعداد کل نيروها],
                                                    dbo.TBL_Gharardad.FK_TarafeGharardad AS TarafeGharardadId,
                                                    CASE TBL_TarafeGharardad.Hoghooghi WHEN 0 THEN ISNULL(TBL_TarafeGharardad.Naam, ' ')
                                                    + ' ' + ISNULL(TBL_TarafeGharardad.NaameKhanevadegi, ' ') ELSE TBL_TarafeGharardad.NameSherkat END AS [طرف قرارداد],
                                                    dbo.TBL_Gharardad.FK_VahedeVagozarKonande AS VahedeVagozarKonandeId,
                                                    dbo.TBL_VahedeVagozarKonande.VahedeVagozarKonande AS [واحد واگذار کننده], dbo.TBL_Gharardad.ShomareGharardad AS [شماره قرارداد],
                                                    dbo.TBL_Gharardad.TarikheGharardad_Jalali AS [تاريخ قرارداد],
                                                    CASE VaziateGharardad WHEN 0 THEN N'لغو شده' WHEN 1 THEN N'ثبت اوليه' WHEN 2 THEN N'فسخ' WHEN 3 THEN N'ثبت نهايي ' WHEN 4 THEN
                                                     N' جاري ' WHEN 5 THEN N'تمام شده ' WHEN 6 THEN N' متمم ' END AS [وضعيت قرارداد], dbo.TBL_NoeMoamele.NoeMoamele AS [نوع معامله]
                             FROM          dbo.TBL_Gharardad INNER JOIN
                                                    dbo.TBL_NoeKhedmat ON dbo.TBL_Gharardad.FK_NoeKhedmat = dbo.TBL_NoeKhedmat.PK_Id INNER JOIN
                                                    dbo.TBL_NahveieTaieeneBarande ON
                                                    dbo.TBL_Gharardad.FK_NahveieTaieeneBarande = dbo.TBL_NahveieTaieeneBarande.PK_Id INNER JOIN
                                                    dbo.TBL_VahedeArz ON dbo.TBL_Gharardad.FK_VahedeArz = dbo.TBL_VahedeArz.PK_Id INNER JOIN
                                                    dbo.TBL_TarafeGharardad ON dbo.TBL_Gharardad.FK_TarafeGharardad = dbo.TBL_TarafeGharardad.PK_Id INNER JOIN
                                                    dbo.TBL_VahedeVagozarKonande ON
                                                    dbo.TBL_Gharardad.FK_VahedeVagozarKonande = dbo.TBL_VahedeVagozarKonande.PK_Id INNER JOIN
                                                    dbo.TBL_NoeMoamele ON dbo.TBL_Gharardad.FK_NoeMoamele = dbo.TBL_NoeMoamele.PK_Id)
    SELECT     v_Gharardad.شناسه, v_Gharardad.NoeKhedmatId, v_Gharardad.[نوع خدمت], v_Gharardad.[عنوان خدمت], v_Gharardad.[محل ارائه خدمت],
                            v_Gharardad.NahveieTaeeneBararndeId, v_Gharardad.[نحوه تعيين برنده], v_Gharardad.[تاريخ شروع قرارداد], v_Gharardad.[تاريخ پايان قرارداد],
                            v_Gharardad.VahedeArzId, v_Gharardad.[واحد ارز], v_Gharardad.[مبلغ دريافتي کل], v_Gharardad.[مبلغ پرداختي کل], v_Gharardad.[درصد مشارکت کارفرما],
                            v_Gharardad.[درصد مشارکت پيمانکار], v_Gharardad.[تعداد نيروي مرد], v_Gharardad.[تعداد نيروي زن], v_Gharardad.[تعداد کل نيروها],
                            v_Gharardad.TarafeGharardadId, v_Gharardad.[طرف قرارداد], v_Gharardad.VahedeVagozarKonandeId, v_Gharardad.[واحد واگذار کننده],
                            v_Gharardad.[شماره قرارداد], v_Gharardad.[تاريخ قرارداد], v_Gharardad.[وضعيت قرارداد], v_Gharardad.[نوع معامله]
     FROM         dbo.TBL_Gharardad AS TBL_Gharardad_3 INNER JOIN
                            dbo.v_GharardadRecords AS v_Gharardad ON v_Gharardad.شناسه = TBL_Gharardad_3.PK_Shenase
     WHERE     (TBL_Gharardad_3.FK_GharardadeAsli IS NULL) AND (TBL_Gharardad_3.PK_Shenase NOT IN
                                (SELECT     FK_GharardadeAsli
                                   FROM         dbo.TBL_Gharardad AS TBL_Gharardad_2
                                   WHERE     (FK_GharardadeAsli IS NOT NULL)))
UNION
SELECT     sub.FK_GharardadeAsli AS شناسه, cte_2.NoeKhedmatId, cte_2.[نوع خدمت], cte_2.[عنوان خدمت], cte_2.[محل ارائه خدمت], cte_2.NahveieTaeeneBararndeId,
                      cte_2.[نحوه تعيين برنده], cte_2.[تاريخ شروع قرارداد], cte_2.[تاريخ پايان قرارداد], cte_2.VahedeArzId, cte_2.[واحد ارز], cte_2.[مبلغ دريافتي کل], cte_2.[مبلغ پرداختي کل],
                      cte_2.[درصد مشارکت کارفرما], cte_2.[درصد مشارکت پيمانکار], cte_2.[تعداد نيروي مرد], cte_2.[تعداد نيروي زن], cte_2.[تعداد کل نيروها], cte_2.TarafeGharardadId,
                      cte_2.[طرف قرارداد], cte_2.VahedeVagozarKonandeId, cte_2.[واحد واگذار کننده], cte_2.[شماره قرارداد], cte_2.[تاريخ قرارداد], cte_2.[وضعيت قرارداد],
                      cte_2.[نوع معامله]
FROM         dbo.v_GharardadRecords AS cte_2 INNER JOIN
                          (SELECT     FK_GharardadeAsli, MAX(PK_Shenase) AS PK_Shenase, MAX(TarikheSabt) AS TarikheSabt
                             FROM         dbo.TBL_Gharardad AS TBL_Gharardad_1
                             WHERE     (FK_GharardadeAsli IS NOT NULL)
                             GROUP BY FK_GharardadeAsli) AS sub ON sub.PK_Shenase = cte_2.شناسه


问:
No setter/getter Firebase
Hi everyone I have one question. I want to retrieve the data from the Firebase live database and it keeps telling me that it doesn't find the getter and the setter but as you can see below I did it, I create a class where I have the setter and the getter with the same name of the database fields.

Can anyone tell me what I'm doing wrong because I don't have a clue?

Thank you in advance.

Photo of the database:

Code of the Activity and the Class where you can see that I have the getter and the setter.

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

public class CartActivity extends AppCompatActivity {

    private TextView total;
    private ImageButton removeFromCart;
    private Button pay;

    private RecyclerView mResultList;
    private DatabaseReference mUserDatabase;
    public static int cart_count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");

        total        = findViewById(R.id.TotalPrice);
        removeFromCart   = findViewById(R.id.removeFromCart);
        mResultList  = findViewById(R.id.cartList);
        pay    = findViewById(R.id.pay);

        mResultList.setHasFixedSize(true);
        mResultList.setLayoutManager(new LinearLayoutManager(this));

         // Attach a listener to read the data at our posts reference
          mUserDatabase.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Users_get post = dataSnapshot.getValue(Users_get.class);
                System.out.println("DATAAAA: "+post);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("The read failed: " + databaseError.getCode());
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        invalidateOptionsMenu();
    }

    // View Holder Class
    public static class UsersViewHolder extends RecyclerView.ViewHolder {
        View mView;
        String nome;
        String surname;
        Long prezzo;
        public UsersViewHolder(View itemView) {
            super(itemView);
            mView = itemView;

        }

        public void getDetails(String name,String cognome,Long price){
            nome=name;
            surname=cognome;
            prezzo=price;
        }

        public void setDetails(String name, String surname, Long price) {

            TextView user_name = (TextView) mView.findViewById(R.id.name_text);
            TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
            TextView user_price = (TextView)mView.findViewById(R.id.price);

            user_name.setText(name);
            user_surname.setText(surname);
            user_price.setText(Long.toString(price));

        }
     }
}
</code>```

CLASS

```<code>public class Users_get  {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    private String name, surname;
    private Long price;
}
</code>```

JSON structure

```<code>{
  "Cart": {
    "-M0U3UXq2ZA00Jq5o9as": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0WlUbQHj1hdH40uWVF": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0WxZhI98Xb1s9Xy5HV": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0X00Zr64RocyQHhoFB": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    }
  },
  "Users": {
    "01": {
      "Name": "Alex",
      "Price": 120,
      "Surname": "Kyto"
    },
    "02": {
      "Name": "Alex",
      "Price": 200,
      "Surname": "Pablo"
    }
  }
}
</code>```

答:
Change the class to this:

```<code>public class Users_get  {

private String name, surname;
private Long price;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public Long getPrice() {
    return price;
}

public void setPrice(Long price) {
    this.price = price;
}

public Users_get(String name,Long price,String surname) {
    this.price = price;
    this.name = name;
    this.surname = surname;

}

public Users_get() {

}
</code>```

Since you are using an IDE, then just click generate getters and setters and it will automatically do that for you instead of manually writing the methods..

Title: No setter/getter Firebase

Body:
Hi everyone I have one question. I want to retrieve the data from the Firebase live database and it keeps telling me that it doesn't find the getter and the setter but as you can see below I did it, I create a class where I have the setter and the getter with the same name of the database fields.

Can anyone tell me what I'm doing wrong because I don't have a clue?

Thank you in advance.

Photo of the database:

Code of the Activity and the Class where you can see that I have the getter and the setter.

package com.example.ipill;

public class CartActivity extends AppCompatActivity {

    private TextView total;
    private ImageButton removeFromCart;
    private Button pay;

    private RecyclerView mResultList;
    private DatabaseReference mUserDatabase;
    public static int cart_count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        mUserDatabase = FirebaseDatabase.getInstance().getReference("Cart");

        total        = findViewById(R.id.TotalPrice);
        removeFromCart   = findViewById(R.id.removeFromCart);
        mResultList  = findViewById(R.id.cartList);
        pay    = findViewById(R.id.pay);

        mResultList.setHasFixedSize(true);
        mResultList.setLayoutManager(new LinearLayoutManager(this));

         // Attach a listener to read the data at our posts reference
          mUserDatabase.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Users_get post = dataSnapshot.getValue(Users_get.class);
                System.out.println("DATAAAA: "+post);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("The read failed: " + databaseError.getCode());
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        invalidateOptionsMenu();
    }

    // View Holder Class
    public static class UsersViewHolder extends RecyclerView.ViewHolder {
        View mView;
        String nome;
        String surname;
        Long prezzo;
        public UsersViewHolder(View itemView) {
            super(itemView);
            mView = itemView;

        }

        public void getDetails(String name,String cognome,Long price){
            nome=name;
            surname=cognome;
            prezzo=price;
        }

        public void setDetails(String name, String surname, Long price) {

            TextView user_name = (TextView) mView.findViewById(R.id.name_text);
            TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
            TextView user_price = (TextView)mView.findViewById(R.id.price);

            user_name.setText(name);
            user_surname.setText(surname);
            user_price.setText(Long.toString(price));

        }
     }
}

CLASS

public class Users_get  {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    private String name, surname;
    private Long price;
}

JSON structure

{
  "Cart": {
    "-M0U3UXq2ZA00Jq5o9as": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0WlUbQHj1hdH40uWVF": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0WxZhI98Xb1s9Xy5HV": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    },
    "-M0X00Zr64RocyQHhoFB": {
      "name": "Alex",
      "price": 120,
      "surname": "Kyto"
    }
  },
  "Users": {
    "01": {
      "Name": "Alex",
      "Price": 120,
      "Surname": "Kyto"
    },
    "02": {
      "Name": "Alex",
      "Price": 200,
      "Surname": "Pablo"
    }
  }
}

Body:
Change the class to this:

public class Users_get  {

private String name, surname;
private Long price;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public Long getPrice() {
    return price;
}

public void setPrice(Long price) {
    this.price = price;
}

public Users_get(String name,Long price,String surname) {
    this.price = price;
    this.name = name;
    this.surname = surname;

}

public Users_get() {

}

Since you are using an IDE, then just click generate getters and setters and it will automatically do that for you instead of manually writing the methods..


问:
Kafka Connect - Failed to commit offsets and flush
I had my Kafka Connectors paused and upon restarting them got these errors in my logs

```<code>[2020-02-19 19:36:00,219] ERROR WorkerSourceTask{id=wem-postgres-source-0} Failed to commit offsets (org.apache.kafka.connect.runtime.SourceTaskOffsetCommitter)
************
************
[2020-02-19 19:36:00,216] ERROR WorkerSourceTask{id=wem-postgres-source-0} Failed to flush, timed out while waiting for producer to flush outstanding 2389 messages (org.apache.kafka.connect.runtime.WorkerSourceTask)
</code>```

I got this error multiple times with the number of outstanding messages changed. Then it stopped and haven't seen it again.

Do I need to take any action here or has Connect retried and committed the offsets and that is why the error has stopped?

Thanks

答:
The error indicates that there are a lot of messages buffered and cannot be flushed before the timeout is reached. To address this issue you can

either increase offset.flush.timeout.ms configuration parameter in your Kafka Connect Worker Configs

or you can reduce the amount of data being buffered by decreasing producer.buffer.memory in your Kafka Connect Worker Configs. This turns to be the best option when you have fairly large messages.

Body:
I had my Kafka Connectors paused and upon restarting them got these errors in my logs

[2020-02-19 19:36:00,219] ERROR WorkerSourceTask{id=wem-postgres-source-0} Failed to commit offsets (org.apache.kafka.connect.runtime.SourceTaskOffsetCommitter)
************
************
[2020-02-19 19:36:00,216] ERROR WorkerSourceTask{id=wem-postgres-source-0} Failed to flush, timed out while waiting for producer to flush outstanding 2389 messages (org.apache.kafka.connect.runtime.WorkerSourceTask)

I got this error multiple times with the number of outstanding messages changed. Then it stopped and haven't seen it again.

Do I need to take any action here or has Connect retried and committed the offsets and that is why the error has stopped?

Thanks


答:
You get the warning because in your Users_get class you don't have correct getters for your fields. If you have a field named name, the correct getter should be:

```<code>public String getName() {
    return name;
}
</code>```

And not:

```<code>public String getname() {
    return name;
}
</code>```

See the capital N versus lowercase n? To solve this you should change all the names of all getters in your Users_get class, as explained above.

Title: No setter/getter Firebase

Body:
You get the warning because in your Users_get class you don't have correct getters for your fields. If you have a field named name, the correct getter should be:

public String getName() {
    return name;
}

And not:

public String getname() {
    return name;
}

See the capital N versus lowercase n? To solve this you should change all the names of all getters in your Users_get class, as explained above.


问:
Bash exit in if statement in a for loop
I am trying to do a for loop in Bash and exit on an if statement but I realised it will break the code before finishing the loop.

```<code>#!/bin/bash

for node in $(ps -ef | awk <something>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    exit 1;

  elif [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    exit 2;

  else
    echo "OK!";
    exit 0;
  fi
done
</code>```

My second option is to set a variable instead of the exit outside the loop but then I realised it will override each node status:

```<code>#!/bin/bash

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    status="warning"

  elif [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    status="critical"

  else
    echo "OK!";
    status="ok"
  fi
done

if [[ status == "warning" ]]; then
  exit 1;
elif [[ status == "critical" ]]; then
  exit 2;
elif [[ status == "ok" ]]; then
  exit 0;
fi
</code>```

How do I exit properly on each node?

答:
Here is an alternative. It counts the results and and creates an exit status depending on the counters. I changed the semantic, because your script never reaches the CRITICAL path. Instead the WARNING path was entered for values >1000000:

```<code>#!/bin/bash

let ok_count=0 warn_count=0 critical_count=0

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  # >1000000 must be checked before >300000
  if [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    let critical_count++

  elif [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    let warn_count++

  else
    echo "OK!";
    let ok_count++
  fi
done

if ((critical_count)); then
  exit 2
elif ((warn_count)); then
  exit 1
else
  exit 0
fi
</code>```

This script can be optimized, if only the exit status is needed:
CRITICAL is the highest warn level. So counting is not necessary.
OK is the fallback. So counting is not necessary.

```<code>#!/bin/bash

let warn_count=0

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL! -> abort";
    exit 2 # no more analysis needed!

  elif [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    let warn_count++
  fi
done

exit $(( warn_count > 0 ))
</code>```

Title: Bash exit in if statement in a for loop

Body:
I am trying to do a for loop in Bash and exit on an if statement but I realised it will break the code before finishing the loop.

#!/bin/bash

for node in $(ps -ef | awk <something>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    exit 1;

  elif [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    exit 2;

  else
    echo "OK!";
    exit 0;
  fi
done

My second option is to set a variable instead of the exit outside the loop but then I realised it will override each node status:

#!/bin/bash

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    status="warning"

  elif [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    status="critical"

  else
    echo "OK!";
    status="ok"
  fi
done

if [[ status == "warning" ]]; then
  exit 1;
elif [[ status == "critical" ]]; then
  exit 2;
elif [[ status == "ok" ]]; then
  exit 0;
fi

How do I exit properly on each node?

Body:
Here is an alternative. It counts the results and and creates an exit status depending on the counters. I changed the semantic, because your script never reaches the CRITICAL path. Instead the WARNING path was entered for values >1000000:

#!/bin/bash

let ok_count=0 warn_count=0 critical_count=0

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  # >1000000 must be checked before >300000
  if [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL!";
    let critical_count++

  elif [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    let warn_count++

  else
    echo "OK!";
    let ok_count++
  fi
done

if ((critical_count)); then
  exit 2
elif ((warn_count)); then
  exit 1
else
  exit 0
fi

This script can be optimized, if only the exit status is needed:
CRITICAL is the highest warn level. So counting is not necessary.
OK is the fallback. So counting is not necessary.

#!/bin/bash

let warn_count=0

for node in $(ps -ef | awk <command>);
do

  var=<command>
  echo "node ${node}"

  if [[ ${var} -gt 1000000 ]]; then
    echo "CRITICAL! -> abort";
    exit 2 # no more analysis needed!

  elif [[ ${var} -gt 300000 ]]; then
    echo "WARNING!";
    let warn_count++
  fi
done

exit $(( warn_count > 0 ))


答:
first you should convert your list of dictionaries into a pandas DataFrame. As you can see here, this is rather easy:

```<code>import pandas as pd
data = pd.DataFrame(a)
</code>```

next you want to convert your time column into date-time objects rather than integers. The best way I know to do this is the to_datetime function in pandas. Please see the documentation for further Details.

```<code>data['time'] = pd.to_datetime(data['time'], unit = 's') #should do the trick, but could not test yet...
</code>```

For the actual grouping, pandas provides the very powerful groupby function, which is implemented for all DataFrame objects. Again, the docs will provide detailed information.

```<code>data.groupby(['time'])
</code>```

please note that if the output is not exactly what you want, you can easily modify it using groupby because it accepts mappings, functions, labels or lists of labels as an argument. This should allow you to get exactly what you want, if you play with it a little.

Title: pandas group by day or week or month for timestamp

Body:
I'm a pandas beginner.

I have the following data:

a = [{"content": '1', "time": 1577870427},
     {"content": '4', "time": 1577870427},
     {"content": '2', "time": 1577956827},
     {"content": '3', "time": 1580548827},
     {"content": '4', "time": 1580635227},
     {"content": '5', "time": 1583054427},
     {"content": '6', "time": 1583140827}]

And I want:

2020-01: [
     {"content": '1', "time": '2020-01-01'},
     {"content": '4', "time": '2020-01-01'},
     {"content": '2', "time": '2020-01-02'},
    ]

    2020-02: [
     {"content": '3', "time": '2020-02-01'},
     {"content": '4', "time": '2020-02-02'},
    ]

    2020-03: [
     {"content": '5', "time": '2020-03-01'},
     {"content": '6', "time": '2020-03-02'}
    ]

Body:
first you should convert your list of dictionaries into a pandas DataFrame. As you can see here, this is rather easy:

import pandas as pd
data = pd.DataFrame(a)

next you want to convert your time column into date-time objects rather than integers. The best way I know to do this is the to_datetime function in pandas. Please see the documentation for further Details.

data['time'] = pd.to_datetime(data['time'], unit = 's') #should do the trick, but could not test yet...

For the actual grouping, pandas provides the very powerful groupby function, which is implemented for all DataFrame objects. Again, the docs will provide detailed information.

data.groupby(['time'])

please note that if the output is not exactly what you want, you can easily modify it using groupby because it accepts mappings, functions, labels or lists of labels as an argument. This should allow you to get exactly what you want, if you play with it a little.


问:
Selenium php-webdriver ignores all the arguments and extensions
UPDATED: I will leave the question open in case someone can explain what I was doing wrong. I didn't fix the issue, but I achieved result after switching from "selenium-hub + chrome node" to "standalone chrome" image in docker-compose.yaml

I'm using facebook/php-webdriver to run Chrome test with Selenium. Here is the simple code example:

I'm using SeleniumHQ/docker-selenium to run Selenium. So docker-compose.yaml is like:

```<code>...
    selenium-hub:
        container_name: selenium-hub
        image: selenium/hub:latest
        ports:
            - "4444:4444"
    chrome:
        container_name: chrome
        image: selenium/node-chrome:latest
        volumes:
            - /dev/shm:/dev/shm
        depends_on:
            - selenium-hub
        environment:
           - HUB_HOST=selenium-hub
           - HUB_PORT=4444
           - SCREEN_WIDTH=1280
           - SCREEN_HEIGHT=800
           - SCREEN_DEPTH=24
        entrypoint: bash -c 'SE_OPTS="-host $$HOSTNAME" /opt/bin/entry_point.sh'
...
</code>```

PHP code:

        $options = (new ChromeOptions())
            ->addArguments([
            '--window-size=640x480',
            ]);
        $capabilities = DesiredCapabilities::chrome();
        $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
        $driver = RemoteWebDriver::create('http://selenium-hub:4444/wd/hub/', $capabilities, 5000);
        $driver->get('chrome://version/');
        header("Content-Type: image/jpeg");
        echo $driver->takeScreenshot();
        $driver->quit();
```

For some reason params in addArguments() doesn't have any impact - the outcome is always the same no matter what was set in the method addArguments(). It is always something like this

Whatever I'll put to addArguments() nothing will change.

Any ideas are appreciated.

Environment information:

Php-webdriver version: 1.7.1

PHP version: 7.2.19

Selenium server version: 3.141.59

Operating system: Alpine Linux

Browser used + version: Chrome 75.0.3770.90

SeleniumHQ/docker-selenium: 3.141.59

答:
I have had the same issue with Java Selenium tests. After couple of hours I have figured out, why no arguments were passed to chrome. You can try to pass whatever arguments ("aaaaa=bbbbb",...), but no args are passed.

Solution is to upgrade webdriver (not chromedriver). In my Java case, updating version numbers in Maven's POM file of all "org.seleniumhq.selenium" dependencies.

Body:
UPDATED: I will leave the question open in case someone can explain what I was doing wrong. I didn't fix the issue, but I achieved result after switching from "selenium-hub + chrome node" to "standalone chrome" image in docker-compose.yaml

I'm using facebook/php-webdriver to run Chrome test with Selenium. Here is the simple code example:

I'm using SeleniumHQ/docker-selenium to run Selenium. So docker-compose.yaml is like:

...
    selenium-hub:
        container_name: selenium-hub
        image: selenium/hub:latest
        ports:
            - "4444:4444"
    chrome:
        container_name: chrome
        image: selenium/node-chrome:latest
        volumes:
            - /dev/shm:/dev/shm
        depends_on:
            - selenium-hub
        environment:
           - HUB_HOST=selenium-hub
           - HUB_PORT=4444
           - SCREEN_WIDTH=1280
           - SCREEN_HEIGHT=800
           - SCREEN_DEPTH=24
        entrypoint: bash -c 'SE_OPTS="-host $$HOSTNAME" /opt/bin/entry_point.sh'
...

PHP code:

        $options = (new ChromeOptions())
            ->addArguments([
            '--window-size=640x480',
            ]);
        $capabilities = DesiredCapabilities::chrome();
        $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
        $driver = RemoteWebDriver::create('http://selenium-hub:4444/wd/hub/', $capabilities, 5000);
        $driver->get('chrome://version/');
        header("Content-Type: image/jpeg");
        echo $driver->takeScreenshot();
        $driver->quit();

For some reason params in addArguments() doesn't have any impact - the outcome is always the same no matter what was set in the method addArguments(). It is always something like this

Whatever I'll put to addArguments() nothing will change.

Any ideas are appreciated.

Environment information:

Php-webdriver version: 1.7.1

PHP version: 7.2.19

Selenium server version: 3.141.59

Operating system: Alpine Linux

Browser used + version: Chrome 75.0.3770.90

SeleniumHQ/docker-selenium: 3.141.59


答:
Try this:</p>

```<code>Article_Keyword = bs.find('div', {'class':'ListTags'})
aes_Article_Keyword  = Article_Keyword.find_all("a")

s_Article_Keyword = ", ".join([x.text for x in aes_Article_Keyword])
</code>```

Title: Fetching a list from a website using beautifulsoup in a dataframe column

Body:
I am trying to fetch the keywords from the article website. The website keywords look like this:

`This is the link:` `https://www.horizont.net/marketing/nachrichten/bgh-haendler-haftet-nicht-fuer-kundenbewertungen-auf-amazon-180980`

I am using this to fetch the keywords:

   Article_Keyword = bs.find('div', {'class':'ListTags'}).get_text()

and this is how what i am getting:

Themen Bundesgerichtshof Amazon Verband Sozialer Wettbewerb Kundenbewertung Tape dpa

I need to get it by separating each keyword by comma. I can do it by RE but some keywords are with more than one word so i need that as one keyword.

is there any way to get each keyword by separating with comma?

Body:
Try this:

Article_Keyword = bs.find('div', {'class':'ListTags'})
aes_Article_Keyword  = Article_Keyword.find_all("a")

s_Article_Keyword = ", ".join([x.text for x in aes_Article_Keyword])


问:
How to make the if statement without repetition of code?
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.</p>

```<code>    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }
</code>```

答:
```<code>function statusToAttrib(v){
    return v.toLowerCase().replace(/\s/g,'')
}

arrow.setAttribute("class","arrow2");
tag.setAttribute("class",statusToAttrib(allTasks[t].status));
tag.innerHTML = allTasks[t].status;
taskCont.appendChild(tag);
</code>```

Body:
Following is the if statement that execute some part of the code before it checks some condition, it is working fine but it looks very basic and repeated lines.

    if(allTasks[t].status === "Completed"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","completed");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Past Due"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","pastdue");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Duetoday"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","duetoday");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Onhold"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","onhold");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }else if(allTasks[t].status === "Canceled"){
        arrow.setAttribute("class","arrow2");
        tag.setAttribute("class","canceled");
        tag.innerHTML = allTasks[t].status;
        taskCont.appendChild(tag);
    }


问:
Razor _Layout.cshtml common section from a specific controller
I'm developing my first ASP.NET MVC app and what I'd like to accomplish is to display a common list in a section on each page.  In my case, I've got a _Layout.cshtml which has a header, footer, main area and a left sidebar where I'd like to always display a list of items retrieved from a DB.

If I do something like:

```<code>@RenderSection("BestSellingFlavors")
</code>```

in the _Layout.cshtml, I can have any particular view display its "BestSellingFlavors" section there, but in my case, this is a standard list retrieved from a database - something I want always displayed on the sidebar, regardless of which page the user is viewing.  Make sense?

Currently, I've got a controller/model/view that provides a view of the bestselling flavors in our inventory but I'm not sure how to have that information retrieved and displayed without duplicating a bunch of code in each controller/view.

One idea was a BaseController that handled retrieving the best sellers.  Something like this:

```<code>public abstract class BaseController : Controller
{
   public PartialViewResult BestSellers()
   {
      try
      {
         var db = IceCreamDBData();
         var all = db.Sales.AsEnumerable();
         var bestsellers = from a in all select new {a.Name, a.UnitsSold};
         return PartialView("BestSellers", bestsellers);
      }
      catch (Exception)
      {
          throw;
      }
   }
}
</code>```

My various controllers would inherit BaseController.
But then I'm stuck wondering how this actually gets called and where the view code resides that would @foreach that collection of data and display it.  This makes me think I"m attacking the problem incorrectly.  How should I be solving this?

UPDATE:
J.W.'s solution and link got me started and now I am (presumably) on the right track.

In my _Layout.cshtml I created a div:

```<code><div id="BestSellers">
   @Html.Action("BestSellers")
</div>
</code>```

then I created a partial view in the Shared folder called _BestSellersPartial.cshtml that has something like this:

```<code>@model HometownIceCream.Models.BestSellersViewModel
<h3>Best Sellers</h3>
@foreach (var item in Model.Entries)
{
   <div>@item.Name</div>
}
</code>```

And then my BaseController looks like this:

```<code>public abstract class BaseController : Controller
{
   public PartialViewResult BestSellers()
   {
      try
      {
         var db = IceCreamDBData();
         var all = db.Sales.AsEnumerable();
         var bestsellers = from a in all select new {a.Name, a.UnitsSold};
         BestSellersViewModel mod = new BestSellersViewModel() {Entries = bestsellers};
         return PartialView("_BestSellersPartial", mod);
      }
      catch (Exception)
      {
          throw;
      }
   }
}
</code>```

And that seems to work quite well.  The only thing I needed to do for my controllers was have them inherit BaseController rather than Controller.

答: I think  Html.RenderAction is what you need. You can create a shared section such as menu using this method.</p>

Body:
I'm developing my first ASP.NET MVC app and what I'd like to accomplish is to display a common list in a section on each page.  In my case, I've got a _Layout.cshtml which has a header, footer, main area and a left sidebar where I'd like to always display a list of items retrieved from a DB.

If I do something like:

@RenderSection("BestSellingFlavors")

in the _Layout.cshtml, I can have any particular view display its "BestSellingFlavors" section there, but in my case, this is a standard list retrieved from a database - something I want always displayed on the sidebar, regardless of which page the user is viewing.  Make sense?

Currently, I've got a controller/model/view that provides a view of the bestselling flavors in our inventory but I'm not sure how to have that information retrieved and displayed without duplicating a bunch of code in each controller/view.

One idea was a BaseController that handled retrieving the best sellers.  Something like this:

public abstract class BaseController : Controller
{
   public PartialViewResult BestSellers()
   {
      try
      {
         var db = IceCreamDBData();
         var all = db.Sales.AsEnumerable();
         var bestsellers = from a in all select new {a.Name, a.UnitsSold};
         return PartialView("BestSellers", bestsellers);
      }
      catch (Exception)
      {
          throw;
      }
   }
}

My various controllers would inherit BaseController.
But then I'm stuck wondering how this actually gets called and where the view code resides that would @foreach that collection of data and display it.  This makes me think I"m attacking the problem incorrectly.  How should I be solving this?

UPDATE:
J.W.'s solution and link got me started and now I am (presumably) on the right track.

In my _Layout.cshtml I created a div:

   @Html.Action("BestSellers")

then I created a partial view in the Shared folder called _BestSellersPartial.cshtml that has something like this:

@model HometownIceCream.Models.BestSellersViewModel

Best Sellers

@foreach (var item in Model.Entries)
{

@item.Name

}

And then my BaseController looks like this:

public abstract class BaseController : Controller
{
   public PartialViewResult BestSellers()
   {
      try
      {
         var db = IceCreamDBData();
         var all = db.Sales.AsEnumerable();
         var bestsellers = from a in all select new {a.Name, a.UnitsSold};
         BestSellersViewModel mod = new BestSellersViewModel() {Entries = bestsellers};
         return PartialView("_BestSellersPartial", mod);
      }
      catch (Exception)
      {
          throw;
      }
   }
}

And that seems to work quite well.  The only thing I needed to do for my controllers was have them inherit BaseController rather than Controller.


答:
I used a child class element to Identify each element separately. I hope the below code helps.

```<code>from bs4 import BeautifulSoup as soup
from requests import get
url = "https://www.horizont.net/marketing/nachrichten/bgh-haendler-haftet-nicht-fuer-kundenbewertungen-auf-amazon-180980"
clnt = get(url)
page=soup(clnt.text,"html.parser")
data = page.find('div', attrs={'class':'ListTags'})
data1 = [ele.text for ele in data.find_all('a',attrs={'class':'PageArticle_keyword'})]
print(data1)
print(",".join(data1))
</code>```

Output:

```<code>>> ['Bundesgerichtshof', 'Amazon', 'Verband Sozialer Wettbewerb', 'Kundenbewertung', 'Tape', 'dpa']
>> Bundesgerichtshof,Amazon,Verband Sozialer Wettbewerb,Kundenbewertung,Tape,dpa
</code>```

Make sure you approve the answer if usefull.

Body:
I used a child class element to Identify each element separately. I hope the below code helps.

from bs4 import BeautifulSoup as soup
from requests import get
url = "https://www.horizont.net/marketing/nachrichten/bgh-haendler-haftet-nicht-fuer-kundenbewertungen-auf-amazon-180980"
clnt = get(url)
page=soup(clnt.text,"html.parser")
data = page.find('div', attrs={'class':'ListTags'})
data1 = [ele.text for ele in data.find_all('a',attrs={'class':'PageArticle_keyword'})]
print(data1)
print(",".join(data1))

Output:

>> ['Bundesgerichtshof', 'Amazon', 'Verband Sozialer Wettbewerb', 'Kundenbewertung', 'Tape', 'dpa']
>> Bundesgerichtshof,Amazon,Verband Sozialer Wettbewerb,Kundenbewertung,Tape,dpa

Make sure you approve the answer if usefull.


问:
How to connect my host mysql in docker container?
my.cnf configured = bind-address = 172.18.0.3(Docker Container ID)
and bind-address = 0.0.0.0 in my host.
I try connecting from docker container.

```<code>DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=default
DB_USERNAME=root
DB_PASSWORD=root
</code>```

But not connecting local mysql.I get this error

SQLSTATE[HY000] [2002] Connection refused

答:
You can use the docker0 interface IP address

run ip route show | awk '/default/ {print $3}' inside your container and check the ip address. try to connect on this IP address and port 3306.

If you have static a host IP address then you can also use host machine IP address to connect.

Body:
my.cnf configured = bind-address = 172.18.0.3(Docker Container ID)
and bind-address = 0.0.0.0 in my host.
I try connecting from docker container.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=default
DB_USERNAME=root
DB_PASSWORD=root

But not connecting local mysql.I get this error

SQLSTATE[HY000] [2002] Connection refused


问:
how to insert a row in the middle of the table. google sheets API
I can't figure out how to add a row to a certain place always adds to the end of the table.</p>

```<code>        {
            SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum valueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.RAW;
            SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum insertDataOption = SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum.INSERTROWS;
            ValueRange requestBody = new ValueRange();
            requestBody.Range = range + "!A4:A";
            IList<Object> obj = new List<Object>();
            obj.Add("A2");
            obj.Add("B2");
            IList<IList<Object>> values = new List<IList<Object>>();
            values.Add(obj);
            requestBody.Values = values;
            SpreadsheetsResource.ValuesResource.AppendRequest request = service.Spreadsheets.Values.Append(requestBody, spreadsheetId, range+"!A4:A");
            request.ValueInputOption = valueInputOption;
            request.InsertDataOption = insertDataOption;

            AppendValuesResponse response = request.Execute();
        }```
</code>```

答:
As you can see in the official documentation, values appended via spreadsheets.values.append are appended "after the last row of the table". With append, you cannot decide where exactly you want to add your data. The API looks for a "table" based on the input range you specify, as explained here.

If you want to add a row in the exact place you want, you should first (1) insert an empty range and then (2) write your desired values to the empty range. You would have to do two successive requests:

In order to insert the empty range where you want to append your data to, use the method spreadsheets.batchUpdate and in the field requests, provide an insertRange request. Specify the row and column indexes you want to insert your range to (field range) and whether the previously existing cells should be shifted down or right (field shiftDimension).

Second, once you have empty cells where you want your values to be, you can use spreadsheets.values.batchUpdate to write those values (defined in the field data). Check this guide to writing values for a detailed explanation.

Reference:

Appending values

Method: spreadsheets.batchUpdate

InsertRangeRequest

Method: spreadsheets.values.batchUpdate

Writing

Body:
I can't figure out how to add a row to a certain place always adds to the end of the table.

        {
            SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum valueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.RAW;
            SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum insertDataOption = SpreadsheetsResource.ValuesResource.AppendRequest.InsertDataOptionEnum.INSERTROWS;
            ValueRange requestBody = new ValueRange();
            requestBody.Range = range + "!A4:A";
            IList<Object> obj = new List<Object>();
            obj.Add("A2");
            obj.Add("B2");
            IList<IList<Object>> values = new List<IList<Object>>();
            values.Add(obj);
            requestBody.Values = values;
            SpreadsheetsResource.ValuesResource.AppendRequest request = service.Spreadsheets.Values.Append(requestBody, spreadsheetId, range+"!A4:A");
            request.ValueInputOption = valueInputOption;
            request.InsertDataOption = insertDataOption;

            AppendValuesResponse response = request.Execute();
        }```


问:
When a variable goes out of scope does that mean it doesn't exist?
I'm not sure I understand scope - does an out-of-scope variable (I'm using Ruby) exist in memory somewhere or does it stop existing (I know you can't access it). Would it be inaccurate to say that an out-of-scope variable does not exist any more?

Maybe this is a philosophical question.

答:
A variable is not the same as the value it holds.

The variable itself ceases to exist when it goes out of scope. The value that the variable held may represent an object, and that object may continue to exist beyond the lifetime of the variable. The garbage collector reclaims the object later.

OwnerDisplayName: Mark

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Rob Kennedy


问:
What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)
Let's make a list of answers where you post your excellent and favorite extension methods.

The requirement is that the full code must be posted and a example and an explanation on how to use it.

Based on the high interest in this topic I have setup an Open Source Project called extensionoverflow on Codeplex.

Please mark your answers with an acceptance to put the code in the Codeplex project.

Please post the full sourcecode and not a link.

Codeplex News:

24.08.2010 The Codeplex page is now here:  http://extensionoverflow.codeplex.com/

11.11.2008 XmlSerialize / XmlDeserialize is now Implemented and Unit Tested.

11.11.2008 There is still room for more developers. ;-) Join NOW!

11.11.2008 Third contributer joined ExtensionOverflow, welcome to BKristensen

11.11.2008 FormatWith is now Implemented and Unit Tested.

09.11.2008 Second contributer joined ExtensionOverflow. welcome to chakrit.

09.11.2008 We need more developers. ;-)

09.11.2008 ThrowIfArgumentIsNull in now Implemented and Unit Tested on Codeplex.

答:
Two color extensions I use, mostly for control development:

```<code>public static class ColorExtensions
{
  // Gets a color that will be readable on top of a given background color
  public static Color GetForegroundColor(this Color input)
  {
    // Math taken from one of the replies to
    // http://stackoverflow.com/questions/2241447/make-foregroundcolor-black-or-white-depending-on-background
    if (Math.Sqrt(input.R * input.R * .241 + input.G * input.G * .691 + input.B * input.B * .068) > 128)
      return Color.Black;
    else
      return Color.White;
  }

  // Converts a given Color to gray
  public static Color ToGray(this Color input)
  {
    int g = (int)(input.R * .299) + (int)(input.G * .587) + (int)(input.B * .114);
    return Color.FromArgb(input.A, g, g, g);
  }
}
</code>```

Usage:

```<code>Color foreColor = someBackColor.GetForegroundColor();
Color grayColor = someBackColor.ToGray();
</code>```

OwnerDisplayName: bovium

LastEditorDisplayName: spinodal

Body:
Two color extensions I use, mostly for control development:

public static class ColorExtensions
{
  // Gets a color that will be readable on top of a given background color
  public static Color GetForegroundColor(this Color input)
  {
    // Math taken from one of the replies to
    // http://stackoverflow.com/questions/2241447/make-foregroundcolor-black-or-white-depending-on-background
    if (Math.Sqrt(input.R * input.R * .241 + input.G * input.G * .691 + input.B * input.B * .068) > 128)
      return Color.Black;
    else
      return Color.White;
  }

  // Converts a given Color to gray
  public static Color ToGray(this Color input)
  {
    int g = (int)(input.R * .299) + (int)(input.G * .587) + (int)(input.B * .114);
    return Color.FromArgb(input.A, g, g, g);
  }
}

Usage:

Color foreColor = someBackColor.GetForegroundColor();
Color grayColor = someBackColor.ToGray();


问:
How to validate decimal variables with php?
I have a product in my sql table. From this product, the minimum order quantity is 19.2

If i want to add 19, the program allows it.

```<code>$product_id = intval($_POST['product_id']);
    $quantity = $_POST['quantity'];
    $color = intval($_POST['szin']);
    $MinimumOrder = $_POST['MinimumOrder'];

    if($quantity%$MinimumOrder == 0 )
    {
        $cart->add($product_id, $quantity, array
            (
                "price" => $price,
                "color" => $color
            )
        );

        echo 'A termék sikeresen hozzá lett adva a kosárhoz.';
    }
    else
    {
        echo 'Ebből a termékből csak egész raklap rendelhető. Egy raklapon  ' . $MinimumOrder . ' ' . $product['mertekegyseg_nev'] .' található.';
    }
</code>```

答:
PHP documentation says:

Operands of modulo are converted to integers (by stripping the decimal part) before processing. For floating-point modulo, see fmod().

If you want to use 19.2, you will have to use the fmod() function

```<code>$MinimumOrder = 19.2;

$quantity = 19;
var_dump($quantity % $MinimumOrder);      // int(0)
var_dump(fmod($quantity, $MinimumOrder)); // int(19)

$quantity = 19.2;
var_dump(fmod($quantity, $MinimumOrder)); // int(0)

$quantity = 38.4;
var_dump(fmod($quantity, $MinimumOrder)); // int(0)

$quantity = 19.3;
var_dump(fmod($quantity, $MinimumOrder)); // int(0.1)

$quantity = 20;
var_dump(fmod($quantity, $MinimumOrder)); // int(0.8)

</code>```

Body:
I have a product in my sql table. From this product, the minimum order quantity is 19.2

If i want to add 19, the program allows it.

$product_id = intval($_POST['product_id']);
    $quantity = $_POST['quantity'];
    $color = intval($_POST['szin']);
    $MinimumOrder = $_POST['MinimumOrder'];

    if($quantity%$MinimumOrder == 0 )
    {
        $cart->add($product_id, $quantity, array
            (
                "price" => $price,
                "color" => $color
            )
        );

        echo 'A termék sikeresen hozzá lett adva a kosárhoz.';
    }
    else
    {
        echo 'Ebből a termékből csak egész raklap rendelhető. Egy raklapon  ' . $MinimumOrder . ' ' . $product['mertekegyseg_nev'] .' található.';
    }

Body:
PHP documentation says:

Operands of modulo are converted to integers (by stripping the decimal part) before processing. For floating-point modulo, see fmod().

If you want to use 19.2, you will have to use the fmod() function

$MinimumOrder = 19.2;

$quantity = 19;
var_dump($quantity % $MinimumOrder);      // int(0)
var_dump(fmod($quantity, $MinimumOrder)); // int(19)

$quantity = 19.2;
var_dump(fmod($quantity, $MinimumOrder)); // int(0)

$quantity = 38.4;
var_dump(fmod($quantity, $MinimumOrder)); // int(0)

$quantity = 19.3;
var_dump(fmod($quantity, $MinimumOrder)); // int(0.1)

$quantity = 20;
var_dump(fmod($quantity, $MinimumOrder)); // int(0.8)


问:
How to hide specific option in the drop-down values while combining two drop-downs in Angular
I have a dropdown named country, which has 3 values "India,china, australia" and I have a dropdown named position which has 3 values " application developer ,application developer- WW, application developer -GEO".

I want to show all 3 values of the second dropdown when country is other than India.

for India it should only show application developer

```<code><mat-form-field class="no-bord">
                                            <mat-select [ngClass]="isValidCountry?'sb-push-unread':'sb-push-read'" id="country" tabindex="21" (ngModelChange)="onChangeCountry($event)" name="country_code" [(ngModel)]="requestData.country_code" class="form-control form-control-cust">
                                                <mat-option value="" selected>Select Physical Country</mat-option>
                                                <mat-option *ngFor="let ele of geocountry" [value]="ele.country_id">{{ele.country_name}}</mat-option>
                                            </mat-select>
                                        </mat-form-field>

    <mat-form-field class="no-bord">
                                            <mat-select [ngClass]="isValidjobrole?'sb-push-unread':'sb-push-read'" #offr="ngModel" tabindex="17" class="form-control form-control-cust offering" (ngModelChange)="onChangeJobrole($event)" name="job_role" [(ngModel)]="requestData.job_role">
                                                <mat-option value="" selected>Select Job Role</mat-option>
                                                <mat-option *ngFor="let ele of jobrole" [value]="ele.JOB_ROLE_ID">{{ele.JOB_ROLE_NAME}}</mat-option>
                                            </mat-select>
                                        </mat-form-field>
</code>```

my ts file is below:

onChangeGeo(newgeoindex) {

```<code>this.requestData.country_code = '';
this.requestData.msc_location = '';
this.nocountry = false;
this.geocountry = [];
this.msccountry = [];
this.msccity = [];
this.isothercity = false;
this.maincity = " ";
this.othercitydata = " ";
for (let geo of this.masterData['geo_country']) {
  if (geo.geo_id == newgeoindex) {
    this.requestData.geo = geo.geo_name;
    this.requestData.geo_code = geo.geo_code;
    this.geocountry = geo.countries;
  }
}
</code>```

}

答:
You can find working example here 1. (using RXJS way) StackBlitz Link

You can find working example here 2. (using simple component way) StackBlitz Link

You can find working example here 3. (using pipe) StackBlitz Link

Above are three different way of doing as per your requirement.

app.component.html

```<code><select (change)="onSelected($event)">
    <option>select </option>
    <option *ngFor="let country of countries" [value]="country">{{country}} </option>
</select>
<hr>
<select>
   <option> select</option>
   <option *ngFor="let dev of developers"> {{dev}} </option>
</select>
</code>```

app.component.ts

```<code>export class AppComponent  {
   countries = ['India', 'China', 'Australia', 'USA'];
   developers = ["application developer" ,"application developer- WW", "application developer -GEO"];
   developersCopy = ["application developer" ,"application developer- WW", "application developer -GEO"];
   onSelected(country){
      if (country.target.value === 'India'){
         this.developers = this.developers.filter(val => val.toString() === 'application developer')
   }else{
     this.developers = this.developersCopy;
   }
  }
</code>```

This is very quick, solution for your reference, since you are not going to tell about your approach of doing solution. There are numerous ways to improve this solution.

Body:
I have a dropdown named country, which has 3 values "India,china, australia" and I have a dropdown named position which has 3 values " application developer ,application developer- WW, application developer -GEO".

I want to show all 3 values of the second dropdown when country is other than India.

for India it should only show application developer

<mat-form-field class="no-bord">
                                            <mat-select [ngClass]="isValidCountry?'sb-push-unread':'sb-push-read'" id="country" tabindex="21" (ngModelChange)="onChangeCountry($event)" name="country_code" [(ngModel)]="requestData.country_code" class="form-control form-control-cust">
                                                <mat-option value="" selected>Select Physical Country</mat-option>
                                                <mat-option *ngFor="let ele of geocountry" [value]="ele.country_id">{{ele.country_name}}</mat-option>
                                            </mat-select>
                                        </mat-form-field>

    <mat-form-field class="no-bord">
                                            <mat-select [ngClass]="isValidjobrole?'sb-push-unread':'sb-push-read'" #offr="ngModel" tabindex="17" class="form-control form-control-cust offering" (ngModelChange)="onChangeJobrole($event)" name="job_role" [(ngModel)]="requestData.job_role">
                                                <mat-option value="" selected>Select Job Role</mat-option>
                                                <mat-option *ngFor="let ele of jobrole" [value]="ele.JOB_ROLE_ID">{{ele.JOB_ROLE_NAME}}</mat-option>
                                            </mat-select>
                                        </mat-form-field>

my ts file is below:

onChangeGeo(newgeoindex) {

this.requestData.country_code = '';
this.requestData.msc_location = '';
this.nocountry = false;
this.geocountry = [];
this.msccountry = [];
this.msccity = [];
this.isothercity = false;
this.maincity = " ";
this.othercitydata = " ";
for (let geo of this.masterData['geo_country']) {
  if (geo.geo_id == newgeoindex) {
    this.requestData.geo = geo.geo_name;
    this.requestData.geo_code = geo.geo_code;
    this.geocountry = geo.countries;
  }
}

}

Body:
You can find working example here 1. (using RXJS way) StackBlitz Link

You can find working example here 2. (using simple component way) StackBlitz Link

You can find working example here 3. (using pipe) StackBlitz Link

Above are three different way of doing as per your requirement.

app.component.html

<select (change)="onSelected($event)">
    <option>select </option>
    <option *ngFor="let country of countries" [value]="country">{{country}} </option>
</select>
<hr>
<select>
   <option> select</option>
   <option *ngFor="let dev of developers"> {{dev}} </option>
</select>

app.component.ts

export class AppComponent  {
   countries = ['India', 'China', 'Australia', 'USA'];
   developers = ["application developer" ,"application developer- WW", "application developer -GEO"];
   developersCopy = ["application developer" ,"application developer- WW", "application developer -GEO"];
   onSelected(country){
      if (country.target.value === 'India'){
         this.developers = this.developers.filter(val => val.toString() === 'application developer')
   }else{
     this.developers = this.developersCopy;
   }
  }

This is very quick, solution for your reference, since you are not going to tell about your approach of doing solution. There are numerous ways to improve this solution.


问:
How to restrict invalid values from entering in an input field having a regex pattern
I have an input field in which I want first 4 characters to be numbers only, after that only dot(.) is allowed, and then only 2 numbers allowed. Example: 9999.99

I also want that if I am entering something else it should not enter in input field.

For this I created a regex as : ^[0-9]{4}+\.+[0-9]{2}+$

HTML: <input type="text" (keypress)="onKeydown($event)">

TS:

```<code>regex = '/^[0-9]{4}+\.+[0-9]{2}+$/';

  onKeydown(event) {
    if(event.target.value.match(this.regex)) {
      return true;
    } else return false;
  }
</code>```

But I guess I am doing something quite wrong here. Kindly let me know about it.

Thanks.

答:
You don't need + (select 1 or more matches) in your regex.

Instead, you need | (or) to catch two cases: when input does not contain dot and when dot is added.

Try something like this: /^(?:\d{0,4}|\d{4}\.\d{0,2})$/.

I've added ?: (non-capturing group mark) to exclude group in match, but it's not necessary.

UPDATE: here's a quick sketch using oninput event handler:

var regex = /^(?:\d{0,4}|\d{4}\.\d{0,2})$/;
var lastValue = "";

function onInput(e) {
 var currentValue = e.target.value;

 if (!currentValue.match(regex))
  e.target.value = lastValue;
 else
  lastValue = currentValue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" oninput="onInput(event)"></code>```

Body:
I have an input field in which I want first 4 characters to be numbers only, after that only dot(.) is allowed, and then only 2 numbers allowed. Example: 9999.99

I also want that if I am entering something else it should not enter in input field.

For this I created a regex as : ^[0-9]{4}+\.+[0-9]{2}+$

HTML: <input type="text" (keypress)="onKeydown($event)">

TS:

regex = '/^[0-9]{4}+\.+[0-9]{2}+$/';

  onKeydown(event) {
    if(event.target.value.match(this.regex)) {
      return true;
    } else return false;
  }

But I guess I am doing something quite wrong here. Kindly let me know about it.

Thanks.

Body:
You don't need + (select 1 or more matches) in your regex.

Instead, you need | (or) to catch two cases: when input does not contain dot and when dot is added.

Try something like this: /^(?:\d{0,4}|\d{4}\.\d{0,2})$/.

I've added ?: (non-capturing group mark) to exclude group in match, but it's not necessary.

UPDATE: here's a quick sketch using oninput event handler:

var regex = /^(?:\d{0,4}|\d{4}\.\d{0,2})$/;
var lastValue = "";

function onInput(e) {
 var currentValue = e.target.value;

 if (!currentValue.match(regex))
  e.target.value = lastValue;
 else
  lastValue = currentValue;
}

<input type="text" oninput="onInput(event)">


问:
Selected data will trigger the image
what i want to do is to when i select "studio unit" the image of the studio unit will display only the studio unit ...
 the problem is when i select the studio unit  the image still shows the 3 image  it should show the studio unit iamge...

enter image description here

here is my code.
.html

```<code><div style="margin-top: -10px"  *ngFor="let house of house_designs; let i - index">
      <div>
    <img src="{{url_asset}}{{house.photo_name}}">
  </div>
  </div>
  <button ion-button full (click)="design()">{{ switchbtn }}</button>
</ion-card>

<form [formGroup]="registerForm"(ngSubmit)="onSubmit()">
<ion-card>
  <ion-item no-lines>
      <ion-label color="primary">House Design:</ion-label>
      <ion-select
        formControlName="house_design_id"
        placeholder="Select house design"
         [(ngModel)]="qa_form.house_designs_id">
        <ion-option
          value="{{house.id}}"
          *ngFor="let house of house_designs; let i - index"
           name="house_design_id"
           >{{house.description}}</ion-option>

      </ion-select>
  </ion-item>
</ion-card>
</code>```

Can someone help me tnx...

答:
I have created a working example for you.
Check the StackBlitz you had created. I have made changes there for you to understand it.

https://angular-c7x7gc.stackblitz.io

First the .ts file:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
 url:any;
 house_designs:any=[];

  ngOnInit(){
    this.house_designs =

   [
    {
      "id": 1,
      "name": "Studio",
      "url": "https://images.unsplash.com/photo-1502759683299-cdcd6974244f?auto=format&fit=crop&w=440&h=220&q=60",

    },
    {
      "id": 2,
      "name": "1 BHK",
      "url": "https://cdn.pixabay.com/photo/2015/03/26/09/47/sky-690293__340.jpg",
    }
  ]

this.url = this.house_designs[0].url;
  } //ngOnInit

  onSelectChange(selectedValue: any)
  {
    this.url = selectedValue;
  }
}
</code>```

Now html file:

```<code><div>
<img src="{{url}}">
</div>

<select (change)="onSelectChange($event.target.value)" >
  <option [value]="data.url" *ngFor="let data of house_designs">{{data.name}}</option>
</select>
</code>```

Try changing the dropdown and you'll be able to see that image changes with the value.

Title: Selected data will trigger the image

Body:
what i want to do is to when i select "studio unit" the image of the studio unit will display only the studio unit ...
 the problem is when i select the studio unit  the image still shows the 3 image  it should show the studio unit iamge...

enter image description here

here is my code.
.html

  <button ion-button full (click)="design()">{{ switchbtn }}</button>
</ion-card>

<form [formGroup]="registerForm"(ngSubmit)="onSubmit()">
<ion-card>
  <ion-item no-lines>
      <ion-label color="primary">House Design:</ion-label>
      <ion-select
        formControlName="house_design_id"
        placeholder="Select house design"
         [(ngModel)]="qa_form.house_designs_id">
        <ion-option
          value="{{house.id}}"
          *ngFor="let house of house_designs; let i - index"
           name="house_design_id"
           >{{house.description}}</ion-option>

      </ion-select>
  </ion-item>
</ion-card>

Can someone help me tnx...

Body:
I have created a working example for you.
Check the StackBlitz you had created. I have made changes there for you to understand it.

https://angular-c7x7gc.stackblitz.io

First the .ts file:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
 url:any;
 house_designs:any=[];

  ngOnInit(){
    this.house_designs =

   [
    {
      "id": 1,
      "name": "Studio",
      "url": "https://images.unsplash.com/photo-1502759683299-cdcd6974244f?auto=format&fit=crop&w=440&h=220&q=60",

    },
    {
      "id": 2,
      "name": "1 BHK",
      "url": "https://cdn.pixabay.com/photo/2015/03/26/09/47/sky-690293__340.jpg",
    }
  ]

this.url = this.house_designs[0].url;
  } //ngOnInit

  onSelectChange(selectedValue: any)
  {
    this.url = selectedValue;
  }
}

Now html file:

<div>
<img src="{{url}}">
</div>

<select (change)="onSelectChange($event.target.value)" >
  <option [value]="data.url" *ngFor="let data of house_designs">{{data.name}}</option>
</select>

Try changing the dropdown and you'll be able to see that image changes with the value.


问:
How to make the link inside Button change color on hover without hovering over link
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

```<code>btn:hover{
color: black;
}
</code>```

This does not work.

```<code>a:hover{
color:black
}
</code>```

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

答:
Probably you didn't add padding to the  tag. it need to add padding or width to define a area to hover over. if you add padding in parent
, therefore you need to hover over the
 to change the color of the  tag.

.nav{overflow:hidden}
.nav ul{list-style:none; text-align:center;}
.nav ul li{display:inline-block; vertical-align:top}
.nav ul li a{display:block; padding:10px 20px; background-color: silver; color: black}
.nav ul li a:hover{background-color: darkgrey; color: white}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
  <ul>
    <li>Link</li>
    <li>Link</li>
    <li>Link</li>
    <li>Link</li>
  </ul>
</div></code>```

Body:
My link changes color on hovering over it directly but does not change color when I hover over the button and not the link directly

btn:hover{
color: black;
}

This does not work.

a:hover{
color:black
}

This is working currently but does not do the job as needed.

How do I make the button change the color of the link when I hover over it?
As seen in the first image.

Body:
Probably you didn't add padding to the <a> tag. it need to add padding or width to define a area to hover over. if you add padding in parent <li>, therefore you need to hover over the <li> to change the color of the <a> tag.

.nav{overflow:hidden}
.nav ul{list-style:none; text-align:center;}
.nav ul li{display:inline-block; vertical-align:top}
.nav ul li a{display:block; padding:10px 20px; background-color: silver; color: black}
.nav ul li a:hover{background-color: darkgrey; color: white}

<div class="nav">
  <ul>
    <li><a href="#!">Link</a></li>
    <li><a href="#!">Link</a></li>
    <li><a href="#!">Link</a></li>
    <li><a href="#!">Link</a></li>
  </ul>
</div>


问:
How can I pass "type" attribute within  in struts1
When I try to write something like this:  in the struts1 it gives me an error

Attribute type invalid for tag text according to TLD

How can I add "type" attribute to  tag?

答:
Thanks to Milebza for the answer, but for me only this way has worked.

```<code><input type="number" name="budgetValue" value="${applicantForm.budgetValue}" />
</code>```

Title: How can I pass "type" attribute within <html:text> in struts1

Body:
Thanks to Milebza for the answer, but for me only this way has worked.

<input type="number" name="budgetValue" value="${applicantForm.budgetValue}" />