问:
how to fix passing variable from view to html
i have a problem passing variable 'res' from view to index.html, it's return the last result in the html page

view file:

def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]

    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            res = "connected"
        else:
            res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
        'res': res
    }

    return render (request, 'posts/index.html', context)
```

<p>html file:</p>

<pre class="lang-html prettyprint-override"><code>      <table>
        <tbody>
            {% for SiteUrls in urlpost %}
          <tr>
            <td>{{SiteUrls.site_title}}</td>
            <td>{{SiteUrls.site_url}}</td>

            <td> {{res}} </td>

            <td>open Site</td>
          </tr>
            {% endfor %}
        </tbody>
      </table>
</code>```

i would like to get back the specific result for each line

答: If the objects in urlpost and res are in the same order, you can use python's zip function and merge them together as tuples, then iterate through this tuple list in your template.

Body:
i have a problem passing variable 'res' from view to index.html, it's return the last result in the html page

view file:

def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]

    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            res = "connected"
        else:
            res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
        'res': res
    }

    return render (request, 'posts/index.html', context)

html file:

            {% for SiteUrls in urlpost %}

            {{SiteUrls.site_title}}
            {{SiteUrls.site_url}}

             {{res}}

            open Site

            {% endfor %}

i would like to get back the specific result for each line


来源: stackexchange

问:
How do I concatenate Strings in Kotlin?
Obviously there are multiple ways to concatenate Strings in Kotlin:

processString(pojo.name + " " + pojo.value)

processString("${pojo.name} ${pojo.value}")

processString(pojo.name.plus(" ").plus(pojo.value))

Of course also with StringBuilder, concat()-Method etc.
Those will work.

But my question is, why is Android Studio proposing "convert concatenation to template" and converts 1. to 2. ? Are there any speed advantages with 2.? So wahts the advantage using 2.?

答: That's because the 1. approach comes from java. Of course the compiler knows what's happening but the suggestion is to use it in Kotlin like the 2. point is stated. Using the 2. approach is better because you might get confused with the + (plus()) operator that is used to sum up numbers.

ContentLicense: CC BY-SA 4.0

Title: How do I concatenate Strings in Kotlin?


答:
You could do it like this:

```<code>a = np.ones((3, 3, 3)) # your original array
b = a.reshape((-1,3)) # array of just rows from 3rd dim
temp = np.random.random(b.shape[0]) # get random value from 0 to 1 for each row from b
prob = 0.4 # up to you - probability of making a row all zeros
mask = temp<prob
b[mask]=0
result = b.reshape(a.shape) # getting back to original shape
</code>```

Example output:

```<code>[[[0. 0. 0.]
  [1. 1. 1.]
  [1. 1. 1.]]

 [[1. 1. 1.]
  [1. 1. 1.]
  [0. 0. 0.]]

 [[0. 0. 0.]
  [1. 1. 1.]
  [0. 0. 0.]]]
</code>```

Title: Replace NumPy array elements with other element

Body:
Suppose I have a randomly generated 3d array srouceArray:

ex: np.random.rand(3, 3, 3)

array([[[0.61961383, 0.26927599, 0.03847151],
        [0.03497162, 0.77748313, 0.15807293],
        [0.15108821, 0.36729448, 0.19007034]],

      [[0.67734758, 0.88312758, 0.97610746],
       [0.5643174 , 0.20660141, 0.58836553],
       [0.59084109, 0.77019768, 0.35961768]],

      [[0.19352397, 0.47284641, 0.97912889],
       [0.48519117, 0.37189048, 0.37113941],
       [0.94934848, 0.92755083, 0.52662299]]])

I would like to randomly replace all 3rd dimennsion elements to zeroes.

Expected array:

array([[[0, 0, 0],
        [0.03497162, 0.77748313, 0.15807293],
        [0.15108821, 0.36729448, 0.19007034]],

      [[0.67734758, 0.88312758, 0.97610746],
       [0 , 0, 0],
       [0.59084109, 0.77019768, 0.35961768]],

      [[0, 0, 0],
       [0, 0, 0],
       [0.94934848, 0.92755083, 0.52662299]]])

I was thinking about generating "mask"? using random

np.random.choice([True, False], sourceArray.shape, p=[...])

and somehow transforming it to 3d array where False=[0, 0, 0] and True=[1, 1, 1] and multiplying with source...

But I do not know how to achieve that transformation. And I bet there is a simpler way I do not know about.

Body:
You could do it like this:

a = np.ones((3, 3, 3)) # your original array
b = a.reshape((-1,3)) # array of just rows from 3rd dim
temp = np.random.random(b.shape[0]) # get random value from 0 to 1 for each row from b
prob = 0.4 # up to you - probability of making a row all zeros
mask = temp<prob
b[mask]=0
result = b.reshape(a.shape) # getting back to original shape

Example output:

[[[0. 0. 0.]
  [1. 1. 1.]
  [1. 1. 1.]]

 [[1. 1. 1.]
  [1. 1. 1.]
  [0. 0. 0.]]

 [[0. 0. 0.]
  [1. 1. 1.]
  [0. 0. 0.]]]


问:
Create a generic serializer with a dynamic model in Meta
when i create a Serializer in django-rest0-framework, based on a ModelSerializer, i will have to pass the model in the Meta class:

```<code>class ClientSerializer(ModelSerializer):
    class Meta:
        model = Client
</code>```

I want to create a general serializer which, based on the URL, includes the model dynamically.

My setup thusfar includes the urls.py and the viewset:

urls.py:

```<code> url(r'^api/v1/general/(?P<model>\w+)', kernel_api_views.GeneralViewSet.as_view({'get':'list'}))
</code>```

and views.py:

```<code>class GeneralViewSet(viewsets.ModelViewSet):

     def get_queryset(self):
            # Dynamically get the model class from myapp.models
            queryset = getattr(myapp.models, model).objects.all()
            return queryset

     def get_serializer_class(self):
         return getattr(myapp.serializers, self.kwargs['model']+'Serializer')
</code>```

Which in case of: http://127.0.0.1:8000/api/v1/general/Client gets Client.objects.all() as queryset and the ClientSerializer class as serializer

Question: How can i make it so that i can call 'GeneralSerializer' and dynamically assign the model in it?

答:
My solution:

Create general serializer with or without model, send model name in url

plugin: django-geojson==2.12.0
django: 2.0.6
python: 3.6.7

api.py

```<code>from djgeojson.serializers import Serializer as GeoJSONSerializer
from django.http import HttpResponse
from django.db import connection

def to_geojson(request):
        model = request.GET['model']
        print(model)
        lista = []
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM %s" % (model))
            # to dict
            lista = dictfetchall(cursor)
            # Serialize
            geo_lista = GeoJSONSerializer().serialize(lista)
        return HttpResponse(geo_lista)

    def dictfetchall(cursor):
        "Return all rows from a cursor as a dict"
        columns = [col[0] for col in cursor.description]
        return [
            dict(zip(columns, row))
            for row in cursor.fetchall()
        ]
</code>```

urls.py

```<code>url(r'^api/geo/', to_geojson, name='to_geojson')
</code>```

my urls to call API:
with model in models.py

```<code>http://127.0.0.1:8000/data/api/geo/?model=data_pointcloud
</code>```

without model in models.py

```<code>http://127.0.0.1:8000/data/api/geo/?model="schema".table_name
</code>```

Body:
when i create a Serializer in django-rest0-framework, based on a ModelSerializer, i will have to pass the model in the Meta class:

class ClientSerializer(ModelSerializer):
    class Meta:
        model = Client

I want to create a general serializer which, based on the URL, includes the model dynamically.

My setup thusfar includes the urls.py and the viewset:

urls.py:

 url(r'^api/v1/general/(?P<model>\w+)', kernel_api_views.GeneralViewSet.as_view({'get':'list'}))

and views.py:

class GeneralViewSet(viewsets.ModelViewSet):

     def get_queryset(self):
            # Dynamically get the model class from myapp.models
            queryset = getattr(myapp.models, model).objects.all()
            return queryset

     def get_serializer_class(self):
         return getattr(myapp.serializers, self.kwargs['model']+'Serializer')

Which in case of: http://127.0.0.1:8000/api/v1/general/Client gets Client.objects.all() as queryset and the ClientSerializer class as serializer

Question: How can i make it so that i can call 'GeneralSerializer' and dynamically assign the model in it?

Body:
My solution:

Create general serializer with or without model, send model name in url

plugin: django-geojson==2.12.0
django: 2.0.6
python: 3.6.7

api.py

from djgeojson.serializers import Serializer as GeoJSONSerializer
from django.http import HttpResponse
from django.db import connection

def to_geojson(request):
        model = request.GET['model']
        print(model)
        lista = []
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM %s" % (model))
            # to dict
            lista = dictfetchall(cursor)
            # Serialize
            geo_lista = GeoJSONSerializer().serialize(lista)
        return HttpResponse(geo_lista)

    def dictfetchall(cursor):
        "Return all rows from a cursor as a dict"
        columns = [col[0] for col in cursor.description]
        return [
            dict(zip(columns, row))
            for row in cursor.fetchall()
        ]

urls.py

url(r'^api/geo/', to_geojson, name='to_geojson')

my urls to call API:
with model in models.py

http://127.0.0.1:8000/data/api/geo/?model=data_pointcloud

without model in models.py

http://127.0.0.1:8000/data/api/geo/?model="schema".table_name


问:
Why my time count of a system call in linux is almost 0 us?
Nowadays, I'm working on a system kernel practice course. However, when I compare a system call with an user call, it's strange that the system call return a time count of 0 us (sometimes return 1). But I pass count=1e8 which is a quite big number.

I'm doubt that the computations didn't happen because the result is not used. Then I change add as result = result + 1 and print the final result. However, the result is right and the time count just from 0 or 1 change to 2-6.

