问:
How do I keep these images constrained properly?
I need to have a lot of different images set in a specific way in a layout. So far, it seems the best way to do this is using a ConstraintLayout. However, nothing seems to want to stay where it should.

This is an image of how the ImageViews currently look in the XML, but they don't have any constraints and they change position whenever I try and constrain them.
ImageViews

Here's the XML code I have written. I've taken out the constraints to try and help make it more understandable.

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context=".MapFragment">

    <!-- TODO: Update blank fragment layout -->

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imgClare"
        android:layout_width="163dp"
        android:layout_height="261dp"
        android:src="@drawable/constituency_clare"
        tools:layout_editor_absoluteX="43dp"
        tools:layout_editor_absoluteY="350dp" />

    <ImageView
        android:id="@+id/imgGalwayWest"
        android:layout_width="199dp"
        android:layout_height="348dp"
        android:src="@drawable/constituency_galway_west"
        tools:layout_editor_absoluteX="-13dp"
        tools:layout_editor_absoluteY="279dp" />

    <ImageView
        android:id="@+id/imgGalwayEast"
        android:layout_width="135dp"
        android:layout_height="302dp"
        android:src="@drawable/constituency_galway_east"
        tools:layout_editor_absoluteX="96dp"
        tools:layout_editor_absoluteY="253dp" />

    <ImageView
        android:id="@+id/imgMayo"
        android:layout_width="156dp"
        android:layout_height="322dp"
        android:src="@drawable/constituency_mayo"
        tools:layout_editor_absoluteX="-21dp"
        tools:layout_editor_absoluteY="216dp" />

    <ImageView
        android:id="@+id/imgCorkSouthWest"
        android:layout_width="195dp"
        android:layout_height="149dp"
        android:src="@drawable/constituency_cork_south_west"
        tools:layout_editor_absoluteX="11dp"
        tools:layout_editor_absoluteY="600dp" />

    <ImageView
        android:id="@+id/imgKerry"
        android:layout_width="160dp"
        android:layout_height="165dp"
        android:src="@drawable/constituency_kerry_cut"
        app:layout_constraintStart_toStartOf="parent"
        tools:layout_editor_absoluteY="513dp" />

    <ImageView
        android:id="@+id/imgWicklow"
        android:layout_width="84dp"
        android:layout_height="180dp"
        android:src="@drawable/constituency_wicklow"
        tools:layout_editor_absoluteX="308dp"
        tools:layout_editor_absoluteY="439dp" />

    <ImageView
        android:id="@+id/imgWexford"
        android:layout_width="135dp"
        android:layout_height="285dp"
        android:layout_marginEnd="12dp"
        android:src="@drawable/constituency_wexford"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <ImageView
        android:id="@+id/imgWaterford"
        android:layout_width="108dp"
        android:layout_height="113dp"
        android:src="@drawable/constituency_waterford"
        tools:layout_editor_absoluteX="195dp"
        tools:layout_editor_absoluteY="594dp" />

    <ImageView
        android:id="@+id/imgDonegal"
        android:layout_width="205dp"
        android:layout_height="560dp"
        android:src="@drawable/constituency_donegal"
        tools:layout_editor_absoluteX="96dp"
        tools:layout_editor_absoluteY="-88dp"
        app:layout_constraintTop_toTopOf="0dp"
        />

    <ImageView
        android:id="@+id/imgLimerickCity"
        android:layout_width="37dp"
        android:layout_height="48dp"
        android:src="@drawable/constituency_limerick_city"
        tools:layout_editor_absoluteX="277dp"
        tools:layout_editor_absoluteY="263dp" />

    <ImageView
        android:id="@+id/imgLimerickCounty"
        android:layout_width="70dp"
        android:layout_height="42dp"
        android:src="@drawable/constituency_limerick_county"
        tools:layout_editor_absoluteX="112dp"
        tools:layout_editor_absoluteY="513dp" />

    <ImageView
        android:id="@+id/imgCorkNorthWest"
        android:layout_width="83dp"
        android:layout_height="130dp"
        android:src="@drawable/constituency_cork_north_west"
        tools:layout_editor_absoluteX="112dp"
        tools:layout_editor_absoluteY="548dp" />

    <ImageView
        android:id="@+id/imgCorkEast"
        android:layout_width="117dp"
        android:layout_height="80dp"
        android:src="@drawable/constituency_cork_east"
        tools:layout_editor_absoluteX="163dp"
        tools:layout_editor_absoluteY="590dp" />

    <ImageView
        android:id="@+id/imgCorkNorthCentral"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:src="@drawable/constituency_cork_north_central"
        tools:layout_editor_absoluteX="171dp"
        tools:layout_editor_absoluteY="611dp" />

    <ImageView
        android:id="@+id/imgCorkSouthCentral"
        android:layout_width="39dp"
        android:layout_height="43dp"
        android:src="@drawable/constituency_cork_south_central"
        tools:layout_editor_absoluteX="186dp"
        tools:layout_editor_absoluteY="627dp" />

    <ImageView
        android:id="@+id/imgCarlowKilkenny"
        android:layout_width="92dp"
        android:layout_height="207dp"
        android:src="@drawable/constituency_carlow_kilkenny"
        tools:layout_editor_absoluteX="236dp"
        tools:layout_editor_absoluteY="487dp"
        app:layout_constraintRight_toLeftOf="@id/imgWexford"/>

    <ImageView
        android:id="@+id/imgTipperary"
        android:layout_width="101dp"
        android:layout_height="225dp"
        android:src="@drawable/constituency_tipperary"
        tools:layout_editor_absoluteX="163dp"
        tools:layout_editor_absoluteY="394dp" />

    <ImageView
        android:id="@+id/imgKildareSouth"
        android:layout_width="74dp"
        android:layout_height="247dp"
        android:src="@drawable/constituency_kildare_south"
        tools:layout_editor_absoluteX="264dp"
        tools:layout_editor_absoluteY="372dp" />

    <ImageView
        android:id="@+id/imgLaoisOffaly"
        android:layout_width="110dp"
        android:layout_height="102dp"
        android:layout_marginEnd="11dp"
        android:layout_marginBottom="9dp"
        android:src="@drawable/constituency_laois_offaly"
        app:layout_constraintBottom_toTopOf="@+id/imgCorkNorthWest"
        app:layout_constraintEnd_toStartOf="@+id/imgWexford"
        app:layout_constraintStart_toEndOf="@+id/imgGalwayEast"
        app:layout_constraintTop_toBottomOf="@+id/imgLongfordWestmeath" />

    <ImageView
        android:id="@+id/imgKildareNorth"
        android:layout_width="61dp"
        android:layout_height="77dp"
        android:src="@drawable/constituency_kildare_north"
        tools:layout_editor_absoluteX="293dp"
        tools:layout_editor_absoluteY="428dp" />

    <ImageView
        android:id="@+id/imgMeathWest"
        android:layout_width="110dp"
        android:layout_height="67dp"
        android:src="@drawable/constituency_meath_west"
        tools:layout_editor_absoluteX="231dp"
        tools:layout_editor_absoluteY="394dp" />

    <ImageView
        android:id="@+id/imgLongfordWestmeath"
        android:layout_width="101dp"
        android:layout_height="100dp"
        android:src="@drawable/constituency_longford_westmeath"
        tools:layout_editor_absoluteX="186dp"
        tools:layout_editor_absoluteY="372dp" />

    <ImageView
        android:id="@+id/imgCavanMonoghan"
        android:layout_width="140dp"
        android:layout_height="230dp"
        android:src="@drawable/constituency_cavan_monoghan"
        tools:layout_editor_absoluteX="188dp"
        tools:layout_editor_absoluteY="234dp" />

    <ImageView
        android:id="@+id/imgMeathEast"
        android:layout_width="66dp"
        android:layout_height="98dp"
        android:src="@drawable/constituency_meath_east"
        tools:layout_editor_absoluteX="288dp"
        tools:layout_editor_absoluteY="366dp" />

    <ImageView
        android:id="@+id/imgLouth"
        android:layout_width="55dp"
        android:layout_height="90dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="48dp"
        android:layout_marginBottom="3dp"
        android:src="@drawable/constituency_louth"
        app:layout_constraintBottom_toTopOf="@+id/imgKildareNorth"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imgDonegal" />

    <ImageView
        android:id="@+id/imgSligoLeitrim"
        android:layout_width="117dp"
        android:layout_height="126dp"
        android:src="@drawable/constituency_sligo_leitirim"
        tools:layout_editor_absoluteX="89dp"
        tools:layout_editor_absoluteY="269dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</code>```

答:
xml property tools:layout_editor_absoluteX and tools:layout_editor_absoluteY is used for layout editor in Android Studio only, it has no influence on view positioning. Essence of ConstraintLayout is to describe connections and position views in relation to each other. I.e you define view A, set it's position to parent, set it margins- then describe position of it's sibling view B, using view A as base, and so on.
There are lot of articles about working with constraint layout, like https://medium.com/@loutry/guide-to-constraintlayout-407cd87bc013
And don't bother visual editor, it's misleading at best.

Body:
I need to have a lot of different images set in a specific way in a layout. So far, it seems the best way to do this is using a ConstraintLayout. However, nothing seems to want to stay where it should.

This is an image of how the ImageViews currently look in the XML, but they don't have any constraints and they change position whenever I try and constrain them.
ImageViews