long yanpan_oper(int* result,int num1,int num2,char* op)
{
    if(op)
    {
        if(*op == '+')
        {
            *result = num1 + num2;
        }
        else if(*op == '-')
        {
            *result = num1 - num2;
        }
        else if(*op == '*')
        {
            *result = num1*num2;
        }
        else if(*op == '\\')
        {
            if(num2!=0)
                *result = num1/num2;
            else
                printk("divided number can't be zero!\n");
        }else
            printk("unrecongized operator %c\n", *op);
    }else
    {
        printk("operation is empty.\n");
    }
    return 0;
}
SYSCALL_DEFINE1(yanpan_func, int, count)
{
    printk("The count is %d.\n", count);
    struct timeval tstart, tend;
    do_gettimeofday(&tstart);
    int i;
    for(i=0;i<count;i++) // +
    {
        int result;
        char op_add = '+';
        yanpan_oper(&result, i, 10, &op_add);
    }
    for(i=0;i<count;i++) // -
    {
        int result;
        char op_sub = '-';
        yanpan_oper(&result, i, 10, &op_sub);
    }
    for(i=0;i<count;i++) // *
    {
        int result;
        char op_mul = '*';
        yanpan_oper(&result, i, 2, &op_mul);
    }
    for(i=0;i<count;i++) // '//'
    {
        int result;
        char op_div = '\\';
        yanpan_oper(&result, i, 10, &op_div);
    }
    do_gettimeofday(&tend);
    long delta_time = 1000000*(tend.tv_sec - tstart.tv_sec) + (tend.tv_usec - tstart.tv_usec);
    printk("The start time is %ld.\n", tstart.tv_sec*1000000+tstart.tv_usec);
    printk("The end time is %ld.\n", tend.tv_sec*1000000+tend.tv_usec);
    printk("Syscall time use:%ld usec", delta_time);
    return delta_time;
}
```

I have tried many times, but the result didn't change. The user call computation of the same amount takes around 1300 ms, can computations occur in kernel be fast like this?

答:
Let's look at one loop:

```<code>for(i=0;i<count;i++) // +
{
    int result;
    char op_add = '+';
    yanpan_oper(&result, i, 10, &op_add);
}
</code>```

This will call the function yanpan_oper count times. But each time it will overwrite the previous result stored in result without using that value for the computation. Chances are that the compiler just optimized the whole loop away, replacing it with just one single call to yanpan_oper since the for loop is actually equivalent to just executing the loop body once.

Furthermore, the loop body ONLY affects variables inside the loop body, so not only can the compiler decide to just keep the last iteration. It can skip basically the whole code, so that what you're actually executing is this:

```<code>SYSCALL_DEFINE1(yanpan_func, int, count)
{
    printk("The count is %d.\n", count);
    struct timeval tstart, tend;
    do_gettimeofday(&tstart);
    do_gettimeofday(&tend);
    long delta_time = 1000000*(tend.tv_sec - tstart.tv_sec) + (tend.tv_usec - tstart.tv_usec);
    printk("The start time is %ld.\n", tstart.tv_sec*1000000+tstart.tv_usec);
    printk("The end time is %ld.\n", tend.tv_sec*1000000+tend.tv_usec);
    printk("Syscall time use:%ld usec", delta_time);
    return delta_time;
}
</code>```

Here are some tips for how to fool the optimizer:

```<code>// Create input that cannot be calculated at compile time
int input1[count];
int input2[count];
srand(time(NULL));
for(int i=0; i<count; i++) {
    input1[i] = rand()%1000;
    input2[i] = rand()%1000;
}

// Store the output, so that the optimizer cannot take away the loop
int output[count];

// Start timer
for(i=0;i<count;i++) // +
{
    char op_add = '+';
    yanpan_oper(&output[i], input1[i], input2[i], &op_add);
}
// End timer

// Use the output to that the optimizer cannot remove the array, and thus
// also the loop
for(int i=0; i<count; i++)
    printf("%d ", output[i]);
</code>```

Do note that those arrays may be to big for the stack. If that's the case, use this instead:

```<code>int *input1 = malloc(count * sizeof(*input1));
int *input2 = malloc(count * sizeof(*input2));
srand(time(NULL));
for(int i=0; i<count; i++) {
    input1[i] = rand()%1000;
    input2[i] = rand()%1000;
}

int *output = malloc(count * sizeof(*output));
</code>```

(Remember to check if malloc succeeded and to free the memory afterwards)

Body:
Nowadays, I'm working on a system kernel practice course. However, when I compare a system call with an user call, it's strange that the system call return a time count of 0 us (sometimes return 1). But I pass count=1e8 which is a quite big number.

I'm doubt that the computations didn't happen because the result is not used. Then I change add as result = result + 1 and print the final result. However, the result is right and the time count just from 0 or 1 change to 2-6.

long yanpan_oper(int* result,int num1,int num2,char* op)
{
    if(op)
    {
        if(*op == '+')
        {
            *result = num1 + num2;
        }
        else if(*op == '-')
        {
            *result = num1 - num2;
        }
        else if(*op == '*')
        {
            *result = num1*num2;
        }
        else if(*op == '\\')
        {
            if(num2!=0)
                *result = num1/num2;
            else
                printk("divided number can't be zero!\n");
        }else
            printk("unrecongized operator %c\n", *op);
    }else
    {
        printk("operation is empty.\n");
    }
    return 0;
}
SYSCALL_DEFINE1(yanpan_func, int, count)
{
    printk("The count is %d.\n", count);
    struct timeval tstart, tend;
    do_gettimeofday(&tstart);
    int i;
    for(i=0;i<count;i++) // +
    {
        int result;
        char op_add = '+';
        yanpan_oper(&result, i, 10, &op_add);
    }
    for(i=0;i<count;i++) // -
    {
        int result;
        char op_sub = '-';
        yanpan_oper(&result, i, 10, &op_sub);
    }
    for(i=0;i<count;i++) // *
    {
        int result;
        char op_mul = '*';
        yanpan_oper(&result, i, 2, &op_mul);
    }
    for(i=0;i<count;i++) // '//'
    {
        int result;
        char op_div = '\\';
        yanpan_oper(&result, i, 10, &op_div);
    }
    do_gettimeofday(&tend);
    long delta_time = 1000000*(tend.tv_sec - tstart.tv_sec) + (tend.tv_usec - tstart.tv_usec);
    printk("The start time is %ld.\n", tstart.tv_sec*1000000+tstart.tv_usec);
    printk("The end time is %ld.\n", tend.tv_sec*1000000+tend.tv_usec);
    printk("Syscall time use:%ld usec", delta_time);
    return delta_time;
}

I have tried many times, but the result didn't change. The user call computation of the same amount takes around 1300 ms, can computations occur in kernel be fast like this?

Body:
Let's look at one loop:

for(i=0;i<count;i++) // +
{
    int result;
    char op_add = '+';
    yanpan_oper(&result, i, 10, &op_add);
}

This will call the function yanpan_oper count times. But each time it will overwrite the previous result stored in result without using that value for the computation. Chances are that the compiler just optimized the whole loop away, replacing it with just one single call to yanpan_oper since the for loop is actually equivalent to just executing the loop body once.

Furthermore, the loop body ONLY affects variables inside the loop body, so not only can the compiler decide to just keep the last iteration. It can skip basically the whole code, so that what you're actually executing is this:

SYSCALL_DEFINE1(yanpan_func, int, count)
{
    printk("The count is %d.\n", count);
    struct timeval tstart, tend;
    do_gettimeofday(&tstart);
    do_gettimeofday(&tend);
    long delta_time = 1000000*(tend.tv_sec - tstart.tv_sec) + (tend.tv_usec - tstart.tv_usec);
    printk("The start time is %ld.\n", tstart.tv_sec*1000000+tstart.tv_usec);
    printk("The end time is %ld.\n", tend.tv_sec*1000000+tend.tv_usec);
    printk("Syscall time use:%ld usec", delta_time);
    return delta_time;
}

Here are some tips for how to fool the optimizer:

// Create input that cannot be calculated at compile time
int input1[count];
int input2[count];
srand(time(NULL));
for(int i=0; i<count; i++) {
    input1[i] = rand()%1000;
    input2[i] = rand()%1000;
}

// Store the output, so that the optimizer cannot take away the loop
int output[count];

// Start timer
for(i=0;i<count;i++) // +
{
    char op_add = '+';
    yanpan_oper(&output[i], input1[i], input2[i], &op_add);
}
// End timer

// Use the output to that the optimizer cannot remove the array, and thus
// also the loop
for(int i=0; i<count; i++)
    printf("%d ", output[i]);

Do note that those arrays may be to big for the stack. If that's the case, use this instead:

int *input1 = malloc(count * sizeof(*input1));
int *input2 = malloc(count * sizeof(*input2));
srand(time(NULL));
for(int i=0; i<count; i++) {
    input1[i] = rand()%1000;
    input2[i] = rand()%1000;
}

int *output = malloc(count * sizeof(*output));

(Remember to check if malloc succeeded and to free the memory afterwards)


问:
How to add commons-math library in Android Studio
I am trying to import common-math library to my Android Studio project. I placed the file  commons-math3-3.6.1.jar file in libs folder and in the gradle file I have this line:

```<code>compile 'commons-math3-3.6.1.jar'
</code>```

But I get this error: `

Error:(32, 0) Supplied String module notation
  'commons-math3-3.6.1.jar' is invalid. Example notations:
  'org.gradle:gradle-core:2.2',
  'org.mockito:mockito-core:1.9.5:javadoc'.

Can anyone tell me what I have to do?

答:
in Android view open Gradle Scripts - build.gradle and add this to dependencies:

```<code>implementation 'org.apache.commons:commons-math3:3.6.1'
</code>```

You can also check their websites if newer version isn't available list of latest versions

ContentLicense: CC BY-SA 3.0

Body:
I am trying to import common-math library to my Android Studio project. I placed the file  commons-math3-3.6.1.jar file in libs folder and in the gradle file I have this line:

compile 'commons-math3-3.6.1.jar'

But I get this error: `

Error:(32, 0) Supplied String module notation
  'commons-math3-3.6.1.jar' is invalid. Example notations:
  'org.gradle:gradle-core:2.2',
  'org.mockito:mockito-core:1.9.5:javadoc'.

Can anyone tell me what I have to do?

Body:
in Android view open Gradle Scripts - build.gradle and add this to dependencies:

implementation 'org.apache.commons:commons-math3:3.6.1'

You can also check their websites if newer version isn't available list of latest versions


问:
ASP.net page without a code behind
I have an ASP.Net page with a C# code behind.

However, I've been asked to not use a code behind - so that it will be easier to deploy in SharePoint.

Is there a way to include the C# code in the ASP.Net page, without using a separate code behind file?

答:
You can actually have all the code in the aspx page.  As explained here.

Sample from here:

```<code><%@ Language=C# %>
<HTML>
   <script runat="server" language="C#">
   void MyButton_OnClick(Object sender, EventArgs e)
   {
      MyLabel.Text = MyTextbox.Text.ToString();
   }
   </script>
   <body>
      <form id="MyForm" runat="server">
         <asp:textbox id="MyTextbox" text="Hello World" runat="server"></asp:textbox>
         <asp:button id="MyButton" text="Echo Input" OnClick="MyButton_OnClick" runat="server"></asp:button>
         <asp:label id="MyLabel" runat="server"></asp:label>
      </form>
   </body>
</HTML>
</code>```

OwnerDisplayName: Sophia

ContentLicense: CC BY-SA 2.5

Title: ASP.net page without a code behind

Body:
You can actually have all the code in the aspx page.  As explained here.

Sample from here:

<%@ Language=C# %>
<HTML>
   <script runat="server" language="C#">
   void MyButton_OnClick(Object sender, EventArgs e)
   {
      MyLabel.Text = MyTextbox.Text.ToString();
   }
   </script>
   <body>
      <form id="MyForm" runat="server">
         <asp:textbox id="MyTextbox" text="Hello World" runat="server"></asp:textbox>
         <asp:button id="MyButton" text="Echo Input" OnClick="MyButton_OnClick" runat="server"></asp:button>
         <asp:label id="MyLabel" runat="server"></asp:label>
      </form>
   </body>
</HTML>


问:
How to fix a datepicker in python with Selenium
I'm trying to make an Auto-Reg bot with python and selenium. I'm getting the most things to work, as they aren't that hard. But atm i'm stuck at a datepicker. The code is able to open the date-box but it doesn't select a date. Another problem is, you cant write anything in the date box, you HAVE to select a date in the date box.

I tried various methods i found on stackoverflow but nothing works for this site.

Site: https://mobilepanel2.nielsen.com/enrol/home?l=de_de&pid=9

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
b = webdriver.Chrome(r'''C:\Users\Florian\PycharmProjects\Auto_Reg\chromedriver''')
b.get('https://mobilepanel2.nielsen.com/enrol/home?l=de_de&pid=9')
b.find_element_by_xpath("//select[@id='platform']/option[contains(text(),'Android')]").click()
b.find_element_by_xpath("//select[@id='deviceType']/option[contains(text(),'Smartphone')]").click()
b.find_element_by_xpath("//label[contains(text(),'Männlich')]").click()
## until here, everything works fine

select = Select(b.find_element_by_name('birthDate'))
select.select_by_visible_text("13")
</code>```

答:
Here you go:</p>

```<code># click calendar to appear
browser.find_element_by_id('birthDateCalendar').click()

# get calendar elements
calendar = browser.find_elements_by_xpath('//*[@id="ui-datepicker-div"]/table/tbody/tr/td')

# click selected day
selection = '15'
for item in calendar:
    day = item.get_attribute("innerText")
    if day == selection:
        item.click()
</code>```

Body:
I'm trying to make an Auto-Reg bot with python and selenium. I'm getting the most things to work, as they aren't that hard. But atm i'm stuck at a datepicker. The code is able to open the date-box but it doesn't select a date. Another problem is, you cant write anything in the date box, you HAVE to select a date in the date box.

I tried various methods i found on stackoverflow but nothing works for this site.

Site: https://mobilepanel2.nielsen.com/enrol/home?l=de_de&pid=9

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
b = webdriver.Chrome(r'''C:\Users\Florian\PycharmProjects\Auto_Reg\chromedriver''')
b.get('https://mobilepanel2.nielsen.com/enrol/home?l=de_de&pid=9')
b.find_element_by_xpath("//select[@id='platform']/option[contains(text(),'Android')]").click()
b.find_element_by_xpath("//select[@id='deviceType']/option[contains(text(),'Smartphone')]").click()
b.find_element_by_xpath("//label[contains(text(),'Männlich')]").click()
## until here, everything works fine

select = Select(b.find_element_by_name('birthDate'))
select.select_by_visible_text("13")

Body:
Here you go:

# click calendar to appear
browser.find_element_by_id('birthDateCalendar').click()

# get calendar elements
calendar = browser.find_elements_by_xpath('//*[@id="ui-datepicker-div"]/table/tbody/tr/td')

# click selected day
selection = '15'
for item in calendar:
    day = item.get_attribute("innerText")
    if day == selection:
        item.click()


问:
Buefy Timepicker watching on change
Good morning.
I have a problem with the buefy timepicker.
It works if I use the "clear" or "Now" buttons but not on selecting time. This seems to have started with a recent buefy update.

https://codepen.io/anon/pen/JqBKGE?&editable=true&editors=101

```<code><div id="app" class="container">
    <textarea style="width: 100%;" readonly>{{ time }}</textarea>

    <b-field label="Select time">
        <b-timepicker v-model="time"
                      inline
                      placeholder="Click to select...">

            <button class="button is-primary"
                    @click="time = new Date()">
                <b-icon icon="clock"></b-icon>
                <span>Now</span>
            </button>

            <button class="button is-danger"
                    @click="time = null">
                <b-icon icon="close"></b-icon>
                <span>Clear</span>
            </button>
        </b-timepicker>
    </b-field>

</div>
</code>```

JS

```<code>const example = {
    data() {
        return {
            time: new Date()
        }
    },
    watch: {
        time: {
            handler: function() {
                console.log(this.time);
            }
        }
    }
}

const app = new Vue(example)

app.$mount('#app')
</code>```

Any suggestions?

答:
Seems to be an issue with the buefy Timepicker
https://github.com/buefy/buefy/issues/1418

Edit: This was fixed with Buefy release 0.7.7

Title: Buefy Timepicker watching on change

Body:
Good morning.
I have a problem with the buefy timepicker.
It works if I use the "clear" or "Now" buttons but not on selecting time. This seems to have started with a recent buefy update.

https://codepen.io/anon/pen/JqBKGE?&editable=true&editors=101

    <textarea style="width: 100%;" readonly>{{ time }}</textarea>

            <button class="button is-primary"
                    @click="time = new Date()">

                Now
            </button>

            <button class="button is-danger"
                    @click="time = null">

                Clear
            </button>

JS

const example = {
    data() {
        return {
            time: new Date()
        }
    },
    watch: {
        time: {
            handler: function() {
                console.log(this.time);
            }
        }
    }
}

const app = new Vue(example)

app.$mount('#app')

Any suggestions?


问:
Using Highmaps for Angular after the component is initialized
I'm using Highmaps with the official Angular wrapper. If I initialize the map in ngOnInit, it works fine (chartMap is set as [options] in the highcharts-chart directive):

```<code>ngOnInit(){
    this.chartMap = {
        chart: {
          map: mapUS
        },
    ........
    ........
}
</code>```

The problem is that I don't know at the time the component starts what map I'm going to show. If I try to set it later (for example when a user clicks a button) and I don't set it in ngOnInit, I get an error when the component starts:

```<code>ERROR TypeError: Cannot read property 'series' of undefined
</code>```

Is it mandatory to create the map when the component starts? Is there a way to set it later?

答: I ended up using Highcharts in Angular without the wrapper</p>

Body:
I'm using Highmaps with the official Angular wrapper. If I initialize the map in ngOnInit, it works fine (chartMap is set as [options] in the highcharts-chart directive):

ngOnInit(){
    this.chartMap = {
        chart: {
          map: mapUS
        },
    ........
    ........
}

The problem is that I don't know at the time the component starts what map I'm going to show. If I try to set it later (for example when a user clicks a button) and I don't set it in ngOnInit, I get an error when the component starts:

ERROR TypeError: Cannot read property 'series' of undefined

Is it mandatory to create the map when the component starts? Is there a way to set it later?


问:
How to implement a drop-down button inside a table header in Ext.js
For a month I have started working with Ext.Js 4, creating all kind of widgets. Right now I am tying to implement a drop-down option for a column header.

That can be based on something like this ColorPicker
https://docs.sencha.com/extjs/4.2.1/#!/api/Ext.menu.ColorPicker

My code creates a Grid Panel like in this img

```<code>Ext.apply(me, {
    items : [{
        xtype : 'gridpanel',
        itemId : 'gridpanelId',
        margin : '0 0 0 0',
        layout : 'fit',
        viewConfig : {
            emptyText : '',
            deferEmptyText : false,
            markDirty : false
        },
            ftype : 'filters'
    }],
    store : errorstore,
    plugins : [Ext.create('Ext.grid.plugin.CellEditing', {
    pluginId : 'celledit',
    clicksToEdit : 1
    })],
    tbar : [{
        xtype : 'ixbutton',
        itemId : 'tbarswitcha',
        text : '',
        bgCls : 'but-image-base tbar_error_quit',
        height : 60,
        width : 90,
        margin : '0 10 0 10'
    }],
    columns : [{
        header : 'Startdate',
        itemId : 'ColumnStartdate',
        dataIndex : 'startdate',
        flex : 2,
        sortable : true,
        renderer : function(value) {
            return MyApp.app.formatDate(value);
                }
        },{
        header : 'Source',
        itemId : 'ColumnSource',
        dataIndex : 'source',
        flex : 3,
        sortable : false
        }
    ],
    bbar : {
        xtype : 'ixpagingtoolbar',
        itemId : 'ixpt',
        margin : '5 10 5 10',
        numbButtons : 4,
        width : 400
        }
    }]
});
</code>```

I am trying to build a possibility for the user to choose a specific type of 'Source'. Something like a filter, where the user has pre-defined options from which to choose, and not to type in.

How should I define a drop-down inside this

```<code>columns : {
        header : 'Source'
}
</code>```

答:
Any items you put in a column is placed in the header. Simple example without any styling:</p>

```<code>columns = [
    {
        header: 'Source',
        items: [
            {
                xtype: 'button',
                text: 'Options',
                menu: {
                    items: [
                        {
                            text: 'Item1'
                        },
                        {
                            text: 'Item2'
                        },
                    ]
                }
            }
        ]
    },
]
</code>```

Body:
For a month I have started working with Ext.Js 4, creating all kind of widgets. Right now I am tying to implement a drop-down option for a column header.

That can be based on something like this ColorPicker
https://docs.sencha.com/extjs/4.2.1/#!/api/Ext.menu.ColorPicker

My code creates a Grid Panel like in this img

Ext.apply(me, {
    items : [{
        xtype : 'gridpanel',
        itemId : 'gridpanelId',
        margin : '0 0 0 0',
        layout : 'fit',
        viewConfig : {
            emptyText : '',
            deferEmptyText : false,
            markDirty : false
        },
            ftype : 'filters'
    }],
    store : errorstore,
    plugins : [Ext.create('Ext.grid.plugin.CellEditing', {
    pluginId : 'celledit',
    clicksToEdit : 1
    })],
    tbar : [{
        xtype : 'ixbutton',
        itemId : 'tbarswitcha',
        text : '',
        bgCls : 'but-image-base tbar_error_quit',
        height : 60,
        width : 90,
        margin : '0 10 0 10'
    }],
    columns : [{
        header : 'Startdate',
        itemId : 'ColumnStartdate',
        dataIndex : 'startdate',
        flex : 2,
        sortable : true,
        renderer : function(value) {
            return MyApp.app.formatDate(value);
                }
        },{
        header : 'Source',
        itemId : 'ColumnSource',
        dataIndex : 'source',
        flex : 3,
        sortable : false
        }
    ],
    bbar : {
        xtype : 'ixpagingtoolbar',
        itemId : 'ixpt',
        margin : '5 10 5 10',
        numbButtons : 4,
        width : 400
        }
    }]
});

I am trying to build a possibility for the user to choose a specific type of 'Source'. Something like a filter, where the user has pre-defined options from which to choose, and not to type in.

How should I define a drop-down inside this

columns : {
        header : 'Source'
}

Body:
Any items you put in a column is placed in the header. Simple example without any styling:

columns = [
    {
        header: 'Source',
        items: [
            {
                xtype: 'button',
                text: 'Options',
                menu: {
                    items: [
                        {
                            text: 'Item1'
                        },
                        {
                            text: 'Item2'
                        },
                    ]
                }
            }
        ]
    },
]