Here's the XML code I have written. I've taken out the constraints to try and help make it more understandable.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context=".MapFragment">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imgClare"
        android:layout_width="163dp"
        android:layout_height="261dp"
        android:src="@drawable/constituency_clare"
        tools:layout_editor_absoluteX="43dp"
        tools:layout_editor_absoluteY="350dp" />

    <ImageView
        android:id="@+id/imgGalwayWest"
        android:layout_width="199dp"
        android:layout_height="348dp"
        android:src="@drawable/constituency_galway_west"
        tools:layout_editor_absoluteX="-13dp"
        tools:layout_editor_absoluteY="279dp" />

    <ImageView
        android:id="@+id/imgGalwayEast"
        android:layout_width="135dp"
        android:layout_height="302dp"
        android:src="@drawable/constituency_galway_east"
        tools:layout_editor_absoluteX="96dp"
        tools:layout_editor_absoluteY="253dp" />

    <ImageView
        android:id="@+id/imgMayo"
        android:layout_width="156dp"
        android:layout_height="322dp"
        android:src="@drawable/constituency_mayo"
        tools:layout_editor_absoluteX="-21dp"
        tools:layout_editor_absoluteY="216dp" />

    <ImageView
        android:id="@+id/imgCorkSouthWest"
        android:layout_width="195dp"
        android:layout_height="149dp"
        android:src="@drawable/constituency_cork_south_west"
        tools:layout_editor_absoluteX="11dp"
        tools:layout_editor_absoluteY="600dp" />

    <ImageView
        android:id="@+id/imgKerry"
        android:layout_width="160dp"
        android:layout_height="165dp"
        android:src="@drawable/constituency_kerry_cut"
        app:layout_constraintStart_toStartOf="parent"
        tools:layout_editor_absoluteY="513dp" />

    <ImageView
        android:id="@+id/imgWicklow"
        android:layout_width="84dp"
        android:layout_height="180dp"
        android:src="@drawable/constituency_wicklow"
        tools:layout_editor_absoluteX="308dp"
        tools:layout_editor_absoluteY="439dp" />

    <ImageView
        android:id="@+id/imgWexford"
        android:layout_width="135dp"
        android:layout_height="285dp"
        android:layout_marginEnd="12dp"
        android:src="@drawable/constituency_wexford"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <ImageView
        android:id="@+id/imgWaterford"
        android:layout_width="108dp"
        android:layout_height="113dp"
        android:src="@drawable/constituency_waterford"
        tools:layout_editor_absoluteX="195dp"
        tools:layout_editor_absoluteY="594dp" />

    <ImageView
        android:id="@+id/imgDonegal"
        android:layout_width="205dp"
        android:layout_height="560dp"
        android:src="@drawable/constituency_donegal"
        tools:layout_editor_absoluteX="96dp"
        tools:layout_editor_absoluteY="-88dp"
        app:layout_constraintTop_toTopOf="0dp"
        />

    <ImageView
        android:id="@+id/imgLimerickCity"
        android:layout_width="37dp"
        android:layout_height="48dp"
        android:src="@drawable/constituency_limerick_city"
        tools:layout_editor_absoluteX="277dp"
        tools:layout_editor_absoluteY="263dp" />

    <ImageView
        android:id="@+id/imgLimerickCounty"
        android:layout_width="70dp"
        android:layout_height="42dp"
        android:src="@drawable/constituency_limerick_county"
        tools:layout_editor_absoluteX="112dp"
        tools:layout_editor_absoluteY="513dp" />

    <ImageView
        android:id="@+id/imgCorkNorthWest"
        android:layout_width="83dp"
        android:layout_height="130dp"
        android:src="@drawable/constituency_cork_north_west"
        tools:layout_editor_absoluteX="112dp"
        tools:layout_editor_absoluteY="548dp" />

    <ImageView
        android:id="@+id/imgCorkEast"
        android:layout_width="117dp"
        android:layout_height="80dp"
        android:src="@drawable/constituency_cork_east"
        tools:layout_editor_absoluteX="163dp"
        tools:layout_editor_absoluteY="590dp" />

    <ImageView
        android:id="@+id/imgCorkNorthCentral"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:src="@drawable/constituency_cork_north_central"
        tools:layout_editor_absoluteX="171dp"
        tools:layout_editor_absoluteY="611dp" />

    <ImageView
        android:id="@+id/imgCorkSouthCentral"
        android:layout_width="39dp"
        android:layout_height="43dp"
        android:src="@drawable/constituency_cork_south_central"
        tools:layout_editor_absoluteX="186dp"
        tools:layout_editor_absoluteY="627dp" />

    <ImageView
        android:id="@+id/imgCarlowKilkenny"
        android:layout_width="92dp"
        android:layout_height="207dp"
        android:src="@drawable/constituency_carlow_kilkenny"
        tools:layout_editor_absoluteX="236dp"
        tools:layout_editor_absoluteY="487dp"
        app:layout_constraintRight_toLeftOf="@id/imgWexford"/>

    <ImageView
        android:id="@+id/imgTipperary"
        android:layout_width="101dp"
        android:layout_height="225dp"
        android:src="@drawable/constituency_tipperary"
        tools:layout_editor_absoluteX="163dp"
        tools:layout_editor_absoluteY="394dp" />

    <ImageView
        android:id="@+id/imgKildareSouth"
        android:layout_width="74dp"
        android:layout_height="247dp"
        android:src="@drawable/constituency_kildare_south"
        tools:layout_editor_absoluteX="264dp"
        tools:layout_editor_absoluteY="372dp" />

    <ImageView
        android:id="@+id/imgLaoisOffaly"
        android:layout_width="110dp"
        android:layout_height="102dp"
        android:layout_marginEnd="11dp"
        android:layout_marginBottom="9dp"
        android:src="@drawable/constituency_laois_offaly"
        app:layout_constraintBottom_toTopOf="@+id/imgCorkNorthWest"
        app:layout_constraintEnd_toStartOf="@+id/imgWexford"
        app:layout_constraintStart_toEndOf="@+id/imgGalwayEast"
        app:layout_constraintTop_toBottomOf="@+id/imgLongfordWestmeath" />

    <ImageView
        android:id="@+id/imgKildareNorth"
        android:layout_width="61dp"
        android:layout_height="77dp"
        android:src="@drawable/constituency_kildare_north"
        tools:layout_editor_absoluteX="293dp"
        tools:layout_editor_absoluteY="428dp" />

    <ImageView
        android:id="@+id/imgMeathWest"
        android:layout_width="110dp"
        android:layout_height="67dp"
        android:src="@drawable/constituency_meath_west"
        tools:layout_editor_absoluteX="231dp"
        tools:layout_editor_absoluteY="394dp" />

    <ImageView
        android:id="@+id/imgLongfordWestmeath"
        android:layout_width="101dp"
        android:layout_height="100dp"
        android:src="@drawable/constituency_longford_westmeath"
        tools:layout_editor_absoluteX="186dp"
        tools:layout_editor_absoluteY="372dp" />

    <ImageView
        android:id="@+id/imgCavanMonoghan"
        android:layout_width="140dp"
        android:layout_height="230dp"
        android:src="@drawable/constituency_cavan_monoghan"
        tools:layout_editor_absoluteX="188dp"
        tools:layout_editor_absoluteY="234dp" />

    <ImageView
        android:id="@+id/imgMeathEast"
        android:layout_width="66dp"
        android:layout_height="98dp"
        android:src="@drawable/constituency_meath_east"
        tools:layout_editor_absoluteX="288dp"
        tools:layout_editor_absoluteY="366dp" />

    <ImageView
        android:id="@+id/imgLouth"
        android:layout_width="55dp"
        android:layout_height="90dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="48dp"
        android:layout_marginBottom="3dp"
        android:src="@drawable/constituency_louth"
        app:layout_constraintBottom_toTopOf="@+id/imgKildareNorth"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imgDonegal" />

    <ImageView
        android:id="@+id/imgSligoLeitrim"
        android:layout_width="117dp"
        android:layout_height="126dp"
        android:src="@drawable/constituency_sligo_leitirim"
        tools:layout_editor_absoluteX="89dp"
        tools:layout_editor_absoluteY="269dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>


来源: stackexchange

问:
check for end of execution of class in java
I have written a small program to validate 3 data files and convert them into a csv file.

-Every file is converted by a different class file

-There is a main class which instantiates all the other classes for processing files one after other

How do i make sure that the next file is processed only after the previous file is done?

The pseudocode for my program is as follows

```<code>mainExecute Class()
{
    executeFile1converter();
    executeFile2Converter();
    executeFile3Converter();
}
</code>```

答: They will execute in the specified order by definition. One row must finish executing before the next row starts. You seem to be talking about simultaneous execution, but you need additional explicit definitions to accompish that - i.e. executeFile1converter spawns a thread. Then you'll need an event fired when it completes.

ContentLicense: CC BY-SA 3.0

Body:
I have written a small program to validate 3 data files and convert them into a csv file.

-Every file is converted by a different class file

-There is a main class which instantiates all the other classes for processing files one after other

How do i make sure that the next file is processed only after the previous file is done?

The pseudocode for my program is as follows

mainExecute Class()
{
    executeFile1converter();
    executeFile2Converter();
    executeFile3Converter();
}


问:
AttributeError: module 'tensorflow_core.compat.v1' has no attribute 'contrib'
```<code>x = tf.placeholder(dtype = tf.float32, shape = [None, 28, 28])
y = tf.placeholder(dtype = tf.int32, shape = [None])
images_flat = tf.contrib.layers.flatten(x)
logits = tf.contrib.layers.fully_connected(images_flat, 62, tf.nn.relu)
loss =
tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
   labels = y, logits = logits))
   train_op =
   tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
   correct_pred = tf.argmax(logits, 1)
   accuracy = tf.reduce_mean(tf.cast(correct_pred,
   tf.float32))

   print("images_flat: ", images_flat)
   print("logits: ", logits)
   print("loss: ", loss)
   print("predicted_labels: ", correct_pred)

AttributeError                            Traceback (most recent call last)
<ipython-input-17-183722ce66a3> in <module>
      1 x = tf.placeholder(dtype = tf.float32, shape = [None, 28, 28])
      2 y = tf.placeholder(dtype = tf.int32, shape = [None])
----> 3 images_flat = tf.contrib.layers.flatten(x)
      4 logits = tf.contrib.layers.fully_connected(images_flat, 62, tf.nn.relu)
      5 loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels = y, logits = logits))

AttributeError: module 'tensorflow_core.compat.v1' has no attribute 'contrib'
</code>```

2.This is my code in Jupyter Notebook.
I just started with python and get the error I mentioned in the headline. I would be very thankful if someone could help me wizh a code example to solve the problem.

答:
I think you need to add the following line in your python file which you are going to execute it.

```<code>import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
x = tf.placeholder(dtype = tf.float32, shape = [None, 28, 28])
y = tf.placeholder(dtype = tf.int32, shape = [None])
images_flat = tf.contrib.layers.flatten(x)
logits = tf.contrib.layers.fully_connected(images_flat, 62, tf.nn.relu)
loss =
tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
   labels = y, logits = logits))
   train_op =
   tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
   correct_pred = tf.argmax(logits, 1)
   accuracy = tf.reduce_mean(tf.cast(correct_pred,
   tf.float32))

   print("images_flat: ", images_flat)
   print("logits: ", logits)
   print("loss: ", loss)
   print("predicted_labels: ", correct_pred)

AttributeError                            Traceback (most recent call last)
<ipython-input-17-183722ce66a3> in <module>
      1 x = tf.placeholder(dtype = tf.float32, shape = [None, 28, 28])
      2 y = tf.placeholder(dtype = tf.int32, shape = [None])
----> 3 images_flat = tf.contrib.layers.flatten(x)
      4 logits = tf.contrib.layers.fully_connected(images_flat, 62, tf.nn.relu)
      5 loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels = y, logits = logits))

AttributeError: module 'tensorflow_core.compat.v1' has no attribute 'contrib'

2.This is my code in Jupyter Notebook.
I just started with python and get the error I mentioned in the headline. I would be very thankful if someone could help me wizh a code example to solve the problem.

Body:
I think you need to add the following line in your python file which you are going to execute it.

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()


问:
how can filter data of calender in c# according to room names?
How can I filter my events of outlook according to room name?

```<code>var queryOptions1 = new List<QueryOption>()
{
  new QueryOption("startDateTime", starttimeluis ),
  new QueryOption("endDateTime", Endtimeluis)

};
var calendarView1 = await graphClient.Me.Calendar.CalendarView
                            .Request(queryOptions1)
                            .GetAsync();

</code>```

I want to filter calendar event data according to room name, how to do a query in c#.net?

答:
You could try following code snippet

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var findRooms = await graphClient.Me
    .FindRooms("Building2Rooms@YourOrganization.onmicrosoft.com")
    .Request()
    .GetAsync();
```

<p>As it is <code>Microsoft Graph beta version</code> so you have install <code>Microsoft.Graph.Beta package</code>. See the below screen shot</p>

<p><img src="https://i.stack.imgur.com/lbpGc.png" alt="enter image description here"></p>

<p>For more details please refer to official docs</p>

<p><strong><em>Update:</em></strong> </p>

<p>You could <code>$filter</code> your query like this format:</p>

```            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=ReceivedDateTime ge 2017-04-01 and receivedDateTime lt 2017-05-01");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFRQUJBQUFB");
            HttpResponseMessage response = await client.SendAsync(request);

            string output = await response.Content.ReadAsStringAsync();
```

Body:
How can I filter my events of outlook according to room name?

var queryOptions1 = new List<QueryOption>()
{
  new QueryOption("startDateTime", starttimeluis ),
  new QueryOption("endDateTime", Endtimeluis)

};
var calendarView1 = await graphClient.Me.Calendar.CalendarView
                            .Request(queryOptions1)
                            .GetAsync();

I want to filter calendar event data according to room name, how to do a query in c#.net?

Body:
You could try following code snippet

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var findRooms = await graphClient.Me
    .FindRooms("Building2Rooms@YourOrganization.onmicrosoft.com")
    .Request()
    .GetAsync();

As it is Microsoft Graph beta version so you have install Microsoft.Graph.Beta package. See the below screen shot

For more details please refer to official docs

Update:

You could $filter your query like this format:

            HttpClient client = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages?$filter=ReceivedDateTime ge 2017-04-01 and receivedDateTime lt 2017-05-01");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFRQUJBQUFB");
            HttpResponseMessage response = await client.SendAsync(request);

            string output = await response.Content.ReadAsStringAsync();


问:
Cannot import onnxruntime in python Windows
I am trying to run onnxruntime model on CPU laptop… but I get an error when trying to import onnxruntime…

Has anyone tried to use this module?

```<code>C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\onnxrunti
me\capi\_pybind_state.py:13: UserWarning: Cannot load onnxruntime.capi. Error: '
DLL load failed: The specified procedure could not be found.'
  warnings.warn("Cannot load onnxruntime.capi. Error: '{0}'".format(str(e)))
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import onnxruntime
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\o
nnxruntime\__init__.py", line 12, in <module>
    from onnxruntime.capi._pybind_state import get_all_providers, get_available_
providers, get_device, RunOptions, SessionOptions, set_default_logger_severity,
NodeArg, ModelMetadata, GraphOptimizationLevel, ExecutionMode
ImportError: cannot import name 'get_all_providers' from 'onnxruntime.capi._pybi
nd_state' (C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-package
s\onnxruntime\capi\_pybind_state.py)
</code>```

答:
see the failure - "DLL load failed: The specified procedure could not be found"
. I don't know how it is in windows, but in linux you need to add the lib path to the environment variable "LD_LIBRARY_PATH=path_to_lib"... (in windows I think you need to set the PATH: C:> set PATH=%PATH%;full_path_here;...).
First check that you have the lib. In the onnx folder (you should be in C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-package
s\onnxruntime) check which lib python is trying to load: C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-package
s\onnxruntime\capi_pybind_state.py their is a line :

```<code>try:
    from onnxruntime.capi.onnxruntime_pybind11_state import *
</code>```

Check that you have onnxruntime_pybind11_state lib somewhere in the onnxruntime folder.
Iif you have it - than adding the onnxruntime folder to the env lib path should do it....

Body:
I am trying to run onnxruntime model on CPU laptop… but I get an error when trying to import onnxruntime…

Has anyone tried to use this module?

C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\onnxrunti
me\capi\_pybind_state.py:13: UserWarning: Cannot load onnxruntime.capi. Error: '
DLL load failed: The specified procedure could not be found.'
  warnings.warn("Cannot load onnxruntime.capi. Error: '{0}'".format(str(e)))
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import onnxruntime
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\o
nnxruntime\__init__.py", line 12, in <module>
    from onnxruntime.capi._pybind_state import get_all_providers, get_available_
providers, get_device, RunOptions, SessionOptions, set_default_logger_severity,
NodeArg, ModelMetadata, GraphOptimizationLevel, ExecutionMode
ImportError: cannot import name 'get_all_providers' from 'onnxruntime.capi._pybi
nd_state' (C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-package
s\onnxruntime\capi\_pybind_state.py)

Body:
see the failure - "DLL load failed: The specified procedure could not be found"
. I don't know how it is in windows, but in linux you need to add the lib path to the environment variable "LD_LIBRARY_PATH=path_to_lib"... (in windows I think you need to set the PATH: C:> set PATH=%PATH%;full_path_here;...).
First check that you have the lib. In the onnx folder (you should be in C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-package
s\onnxruntime) check which lib python is trying to load: C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-package
s\onnxruntime\capi_pybind_state.py their is a line :

try:
    from onnxruntime.capi.onnxruntime_pybind11_state import *

Check that you have onnxruntime_pybind11_state lib somewhere in the onnxruntime folder.
Iif you have it - than adding the onnxruntime folder to the env lib path should do it....


答:
@Guy's solution has one side-effect. It makes list flatten.

This could be more suitable.

```<code>l_b = [[['%.2f' % z for z in y] for y in x] for x in l_b]
</code>```

Title: How to round floats in a nested list to 2 decimal places?

Body:
I have coordinate lists of several polygons as listed below:

l_b =  [[[57.5, 2.875],
   [83.75, 4.1875],
   [83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 2.875]],
  [[83.75, 18.70923913043478],
   [57.50000000000001, 18.70923913043478],
   [57.5, 34.08695652173913],
   [83.75, 34.54347826086956],
   [83.75, 18.70923913043478]],
  [[0.0, 0.0],
   [18.125, 0.90625],
   [18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [0.0, 0.0]],
  [[18.125, 16.70108695652174],
   [-2.530467720685112, 16.70108695652174],
   [-5.0, 33.0],
   [18.125, 33.40217391304348],
   [18.125, 16.70108695652174]]]

How can I make all the numbers in list to round to 2 decimal places while keeping its format?

I've tried l_b = [ '%.2f' % elem for elem in l_b ] but it's giving me TypeError: must be real number, not list

Body:
@Guy's solution has one side-effect. It makes list flatten.

This could be more suitable.

l_b = [[['%.2f' % z for z in y] for y in x] for x in l_b]


问:
replacing nan dates using a date range
I have a dataframe that has two columnns: date and number of passesngers. The date column has dates ranges from 1950 to 2019. However some dates are recorded as 1600 which is definetly an error. When i try to change the date object to datetimeindex i get an out of bounds error which makes sense. So i decided to first replace the 1600 dates with nan values instead

```<code>new_set=drop_dup.replace(to_replace =["1610-01-01", "1610/01/01"],
             value = np.nan)
</code>```

This was just a temporary fix to change the date obect into datetimeindex. The dates with 1600 as a value are about 27 and i didnt want to change them to a single value. Instead i want to replace those nan values with a certain date range i.e from 1955 - 1982. The below code does not work but i was aiming for something like that

```<code>new_set=drop_dup.replace(to_replace =np.nan, value = pd.date_range(start='1-1-1955', end='1-1-1982', freq='12M')
</code>```

So the 27 1600 dates should range from the period 1955 to 1982

Title: replacing nan dates using a date range

Body:
I have a dataframe that has two columnns: date and number of passesngers. The date column has dates ranges from 1950 to 2019. However some dates are recorded as 1600 which is definetly an error. When i try to change the date object to datetimeindex i get an out of bounds error which makes sense. So i decided to first replace the 1600 dates with nan values instead

new_set=drop_dup.replace(to_replace =["1610-01-01", "1610/01/01"],
             value = np.nan)

This was just a temporary fix to change the date obect into datetimeindex. The dates with 1600 as a value are about 27 and i didnt want to change them to a single value. Instead i want to replace those nan values with a certain date range i.e from 1955 - 1982. The below code does not work but i was aiming for something like that

new_set=drop_dup.replace(to_replace =np.nan, value = pd.date_range(start='1-1-1955', end='1-1-1982', freq='12M')

So the 27 1600 dates should range from the period 1955 to 1982

Body:
Sample data:

df = pd.DataFrame({'date': pd.to_datetime([np.nan] * 10 +
                                          ['2000-01-31','2001-01-31','2002-01-31'])})
print (df)
         date
0         NaT
1         NaT
2         NaT
3         NaT
4         NaT
5         NaT
6         NaT
7         NaT
8         NaT
9         NaT
10 2000-01-31
11 2001-01-31
12 2002-01-31

First idea is create mask for missing data and append date_range without end parameter, but with period by number of missing values created by sum:

m = df['date'].isna()
df.loc[m, 'date'] = pd.date_range(start='1-1-1955', freq='12M', periods=m.sum())
print (df)
         date
0  1955-01-31
1  1956-01-31
2  1957-01-31
3  1958-01-31
4  1959-01-31
5  1960-01-31
6  1961-01-31
7  1962-01-31
8  1963-01-31
9  1964-01-31
10 2000-01-31
11 2001-01-31
12 2002-01-31

Another idea is remove start and to parameter end is added minimal date and to period also count of missing values:

m = df['date'].isna()
df.loc[m, 'date'] = pd.date_range(end=df['date'].min(), freq='12M', periods=m.sum())
print (df)
         date
0  1991-01-31
1  1992-01-31
2  1993-01-31
3  1994-01-31
4  1995-01-31
5  1996-01-31
6  1997-01-31
7  1998-01-31
8  1999-01-31
9  2000-01-31
10 2000-01-31
11 2001-01-31
12 2002-01-31


问:
Python for loop for list
I have a list containing some integer values.

My list is l = [5,10,15,25,30,45].

I want to write a program that the values in list is between 5 to 35

```<code>list1 = [15,35]
list2 = ['Height','Weight','5','10','25','30','40']
res = [int(ele) if ele.isdigit() else ele for ele in list2]
print([ x for x in res if type(x)==int ])
</code>```

this is the code that I written,now I want to compare list 1 and list 2 , then print values in list 2 of range in the first list

Title: Python for loop for list

Body:
I have a list containing some integer values.

My list is l = [5,10,15,25,30,45].

I want to write a program that the values in list is between 5 to 35

list1 = [15,35]
list2 = ['Height','Weight','5','10','25','30','40']
res = [int(ele) if ele.isdigit() else ele for ele in list2]
print([ x for x in res if type(x)==int ])

this is the code that I written,now I want to compare list 1 and list 2 , then print values in list 2 of range in the first list

Body:
You can use range function

>>> l = [5,10,15,25,30,45]
>>> result = [i for i in l if i in range(5,36)]
>>> result
[5, 10, 15, 25, 30]


答:
Code execution is linear if you don't introduce concurrency yourself. So just calling the things one after the other is enough.

Unless of course you're calling into libraries that process data asynchronously, but then they should have APIs that let you know when they're done.

Title: check for end of execution of class in java


问:
Most elegant way to start several scotty servers in the same application?
Is there a standard way to start two scotty servers in the same application? In a toy project I'm trying:

main :: IO ()
main = do
  scotty 3000 $ do
    get "/" $ do
      text "hello"
  scotty 4000 $ do
    post "/" $ do
      text "world"
```

The first server spins up but the second one does not. It could also be a flaw in the way I'm understanding Haskell IO. Thanks!

答:
The scotty procedure does not return, it takes over control and continually serves requests to the webroutes.  If it did return then you'd have an issue with control flow - how would you keep the port open for when a request arrived?

One solution is to put each call to scotty in a separate thread.  For example:

```<code>#!/usr/bin/env cabal
{- cabal:
     build-depends: base, scotty
-}
{-# LANGUAGE OverloadedStrings #-}

import Control.Concurrent
import Web.Scotty

main :: IO ()
main = do
  forkIO $ scotty 3000 $ do
    get "/" $ do
      text "hello"
  scotty 4000 $ do
    post "/" $ do
      text "world"
</code>```

With operation of:

```<code>% curl -XPOST localhost:4000
world%
% curl -XGET localhost:3000
hello%
</code>```

Body:
Is there a standard way to start two scotty servers in the same application? In a toy project I'm trying:

main :: IO ()
main = do
  scotty 3000 $ do
    get "/" $ do
      text "hello"
  scotty 4000 $ do
    post "/" $ do
      text "world"

The first server spins up but the second one does not. It could also be a flaw in the way I'm understanding Haskell IO. Thanks!

Body:
The scotty procedure does not return, it takes over control and continually serves requests to the webroutes.  If it did return then you'd have an issue with control flow - how would you keep the port open for when a request arrived?

One solution is to put each call to scotty in a separate thread.  For example:

#!/usr/bin/env cabal
{- cabal:
     build-depends: base, scotty
-}
{-# LANGUAGE OverloadedStrings #-}

import Control.Concurrent
import Web.Scotty

main :: IO ()
main = do
  forkIO $ scotty 3000 $ do
    get "/" $ do
      text "hello"
  scotty 4000 $ do
    post "/" $ do
      text "world"

With operation of:

% curl -XPOST localhost:4000
world%
% curl -XGET localhost:3000
hello%


问:
SpringBoot JPA persist child of parent with nulls columns
I have strange problem. I have entity Company, Branch and Address.
Company has list of branch and every branch has address.
Im trying to persist branch with not exist before address entity, but Address is persist with nulls columns.

```<code>@Data
@Entity
@Indexed
@Table(name = "company")
public class Company {

    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
            name = "UUID",
            strategy = "org.hibernate.id.UUIDGenerator"
    )
    private String id;

    @Field
    @Column(name = "full_name", nullable = false, unique = true)
    private String fullName;

    @OneToMany(mappedBy = "company")
    private Set<Branch> branches;

}
</code>```

```<code>@Data
@Entity
@Table(name = "branch")
public class Branch {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column
    private String phone;

    @Column
    private String email;

    @OneToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "address_id", referencedColumnName = "id")
    private Address address;

    @ManyToOne
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private Company company;
}
</code>```

```<code>@Entity
@Table(name = "address")
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column
    private String street;

    @OneToOne(mappedBy = "address")
    private Company company;

    @OneToOne(mappedBy = "address")
    private Branch branch;
}
</code>```

Service ...

```<code>    public Integer addBranch(BranchDto branchDto) {
        Branch branch = modelMapper.map(branchDto, Branch.class);

        Company company = companyRepository.getCompanyById(branchDto.getCompanyId());
        branch.setCompany(company);

        return branchRepository.save(branch).getId();
    }
</code>```

Dto...

```<code>@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BranchDto {

    private Integer id;

    private String phone;

    private String email;

    private AddressDto address;

    private String companyId;
}
</code>```

And that is effect...

Debugger...

What is the problem? Can you help me ?

答:
You are using 'mappedBy' with the same id, It only works with the first one he find.

Try to change to other id.

Body:
I have strange problem. I have entity Company, Branch and Address.
Company has list of branch and every branch has address.
Im trying to persist branch with not exist before address entity, but Address is persist with nulls columns.

@Data
@Entity
@Indexed
@Table(name = "company")
public class Company {

    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
            name = "UUID",
            strategy = "org.hibernate.id.UUIDGenerator"
    )
    private String id;

    @Field
    @Column(name = "full_name", nullable = false, unique = true)
    private String fullName;

    @OneToMany(mappedBy = "company")
    private Set<Branch> branches;

}

@Data
@Entity
@Table(name = "branch")
public class Branch {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column
    private String phone;

    @Column
    private String email;

    @OneToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "address_id", referencedColumnName = "id")
    private Address address;

    @ManyToOne
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    private Company company;
}

@Entity
@Table(name = "address")
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column
    private String street;

    @OneToOne(mappedBy = "address")
    private Company company;

    @OneToOne(mappedBy = "address")
    private Branch branch;
}

Service ...

    public Integer addBranch(BranchDto branchDto) {
        Branch branch = modelMapper.map(branchDto, Branch.class);

        Company company = companyRepository.getCompanyById(branchDto.getCompanyId());
        branch.setCompany(company);

        return branchRepository.save(branch).getId();
    }

Dto...

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BranchDto {

    private Integer id;

    private String phone;

    private String email;

    private AddressDto address;

    private String companyId;
}

And that is effect...

Debugger...

What is the problem? Can you help me ?


问:
Typescript type for getting class properties from static method on a parent class
Let's say you have these two classes:

```<code>class Form {
    static fields(){
       return []; // some magic happens here
    }
}

class UserForm extends Form{
    email: string;
}

const formFields = UserForm.fields();
</code>```

What type can I add for the static fields method in order to get a list of UserForm properties, in this case, only the email property as ("email")[]?

I tried using keyof T but it doesn't give me the desired answer:

```<code>static fields<T>(this: T): (keyof T)[] {
       return []; // some magic happens here
    }
</code>```

This returns ("prototype" | "fields")[] instead of ("email")[].

Do you have any ideas on how to solve this?

Thank you!

答:
You can create a new instance of this and return Object.getOwnPropertyNames(instance)

```<code>class Form {
    foo: string = 'bar'
    static fields<T>(): (keyof T)[]{
       return Object.getOwnPropertyNames(new this) as (keyof T)[]
    }
}

class UserForm extends Form{
    email: string = '';
}

const formFields = UserForm.fields<UserForm>();
console.log(formFields)
</code>```

Working repl.it project: https://repl.it/@HarunYlmaz/ts-property-list

Body:
Let's say you have these two classes:

class Form {
    static fields(){
       return []; // some magic happens here
    }
}

class UserForm extends Form{
    email: string;
}

const formFields = UserForm.fields();

What type can I add for the static fields method in order to get a list of UserForm properties, in this case, only the email property as ("email")[]?

I tried using keyof T but it doesn't give me the desired answer:

static fields<T>(this: T): (keyof T)[] {
       return []; // some magic happens here
    }

This returns ("prototype" | "fields")[] instead of ("email")[].

Do you have any ideas on how to solve this?

Thank you!

Body:
You can create a new instance of this and return Object.getOwnPropertyNames(instance)

class Form {
    foo: string = 'bar'
    static fields<T>(): (keyof T)[]{
       return Object.getOwnPropertyNames(new this) as (keyof T)[]
    }
}

class UserForm extends Form{
    email: string = '';
}

const formFields = UserForm.fields<UserForm>();
console.log(formFields)

Working repl.it project: https://repl.it/@HarunYlmaz/ts-property-list


问:
https for localhost:8080
I am trying to develop a facebook app written in Python running on Google App Engine, so i need to make my http://localhost:8080 to https://localhost:8080 since facebook is asking for a Secure Canvas URL
how can i make https in localhost:8080 ?</p>

答:
Have a look here . I think this will answer your question

Add this to your app.yaml

```<code>handlers:

- url: #url
  script: #script
  login: required
  secure: always
</code>```

more reference here

Title: https for localhost:8080

Body:
Have a look here . I think this will answer your question

Add this to your app.yaml

handlers:

- url: #url
  script: #script
  login: required
  secure: always

more reference here


问:
Why does Drools throw an IllegalAccessError when jitting?
I'm getting the following stack trace when using drools (latest version - 7.32):

"stack_trace":"java.lang.IllegalAccessError:
  org/drools/core/rule/constraint/ASMConditionEvaluatorJitter$EvaluateMethodGenerator$CoercingComparisonType
  at ConditionEvaluator5003d21b2c7846fb81f75c4b75fe103a.evaluate(Unknown
  Source) at
  org.drools.core.rule.constraint.MvelConstraint.evaluate(MvelConstraint.java:275)

The error seems to occur randomly, and restarting the application fixes it (at least for a time). I tried updating to the latest drools version as I could see recent activity in the class (https://github.com/kiegroup/drools/commits/master/drools-core/src/main/java/org/drools/core/rule/constraint/ASMConditionEvaluatorJitter.java) - but it didn't help.

Does anyone know what might cause this kind of stack trace? (bearing in mind it works find after restart or recreating the same kbase). Thank you.

答:
No, without more details we cannot investigate.

File a bug on https://issues.jboss.org/ and provide us a reproducer please.

Thank you


问:
Unhandled exception: Bad state: Future already completed
Running some very simple code but got this Unhandled exception which I have no idea what's going on since I'm quite new to this language.

The problem happened probably because I'm based in China. I have checked https://flutter.dev/community/china , and followed their steps. But I'm just not quite sure if everything I did was 100% right since I'm not really familiar with all the coding terminologies yet(
This is just my guessing, probably this isn't the reason why I'm getting this Unhandled exception error.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.red,
        body: Container(),
      ),
    );
  }
}
```