问:
Could not find tools.jar in the active JRE - Spring Tools Suite
I know there are multiple topics about that, but none of it is about Spring Tools Suite. And i'm finding informations that this file no longer exists in newer Java versions, which seems to be true, since i cannot find it.
I'm absolutely lost now.</p>

答:
No matter how many times did I change the JRE to JDK, updated paths and system variables, in the end my problem was solved by adding the -vm argument and the absolute path to the JDK to the SpringToolSuite4.ini file. I had the same behavior on Eclipse Photon as well, and it solved the problem there too.

```<code>-vm
C:\Program Files\Java\jdk1.8.0_181\bin\javaw.exe
</code>```

You can read more here on this Eclipse wiki.

Body:
No matter how many times did I change the JRE to JDK, updated paths and system variables, in the end my problem was solved by adding the -vm argument and the absolute path to the JDK to the SpringToolSuite4.ini file. I had the same behavior on Eclipse Photon as well, and it solved the problem there too.

-vm
C:\Program Files\Java\jdk1.8.0_181\bin\javaw.exe

You can read more here on this Eclipse wiki.


问:
How should I use the new static option for @ViewChild in Angular 8?
How should I configure the new Angular 8 view child?

```<code>@ViewChild('searchText', {read: ElementRef, static: false})
public searchTextInput: ElementRef;
</code>```

vs

```<code>@ViewChild('searchText', {read: ElementRef, static: true})
public searchTextInput: ElementRef;
</code>```

Which is better? When should I use static:true vs static:false?

答:
In most cases you will want to use {static: false}. Setting it like this will ensure query matches that are dependent on binding resolution (like structural directives *ngIf, etc...) will be found.

Example of when to use static: false:

```<code>@Component({
  template: `
    <div *ngIf="showMe" #viewMe>Am I here?</div>
    <button (click)="showMe = !showMe"></button>
  `
})
export class ExampleComponent {
  @ViewChild('viewMe', { static: false })
  viewMe?: ElementRef<HTMLElement>;

  showMe = false;
}
</code>```

The static: false is going to be the default fallback behaviour in Angular 9. Read more here and here

The { static: true } option was introduced to support creating embedded views on the fly. When you are creating a view dynamically and want to acces the TemplateRef, you won't be able to do so in ngAfterViewInit as it will cause a ExpressionHasChangedAfterChecked error. Setting the static flag to true will create your view in ngOnInit.

Nevertheless:

In most other cases, the best practice is to use {static: false}.

Be aware though that the { static: false } option will be made default in Angular 9. Which means that setting the static flag is no longer necessary, unless you want to use the static: true option.

You can use the angular cli ng update command to automatically upgrade your current code base.

For a migration guide and even more information about this, you can check here and here

#What is the difference between static and dynamic queries?
The static option for @ViewChild() and @ContentChild() queries determines when the query results become available.

With static queries (static: true), the query resolves once the view has been created, but before change detection runs. The result, though, will never be updated to reflect changes to your view, such as changes to ngIf and ngFor blocks.

With dynamic queries (static: false), the query resolves after either ngAfterViewInit() or ngAfterContentInit() for @ViewChild() and @ContentChild() respectively. The result will be updated for changes to your view, such as changes to ngIf and ngFor blocks.

A nice use-case for using static: true, is if you are using fromEvent to bind to an element defined in the template. Consider the following template:

```<code><div [ngStyle]="thumbStyle$ | async" #thumb></div>
</code>```

You can then handle events on this element without the need of using subscriptions or init hooks (if you don't want to or cannot use angular event binding):

```<code>@Component({})
export class ThumbComponent {
  @ViewChild('thumb', { static: true })
  thumb?: ElementRef<HTMLElement>;

  readonly thumbStyle$ = defer(() => fromEvent(this.thumb, 'pointerdown').pipe(
    switchMap((startEvent) => fromEvent(document, 'pointermove', { passive: true })
    // transform to proper positioning
  ));
}
</code>```

It is important to use defer. This will make sure the observable is only resolved when it's subscribed to. This will happen before the ngAfterViewInit gets triggered, when the async pipe subscribes to it. Because we are using static: true, the this.thumb is already populated.

Body:
How should I configure the new Angular 8 view child?

@ViewChild('searchText', {read: ElementRef, static: false})
public searchTextInput: ElementRef;

vs

@ViewChild('searchText', {read: ElementRef, static: true})
public searchTextInput: ElementRef;

Which is better? When should I use static:true vs static:false?

Body:
In most cases you will want to use {static: false}. Setting it like this will ensure query matches that are dependent on binding resolution (like structural directives *ngIf, etc...) will be found.

Example of when to use static: false:

@Component({
  template: `
    <div *ngIf="showMe" #viewMe>Am I here?</div>
    <button (click)="showMe = !showMe"></button>
  `
})
export class ExampleComponent {
  @ViewChild('viewMe', { static: false })
  viewMe?: ElementRef<HTMLElement>;

  showMe = false;
}

The static: false is going to be the default fallback behaviour in Angular 9. Read more here and here

The { static: true } option was introduced to support creating embedded views on the fly. When you are creating a view dynamically and want to acces the TemplateRef, you won't be able to do so in ngAfterViewInit as it will cause a ExpressionHasChangedAfterChecked error. Setting the static flag to true will create your view in ngOnInit.

Nevertheless:

In most other cases, the best practice is to use {static: false}.

Be aware though that the { static: false } option will be made default in Angular 9. Which means that setting the static flag is no longer necessary, unless you want to use the static: true option.

You can use the angular cli ng update command to automatically upgrade your current code base.

For a migration guide and even more information about this, you can check here and here

#What is the difference between static and dynamic queries?
The static option for @ViewChild() and @ContentChild() queries determines when the query results become available.

With static queries (static: true), the query resolves once the view has been created, but before change detection runs. The result, though, will never be updated to reflect changes to your view, such as changes to ngIf and ngFor blocks.

With dynamic queries (static: false), the query resolves after either ngAfterViewInit() or ngAfterContentInit() for @ViewChild() and @ContentChild() respectively. The result will be updated for changes to your view, such as changes to ngIf and ngFor blocks.

A nice use-case for using static: true, is if you are using fromEvent to bind to an element defined in the template. Consider the following template:

<div [ngStyle]="thumbStyle$ | async" #thumb></div>

You can then handle events on this element without the need of using subscriptions or init hooks (if you don't want to or cannot use angular event binding):

@Component({})
export class ThumbComponent {
  @ViewChild('thumb', { static: true })
  thumb?: ElementRef<HTMLElement>;

  readonly thumbStyle$ = defer(() => fromEvent(this.thumb, 'pointerdown').pipe(
    switchMap((startEvent) => fromEvent(document, 'pointermove', { passive: true })
    // transform to proper positioning
  ));
}

It is important to use defer. This will make sure the observable is only resolved when it's subscribed to. This will happen before the ngAfterViewInit gets triggered, when the async pipe subscribes to it. Because we are using static: true, the this.thumb is already populated.


问:
How to add a null value in the group_concat if the record does not exist?
I have this SQL query with substring_index and group_concat but the results I get does not give the right location of the values because the values does not exist.

I need to add a null or zero value in order to have the right location of the values in the sql result.

In the table there are three lid (1, 2, 3). The lid should be the basis count of the P's (P1, P2, P3) for the substring_index.

This is the table:

```<code>lid   class_id   class          total
-----  -------    -----        -----
  1     73       Leader         10000
  1     77       Consultant     8000
  1     83       Coordinator    6000
  2     73       Leader         20000
  2     76       Staff          8000
  2     77       Consultant     10000
  3     73       Leader         30000
  3     78       Team Leader    8000
</code>```

This is the SQL query I used to group_concat for the totals and substring_index to separate the grouped values with their each column (P1, P2, P3)

```<code>SELECT *, GROUP_CONCAT(lid) as lids, GROUP_CONCAT(pyear) as pyears,
 COUNT(DISTINCT lib_id) AS total_count,
 CASE WHEN COUNT(*)>=1 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',1),' ',-1) END AS P1,
 CASE WHEN COUNT(*)>=2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',2),' ',-1) END AS P2,
 CASE WHEN COUNT(*)>=3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',3),' ',-1) END AS P3
 FROM (
  SELECT * FROM view_items WHERE lid='1'
  UNION
  SELECT * FROM view_items WHERE lid='2'
  UNION
  SELECT * FROM view_items WHERE lid='3'
 ) AS AZ GROUP BY class_id
</code>```

This is the result of the above query:

```<code>class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          2       8000
   77      Consultant     1,2     8000    10000
   78      Team Leader    3       8000
   83      Coordinator    1       6000
</code>```

The lids should always have three count even though the record does not exists, a zero or null value should be added. How to do the adding of null value?

This is the expected result I need.

```<code> class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          0,2,0     0     8000      0
   77      Consultant     1,2,0    8000   10000     0
   78      Team Leader    0,0,3     0       0      8000
   83      Coordinator    1,0,0    6000     0       0
</code>```

答:
I don't think GROUP_CONCAT() is the right approach for what you want.  Try this:

```<code>SELECT vi.class_id, vi.class,
       COUNT(DISTINCT vi.lib_id) AS total_count,
       CONCAT_WS(',',
                 MAX(CASE WHEN vi.lid = 1 THEN 1 ELSE 0 END),
                 MAX(CASE WHEN vi.lid = 2 THEN 1 ELSE 0 END),
                 MAX(CASE WHEN vi.lid = 3 THEN 1 ELSE 0 END)
                ) as lids,
       SUM(CASE WHEN vi.lid = 1 THEN vi.total ELSE 0 END) as total_1,
       SUM(CASE WHEN vi.lid = 2 THEN vi.total ELSE 0 END) as total_2,
       SUM(CASE WHEN vi.lid = 3 THEN vi.total ELSE 0 END) as total_3
FROM view_items vi
WHERE vi.lid IN (1, 2, 3)
GROUP BY vi.class_id;
</code>```

Notes:

Your subquery and UNION are not needed.  In MySQL, these can actually hurt performance.

I assume that lid is a number, so I've removed the single quotes.

You can use conditional aggregation for each of the totals that you want.  Parsing GROUP_CONCAT() is not the right way to do this.

Your question is about the lids.  The CONCAT_WS() does what you want -- concatenating either the value (if it appears) or zero if it does not.

Body:
I have this SQL query with substring_index and group_concat but the results I get does not give the right location of the values because the values does not exist.

I need to add a null or zero value in order to have the right location of the values in the sql result.

In the table there are three lid (1, 2, 3). The lid should be the basis count of the P's (P1, P2, P3) for the substring_index.

This is the table:

lid   class_id   class          total
-----  -------    -----        -----
  1     73       Leader         10000
  1     77       Consultant     8000
  1     83       Coordinator    6000
  2     73       Leader         20000
  2     76       Staff          8000
  2     77       Consultant     10000
  3     73       Leader         30000
  3     78       Team Leader    8000

This is the SQL query I used to group_concat for the totals and substring_index to separate the grouped values with their each column (P1, P2, P3)

SELECT *, GROUP_CONCAT(lid) as lids, GROUP_CONCAT(pyear) as pyears,
 COUNT(DISTINCT lib_id) AS total_count,
 CASE WHEN COUNT(*)>=1 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',1),' ',-1) END AS P1,
 CASE WHEN COUNT(*)>=2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',2),' ',-1) END AS P2,
 CASE WHEN COUNT(*)>=3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(if(total is null,0,total) ORDER BY lid ASC SEPARATOR ' '),' ',3),' ',-1) END AS P3
 FROM (
  SELECT * FROM view_items WHERE lid='1'
  UNION
  SELECT * FROM view_items WHERE lid='2'
  UNION
  SELECT * FROM view_items WHERE lid='3'
 ) AS AZ GROUP BY class_id

This is the result of the above query:

class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          2       8000
   77      Consultant     1,2     8000    10000
   78      Team Leader    3       8000
   83      Coordinator    1       6000

The lids should always have three count even though the record does not exists, a zero or null value should be added. How to do the adding of null value?

This is the expected result I need.

 class id    class         lids     P1      P2      P3
---------   -----        -----    ----    ----     ----
   73      Leader         1,2,3   10000   20000   30000
   76      Staff          0,2,0     0     8000      0
   77      Consultant     1,2,0    8000   10000     0
   78      Team Leader    0,0,3     0       0      8000
   83      Coordinator    1,0,0    6000     0       0

Body:
I don't think GROUP_CONCAT() is the right approach for what you want.  Try this:

SELECT vi.class_id, vi.class,
       COUNT(DISTINCT vi.lib_id) AS total_count,
       CONCAT_WS(',',
                 MAX(CASE WHEN vi.lid = 1 THEN 1 ELSE 0 END),
                 MAX(CASE WHEN vi.lid = 2 THEN 1 ELSE 0 END),
                 MAX(CASE WHEN vi.lid = 3 THEN 1 ELSE 0 END)
                ) as lids,
       SUM(CASE WHEN vi.lid = 1 THEN vi.total ELSE 0 END) as total_1,
       SUM(CASE WHEN vi.lid = 2 THEN vi.total ELSE 0 END) as total_2,
       SUM(CASE WHEN vi.lid = 3 THEN vi.total ELSE 0 END) as total_3
FROM view_items vi
WHERE vi.lid IN (1, 2, 3)
GROUP BY vi.class_id;

Notes:

Your subquery and UNION are not needed.  In MySQL, these can actually hurt performance.

I assume that lid is a number, so I've removed the single quotes.

You can use conditional aggregation for each of the totals that you want.  Parsing GROUP_CONCAT() is not the right way to do this.

Your question is about the lids.  The CONCAT_WS() does what you want -- concatenating either the value (if it appears) or zero if it does not.


问:
I'm confused with this database, should I create more Foreign Keys or more columns?
I'm creating this database about Movies, Series and Actors. The Movies part is done, but I'm confused with the Series+Actors part. My goal is to have 4 tables, 1 of series in general, 1 with the number of seasons and episodes, 1 with the actors info (already connected by foreign key with the movies table).

I've created this tables:

```<code>SeriesData (
  SerieID int PK,
  SerieName varchar(50),
  SerieDescription text,
  SerieCategory varchar(50),
  SerieYear varchar(4),
  ActorID int FK);

ActorsData (
  ActorID int PK,
  ActorName varchar(50),
  ActorAge varchar(3),
  MoviesParticipated varchar(50))
</code>```

For now its OK, but now comes my confusion.
I need to create 2 more tables right? A seasons and episodes table, since we can't put that type of data in the first table and I need a MoviesParticipated table. How do I do it so that I can get the data of 'How many episodes does every season have?'

This is my current SeasonsEpisodes table, but this will only tell me how many seasons and how many episodes the series has right?

```<code>SeasonsEpisodes (
  SerieID int PK,
  SerieSeasons int,
  SerieEpisodes int
</code>```

For the MoviesParticipated table would be something like this (My goal is to output each movie/series he participated)?

```<code>MoviesParticipated (
ActorID int PK
MovieID varchar(50) FK,
SerieID varchar(50) FK)
</code>```

Which Foreign Keys should I create? Should I add more columns?

答:
Since the relationship between the tables Series and the table Episode is [1 to N]
you don't necessairly need a third table. Just add a Foreign Key to Episode that refers to the Primary Key of Series.

You should get something like this for Series:

```<code>  Series (
  SerieID int PK,
  SerieName varchar(50),
  SerieDescription text,
  SerieCategory varchar(50),
  SerieYear varchar(4));
</code>```

And something like this for Episode

```<code>  Episodes (
  SerieID int PK,
  SeasonNumber int,
  EpisodeNumber int,
  EpisodeLength int,
  ...
  SeriesID FK)
</code>```

As for the Series - Actor relationship you need a third table.

Body:
I'm creating this database about Movies, Series and Actors. The Movies part is done, but I'm confused with the Series+Actors part. My goal is to have 4 tables, 1 of series in general, 1 with the number of seasons and episodes, 1 with the actors info (already connected by foreign key with the movies table).

I've created this tables:

SeriesData (
  SerieID int PK,
  SerieName varchar(50),
  SerieDescription text,
  SerieCategory varchar(50),
  SerieYear varchar(4),
  ActorID int FK);

ActorsData (
  ActorID int PK,
  ActorName varchar(50),
  ActorAge varchar(3),
  MoviesParticipated varchar(50))

For now its OK, but now comes my confusion.
I need to create 2 more tables right? A seasons and episodes table, since we can't put that type of data in the first table and I need a MoviesParticipated table. How do I do it so that I can get the data of 'How many episodes does every season have?'

This is my current SeasonsEpisodes table, but this will only tell me how many seasons and how many episodes the series has right?

SeasonsEpisodes (
  SerieID int PK,
  SerieSeasons int,
  SerieEpisodes int

For the MoviesParticipated table would be something like this (My goal is to output each movie/series he participated)?

MoviesParticipated (
ActorID int PK
MovieID varchar(50) FK,
SerieID varchar(50) FK)

Which Foreign Keys should I create? Should I add more columns?

Body:
Since the relationship between the tables Series and the table Episode is [1 to N]
you don't necessairly need a third table. Just add a Foreign Key to Episode that refers to the Primary Key of Series.

You should get something like this for Series:

  Series (
  SerieID int PK,
  SerieName varchar(50),
  SerieDescription text,
  SerieCategory varchar(50),
  SerieYear varchar(4));

And something like this for Episode

  Episodes (
  SerieID int PK,
  SeasonNumber int,
  EpisodeNumber int,
  EpisodeLength int,
  ...
  SeriesID FK)

As for the Series - Actor relationship you need a third table.


问:
DropDownList has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value
I keep getting the above error in the title line and it makes no sense, because I am using a sample table with only 5 records and each record has a value as per the drop down menu.

This is my code used to declare the drop down list. I have joined two tables in my SQL data source to reflect what I want populated in the grid view and have hidden columns as necessary. I am using the same data source to populate the drop down list any help would be most appreciated

```<code><asp:DropDownList ID="DropDownListCurrency" runat="server"
                  CausesValidation="True" DataSourceID="GridView"
                  DataTextField="Currency" DataValueField="Currency_ID"
                  AppendDataBoundItems="True">

          <asp:ListItem Value="0" Text="<Select>" Enabled="True"></asp:ListItem>
</asp:DropDownList>
</code>```

```<code>protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        GridViewRow row = GridView1.SelectedRow;

        AccountNumber.Text = (string)row.Cells[0].Text;
        ....

        DropDownListCurrency.SelectedValue = (string)row.Cells[8].Text;
    }
    catch (Exception ex)
    {
        Console.WriteLine("{0} Exception caught.", ex);
    }
}
</code>```

答:
```<code>#region by zia for if item not exist in dropdownlist
                    string qlf = dsEmp.Tables["tblEmp"].Rows[0]["Group"].ToString();
                    ListItem selLqli = ddlGroup.Items.FindByText(qlf.Trim());
                    if (selLqli != null)
                    {
                        ddlGroup.ClearSelection();
                    }
                    else
                    {
                        ddlGroup.SelectedIndex = 0;

                    }
                    #endregion
</code>```

Body:
I keep getting the above error in the title line and it makes no sense, because I am using a sample table with only 5 records and each record has a value as per the drop down menu.

This is my code used to declare the drop down list. I have joined two tables in my SQL data source to reflect what I want populated in the grid view and have hidden columns as necessary. I am using the same data source to populate the drop down list any help would be most appreciated

<asp:DropDownList ID="DropDownListCurrency" runat="server"
                  CausesValidation="True" DataSourceID="GridView"
                  DataTextField="Currency" DataValueField="Currency_ID"
                  AppendDataBoundItems="True">

          <asp:ListItem Value="0" Text="<Select>" Enabled="True"></asp:ListItem>
</asp:DropDownList>

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        GridViewRow row = GridView1.SelectedRow;

        AccountNumber.Text = (string)row.Cells[0].Text;
        ....

        DropDownListCurrency.SelectedValue = (string)row.Cells[8].Text;
    }
    catch (Exception ex)
    {
        Console.WriteLine("{0} Exception caught.", ex);
    }
}


问:
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
I want to simplify my configuration in my ASP.NET Core Web Application (.NET Framework) application using VS 2017.

I already know that my website will be running under Windows/IIS in x64 environment and .NET 4.6.2. There is no chance in the foreseen and unforeseen future for this application to use any other environment from the dev to production.

So, I only need Debug x64 and Release x64 modes only. (AnyCPU and x86 are not needed!), so I went ahead and removed all other configuration from the project.

Now, upon compilation, I am getting the following error:

'C:\Projects\MyProject\My.Website\obj\project.assets.json' doesn't
  have a target for '.NETFramework,Version=v4.6.2/win7-x64'.

Ensure you
  have restored this project for TargetFramework='net462' and
  RuntimeIdentifier='win7-x64'. MD.Website  C:\Program Files
  (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.targets

I am developing on Windows 7, I am not sure how to fix this one. Any idea?

答:
Check the actual publishing profile file of the Publish you are trying to run.  In our case, we have a set of projects that have to be shared between Core and regular asp.net, so we target Core 1.1 and set the runtime version to 4.6.1.  After running through all of the projects and updating them to target version 4.7, I started getting this error on publish (the actual builds worked fine, as did localhost debugging, it was the publish that was jacked).

Checking the actual "widgets - Web Deploy.pubxml" file, I found this at the bottom:

```<code>    <_DestinationType>AzureWebSite</_DestinationType>
    <TargetFramework>net461</TargetFramework>
    <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
  </PropertyGroup>
</Project>
</code>```

As others on this thread have mentioned, simply opening up the property sheet of the publishing profile will show you, in my case, that the framework was targeted to 4.7 (which was accurate per the projects involved but did not reflect the actual value in the file)... I did still need to click the Save button to get the underlying .pubxml file to actually be updated with the correct value.  You can probably edit that file manually too, if you feel so inclined.

This one drove me nuts.  :)