```Unhandled exception:
Bad state: Future already completed
#0      _AsyncCompleter.complete (dart:async/future_impl.dart:39:31)
#1      _NativeSocket.startConnect.<anonymous closure>.connectNext.<anonymous closure> (dart:io-patch/socket_patch.dart:508:23)
#2      _NativeSocket.issueWriteEvent.issue (dart:io-patch/socket_patch.dart:862:14)
#3      _NativeSocket.issueWriteEvent (dart:io-patch/socket_patch.dart:869:12)
#4      _NativeSocket.multiplex (dart:io-patch/socket_patch.dart:890:11)
#5      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
```

答: I think you have use the VPN connection.</p>

Body:
Running some very simple code but got this Unhandled exception which I have no idea what's going on since I'm quite new to this language.

The problem happened probably because I'm based in China. I have checked https://flutter.dev/community/china , and followed their steps. But I'm just not quite sure if everything I did was 100% right since I'm not really familiar with all the coding terminologies yet(
This is just my guessing, probably this isn't the reason why I'm getting this Unhandled exception error.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.red,
        body: Container(),
      ),
    );
  }
}

Unhandled exception:
Bad state: Future already completed
#0      _AsyncCompleter.complete (dart:async/future_impl.dart:39:31)
#1      _NativeSocket.startConnect.<anonymous closure>.connectNext.<anonymous closure> (dart:io-patch/socket_patch.dart:508:23)
#2      _NativeSocket.issueWriteEvent.issue (dart:io-patch/socket_patch.dart:862:14)
#3      _NativeSocket.issueWriteEvent (dart:io-patch/socket_patch.dart:869:12)
#4      _NativeSocket.multiplex (dart:io-patch/socket_patch.dart:890:11)
#5      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)


问:
How does one mock.patch a function inside a Flask Blueprint?
I'm trying to use the unittest.mock library to patch a function inside a Flask Blueprint. Specifically, I'm trying to patch the os module inside the blueprint. Simplified code (cannot provide all/actual code):

test_route.py (the test I am trying to run)

```<code>import unittest
from unittest import mock

from server.index import create_app as Server

class TestRoute(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.server = Server()
        cls.server.config['TESTING'] = True
        cls.client = cls.server.test_client()
        #
        # more code...
        #
    @mock.patch('server.routes.blueprint.os')
    def test_route(self, mockOS):
        mockOS.listdir.return_value = ['/mockedvalue']
        res = client.post('/some/url')
        #
        # more code...
        #

</code>```

server/index.py (the module to create the Flask server)

```<code>from flask import Flask
from routes.blueprint import bp

def create_app():
    app = Flask(__name__)
    app.register_blueprint(bp)
    #
    # more code...
    #
</code>```

server/routes/blueprint.py (the Blueprint logic used by the Flask server)

```<code>import os
from flask import Flask, Blueprint

bp = Blueprint('bp', __name__)

@bp.route('/some/url')
def run():
    #
    # code...
    #

    dirs = os.listdir('/some/path')

    #
    # more code...
    #
</code>```

When I run this, os.listdir() is not getting patched. I get the actual contents of '/some/path' when what I really want is the mocked value:

```<code>    Actual   : ['/something1', '/some/other/thing', ...]
    Expected : ['/mockedvalue']
</code>```

I've read https://docs.python.org/3/library/unittest.mock.html#where-to-patch , but maybe I am still making a mistake. It seems appropriate to patch at the blueprint module, but if this is incorrect, any guidance or corrections would be appreciated.

答:
what is happening if you set

    @mock.patch('server.routes.blueprint.os')
    def test_route(self, mockOS):
        with Server.app.app_context():
            mockOS.listdir.return_value = ['/mockedvalue']
            res = client.post('/some/url')
```

Body:
I'm trying to use the unittest.mock library to patch a function inside a Flask Blueprint. Specifically, I'm trying to patch the os module inside the blueprint. Simplified code (cannot provide all/actual code):

test_route.py (the test I am trying to run)

import unittest
from unittest import mock

from server.index import create_app as Server

class TestRoute(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.server = Server()
        cls.server.config['TESTING'] = True
        cls.client = cls.server.test_client()
        #
        # more code...
        #
    @mock.patch('server.routes.blueprint.os')
    def test_route(self, mockOS):
        mockOS.listdir.return_value = ['/mockedvalue']
        res = client.post('/some/url')
        #
        # more code...
        #

server/index.py (the module to create the Flask server)

from flask import Flask
from routes.blueprint import bp

def create_app():
    app = Flask(__name__)
    app.register_blueprint(bp)
    #
    # more code...
    #

server/routes/blueprint.py (the Blueprint logic used by the Flask server)

import os
from flask import Flask, Blueprint

bp = Blueprint('bp', __name__)

@bp.route('/some/url')
def run():
    #
    # code...
    #

    dirs = os.listdir('/some/path')

    #
    # more code...
    #

When I run this, os.listdir() is not getting patched. I get the actual contents of '/some/path' when what I really want is the mocked value:

    Actual   : ['/something1', '/some/other/thing', ...]
    Expected : ['/mockedvalue']

I've read https://docs.python.org/3/library/unittest.mock.html#where-to-patch , but maybe I am still making a mistake. It seems appropriate to patch at the blueprint module, but if this is incorrect, any guidance or corrections would be appreciated.


问:
unindent does not match any outer indentation level 1
i am using python3 to compline this code , but whenever i do so , it gives me the error

unindent does not match any outer indentation level, i need help below is my codes

```<code>import torch
import torchvision
import cv2
import PIL
from torch.autograd import Variable
from data import BaseTransform, VOC_CLASSES as labelmap
from ssd import build_ssd
import imageio

def detect(frame, net, tansform):
      height, width = frame.shape[:2]
      frame_t =transform(frame)[0]
      x = torch.from_numpy(frame_t).permute(2, 0, 1)
      x = Variable(x.unsequeeze(0))
      y = net(x)
      detections = y.data
      scale = torch.Tensor([width, height, width, height])

      for 1 in range(detections.size(1)):
          j = 0
          while detections(0, i, j, 0) >=0.6:
              pt = (detections[0, i, j, 1:]*scale)
              cv2.rectangle(frame, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])),(255, 0, 0), 2)
              cv2.putText(frame, labelmap[i - 1], (int(pt[0]), int(pt[1])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 2, cv2.LINE_AA)
              j +=1
              return frame

            net = build_ssd('test')
            net.load_state_dict(torch.load('ssd300_mAP_77.43_v2.pth', map_location=lambda storage, loc: storage))

            transform = BaseTransform(net.size, (104/256.0,117/256.0,123/256.0))

                                reader=imageio.get_reader(funny_dog.mp4)
                                fps = reader.get_meta_data()['fps']
                                writer = imageio.get_writer('output.mp4',fps = fps)
            for i, frame in enumerate(reader):
                        frame = detect(frame, net.eval(), transform)
                    writer.append_data(frame)
                    print(i)
                writer.close()
</code>```

答:
These lines don't look like they're indented correctly:

```<code>net = build_ssd('test')
net.load_state_dict(torch.load('ssd300_mAP_77.43_v2.pth', map_location=lambda storage, loc: storage))
</code>```

Here is the code indented correctly:

```<code>import torch
import torchvision
import cv2
import PIL
from torch.autograd import Variable
from data import BaseTransform, VOC_CLASSES as labelmap
from ssd import build_ssd
import imageio

def detect(frame, net, tansform):
    height, width = frame.shape[:2]
    frame_t = transform(frame)[0]
    x = torch.from_numpy(frame_t).permute(2, 0, 1)
    x = Variable(x.unsequeeze(0))
    y = net(x)
    detections = y.data
    scale = torch.Tensor([width, height, width, height])

    for 1 in range(detections.size(1)):
        j = 0
        while detections(0, i, j, 0) >= 0.6:
            pt = (detections[0, i, j, 1:] * scale)
            cv2.rectangle(frame, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])), (255, 0, 0), 2)
            cv2.putText(frame, labelmap[i - 1], (int(pt[0]), int(pt[1])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255),
                        2, cv2.LINE_AA)
            j += 1
            return frame

        net = build_ssd('test')
        net.load_state_dict(torch.load('ssd300_mAP_77.43_v2.pth', map_location=lambda storage, loc: storage))

        transform = BaseTransform(net.size, (104 / 256.0, 117 / 256.0, 123 / 256.0))

        reader = imageio.get_reader(funny_dog.mp4)
        fps = reader.get_meta_data()['fps']
        writer = imageio.get_writer('output.mp4', fps=fps)
    for i, frame in enumerate(reader):
        frame = detect(frame, net.eval(), transform)
    writer.append_data(frame)
    print(i)