Body:
Check the actual publishing profile file of the Publish you are trying to run.  In our case, we have a set of projects that have to be shared between Core and regular asp.net, so we target Core 1.1 and set the runtime version to 4.6.1.  After running through all of the projects and updating them to target version 4.7, I started getting this error on publish (the actual builds worked fine, as did localhost debugging, it was the publish that was jacked).

Checking the actual "widgets - Web Deploy.pubxml" file, I found this at the bottom:

    <_DestinationType>AzureWebSite</_DestinationType>
    <TargetFramework>net461</TargetFramework>
    <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
  </PropertyGroup>
</Project>

As others on this thread have mentioned, simply opening up the property sheet of the publishing profile will show you, in my case, that the framework was targeted to 4.7 (which was accurate per the projects involved but did not reflect the actual value in the file)... I did still need to click the Save button to get the underlying .pubxml file to actually be updated with the correct value.  You can probably edit that file manually too, if you feel so inclined.

This one drove me nuts.  :)


问:
rendering application class in Blackberry
What is the purpose of the rendering application class in Blackberry?</p>

答:
First, it is an Interface(@see http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/browser/field/RenderingApplication.html), it can allow you to implement HTML rendering in a variety of applications (@see http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/browser/field/BrowserContent.html)
I personally have used it to render RSS HTML content for display in a typical Field among other things.
It allows you to implement callback functionality to gather resources from the HTML (images, etc) and render them appropriately (if you desire).
This of course is the 5.0 and under version, as I have not been privileged to have a 6.0 user base so I cannot comment past 5.0   :)

edit: Oh yeah, it also allows you to handle HTTP events (redirects, etc)


问:
EF Core cannot update entity with two navigation properties to same object (other entity)
I have two tables. User table has two links to another (identical) entity, i.e. Languages:

```<code>public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Language OrigLanguage { get; set; }
    public Language Language { get; set; }
}

public class Language
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

EF creates the tables properly:

Table "Users": Id, FirstName, LastName, LanguageId, OrigLanguageId

I can add users with same values for OrigLanguage and Language w/o any problem.
As soon as I try to update and existing user with same values I get the following error message:

InvalidOperationException: The instance of entity type 'Language'
  cannot be tracked because another instance with the key value '{Id:
  1}' is already being tracked. When attaching existing entities, ensure
  that only one entity instance with a given key value is attached.

with the following stack:

Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap.ThrowIdentityConflict(InternalEntityEntry
  entry)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap.Add(TKey
  key, InternalEntityEntry entry, bool updateDuplicate)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry
  entry)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState
  oldState, EntityState newState, bool acceptChanges)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState
  entityState, bool acceptChanges, Nullable
  forceStateWhenUnknownKey)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode
  node, bool force)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode
  node, TState state, Func
  handleNode)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode
  node, TState state, Func
  handleNode)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry
  rootEntry, EntityState entityState, bool forceStateWhenUnknownKey)
  Microsoft.EntityFrameworkCore.DbContext.SetEntityState(InternalEntityEntry
  entry, EntityState entityState)
  Microsoft.EntityFrameworkCore.DbContext.SetEntityState(TEntity
  entity, EntityState entityState)
  Microsoft.EntityFrameworkCore.DbContext.Attach(TEntity
  entity) Namespace.Data.Repository.UpdateAsync(T entity) in
  Repository.cs

In my Startup.cs I have the following setting to prevent tracking:

```<code>services.AddDbContext<DocLogDBContext>(
    options => options.UseSqlServer(...)
    .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
</code>```

In my repository I have the following code to update:

```<code>public override async Task<User> UpdateAsync(User entity)
{
    // below two detachments have no effect
    _context.Attach(entity.OrigLanguage).State = EntityState.Detached;
    _context.Attach(entity.Language).State = EntityState.Detached;
    _context.Attach(entity).State = EntityState.Modified;
    await _context.SaveChangesAsync();
    return entity;
}
</code>```

My API controller looks like this:

```<code>[HttpPost]
public virtual async Task<IActionResult> Edit(T model)
{
    await _repository.UpdateAsync(model);
    return Ok(model);
}
</code>```

And this is the request from the client:

```<code>Request URL: https://localhost:44344/api/User/Edit
Request Payload:
{
    Id: 3
    , FirstName: "Joe"
    , LastName: "Frazer"
    , Language: { Name: "english", ShortName: "en", Id: 1 }
    , OrigLanguage: { Name: "english", ShortName: "en", Id: 1 }
}
</code>```

What am I missing here?

答:
We can resolved by using "[ForeignKey("xxxxx")]" atrribute on poco class.
Here I am trying to correct code as below:</p>

```<code>   public class User
   {
       public int Id { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       [ForeignKey("OrigLanguage")]
       public int OrigLanguageId { get; set; }
       [ForeignKey("Language")]
       public int LanguageId { get; set; }

       public Language OrigLanguage { get; set; }
       public Language Language { get; set; }
   }
</code>```

Body:
I have two tables. User table has two links to another (identical) entity, i.e. Languages:

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Language OrigLanguage { get; set; }
    public Language Language { get; set; }
}

public class Language
{
    public int Id { get; set; }
    public string Name { get; set; }
}

EF creates the tables properly:

Table "Users": Id, FirstName, LastName, LanguageId, OrigLanguageId

I can add users with same values for OrigLanguage and Language w/o any problem.
As soon as I try to update and existing user with same values I get the following error message:

InvalidOperationException: The instance of entity type 'Language'
  cannot be tracked because another instance with the key value '{Id:
  1}' is already being tracked. When attaching existing entities, ensure
  that only one entity instance with a given key value is attached.

with the following stack:

Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap.ThrowIdentityConflict(InternalEntityEntry
  entry)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap.Add(TKey
  key, InternalEntityEntry entry, bool updateDuplicate)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry
  entry)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState
  oldState, EntityState newState, bool acceptChanges)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState
  entityState, bool acceptChanges, Nullable
  forceStateWhenUnknownKey)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode
  node, bool force)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode
  node, TState state, Func
  handleNode)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph(EntityEntryGraphNode
  node, TState state, Func
  handleNode)
  Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry
  rootEntry, EntityState entityState, bool forceStateWhenUnknownKey)
  Microsoft.EntityFrameworkCore.DbContext.SetEntityState(InternalEntityEntry
  entry, EntityState entityState)
  Microsoft.EntityFrameworkCore.DbContext.SetEntityState(TEntity
  entity, EntityState entityState)
  Microsoft.EntityFrameworkCore.DbContext.Attach(TEntity
  entity) Namespace.Data.Repository.UpdateAsync(T entity) in
  Repository.cs

In my Startup.cs I have the following setting to prevent tracking:

services.AddDbContext<DocLogDBContext>(
    options => options.UseSqlServer(...)
    .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)

In my repository I have the following code to update:

public override async Task<User> UpdateAsync(User entity)
{
    // below two detachments have no effect
    _context.Attach(entity.OrigLanguage).State = EntityState.Detached;
    _context.Attach(entity.Language).State = EntityState.Detached;
    _context.Attach(entity).State = EntityState.Modified;
    await _context.SaveChangesAsync();
    return entity;
}

My API controller looks like this:

[HttpPost]
public virtual async Task<IActionResult> Edit(T model)
{
    await _repository.UpdateAsync(model);
    return Ok(model);
}

And this is the request from the client:

Request URL: https://localhost:44344/api/User/Edit
Request Payload:
{
    Id: 3
    , FirstName: "Joe"
    , LastName: "Frazer"
    , Language: { Name: "english", ShortName: "en", Id: 1 }
    , OrigLanguage: { Name: "english", ShortName: "en", Id: 1 }
}

What am I missing here?

Body:
We can resolved by using "[ForeignKey("xxxxx")]" atrribute on poco class.
Here I am trying to correct code as below:

   public class User
   {
       public int Id { get; set; }
       public string FirstName { get; set; }
       public string LastName { get; set; }
       [ForeignKey("OrigLanguage")]
       public int OrigLanguageId { get; set; }
       [ForeignKey("Language")]
       public int LanguageId { get; set; }

       public Language OrigLanguage { get; set; }
       public Language Language { get; set; }
   }


问:
LMFIT: ' ValueError: The input contains nan values'when Data Input is all Float
I'm trying to Curve-Fit a data-set, that I got from and Integration, which lmfit says contains NaN value.

The same Data were fitted with scipy_curvefit, that was SUPER Bad.  I'm trying this library for some better results.

I tried to change my yData and xData to some simple arrays (you will see below) and got the same error!

```<code>from lmfit import Model
def poly(x, a1,a2,a3,a4,a5):
    return a1+a2*x**a3+a4*x**a5
x=s
y=vrr
x=[0.,1.,2.,3.,5.,6.]
y=[4.,5.,6.,12.,3.,5.]
gmodel = Model(poly)
gmodel_parameters= gmodel.make_params()
gmodel_parameters['a1'].set(value=10)
gmodel_parameters['a2'].set(value=10)
gmodel_parameters['a3'].set(value=7)
gmodel_parameters['a4'].set(value=10)
gmodel_parameters['a5'].set(value=7)
result=gmodel.fit(x=x,data=y,params=gmodel_parameters)

plt.plot(x, y, 'k--')
plt.plot(x, result.best_fit, 'r-')
plt.show()
</code>```

答:
Be careful when you fit an exponent. If the program sets this variable to less than zero, you may have a NaN error. Read the documentation and try to add min=0 to a3 and a5 as a optimization option.

https://lmfit.github.io/lmfit-py/model.html#the-model-class

Good luck!

Body:
I'm trying to Curve-Fit a data-set, that I got from and Integration, which lmfit says contains NaN value.

The same Data were fitted with scipy_curvefit, that was SUPER Bad.  I'm trying this library for some better results.

I tried to change my yData and xData to some simple arrays (you will see below) and got the same error!

from lmfit import Model
def poly(x, a1,a2,a3,a4,a5):
    return a1+a2*x**a3+a4*x**a5
x=s
y=vrr
x=[0.,1.,2.,3.,5.,6.]
y=[4.,5.,6.,12.,3.,5.]
gmodel = Model(poly)
gmodel_parameters= gmodel.make_params()
gmodel_parameters['a1'].set(value=10)
gmodel_parameters['a2'].set(value=10)
gmodel_parameters['a3'].set(value=7)
gmodel_parameters['a4'].set(value=10)
gmodel_parameters['a5'].set(value=7)
result=gmodel.fit(x=x,data=y,params=gmodel_parameters)

plt.plot(x, y, 'k--')
plt.plot(x, result.best_fit, 'r-')
plt.show()


问:
How to Convince management to upgrade to .Net 4.0
We developed an application using .net 2.0.
We license our software which means whenever we release a new version, we have to push out the change to all our existing clients.

No one in my group has the slightest motivation to upgrade to a newer version of .net. They simple see it as more work for our support team to deploy and argue that clients will be resistant to any change.

Can anyone point me in the direction of some argument i could present to Non programmers that might sway them.

If noting else, some argument that it is safe, and will not cause our clients any harm who already have the .net 2.0 framework on their machines?

I figure it's hopeless. I'm gonna be stuck using the .net 2.0 framework until for another 4 or 5 years i bet... perhaps longer :( help!

I really want to be able to use WCF, LINQ, WPF (possible), and the option to use the Entity Framework 4.0.!

thanks

jonathan

答:
You should find out how many of your existing clients have the .NET 4 framework installed. This will quantify the upgrade task you and your support team face. If you have 50 end users then perhaps half of them will have the newer framework already (i found this to be the case).
If you have 5,000 end users well then your task is larger.

As for arguments to convince management:

1) You need to keep up with the latest technologies (to some degree) to attract and maintain staff.

2) The technology offers new ways to test and debug code (eg code dumps, parallel stacks)

3) You can use that library that you really need that is only available in .NET>2.0

4) you don't want to be forced to migrate/upgrade - best to do it when it suits the company rather than when all the COBOL programmers have died.

disclaiimer I don't necessarily believe each of these is valid 100% of the time but they can be used.


问:
JS/JQuery: Detect when child element is added to parent
I have parent div where child elements are added dynamically and i need to detect when child is added. I heard about mutation observer which is new version of DOMSubTreeModified event, but are there better alternatives?

for example

```<code>$('div').//event = () => {
  //do stuff
}
</code>```

Thanks You!

答:
Use DOMNodeInserted on the parent and check the event.target.parentNode of the added element. If its id is parent, then the element is a direct descendant.

Demo

```<code>document.getElementById( 'parent' ).addEventListener( 'DOMNodeInserted', function ( event ) {
   if( event.target.parentNode.id === 'parent' ) {
       //direct descendant
   };
}, false );
</code>```

Credit goes to ThinkingStiff who already answered that question

Body:
I have parent div where child elements are added dynamically and i need to detect when child is added. I heard about mutation observer which is new version of DOMSubTreeModified event, but are there better alternatives?

for example

$('div').//event = () => {
  //do stuff
}

Thanks You!

Body:
Use DOMNodeInserted on the parent and check the event.target.parentNode of the added element. If its id is parent, then the element is a direct descendant.

Demo

document.getElementById( 'parent' ).addEventListener( 'DOMNodeInserted', function ( event ) {
   if( event.target.parentNode.id === 'parent' ) {
       //direct descendant
   };
}, false );

Credit goes to ThinkingStiff who already answered that question


问:
How to set Retrofit URL string from Resources
I've refactored some parts of my code which is written in Kotlin and tend to put url's in strings.xml, but when I want to point to the string in strings.xml file in annotation part of the Retrofit, I get the following error.

An annotation argument must be a compile-time constant

Here is my code:

```<code>interface SampleApiService {
    @GET(Resources.getSystem().getString(R.string.sample_url))
    fun getSamples(){
    }
}
</code>```

Could anyone please tell me what is wrong?

Found the answer in the following post.

答:
As documentation states it compiles your application resources at build time. and Annotation processing takes place at compile time. So you see you cannot pass resources string to a annotation

The Android SDK tools compile your application's resources into the
  application binary at build time.

instead create static string variable and pass it in annotation

Body:
I've refactored some parts of my code which is written in Kotlin and tend to put url's in strings.xml, but when I want to point to the string in strings.xml file in annotation part of the Retrofit, I get the following error.

An annotation argument must be a compile-time constant

Here is my code:

interface SampleApiService {
    @GET(Resources.getSystem().getString(R.string.sample_url))
    fun getSamples(){
    }
}

Could anyone please tell me what is wrong?

Found the answer in the following post.


问:
Expo cli update not happening
I am trying to upgrade expo-cli from 2.11 to 2.18 but npm i -g expo-cli@latest still points to the old version.

when I typed expo-cli -V it resulted:

2.11  ...so naturally npm i -g expo-cli@latest will grab the latest version and install it but still expo-cli -v is still pointing to the old version.

I remember installing packages in bash level is a no go operation.

these are some images to put it all into context:

Update: Removed Nodes modules as suggested in the first answer, and that lead to npm removal both expo and expo-cli are not found with the command where

答:
the hole system was behaving oddly!, npm should've been installed with node but it was nowhere to be found.
I had to remove node and reinstall it again, then I had to install expo-cli again and all errors went away.

Title: Expo cli update not happening


问:
how can i map lat and lng to geo_point type in elasticsearch
Im using elasticsearch 7 and nest 6.7 .

I have index that has any type like coordinate .

in any way im mapping geo_type i have problem .

```<code> client.CreateIndex("staging2", c => c.Mappings(m => m.Map<VenueIndex>(mm => mm.AutoMap())));
</code>```

this is my nest code and this is som part of my poko class :

```<code>     public object Promotion { get; set; }
    public object Checkin { get; set; }
    public Featured Featured { get; set; }
    public int BinaryType { get; set; }
    public List<WorkingHour> WorkingHours { get; set; }
    [GeoPoint(Name = "location", IgnoreMalformed = true)]
    public Geoloc _geoloc { get; set; }
    public string Neighbourhood { get; set; }
    public List<int> MealTimes { get; set; }
    public string objectID { get; set; }

    public class Geoloc
{

    [Number(NumberType.Double, Name = "lat")]
    public double lat { get; set; }
    [Number(NumberType.Double, Name = "lon")]
    public double lon { get; set; }
}
</code>```

in this way GeoLoc type is float

other way when i user post man still have this problem .

my json object is somthing like this :

```<code>{
  "isClubMember": false,
 "rating": 0.0,
 "binaryType": 2,
 "location": {
 "lat":"32.11",
 "lon":"-34.22"
 },
   "neighbourhood": "شهرک والفجر,امیر آباد",
   "mealTimes": [],
   "objectID": "188dc91e-8088-4099-9eb8-00aa73653192"}
</code>```

where is my mistake ?

答:
Model:

```<code>    public class TestClass
    {
        public object Promotion { get; set; }
        public object Checkin { get; set; }
        [GeoPoint(Name = "location", IgnoreMalformed = true)]
        public Geoloc _geoloc { get; set; }
        public string Neighbourhood { get; set; }
        public List<int> MealTimes { get; set; }
        public string objectID { get; set; }
    }
    public class Geoloc
    {
        [Number(NumberType.Double, Name = "lat")]
        public double lat { get; set; }
        [Number(NumberType.Double, Name = "lon")]
        public double lon { get; set; }
    }
</code>```

Code to create mapping using NEST

```<code>var url = "http://localhost:9200";
            var settings = new ConnectionSettings(new Uri(url));
            EsClient = new ElasticClient(settings);

            if (!EsClient.IndexExists("gcheck").Exists)
            {
                var resp = EsClient.CreateIndex("gcheck", c => c
                 .Map<TestClass>(mp => mp
                 .Properties(
                     ps => ps
                 ).AutoMap()
                ));
            }
</code>```

Output mapping:

```<code> "gcheck" : {
    "mappings" : {
      "properties" : {
        "binaryType" : {
          "type" : "long"
        },
        "checkin" : {
          "type" : "object"
        },
        "isClubMember" : {
          "type" : "boolean"
        },
        "location" : {
          "type" : "geo_point",
          "ignore_malformed" : true
        },
        "mealTimes" : {
          "type" : "integer"
        },
        "neighbourhood" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "objectID" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "promotion" : {
          "type" : "object"
        },
        "rating" : {
          "type" : "long"
        }
      }
    }
  }
</code>```

Body:
Im using elasticsearch 7 and nest 6.7 .

I have index that has any type like coordinate .

in any way im mapping geo_type i have problem .

 client.CreateIndex("staging2", c => c.Mappings(m => m.Map<VenueIndex>(mm => mm.AutoMap())));

this is my nest code and this is som part of my poko class :

     public object Promotion { get; set; }
    public object Checkin { get; set; }
    public Featured Featured { get; set; }
    public int BinaryType { get; set; }
    public List<WorkingHour> WorkingHours { get; set; }
    [GeoPoint(Name = "location", IgnoreMalformed = true)]
    public Geoloc _geoloc { get; set; }
    public string Neighbourhood { get; set; }
    public List<int> MealTimes { get; set; }
    public string objectID { get; set; }

    public class Geoloc
{

    [Number(NumberType.Double, Name = "lat")]
    public double lat { get; set; }
    [Number(NumberType.Double, Name = "lon")]
    public double lon { get; set; }
}

in this way GeoLoc type is float

other way when i user post man still have this problem .

my json object is somthing like this :

{
  "isClubMember": false,
 "rating": 0.0,
 "binaryType": 2,
 "location": {
 "lat":"32.11",
 "lon":"-34.22"
 },
   "neighbourhood": "شهرک والفجر,امیر آباد",
   "mealTimes": [],
   "objectID": "188dc91e-8088-4099-9eb8-00aa73653192"}

where is my mistake ?

Body:
Model:

    public class TestClass
    {
        public object Promotion { get; set; }
        public object Checkin { get; set; }
        [GeoPoint(Name = "location", IgnoreMalformed = true)]
        public Geoloc _geoloc { get; set; }
        public string Neighbourhood { get; set; }
        public List<int> MealTimes { get; set; }
        public string objectID { get; set; }
    }
    public class Geoloc
    {
        [Number(NumberType.Double, Name = "lat")]
        public double lat { get; set; }
        [Number(NumberType.Double, Name = "lon")]
        public double lon { get; set; }
    }

Code to create mapping using NEST

var url = "http://localhost:9200";
            var settings = new ConnectionSettings(new Uri(url));
            EsClient = new ElasticClient(settings);

            if (!EsClient.IndexExists("gcheck").Exists)
            {
                var resp = EsClient.CreateIndex("gcheck", c => c
                 .Map<TestClass>(mp => mp
                 .Properties(
                     ps => ps
                 ).AutoMap()
                ));
            }

Output mapping:

 "gcheck" : {
    "mappings" : {
      "properties" : {
        "binaryType" : {
          "type" : "long"
        },
        "checkin" : {
          "type" : "object"
        },
        "isClubMember" : {
          "type" : "boolean"
        },
        "location" : {
          "type" : "geo_point",
          "ignore_malformed" : true
        },
        "mealTimes" : {
          "type" : "integer"
        },
        "neighbourhood" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "objectID" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "promotion" : {
          "type" : "object"
        },
        "rating" : {
          "type" : "long"
        }
      }
    }
  }


问:
Can't redirect if not logged in React Token auth
I have this app, frontend is React and backend is Laravel. I did the auth system using Laravel Passport. When the user is logged in, I save the token in local storage. If the user is not logged in, I want to automatically redirect to /login. Basically the user can't do anything if it's not logged in. I tried this:

```<code><BrowserRouter>
    <Route path="/login" exact component={FormularAuth} />
        {
          isAuthenticated ? (
            <React.Fragment>
              *ALL OTHER ROUTES ARE HERE, AND IF LOGGED IN, IT WORKS*
            </React.Fragment>
           ) : (
                   window.location = '/login')
               )
         }