writer.close()
</code>```

Body:
i am using python3 to compline this code , but whenever i do so , it gives me the error

unindent does not match any outer indentation level, i need help below is my codes

import torch
import torchvision
import cv2
import PIL
from torch.autograd import Variable
from data import BaseTransform, VOC_CLASSES as labelmap
from ssd import build_ssd
import imageio

def detect(frame, net, tansform):
      height, width = frame.shape[:2]
      frame_t =transform(frame)[0]
      x = torch.from_numpy(frame_t).permute(2, 0, 1)
      x = Variable(x.unsequeeze(0))
      y = net(x)
      detections = y.data
      scale = torch.Tensor([width, height, width, height])

      for 1 in range(detections.size(1)):
          j = 0
          while detections(0, i, j, 0) >=0.6:
              pt = (detections[0, i, j, 1:]*scale)
              cv2.rectangle(frame, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])),(255, 0, 0), 2)
              cv2.putText(frame, labelmap[i - 1], (int(pt[0]), int(pt[1])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 2, cv2.LINE_AA)
              j +=1
              return frame

            net = build_ssd('test')
            net.load_state_dict(torch.load('ssd300_mAP_77.43_v2.pth', map_location=lambda storage, loc: storage))

            transform = BaseTransform(net.size, (104/256.0,117/256.0,123/256.0))

                                reader=imageio.get_reader(funny_dog.mp4)
                                fps = reader.get_meta_data()['fps']
                                writer = imageio.get_writer('output.mp4',fps = fps)
            for i, frame in enumerate(reader):
                        frame = detect(frame, net.eval(), transform)
                    writer.append_data(frame)
                    print(i)
                writer.close()

Body:
These lines don't look like they're indented correctly:

net = build_ssd('test')
net.load_state_dict(torch.load('ssd300_mAP_77.43_v2.pth', map_location=lambda storage, loc: storage))

Here is the code indented correctly:

import torch
import torchvision
import cv2
import PIL
from torch.autograd import Variable
from data import BaseTransform, VOC_CLASSES as labelmap
from ssd import build_ssd
import imageio

def detect(frame, net, tansform):
    height, width = frame.shape[:2]
    frame_t = transform(frame)[0]
    x = torch.from_numpy(frame_t).permute(2, 0, 1)
    x = Variable(x.unsequeeze(0))
    y = net(x)
    detections = y.data
    scale = torch.Tensor([width, height, width, height])

    for 1 in range(detections.size(1)):
        j = 0
        while detections(0, i, j, 0) >= 0.6:
            pt = (detections[0, i, j, 1:] * scale)
            cv2.rectangle(frame, (int(pt[0]), int(pt[1])), (int(pt[2]), int(pt[3])), (255, 0, 0), 2)
            cv2.putText(frame, labelmap[i - 1], (int(pt[0]), int(pt[1])), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255),
                        2, cv2.LINE_AA)
            j += 1
            return frame

        net = build_ssd('test')
        net.load_state_dict(torch.load('ssd300_mAP_77.43_v2.pth', map_location=lambda storage, loc: storage))

        transform = BaseTransform(net.size, (104 / 256.0, 117 / 256.0, 123 / 256.0))

        reader = imageio.get_reader(funny_dog.mp4)
        fps = reader.get_meta_data()['fps']
        writer = imageio.get_writer('output.mp4', fps=fps)
    for i, frame in enumerate(reader):
        frame = detect(frame, net.eval(), transform)
    writer.append_data(frame)
    print(i)

writer.close()


问:
Adding ng-controller stops AngularJS
With the below HTML AngularJS is invoked and the webpage prints "5" as the result of {{10/2}} in the "body".

```<code><!DOCTYPE html>
<html ng-app>
<head>
    <title>AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
    <script src="script.js"></script>
</head>

<body>
    <h2>hello angular</h2>
    {{ 10/2 }}
</body>
</html>
</code>```

When I add an ng-controller:

```<code><!DOCTYPE html>
<html ng-app>
<head>
    <title>AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
    <script src="script.js"></script>
</head>

<body ng-controller="MainController">
    <h2>hello angular</h2>
    {{ 10/2 }}
</body>
</html>
</code>```

with the script.js:

```<code>var MainController = function($scope){

    $scope.message = "Hello!"
}
</code>```

AngularJS stops working and the webpage prints {{10/2}} instead of 5. What am I doing wrong here? Thanks.

答:
In script.js, change

```<code>var MainController = function($scope){

    $scope.message = "Hello!"
}
</code>```

to

```<code>app.controller('MainController', function($scope) {

  $scope.message = "Hello!"

});
</code>```

Working Plunker

Title: Adding ng-controller stops AngularJS

Body:
With the below HTML AngularJS is invoked and the webpage prints "5" as the result of {{10/2}} in the "body".

<!DOCTYPE html>

    <title>AngularJS</title>

hello angular

    {{ 10/2 }}

When I add an ng-controller:

<!DOCTYPE html>

    <title>AngularJS</title>

hello angular

    {{ 10/2 }}

with the script.js:

var MainController = function($scope){

    $scope.message = "Hello!"
}

AngularJS stops working and the webpage prints {{10/2}} instead of 5. What am I doing wrong here? Thanks.

Body:
In script.js, change

var MainController = function($scope){

    $scope.message = "Hello!"
}

to

app.controller('MainController', function($scope) {

  $scope.message = "Hello!"

});

Working Plunker


问:
How to ignore default start up code and linker script in the compiler
Currently, I try to compile my code on SPC58 board, powerpc. I use Green Hill and Wind river (Diab) compilers.
* I write myself a startup code crt0.c file, my entry point is _start
When I compile my code it said the symbol multiply defined in
D:\compiler\ghs\PPC\comp_201914\lib\ppc\crt0.o
It looks like my installation folder for Green Hill compiler already have startup code. (I guess crt0.o here is the default startup code)
I would like my compiler to ignore default startup code and take my written startup code crt0.c instead. How can I do that? also I have a doubt why do we have the default startup code here? because we may use the same compiler for different boards, the startup code for different board my be different.

When I install Diab compiler, and write my linker script. When compiling and linking. it also reports that defaultvle.dld (the linker script already exist in the installation folder) If I write a new linker script, it said I just redefine the whole thing in default linker script.
I may misunderstand something here.

答: For diab compiler you can use -Wm newLinkerScript(the -Wm will ignore the default linker script) and the -Ws to ignore the default start-up code.</p>


问:
indexOf running within Map function relying on Variable (array) from parent function (Google Apps Script)
I'm new to Google Apps Script/Javascript and I'm in the midst of working on the second iteration of my original code in order to make it faster. My first code made a lot of gets and sets to the underlying Google Sheet, while now I'm trying to do everything in arrays before setting the revised values. The current block of code I'm stuck on is my attempt to run an indexOf while running a map function.

The below script is about to run through every row of an array full of timesheet data and make
various amendments to the columns and calculate new column values.

```<code>var = amendedTimesheetData = timesheetdata.map(function(item){
    item.splice(2, 0, item[0] + " " + item[1]);
    item.splice(4, 0, item[0].slice(0, 2) + item[1].slice(0, 2) + date(item[3]));
    item.splice(0, 2);
    item.splice(3, 0, "Open");
    item.splice(4, 0, accountingCode); //SEE ISSUE BELOW

    return item
  })
}
</code>```

The accounting code variable relies on having performed a Javascript version of a vlookup based on a value in one of the array columns. The looked-up value exists in another array pulled from a different tab in the sheet. I know the code to perform the lookup looks like this:

```<code>  var timeTrackingCode = item[6]; //this is the location in the mapped array of the value to be looked up
  var timeTrackingCodeRow = codeMappingData.map(function(r){ return r[0]; }).indexOf(timeTrackingCode);
  var accountingCode = codeMappingData[timeTrackingCodeRow][1]
</code>```

The formula in the code above relies on the codeMappingData variable which was made earlier in the parent function before the map function started running.

```<code>  var codeMappingSheet = ss.getSheetByName('CodeMapping');
  var codeMappingRange = codeMappingSheet.getDataRange();
  var codeMappingData = codeMappingRange.getValues();
</code>```

The Question: How do I reference the codeMappingData array while in the map function?

Other options to get around this would be to run a For loop separate from the map, but while trying to learn all the possibilities I'm stuck on trying to understand how I could pass the variable through and achieve all of the column manipulations in as little code as possible. Any guidance on how I could achieve the variable pass through, or tips on how the code could be more efficient would all be very valuable. I've only copied a bit of the code, so it might lack context, but I think the question is clear.

Note that I've assumed that it would be ill-advised to establish the codeMappingData variable within the Map function because then every time it iterates through a row it would be performing a get from the sheet? If I'm incorrect in assuming this, then perhaps the simplest approach is to establish the variable within the map.

Thank you,

答:
The inner or child scope always has access to  variables in the outer or parent scope.

function outerFunction(){
  const outerScopeVar = 5;
  const arr = [1,2,3];
  arr.map(num => {
    console.info(`I have access to both inner and outer scope variable: ${num} and ${outerScopeVar}`);
  })
}
outerFunction();```

References:

Scope

Body:
I'm new to Google Apps Script/Javascript and I'm in the midst of working on the second iteration of my original code in order to make it faster. My first code made a lot of gets and sets to the underlying Google Sheet, while now I'm trying to do everything in arrays before setting the revised values. The current block of code I'm stuck on is my attempt to run an indexOf while running a map function.

The below script is about to run through every row of an array full of timesheet data and make
various amendments to the columns and calculate new column values.

var = amendedTimesheetData = timesheetdata.map(function(item){
    item.splice(2, 0, item[0] + " " + item[1]);
    item.splice(4, 0, item[0].slice(0, 2) + item[1].slice(0, 2) + date(item[3]));
    item.splice(0, 2);
    item.splice(3, 0, "Open");
    item.splice(4, 0, accountingCode); //SEE ISSUE BELOW

    return item
  })
}

The accounting code variable relies on having performed a Javascript version of a vlookup based on a value in one of the array columns. The looked-up value exists in another array pulled from a different tab in the sheet. I know the code to perform the lookup looks like this:

  var timeTrackingCode = item[6]; //this is the location in the mapped array of the value to be looked up
  var timeTrackingCodeRow = codeMappingData.map(function(r){ return r[0]; }).indexOf(timeTrackingCode);
  var accountingCode = codeMappingData[timeTrackingCodeRow][1]

The formula in the code above relies on the codeMappingData variable which was made earlier in the parent function before the map function started running.

  var codeMappingSheet = ss.getSheetByName('CodeMapping');
  var codeMappingRange = codeMappingSheet.getDataRange();
  var codeMappingData = codeMappingRange.getValues();

The Question: How do I reference the codeMappingData array while in the map function?

Other options to get around this would be to run a For loop separate from the map, but while trying to learn all the possibilities I'm stuck on trying to understand how I could pass the variable through and achieve all of the column manipulations in as little code as possible. Any guidance on how I could achieve the variable pass through, or tips on how the code could be more efficient would all be very valuable. I've only copied a bit of the code, so it might lack context, but I think the question is clear.

Note that I've assumed that it would be ill-advised to establish the codeMappingData variable within the Map function because then every time it iterates through a row it would be performing a get from the sheet? If I'm incorrect in assuming this, then perhaps the simplest approach is to establish the variable within the map.

Thank you,

Body:
The inner or child scope always has access to  variables in the outer or parent scope.

function outerFunction(){
  const outerScopeVar = 5;
  const arr = [1,2,3];
  arr.map(num => {
    console.info(`I have access to both inner and outer scope variable: ${num} and ${outerScopeVar}`);
  })
}
outerFunction();

References:

Scope


问:
pycharm on windows and docker in linux vm
By any chance can Pycharm on Windows be configured to run docker inside a linux VM (VirtualBox) ?

Meaning that i would like to take advantage of the Pycharm Docker tools of professional version but avoid installing docker for windows, since im using Linux VMs that have Docker installed.

Tried to set the tcp://xx.xx.xx.xx:2375 of the guest host vm but failing. Not sure if this can be done at all.

答:
There's no native support, but you can configure PyCharm to work with remote Docker daemon. Basically you need a deployment configuration alongside the Docker-based remote interpreter to transfer the project files to remote machine where they can be mounted inside a container.

See the detailed instruction in PyCharm's bug tracker https://youtrack.jetbrains.com/issue/PY-33489 and please vote for the ticket if you want this support to be a first-class citizen in PyCharm.


问:
Should notifications be removed using removeObserver(self) in iOS?
Should notification be removed using self in iOS?