</BrowserRouter>
</code>```

It send's me to the /login page, but it keeps refreshing, and I can't login or anything. What is the problem here?

答:
react router v4 supports use of PrivateRoute.

```<code>// create a private route, if user is not logged in redirect to login page
const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
      isAuthenticated() === true
        ? <Component {...props} />
        : <Redirect to='/login' />
  )} />
)
</code>```

Use it like a normal route and check authentication in the private route.

```<code><BrowserRouter>
  <Route path="/login" exact component={FormularAuth} />
  <PrivateRoute path='/private' component={Private} />
</BrowserRouter>
</code>```

Body:
I have this app, frontend is React and backend is Laravel. I did the auth system using Laravel Passport. When the user is logged in, I save the token in local storage. If the user is not logged in, I want to automatically redirect to /login. Basically the user can't do anything if it's not logged in. I tried this:

<BrowserRouter>
    <Route path="/login" exact component={FormularAuth} />
        {
          isAuthenticated ? (
            <React.Fragment>
              *ALL OTHER ROUTES ARE HERE, AND IF LOGGED IN, IT WORKS*
            </React.Fragment>
           ) : (
                   window.location = '/login')
               )
         }
</BrowserRouter>

It send's me to the /login page, but it keeps refreshing, and I can't login or anything. What is the problem here?

Body:
react router v4 supports use of PrivateRoute.

// create a private route, if user is not logged in redirect to login page
const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
      isAuthenticated() === true
        ? <Component {...props} />
        : <Redirect to='/login' />
  )} />
)

Use it like a normal route and check authentication in the private route.

<BrowserRouter>
  <Route path="/login" exact component={FormularAuth} />
  <PrivateRoute path='/private' component={Private} />
</BrowserRouter>


问:
Async function: for-Loop object empty after await statement
tldr at the bottom:

I don't really know how to explain my problem so I start with an example.
I have this async function (in reactJS but I think this is a JS related issue).

```<code> onUploadDrop = async (e, folderId) => {
        e.preventDefault();
        // check if the user uploaded files or folders
        var uploadedItems = e.dataTransfer.items;
        let files = [];
        for (var i = 0; i < uploadedItems.length; i++) {
            let item = uploadedItems[i].webkitGetAsEntry();
            if (item.isDirectory) {
                alert("is directory")
            } else {
                var file = await this.getFileByWebkitEntry(item);
                files.push(file);
            }
            console.log(i);
        }

     // do something with files[]
    }
</code>```

This function is calling another async function:

```<code>getFileByWebkitEntry = async (item) => {
    return new Promise(resolve => {
        item.file(function (file) {
            resolve(file);
        }, function (err) {
            console.log(err);
            resolve("");
        });
    });
}
</code>```

I'm looping through e.datatransfer.files which are basically some uploaded files or folders. Unfortunately this for-loop gets only executed once.

I did some debugging and found out that if I place a console.log before and after this line: var file = await ... This comes out:

tldr: After the await statement uploadedItems is empty thus ending the loop. Why is this happening?

答:
I solved this by not using async - await but Promises instead.
It looks like this:</p>

```<code>onUploadDrop = (e, folderId) => {
        e.preventDefault();
        // check if the user uploaded files or folders
        var uploadedItems = e.dataTransfer.items;
        let promises = [];
        for (var i = 0; i < uploadedItems.length; i++) {
            let item = uploadedItems[i].webkitGetAsEntry();
            if (item.isDirectory) {
                alert("is directory")
            } else {
                promises.push(this.getFileByWebkitEntry(item));
            }
            console.log(i);
        }

        Promise.all(promises).then(result => {
            // do something with result (result = files)
        });
</code>```

Body:
tldr at the bottom:

I don't really know how to explain my problem so I start with an example.
I have this async function (in reactJS but I think this is a JS related issue).

 onUploadDrop = async (e, folderId) => {
        e.preventDefault();
        // check if the user uploaded files or folders
        var uploadedItems = e.dataTransfer.items;
        let files = [];
        for (var i = 0; i < uploadedItems.length; i++) {
            let item = uploadedItems[i].webkitGetAsEntry();
            if (item.isDirectory) {
                alert("is directory")
            } else {
                var file = await this.getFileByWebkitEntry(item);
                files.push(file);
            }
            console.log(i);
        }

     // do something with files[]
    }

This function is calling another async function:

getFileByWebkitEntry = async (item) => {
    return new Promise(resolve => {
        item.file(function (file) {
            resolve(file);
        }, function (err) {
            console.log(err);
            resolve("");
        });
    });
}

I'm looping through e.datatransfer.files which are basically some uploaded files or folders. Unfortunately this for-loop gets only executed once.

I did some debugging and found out that if I place a console.log before and after this line: var file = await ... This comes out:

tldr: After the await statement uploadedItems is empty thus ending the loop. Why is this happening?

Body:
I solved this by not using async - await but Promises instead.
It looks like this:

onUploadDrop = (e, folderId) => {
        e.preventDefault();
        // check if the user uploaded files or folders
        var uploadedItems = e.dataTransfer.items;
        let promises = [];
        for (var i = 0; i < uploadedItems.length; i++) {
            let item = uploadedItems[i].webkitGetAsEntry();
            if (item.isDirectory) {
                alert("is directory")
            } else {
                promises.push(this.getFileByWebkitEntry(item));
            }
            console.log(i);
        }

        Promise.all(promises).then(result => {
            // do something with result (result = files)
        });


问:
How to limit duplicated rows
I would like help regarding an SQL query.
Looking around the site, I found several code snippets to return duplicate rows.
Here is the one I went with:

```<code>select unumber, name, localid
from table1
where unumber
in (select unumber from table1 group by unumber having count (*) > 1 )
order by unumber
</code>```

which works fine, however, in the table I have other columns as well, like timestamp etc.
As such, when I run the query I indeed get the duplicate rows, however, I get the duplicates several times due to different timestamps for example.
Is there any way to limit the results to 'unique' duplicate rows only?

Hope this makes sense!
Thank you in advance!

答:
For what you describe, you can just use select distinct:

```<code>select distinct unumber, name, localid
from table1
where unumber in (select unumber from table1 group by unumber having count (*) > 1 )
order by unumber;
</code>```

However, I would be more likely to write this using window functions:

```<code>select unumber, name, localid
from (select t1.*,
             count(*) over (partition by unumber) as cnt,
             row_number() over (partition by unumber, name, localid order by unumber) as seqnum
      from table1 t1
     ) t1
where cnt > 1 and seqnum = 1;
</code>```

Title: How to limit duplicated rows

Body:
I would like help regarding an SQL query.
Looking around the site, I found several code snippets to return duplicate rows.
Here is the one I went with:

select unumber, name, localid
from table1
where unumber
in (select unumber from table1 group by unumber having count (*) > 1 )
order by unumber

which works fine, however, in the table I have other columns as well, like timestamp etc.
As such, when I run the query I indeed get the duplicate rows, however, I get the duplicates several times due to different timestamps for example.
Is there any way to limit the results to 'unique' duplicate rows only?

Hope this makes sense!
Thank you in advance!

Body:
For what you describe, you can just use select distinct:

select distinct unumber, name, localid
from table1
where unumber in (select unumber from table1 group by unumber having count (*) > 1 )
order by unumber;

However, I would be more likely to write this using window functions:

select unumber, name, localid
from (select t1.*,
             count(*) over (partition by unumber) as cnt,
             row_number() over (partition by unumber, name, localid order by unumber) as seqnum
      from table1 t1
     ) t1
where cnt > 1 and seqnum = 1;


问:
Couldn't launch android studio on Ubuntu 18.4 LTS Error: Could not find or load main class Dsun.java2d.d3d=false
I have followed the steps [here] (Android Studio is slow (how to speed up)?) in order to try and make my android studio faster.
after doing so android studio won't even launch .

I have tried the command ./studio.sh from the terminal but I am getting this

error: Error: Could not find or load main class Dsun.java2d.d3d=false

答:
Fixed it by:

going to dir home/username/AndroidStudiox.x/config/studio.vmoptions
I had added a couple of lines there before
I edited the file and deleted it's contents. and I was able to launch android studio again


问:
Get name of currently logged in user
I made a simple login using Identity. I logged in with signInManager.PasswordSignInAsync().

If the login was successful, I would like to get the currently logged in user's data using the userManager.

The problem is that I can only get an id from the GetUserAsync and don't know what to do with it.

```<code>var result = await mSignInManager.PasswordSignInAsync(username, password, true, false);

if (result.Succeeded)
{
    //var loggedUser = mUserManager.GetUserName(HttpContext.User);
    var userData = mUserManager.GetUserAsync(HttpContext.User);
    var user = await mUserManager.FindByIdAsync(userData.Id.ToString());
    return Redirect("/createpost");
}
</code>```

答:
To me it looks like you are logging the user in and immediately trying to access the user info. The httpContext has not had the chance to update and still reflects the time when there was no user logged in. Try moving your user info retrieval logic to "createpost" where it gets executed on the next http roundtrip. </p>

```<code>    public async Task<IActionResult> createpost()
    {
        var userData = await mUserManager.GetUserAsync(HttpContext.User);
        Debug.WriteLine(userData.Id);
        Debug.WriteLine(userData.UserName);
        Debug.WriteLine(userData.Email);
        return View();
    }
</code>```

Title: Get name of currently logged in user

Body:
I made a simple login using Identity. I logged in with signInManager.PasswordSignInAsync().

If the login was successful, I would like to get the currently logged in user's data using the userManager.

The problem is that I can only get an id from the GetUserAsync and don't know what to do with it.

var result = await mSignInManager.PasswordSignInAsync(username, password, true, false);

if (result.Succeeded)
{
    //var loggedUser = mUserManager.GetUserName(HttpContext.User);
    var userData = mUserManager.GetUserAsync(HttpContext.User);
    var user = await mUserManager.FindByIdAsync(userData.Id.ToString());
    return Redirect("/createpost");
}

Body:
To me it looks like you are logging the user in and immediately trying to access the user info. The httpContext has not had the chance to update and still reflects the time when there was no user logged in. Try moving your user info retrieval logic to "createpost" where it gets executed on the next http roundtrip.

    public async Task<IActionResult> createpost()
    {
        var userData = await mUserManager.GetUserAsync(HttpContext.User);
        Debug.WriteLine(userData.Id);
        Debug.WriteLine(userData.UserName);
        Debug.WriteLine(userData.Email);
        return View();
    }