Team mate have registered a notification in viewWillAppear and removed in viewDidDisappear like,

```<code>override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: API.shared)
}

override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self)
}
</code>```

While reviewing I have commented and suggested to remove notification with explicit name instead of removing with self because, I think in future some other notifications might need to be registered in viewWillLoad which should not be affected by the call NotificationCenter.default.removeObserver(self) by accident or by developers mistake. My suggestion was to remove observer using,

```<code>override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name:.didReceiveData, object: nil)
}
</code>```

Team mates replied that removing with NotificationCenter.default.removeObserver(self) is perfectly ok because we do not register other notification for now. I was seeking for reference or guideline to convince him, why it is important to remove notification explicitly using name rather by self.

Is there any guideline from Apple about best practice of removing notification observers?

答: After iOS 9, no need to remove the observer as iOS would remove observers from de-alloced ViewControllers</p>

Body:
Should notification be removed using self in iOS?

Team mate have registered a notification in viewWillAppear and removed in viewDidDisappear like,

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: API.shared)
}

override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self)
}

While reviewing I have commented and suggested to remove notification with explicit name instead of removing with self because, I think in future some other notifications might need to be registered in viewWillLoad which should not be affected by the call NotificationCenter.default.removeObserver(self) by accident or by developers mistake. My suggestion was to remove observer using,

override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name:.didReceiveData, object: nil)
}

Team mates replied that removing with NotificationCenter.default.removeObserver(self) is perfectly ok because we do not register other notification for now. I was seeking for reference or guideline to convince him, why it is important to remove notification explicitly using name rather by self.

Is there any guideline from Apple about best practice of removing notification observers?


问:
Modernizr help?
I can't seem to get modernizr to work on my website. I have added the javascript files into a folder and called to them. I've also added no-js to the html but still nothing.

When I view source, it doesn't populate the html like it should.

I'm not using it for css3 elements yet so I don't need any fallback styles, I just want to be able to use the more semantic tags like header, nav, footer etc...

This is my document code:

```<code><!DOCTYPE html>

<html class="no-js" lang="en">
<head>
    <meta charset=utf-8>
    <title></title>
    <!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
    </script>
    <![endif]-->

    <script type="text/javascript" src="/js/modernizr-1.7.min.js"></script>
</code>```

答:
It is most likely a path issue. Try temporally replacing

```<code><script type="text/javascript" src="/js/modernizr-1.7.min.js"></script>
</code>```

With

```<code><script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/modernizr/1.7/modernizr-1.7.min.js"></script>
</code>```

Or it could be working, but it's not obvious. Keep in mind you don't see the Modernizr classes when you view the source, you need a tool like Firebug on FF or the Developer Tools on Chrome to actually inspect the post-javascript code.

An additional test would be doing something like...

```<code>.borderradius body {
  background: #c00;
}
</code>```

And if the background is red, then Modernizr is running.

Title: Modernizr help?

Body:
I can't seem to get modernizr to work on my website. I have added the javascript files into a folder and called to them. I've also added no-js to the html but still nothing.

When I view source, it doesn't populate the html like it should.

I'm not using it for css3 elements yet so I don't need any fallback styles, I just want to be able to use the more semantic tags like header, nav, footer etc...

This is my document code:

<!DOCTYPE html>

    <meta charset=utf-8>
    <title></title>

Body:
It is most likely a path issue. Try temporally replacing

<script type="text/javascript" src="/js/modernizr-1.7.min.js"></script>

With

<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/modernizr/1.7/modernizr-1.7.min.js"></script>

Or it could be working, but it's not obvious. Keep in mind you don't see the Modernizr classes when you view the source, you need a tool like Firebug on FF or the Developer Tools on Chrome to actually inspect the post-javascript code.

An additional test would be doing something like...

.borderradius body {
  background: #c00;
}

And if the background is red, then Modernizr is running.


问:
How to compare two string value and give back which is not exits?
Here I have two string as:

string a1 = "A1,A2,A3,B1-1,B2-1";
string a2 = "A1,A2,A3,B1-1,B2-1,A4,A5";
```

<p>Here <code>A4</code> and <code>A5</code> do not exist in <code>a1</code>. How can I find them as new values?</p>

<pre class="lang-cs prettyprint-override"><code>string finalValue = string.compare(a1, a2);
</code>```

Here I'm getting numeric value.

答:
Should be as simple as

```<code>var a = a1.Split(',');
var b = a2.Split(',');
var results = a.Except(b).Union(b.Except(a));

Console.WriteLine(string.Join(", ", results));
</code>```

Output

```<code>A4, A5
</code>```

Essentially, it's just splitting the strings, using the Except method (both ways) and unioning the results

Additional Resources

String.Split Method

Returns a string array that contains the substrings in this instance
  that are delimited by elements of a specified string or Unicode
  character array.

Enumerable.Except Method

Produces the set difference of two sequences.

Enumerable.Union Method

Produces the set union of two sequences.

Body:
Here I have two string as:

string a1 = "A1,A2,A3,B1-1,B2-1";
string a2 = "A1,A2,A3,B1-1,B2-1,A4,A5";

Here A4 and A5 do not exist in a1. How can I find them as new values?

string finalValue = string.compare(a1, a2);

Here I'm getting numeric value.

Body:
Should be as simple as

var a = a1.Split(',');
var b = a2.Split(',');
var results = a.Except(b).Union(b.Except(a));

Console.WriteLine(string.Join(", ", results));

Output

A4, A5

Essentially, it's just splitting the strings, using the Except method (both ways) and unioning the results

Additional Resources

String.Split Method

Returns a string array that contains the substrings in this instance
  that are delimited by elements of a specified string or Unicode
  character array.

Enumerable.Except Method

Produces the set difference of two sequences.

Enumerable.Union Method

Produces the set union of two sequences.


问:
I can't see or edit MySQL stored procedures in NetBeans
I can connect to MySQL database (5.7.23) from NetBeans (8.2) using JDBC (MySQL-AB JDBC Driver, mysql-connector-java-5.1.23). I can see tables and views, execute SQL statements and everything else with database but I cannot see or edit stored procedures (or functions) in NetBeans. I have them inside database, I can see and manage them in MySQL Workbench but cannot see them in NetBeans (folder "Procedures" in NetBeans is empty). What could be the problem?

Left in NetBeans, right in Workbench:

I have 64-bit Windows 10 Pro (1709), 64-bit NetBeans 8.2 (PHP) and 64-bit MySQL 5.7.14 (from WAMP).

答:
There are possibly two reasons:

1. User doesn't have access to mysql.proc

NetBeans uses something like that to get the list of procedures and functions (see the source code):

```<code>SELECT
    db, name, type, param_list, returns, body
FROM
    mysql.proc
WHERE
    TYPE = 'PROCEDURE' OR TYPE = 'FUNCTION';
</code>```

Try to execute the query in NetBeans and see the result.

See the screenshot. On the first one, the user root has access to the mysql schema and you can see all system schemas including the mysql. On the second one, the user has access only to the information_schema and performance_schema and can not see procedures and functions:

Try to add to your user access to the MySQL schema. In workbench go to Server -> Users and Privileges -> Schema Privileges:

2. There is no mysql.proc in 8.0 mysql

Again, NetBeans uses mysql.pros extensively to get metadata about procedures and funcstions (see in source code). I suppose a simple workaround we can get is to create a view that would mimic the behavior of original mysql.proc:

```<code>CREATE VIEW mysql.proc AS
    SELECT
        ROUTINE_SCHEMA AS db,
        ROUTINE_NAME AS name,
        ROUTINE_TYPE AS type,
        ROUTINE_DEFINITION AS body,
        CONCAT(DTD_IDENTIFIER,
                ' CHARSET ',
                CHARACTER_SET_NAME) AS returns,
        (SELECT
                GROUP_CONCAT(CONCAT(parameter_name, ' ', dtd_identifier))
            FROM
                information_schema.parameters p
            WHERE
                p.specific_name = outertable.routine_name
                    AND ordinal_position > 0) AS param_list
    FROM
        information_schema.routines outertable
</code>```

After creating a view we can view procedures and functions from NetBeans 11.2 and view their bodies and param list. Also, I would not recommend editing procedures using NetBeans because it can't get full metadata. For example, it could not get declaration options such as DETERMINISTIC SQL SECURITY INVOKER.

Body:
There are possibly two reasons:

1. User doesn't have access to mysql.proc

NetBeans uses something like that to get the list of procedures and functions (see the source code):

SELECT
    db, name, type, param_list, returns, body
FROM
    mysql.proc
WHERE
    TYPE = 'PROCEDURE' OR TYPE = 'FUNCTION';

Try to execute the query in NetBeans and see the result.

See the screenshot. On the first one, the user root has access to the mysql schema and you can see all system schemas including the mysql. On the second one, the user has access only to the information_schema and performance_schema and can not see procedures and functions:

Try to add to your user access to the MySQL schema. In workbench go to Server -> Users and Privileges -> Schema Privileges:

2. There is no mysql.proc in 8.0 mysql

Again, NetBeans uses mysql.pros extensively to get metadata about procedures and funcstions (see in source code). I suppose a simple workaround we can get is to create a view that would mimic the behavior of original mysql.proc:

CREATE VIEW mysql.proc AS
    SELECT
        ROUTINE_SCHEMA AS db,
        ROUTINE_NAME AS name,
        ROUTINE_TYPE AS type,
        ROUTINE_DEFINITION AS body,
        CONCAT(DTD_IDENTIFIER,
                ' CHARSET ',
                CHARACTER_SET_NAME) AS returns,
        (SELECT
                GROUP_CONCAT(CONCAT(parameter_name, ' ', dtd_identifier))
            FROM
                information_schema.parameters p
            WHERE
                p.specific_name = outertable.routine_name
                    AND ordinal_position > 0) AS param_list
    FROM
        information_schema.routines outertable

After creating a view we can view procedures and functions from NetBeans 11.2 and view their bodies and param list. Also, I would not recommend editing procedures using NetBeans because it can't get full metadata. For example, it could not get declaration options such as DETERMINISTIC SQL SECURITY INVOKER.


问:
Using two array values in foreach loop
I have the following loop:

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr) {
  $(".department").append('<option value="' + array + '">' + textArray + '</option>');
});
</code>```

What I'm trying to achieve is the <option> label to use the text but its value to use the array array.

If I do the following:

```<code>$(".filterSection .department").append('<option value="'+array+'">'+textArray+'</option>');
</code>```

My output looks like this:

```<code><option value="Value 1,Value 2,Value 3">Text 1</option>
<option value="Value 1,Value 2,Value 3">Text 2</option>
</code>```

Whereas I'm looking for:

```<code><option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</code>```

答:
Just take a plain for loop over the indices and take the elements from both arrays.

```<code>var array = ["Value 1", "Value 2", "Value 3"],
    textArray = ["Text 1", "Text 2", "Text 3"];

for (let i = 0; i < array.length; i++) {
    $(".department").append('<option value="' + array[i] + '">' + textArray[i] + '</option>');
}
</code>```

Title: Using two array values in foreach loop

Body:
I have the following loop:

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr) {
  $(".department").append('<option value="' + array + '">' + textArray + '</option>');
});

What I'm trying to achieve is the <option> label to use the text but its value to use the array array.

If I do the following:

$(".filterSection .department").append('<option value="'+array+'">'+textArray+'</option>');

My output looks like this:

<option value="Value 1,Value 2,Value 3">Text 1</option>
<option value="Value 1,Value 2,Value 3">Text 2</option>

Whereas I'm looking for:

<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>

Body:
Just take a plain for loop over the indices and take the elements from both arrays.

var array = ["Value 1", "Value 2", "Value 3"],
    textArray = ["Text 1", "Text 2", "Text 3"];

for (let i = 0; i < array.length; i++) {
    $(".department").append('<option value="' + array[i] + '">' + textArray[i] + '</option>');
}


问:
Apache Camel route marshall Java Object to XML
I have java object with XML annotations

```<code>@XmlRootElement(name = "ROOT")
public class Root {

    @XmlAttribute(name = "ATTR")
    private long site;

    @XmlElement(name = "LIST")
    List<MyObject> transaction;
}
</code>```

and I have route to folder

```<code>from("firstPoint")
                .process(new RootToXMLConvertor())
                .to(FTP_FOLDER)
                .end();
</code>```

I want to marshall my Root object (I have it in exchange.getIn().getBody()) to XML file and send to FTP_FOLDER.

答:
You could use the JacksonXML Dataformat from Camel

```<code>JacksonXMLDataFormat formatPojo = new JacksonXMLDataFormat(Root.class);
from("firstPoint")
                .marshall(formatPojo)
                .to("file..")
                .to(FTP_FOLDER);
</code>```

For doing this you'll need camel-jacksonxml, camel-ftp and the camel-file components.

Body:
I have java object with XML annotations

@XmlRootElement(name = "ROOT")
public class Root {

    @XmlAttribute(name = "ATTR")
    private long site;

    @XmlElement(name = "LIST")
    List<MyObject> transaction;
}

and I have route to folder

from("firstPoint")
                .process(new RootToXMLConvertor())
                .to(FTP_FOLDER)
                .end();

I want to marshall my Root object (I have it in exchange.getIn().getBody()) to XML file and send to FTP_FOLDER.

Body:
You could use the JacksonXML Dataformat from Camel

JacksonXMLDataFormat formatPojo = new JacksonXMLDataFormat(Root.class);
from("firstPoint")
                .marshall(formatPojo)
                .to("file..")
                .to(FTP_FOLDER);

For doing this you'll need camel-jacksonxml, camel-ftp and the camel-file components.


问:
How to get sleep data DIRECTLY from Wear OS?
I am new to Wear OS development, and am trying to get user's sleep duration.

I've managed to get sleep data from other smartbands using raw BLE stack, but  I don't know how should I gather sleep data from Wear OS?.

I've searched a bit in the web, and most people suggest to use Google Fit API, but in my case, I can't depend on external APIs.

So these are my questions

1) Is there anyway I can get sleep data from the Wear OS direclty ? If Yes, How?

If No,

2) Should I build a sleep tracker myself (by analyzing watch's movement and heart rate) ?

答:
1) No. WearOS is just a system that provides a runtime environment, maybe along with some base functions. Sleep data is not a basic function, while the raw sensor data is yes.

2) Yes. If you don't want to rely on GoogleFit or other 3rd part API. The only way is to fetch the raw sensor data and analyze them your self.


问:
Fading one div into another: Make more stable, remove white pause, multiple fades
I have a test setup where the thumbnail div fades into another div, there's a couple of problems with it though.

How can I remove the white pause? At the moment it fades one div out to white then fades in the second div. How can I make it fade from one div to the other without it fading to white?

It's a little unstable, if you hover over quickly and out the second div appears below the original. How can I make it a bit more stable?

I'm going have multiple thumbnails with different images and text in each one, how can I setup the grid to include multiple boxes without them all fading in/out at once (i.e separately).

Here's the code:

Javacript:

```<code><script type="text/javascript">

$(document).ready(function(){
            $(".phase-2").hide();
        });

$(function(){
$('.grid-box').hover(
        function(){
            $('.grid-box .phase-1').fadeOut(300, function(){
                $('.grid-box .phase-2').fadeIn(300);
            });
        },
        function(){
            $('.grid-box .phase-2').fadeOut(300, function(){
                $('.grid-box .phase-1').fadeIn(300);
            });
        }
        );
});
</script>
</code>```

HTML:

```<code><div class="grid-box">
<div class="phase-1">
       <img class="grid-image" src="http://teamworksdesign.com/v2/wp-content/themes/default/images/dtr.jpg" alt="" height="152" width="210" />
   <div class="grid-heading">
        <h2>DTR Medical</h2>
        <h3>Branding, Web, Print</h3>
    </div>
</div>
<div class="phase-2">
    <div class="grid-info">
        <h4>Probeything 2000</h4>
        <p>Marketing unglamorous single-use medical intruments is not simple. We helped Neurosign increasetheir sales by 25% and increasemarket awareness.</p>
    </div>
    <div class="grid-heading-hover">
        <h2>DTR Medical</h2>
        <h3>Branding, Web, Print</h3>
    </div>
</div>
</code>```

答:
HTML

```<code><div class="grid-box">
    <div class="phase-1"></div>
    <div class="phase-2"></div>
</div>
</code>```

JQ

```<code>$(document).click(function (){
$('.grid-box .phase-1').animate({opacity:50},2000).queue(function(){
     $(this).hide();

});
$('.grid-box .phase-2').fadeIn(2000);
});
</code>```

CSS

```<code>.phase-1{width: 100px;height: 100px;background: red; position:absolute;}
.phase-2{width: 100px;height: 100px;background: blue;display: none; position:absolute;}
</code>```

I know this isn't exactly how your code looks like but you can see what I mean in a simple explaination.

here is a demo of it in jsfiddle http://jsfiddle.net/NxJf8/

Body:
I have a test setup where the thumbnail div fades into another div, there's a couple of problems with it though.

How can I remove the white pause? At the moment it fades one div out to white then fades in the second div. How can I make it fade from one div to the other without it fading to white?

It's a little unstable, if you hover over quickly and out the second div appears below the original. How can I make it a bit more stable?

I'm going have multiple thumbnails with different images and text in each one, how can I setup the grid to include multiple boxes without them all fading in/out at once (i.e separately).

Here's the code:

Javacript:

HTML:

DTR Medical

Branding, Web, Print

Probeything 2000

Marketing unglamorous single-use medical intruments is not simple. We helped Neurosign increasetheir sales by 25% and increasemarket awareness.

DTR Medical

Branding, Web, Print

Body:
HTML

<div class="grid-box">
    <div class="phase-1"></div>
    <div class="phase-2"></div>
</div>

JQ

$(document).click(function (){
$('.grid-box .phase-1').animate({opacity:50},2000).queue(function(){
     $(this).hide();

});
$('.grid-box .phase-2').fadeIn(2000);
});

CSS

.phase-1{width: 100px;height: 100px;background: red; position:absolute;}
.phase-2{width: 100px;height: 100px;background: blue;display: none; position:absolute;}

I know this isn't exactly how your code looks like but you can see what I mean in a simple explaination.

here is a demo of it in jsfiddle http://jsfiddle.net/NxJf8/


问:
Getting the error in react js that "this.props.sumOfPrices is not a function"?
I am new in react js and i am getting the following error "TypeError: this.props.sumOfPrices is not a function"
I am calling this function in the Course class clicker function using props.
My code is given below:

```<code>import React, { Component } from 'react';

class CourseSles extends Component {
    sumOfPrices(price){
        this.setState({total:this.state.total + price});
    }
    constructor(props) {
        super(props);
        this.state = { total:0 };
        this.sumOfPrices=this.sumOfPrices.bind(this);
    }

    render()
    {
        var courses=this.props.items.map(
        (item,i)=>{
         return <Course name={item.name} price={item.price} key={i} sumofPrices={this.sumOfPrices} active={item.active}/>
        });
        return(
        <div>
          <h1>You Can Buy Courses:</h1>
          <div id="courses">
              {courses}
        <p id="total">Toatal: <b>{this.state.total}</b></p>
          </div>
        </div>
        );
    }
}

class Course extends Component {
    clicker(){
      var active= !this.state.active;
      this.setState({active:active});
      this.props.sumOfPrices(active ? this.props.price : -this.props.price);
    }
    constructor(props) {
        super(props);
        this.state = { active:false };
        this.clicker=this.clicker.bind(this);
    }
    render() {
        return ( <div>
            <p onClick={this.clicker}>{this.props.name} <b>{this.props.price}</b></p>
        </div> );
    }
}

export default CourseSles;
</code>```

答:
Change your sumOfPrices method like:</p>

```<code>class CourseSles extends Component {
    sumOfPrices  = (price) => {
        this.setState({total:this.state.total + price});
    }
//Rest of Code
}
</code>```

Body:
I am new in react js and i am getting the following error "TypeError: this.props.sumOfPrices is not a function"
I am calling this function in the Course class clicker function using props.
My code is given below:

import React, { Component } from 'react';

class CourseSles extends Component {
    sumOfPrices(price){
        this.setState({total:this.state.total + price});
    }
    constructor(props) {
        super(props);
        this.state = { total:0 };
        this.sumOfPrices=this.sumOfPrices.bind(this);
    }

    render()
    {
        var courses=this.props.items.map(
        (item,i)=>{
         return <Course name={item.name} price={item.price} key={i} sumofPrices={this.sumOfPrices} active={item.active}/>
        });
        return(

You Can Buy Courses:

              {courses}

Toatal: {this.state.total}

        );
    }
}

class Course extends Component {
    clicker(){
      var active= !this.state.active;
      this.setState({active:active});
      this.props.sumOfPrices(active ? this.props.price : -this.props.price);
    }
    constructor(props) {
        super(props);
        this.state = { active:false };
        this.clicker=this.clicker.bind(this);
    }
    render() {
        return (

{this.props.name} {this.props.price}

 );
    }
}

export default CourseSles;

Body:
Change your sumOfPrices method like:

class CourseSles extends Component {
    sumOfPrices  = (price) => {
        this.setState({total:this.state.total + price});
    }
//Rest of Code
}