问:
Change action bar icon position
I want to display the menu icon to left of the toolbar and the search icon to be in the actual place of the menu icon

This is my main.xml file inside the main folder

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/my_search"
        android:icon="@drawable/ic_search_black_24dp"
        android:title="search"
        app:showAsAction="always">

    </item>
    <item
        android:id="@+id/my_menu_icon"
        android:icon="@drawable/ic_menu_black_24dp"
        android:title="side_menu"
        app:showAsAction="always">

    </item>

</menu>
</code>```

This is the result of this page:
my result

And this is my MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);//affect the menu file to the main activity and call this last one

        return true;
    }
}
</code>```

答:
I prefer use Toolbar instead of ActionBar, and Customize layout in xml form. you can change AppTheme like this inside /src/main/res/values/style.xml:

```<code><style name="AppTheme" parent="Base.Theme.AppCompat.Light">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
</style>
</code>```

do not forget to set AppTheme in manifest, like this:

```<code><application
        android:theme="@style/AppTheme"
        //and other properties
</application>
</code>```

then you can use android Toolbar inside layouts:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:fitsSystemWindows="true"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary">

           <LinearLayout
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize"
               android:orientation="horizontal">

            <ImageButton
                android:id="@+id/menu_btn"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="left"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/ic_menu_black_24dp""/>

            <TextView
                android:id="@+id/title"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="match_parent"
                android:gravity="left"
                android:text="App Title"
                android:textSize="16dp"
                android:textStyle="bold"/>

            <ImageButton
                android:id="@+id/search_btn"
                android:layout_width="?attr/actionBarSize"
                android:layout_height="match_parent"
                android:layout_gravity="right"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/ic_search_black_24dp"/>

           </LinearLayout>

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    // and other views
    // .
    // .
    // .

</android.support.design.widget.CoordinatorLayout>
</code>```

Title: Change action bar icon position

Body:
I want to display the menu icon to left of the toolbar and the search icon to be in the actual place of the menu icon

This is my main.xml file inside the main folder

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/my_search"
        android:icon="@drawable/ic_search_black_24dp"
        android:title="search"
        app:showAsAction="always">

    </item>
    <item
        android:id="@+id/my_menu_icon"
        android:icon="@drawable/ic_menu_black_24dp"
        android:title="side_menu"
        app:showAsAction="always">

    </item>

</menu>

This is the result of this page:
my result

And this is my MainActivity.java:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);//affect the menu file to the main activity and call this last one

        return true;
    }
}

Body:
I prefer use Toolbar instead of ActionBar, and Customize layout in xml form. you can change AppTheme like this inside /src/main/res/values/style.xml:

<style name="AppTheme" parent="Base.Theme.AppCompat.Light">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
</style>

do not forget to set AppTheme in manifest, like this:

<application
        android:theme="@style/AppTheme"
        //and other properties
</application>

then you can use android Toolbar inside layouts:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:fitsSystemWindows="true"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary">

           <LinearLayout
               android:layout_width="match_parent"
               android:layout_height="?attr/actionBarSize"
               android:orientation="horizontal">

            <ImageButton
                android:id="@+id/menu_btn"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="left"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/ic_menu_black_24dp""/>

            <TextView
                android:id="@+id/title"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="match_parent"
                android:gravity="left"
                android:text="App Title"
                android:textSize="16dp"
                android:textStyle="bold"/>

            <ImageButton
                android:id="@+id/search_btn"
                android:layout_width="?attr/actionBarSize"
                android:layout_height="match_parent"
                android:layout_gravity="right"
                android:background="?attr/selectableItemBackgroundBorderless"
                android:src="@drawable/ic_search_black_24dp"/>

           </LinearLayout>

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    // and other views
    // .
    // .
    // .

</android.support.design.widget.CoordinatorLayout>


来源: stackexchange

问:
Hide payment instructions from WooCommerce email completed order notifications
In my woocommerce store I have activated the payments instructions and they are displayed on all email notifications. I have the following code (taken from another answer), that remove payment instructions for "COD" payment method:

```<code>add_action( 'woocommerce_email_before_order_table', function(){
    if ( ! class_exists( 'WC_Payment_Gateways' ) ) return;

    $gateways = WC_Payment_Gateways::instance(); // gateway instance
    $available_gateways = $gateways->get_available_payment_gateways();

    if ( isset( $available_gateways['cod'] ) )
        remove_action( 'woocommerce_email_before_order_table', array( $available_gateways['cod'], 'email_instructions' ), 10, 3 );
}, 1 );
</code>```

It is applied globally on all email notifications and I need to remove the payment instructions only from "Customer completed order" email notification.

Any help is appreciated.

答:
Your code is a bit outdated (or old) and you missed the hook function arguments, that will allow you to target "Customer Completed Order" Email notification. Try instead the following:

```<code>add_action( 'woocommerce_email_before_order_table', 'action_email_before_order_table_callback', 9, 4 );
function action_email_before_order_table_callback( $order, $sent_to_admin, $plain_text, $email ){
    $payment_method = $order->get_payment_method();

    // Targeting "COD" payment method on Customer completed order email notification
    if ( 'customer_completed_order' === $email->id && 'cod' === $payment_method ) {
        $available_gateways = WC()->payment_gateways->get_available_payment_gateways();

        remove_action( 'woocommerce_email_before_order_table', [ $available_gateways[$payment_method], 'email_instructions' ], 10 );
    }
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

ContentLicense: CC BY-SA 4.0

Body:
In my woocommerce store I have activated the payments instructions and they are displayed on all email notifications. I have the following code (taken from another answer), that remove payment instructions for "COD" payment method:

add_action( 'woocommerce_email_before_order_table', function(){
    if ( ! class_exists( 'WC_Payment_Gateways' ) ) return;

    $gateways = WC_Payment_Gateways::instance(); // gateway instance
    $available_gateways = $gateways->get_available_payment_gateways();

    if ( isset( $available_gateways['cod'] ) )
        remove_action( 'woocommerce_email_before_order_table', array( $available_gateways['cod'], 'email_instructions' ), 10, 3 );
}, 1 );

It is applied globally on all email notifications and I need to remove the payment instructions only from "Customer completed order" email notification.

Any help is appreciated.

Body:
Your code is a bit outdated (or old) and you missed the hook function arguments, that will allow you to target "Customer Completed Order" Email notification. Try instead the following:

add_action( 'woocommerce_email_before_order_table', 'action_email_before_order_table_callback', 9, 4 );
function action_email_before_order_table_callback( $order, $sent_to_admin, $plain_text, $email ){
    $payment_method = $order->get_payment_method();

    // Targeting "COD" payment method on Customer completed order email notification
    if ( 'customer_completed_order' === $email->id && 'cod' === $payment_method ) {
        $available_gateways = WC()->payment_gateways->get_available_payment_gateways();

        remove_action( 'woocommerce_email_before_order_table', [ $available_gateways[$payment_method], 'email_instructions' ], 10 );
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


问:
I am trying to write a class object that performs manipulation of an image
I believe I have most of the code correct until I get to last line of code. My first time writing a class method. Not sure how specify image location.

Not sure how to proceed

from PIL import Image

class image_play(object):
    def __init__(self, im_name):
        self.im_name = im_name

    def rgb_to_gray_image(self):
        im = Image.open(self.im_name)
        im = im.convert('LA')
        return im

    # editing pixels of image to white
    def loop_over_image(self):
        im = Image.open(self.im_name)
        width, height = im.size
        # nested loop over all pixels of image
        temp = []
        for i in range(width):
            for j in range(height):
                temp.append((255,255,255))#append a tuple for the RGB channel values for each pixel

        image_out = Image.new(im.mode,im.size) #create a new image usig PIl
        image_out.putdata(temp) #use the temp list to create the image
        return image_out

obj = image_play()
```

```TypeError                                 Traceback (most recent call last)
<ipython-input-8-d6175b134ccc> in <module>
     25         return image_out
     26
---> 27 obj = image_play()

TypeError: __init__() missing 1 required positional argument: 'im_name'
```

答:
You have to pass the name of the image when you instantiate the class. In your __init__ you say it takes an input im_name

So you would write something like

obj = image_play("./image.png")

Body:
I believe I have most of the code correct until I get to last line of code. My first time writing a class method. Not sure how specify image location.

Not sure how to proceed

from PIL import Image

class image_play(object):
    def __init__(self, im_name):
        self.im_name = im_name

    def rgb_to_gray_image(self):
        im = Image.open(self.im_name)
        im = im.convert('LA')
        return im

    # editing pixels of image to white
    def loop_over_image(self):
        im = Image.open(self.im_name)
        width, height = im.size
        # nested loop over all pixels of image
        temp = []
        for i in range(width):
            for j in range(height):
                temp.append((255,255,255))#append a tuple for the RGB channel values for each pixel

        image_out = Image.new(im.mode,im.size) #create a new image usig PIl
        image_out.putdata(temp) #use the temp list to create the image
        return image_out

obj = image_play()

TypeError                                 Traceback (most recent call last)
<ipython-input-8-d6175b134ccc> in <module>
     25         return image_out
     26
---> 27 obj = image_play()

TypeError: __init__() missing 1 required positional argument: 'im_name'


问:
Detecting and isolating lines in an image
I'm trying to write a piece of code that can detect and isolate straight lines from an image. I'm using the opencv library, together with Canny edge detection and Hough transformation to achieve this. So far I've come up with the following:

```<code>import numpy as np
import cv2

# Reading the image
img = cv2.imread('sudoku-original.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Edge detection
edges = cv2.Canny(gray,50,150,apertureSize = 3)
# Line detection
lines = cv2.HoughLines(edges,1,np.pi/180,200)

for rho,theta in lines[0]:
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)

cv2.imwrite('linesDetected.jpg',img)
</code>```

In theory this code snippet should do the job, but unfortunately it doesn't. The resulting picture clearly shows only one line being found. I'm not quite sure what I'm doing wrong here and why it's only detecting one specific line. Could someone possibly figure out the problem here?

答:
Despite opencv's Hough Transform tutorial is using just one loop, the shape of lines is actual [None,1,2], thus when you use lines[0] you will only get one item for rho and one item for theta, which will only get you one line. therefore, my suggestion is to use a double loop (below) or some numpy slice magic to maintain using just 1 loop.  To get all the grid detected, as Dan Masek mentioned, you will need to play with the edge detection logic.  Maybe see the solution that uses HoughLinesP.

```<code>for item in lines:
    for rho,theta in item:
        ...
</code>```

Body:
I'm trying to write a piece of code that can detect and isolate straight lines from an image. I'm using the opencv library, together with Canny edge detection and Hough transformation to achieve this. So far I've come up with the following:

import numpy as np
import cv2

# Reading the image
img = cv2.imread('sudoku-original.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Edge detection
edges = cv2.Canny(gray,50,150,apertureSize = 3)
# Line detection
lines = cv2.HoughLines(edges,1,np.pi/180,200)

for rho,theta in lines[0]:
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)

cv2.imwrite('linesDetected.jpg',img)

In theory this code snippet should do the job, but unfortunately it doesn't. The resulting picture clearly shows only one line being found. I'm not quite sure what I'm doing wrong here and why it's only detecting one specific line. Could someone possibly figure out the problem here?

Body:
Despite opencv's Hough Transform tutorial is using just one loop, the shape of lines is actual [None,1,2], thus when you use lines[0] you will only get one item for rho and one item for theta, which will only get you one line. therefore, my suggestion is to use a double loop (below) or some numpy slice magic to maintain using just 1 loop.  To get all the grid detected, as Dan Masek mentioned, you will need to play with the edge detection logic.  Maybe see the solution that uses HoughLinesP.

for item in lines:
    for rho,theta in item:
        ...


问:
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array

```<code>HTTP 200 OK
Allow: GET, POST, PUT, DELETE, PATCH
Content-Type: application/json
Vary: Accept

[
{
    "id": 1,
    "title": "Push Workout Bjarred",
    "description": "Kör Hårt!",
    "exercises": [
        3,
        4,
        5,
        6,
        9,
        10
    ],
    "cardio": [
        4
    ]
},
{
    "id": 2,
    "title": "Pull Workout Loddekopinge",
    "description": "",
    "exercises": [
        1,
        2,
        7,
        8
    ],
    "cardio": []
},
{
    "id": 3,
    "title": "CardioPass",
    "description": "",
    "exercises": [],
    "cardio": [
        2,
        3,
        4
    ]
}
]
</code>```

Serializer (So I want to display the title and not the id for every exercise)

```<code>class WorkoutSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workout
        fields = ('id', 'title', 'description', 'exercises', 'cardio')
</code>```

Here are the models, note that I want to display the exercise name for every exercise in the api array, I don't want the id! - That is passed right now! :)

```<code>class Bodypart(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Exercise(models.Model):
    name = models.CharField(max_length=40)
    bodyparts = models.ManyToManyField(Bodypart, blank=True)

    def __str__(self):
        return self.name

class Cardio(models.Model):
    name = models.CharField(max_length=40)
    time = models.IntegerField(default=10)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'cardio'

class Workout(models.Model):
    title = models.CharField(max_length=120)
    description = models.CharField(max_length=1000, blank=True)
    exercises = models.ManyToManyField(Exercise, blank=True)
    cardio = models.ManyToManyField(Cardio, blank=True)

    def __str__(self):
        return self.title
</code>```

答:
Create a serializer for the Exercise model with the name field:

```<code>class ExerciseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Exercise
        fields = ('name', )
</code>```

And add it to the Workout serializer:

```<code>class WorkoutSerializer(serializers.ModelSerializer):
    exercises = ExerciseSerializer(many=True, read_only=True)
    class Meta:
        fields = ('id', 'title', 'description', 'exercises', 'cardio', )
</code>```

Body:
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array

HTTP 200 OK
Allow: GET, POST, PUT, DELETE, PATCH
Content-Type: application/json
Vary: Accept

[
{
    "id": 1,
    "title": "Push Workout Bjarred",
    "description": "Kör Hårt!",
    "exercises": [
        3,
        4,
        5,
        6,
        9,
        10
    ],
    "cardio": [
        4
    ]
},
{
    "id": 2,
    "title": "Pull Workout Loddekopinge",
    "description": "",
    "exercises": [
        1,
        2,
        7,
        8
    ],
    "cardio": []
},
{
    "id": 3,
    "title": "CardioPass",
    "description": "",
    "exercises": [],
    "cardio": [
        2,
        3,
        4
    ]
}
]

Serializer (So I want to display the title and not the id for every exercise)

class WorkoutSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workout
        fields = ('id', 'title', 'description', 'exercises', 'cardio')

Here are the models, note that I want to display the exercise name for every exercise in the api array, I don't want the id! - That is passed right now! :)

class Bodypart(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Exercise(models.Model):
    name = models.CharField(max_length=40)
    bodyparts = models.ManyToManyField(Bodypart, blank=True)

    def __str__(self):
        return self.name

class Cardio(models.Model):
    name = models.CharField(max_length=40)
    time = models.IntegerField(default=10)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'cardio'

class Workout(models.Model):
    title = models.CharField(max_length=120)
    description = models.CharField(max_length=1000, blank=True)
    exercises = models.ManyToManyField(Exercise, blank=True)
    cardio = models.ManyToManyField(Cardio, blank=True)

    def __str__(self):
        return self.title

Body:
Create a serializer for the Exercise model with the name field:

class ExerciseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Exercise
        fields = ('name', )

And add it to the Workout serializer:

class WorkoutSerializer(serializers.ModelSerializer):
    exercises = ExerciseSerializer(many=True, read_only=True)
    class Meta:
        fields = ('id', 'title', 'description', 'exercises', 'cardio', )


问:
cumulative sum by ID with lag
I want to create a cumulative sum by id. But, it should not sum the value that belongs to the row where is being calculated.

I've already tried with cumsum. However, I do not know how to add a statement which specifies to do not add the amount of the row where the sum is made. The result column I am looking for is the third column called: "sum".

For example, for id 1, the first row is sum=0, because should not add this row. But, for id 1 and row 2 sum=100 because the amount of id 1 previous to the row 2 was 100 and so on.

```<code>   id amount sum
1:  1    100   0
2:  1     20 100
3:  1    150 120
4:  2     60   0
5:  2    100  60
6:  1     30 270
7:  2     40 160
</code>```

This is what I've tried:

```<code>  df[,sum:=cumsum(amount),
      by ="id"]

  data: df <- data.table(id = c(1, 1, 1, 2, 2,1,2), amount = c(100, 20,
  150,60,100,30,40),sum=c(0,100,120,0,60,270,160) ,stringsAsFactors =
  FALSE)
</code>```

答:
You can shift the values you're summing by using the lag function.

```<code>library(tidyverse)

df <- data.frame(id = c(1, 1, 1, 2, 2,1,2), amount = c(100, 20,
150,60,100,30,40),sum=c(0,100,120,0,60,270,160) ,stringsAsFactors =
FALSE)

df %>%
    group_by(id) %>%
    mutate(sum = cumsum(lag(amount, 1, default=0)))

# A tibble: 7 x 3
# Groups:   id [2]
     id amount   sum
  <dbl>  <dbl> <dbl>
1     1    100     0
2     1     20   100
3     1    150   120
4     2     60     0
5     2    100    60
6     1     30   270
7     2     40   160
</code>```

Title: cumulative sum by ID with lag

Body:
I want to create a cumulative sum by id. But, it should not sum the value that belongs to the row where is being calculated.

I've already tried with cumsum. However, I do not know how to add a statement which specifies to do not add the amount of the row where the sum is made. The result column I am looking for is the third column called: "sum".

For example, for id 1, the first row is sum=0, because should not add this row. But, for id 1 and row 2 sum=100 because the amount of id 1 previous to the row 2 was 100 and so on.

   id amount sum
1:  1    100   0
2:  1     20 100
3:  1    150 120
4:  2     60   0
5:  2    100  60
6:  1     30 270
7:  2     40 160

This is what I've tried:

  df[,sum:=cumsum(amount),
      by ="id"]

  data: df <- data.table(id = c(1, 1, 1, 2, 2,1,2), amount = c(100, 20,
  150,60,100,30,40),sum=c(0,100,120,0,60,270,160) ,stringsAsFactors =
  FALSE)

Body:
You can shift the values you're summing by using the lag function.

library(tidyverse)

df <- data.frame(id = c(1, 1, 1, 2, 2,1,2), amount = c(100, 20,
150,60,100,30,40),sum=c(0,100,120,0,60,270,160) ,stringsAsFactors =
FALSE)

df %>%
    group_by(id) %>%
    mutate(sum = cumsum(lag(amount, 1, default=0)))

# A tibble: 7 x 3
# Groups:   id [2]
     id amount   sum
  <dbl>  <dbl> <dbl>
1     1    100     0
2     1     20   100
3     1    150   120
4     2     60     0
5     2    100    60
6     1     30   270
7     2     40   160


问:
SSIS Lookup Multiple Columns in one table to the same ID column in another
I have the following table:

```<code>EventValue | Person1           | Person2    | Person3     | Person4       | Meta1  | Meta2
-------------------------------------------------------------------------------------------
123        | joePerson01       | samRock01  | nancyDrew01 | steveRogers01 | 505   | 606
321        | steveRogers02     | yoMama01   | ruMo01      | lukeJedi01    | 707   | 808
</code>```

I want to transform the Person columns into IDs for my destination table, so all of the ID's would be coming from the same Person table in my Destination DB:

```<code>ID | FirstName | LastName  | DatabaseOneID | DatabaseTwoID
----------------------------------------------------------
1  | Joe       | Person    | joePerson01   | personJoe01
2  | Sam       | Rockwell  | samRock01     | rockSam01
3  | Nancy     | Drew      | nancyDrew01   | drewNancy01
4  | Steve     | Rogers    | steveRogers01 | rogersSteve01
5  | Steve R   | Rogers    | steveRogers02 | rogersSteve02
6  | Yo        | Mama      | yoMama01      | mamaYo01
7  | Rufus     | Murdock   | ruMo01        | moRu01
8  | Luke      | Skywalker | lukeJedi01    | jediLuke01
</code>```

With results like so:

```<code>MetaID     | EventValue | Person1ID | Person2ID | Person3ID | Person4ID
------------------------------------------------------------------------
1          | 123        | 1         | 2         | 3         | 4
2          | 321        | 5         | 6         | 7         | 8
</code>```

I currently have a Lookup Transform looking up the first Person column, but couldn't figure out how to convert all 4 Person columns into IDs within the same lookup.

答:
I currently have a Lookup Transform looking up the first Person column, but couldn't figure out how to convert all 4 Person columns into IDs within the same lookup.

You cannot do this within the same lookup, you have to add a Lookup Transformation for each Column. In your case you should add 4 Lookup Transformation.

If source database and destination database are on the same server, then you can use a SQL query to achieve that as mentioned in the other answer, but in case that each database is on a separate server you have to go with Lookup transformation or you have to import data into a staging table and perform Join operations using SQL.

Body:
I have the following table:

EventValue | Person1           | Person2    | Person3     | Person4       | Meta1  | Meta2
-------------------------------------------------------------------------------------------
123        | joePerson01       | samRock01  | nancyDrew01 | steveRogers01 | 505   | 606
321        | steveRogers02     | yoMama01   | ruMo01      | lukeJedi01    | 707   | 808

I want to transform the Person columns into IDs for my destination table, so all of the ID's would be coming from the same Person table in my Destination DB:

ID | FirstName | LastName  | DatabaseOneID | DatabaseTwoID
----------------------------------------------------------
1  | Joe       | Person    | joePerson01   | personJoe01
2  | Sam       | Rockwell  | samRock01     | rockSam01
3  | Nancy     | Drew      | nancyDrew01   | drewNancy01
4  | Steve     | Rogers    | steveRogers01 | rogersSteve01
5  | Steve R   | Rogers    | steveRogers02 | rogersSteve02
6  | Yo        | Mama      | yoMama01      | mamaYo01
7  | Rufus     | Murdock   | ruMo01        | moRu01
8  | Luke      | Skywalker | lukeJedi01    | jediLuke01

With results like so:

MetaID     | EventValue | Person1ID | Person2ID | Person3ID | Person4ID
------------------------------------------------------------------------
1          | 123        | 1         | 2         | 3         | 4
2          | 321        | 5         | 6         | 7         | 8

I currently have a Lookup Transform looking up the first Person column, but couldn't figure out how to convert all 4 Person columns into IDs within the same lookup.


问:
Dynamically change dropdown select defaults depending on existing values in array
I am new to web development and AngularJS and I have been struggling with how to go about this. Sorry for the bad English.

I use an ng-repeat that creates the correct number of dropdowns I need as this needs to be dynamic. The dropdowns have a label like:

```<code>Test1: <dropdown here>
Test2: <dropdown here> ...etc.
</code>```

I have a HTTP request that returns an array. If the array has "Test1 State1" in it, I would like the dropdown for Test1: to change to State1 on default. (continues with all the Tests)

How can I go about this?

HTML

```<code><div ng-repeat="o in options track by $index">
    <label for="{{::$o}}" class="col-xs-3">{{o}}:</label>
    <select id="{{::$o}}" ng-model="stateModel"
            ng-options="state.changeToState for state in states"
            ng-change="onStateSelect(stateModel.platformReleaseNotes, o)">
      {{state}}
    </select>
</div>
</code>```

```<code>$scope.states = [
    {
      changeToState: 'State1',
      notes: 'Hello World'
    },
    {
      changeToState: 'State2',
      notes: 'Goodbye'
    },
    {
      changeToState: 'State3',
      notes: ' is State3'
    },
    {
      changeToState: 'State4',
      notes: ' is State4'
    }
  ];
</code>```

答:
You cannot share model if you want to have different values for all drop downs.
ng-model should be different for all drop downs and this can be achieved by having array of drop downs as below.

```<code>  $scope.dropDowns = [{
    dropDownName: 'Test1:',
    id: 'test1',
    selectedOption: ''
  }, {
    dropDownName: 'Test2:',
    id: 'test2',
    selectedOption: ''
  }];
</code>```

see the running example in
http://plnkr.co/edit/jsAn1jwGkQfxXK5I9G6J?p=preview

Body:
I am new to web development and AngularJS and I have been struggling with how to go about this. Sorry for the bad English.

I use an ng-repeat that creates the correct number of dropdowns I need as this needs to be dynamic. The dropdowns have a label like:

Test1: <dropdown here>
Test2: <dropdown here> ...etc.

I have a HTTP request that returns an array. If the array has "Test1 State1" in it, I would like the dropdown for Test1: to change to State1 on default. (continues with all the Tests)

How can I go about this?

HTML

    {{o}}:
    <select id="{{::$o}}" ng-model="stateModel"
            ng-options="state.changeToState for state in states"
            ng-change="onStateSelect(stateModel.platformReleaseNotes, o)">
      {{state}}
    </select>

$scope.states = [
    {
      changeToState: 'State1',
      notes: 'Hello World'
    },
    {
      changeToState: 'State2',
      notes: 'Goodbye'
    },
    {
      changeToState: 'State3',
      notes: ' is State3'
    },
    {
      changeToState: 'State4',
      notes: ' is State4'
    }
  ];

Body:
You cannot share model if you want to have different values for all drop downs.
ng-model should be different for all drop downs and this can be achieved by having array of drop downs as below.

  $scope.dropDowns = [{
    dropDownName: 'Test1:',
    id: 'test1',
    selectedOption: ''
  }, {
    dropDownName: 'Test2:',
    id: 'test2',
    selectedOption: ''
  }];

see the running example in
http://plnkr.co/edit/jsAn1jwGkQfxXK5I9G6J?p=preview


问:
Code with ?, Compile in Objective-C
So I'm jumping into iPhone development and I've begun looking into Objective-C and have noticed that... it sucks. Ultimately, there's all kinds of odd syntax requirements, ex:

```<code>NSString *city = @"Victoria";
</code>```

or

```<code>[MyClass myMethod]
</code>```

This is alien. The language should be smart enough to know what do do with a normal variable and string.

But, this is the language, and I can't do anything about it. So, my main question is: Is there any way to write my code in PHP/AS3/C# or some other normal language and then compile or convert it to legal Objective-C? I was going to use AS3 but necessary functionality like the Camera is not currently supported.

I know it's an odd question, but what about when I need to develop for Android or Windows 7? There are only so many languages one can learn before one loses his/her mind. I'd like to stop at 7.

答:
You can have a look at MonoTouch: MonoTouch
I can feel with you, I was coming from C# to Objective C about a year ago and it ws very painful to learn the syntax

Oh, and of course the Adobe Flash Builder 4.5

ContentLicense: CC BY-SA 3.0

Title: Code with ?, Compile in Objective-C

Body:
So I'm jumping into iPhone development and I've begun looking into Objective-C and have noticed that... it sucks. Ultimately, there's all kinds of odd syntax requirements, ex:

NSString *city = @"Victoria";

or

[MyClass myMethod]

This is alien. The language should be smart enough to know what do do with a normal variable and string.

But, this is the language, and I can't do anything about it. So, my main question is: Is there any way to write my code in PHP/AS3/C# or some other normal language and then compile or convert it to legal Objective-C? I was going to use AS3 but necessary functionality like the Camera is not currently supported.

I know it's an odd question, but what about when I need to develop for Android or Windows 7? There are only so many languages one can learn before one loses his/her mind. I'd like to stop at 7.


问:
Pandas to_sql doesn't create a file
I'm trying to save my pandas dataframe as a SQL file

I followed the documentation and tried

```<code>from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
df.to_sql('filename.sql', engine, chunksize=1000)
</code>```

However, when I check the directory with os.listdir(), the file is not there

答:
The first argument you pass to to_sql should be the name of the table in your database, not the name of the file. Take a look at the docs.

Also, if you want to create a sqlite file, you should create an engine with a file database, not in-memory:

```<code>engine = sqlalchemy.create_engine("sqlite:///mydb.db")  # relative path to db
df.to_sql("my_table", engine)
</code>```

Now there should be a file named mydb.db in the same directory where you run your application/script, with a table my_table containing the data in df.

Title: Pandas to_sql doesn't create a file

Body:
I'm trying to save my pandas dataframe as a SQL file

I followed the documentation and tried

from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
df.to_sql('filename.sql', engine, chunksize=1000)

However, when I check the directory with os.listdir(), the file is not there

Body:
The first argument you pass to to_sql should be the name of the table in your database, not the name of the file. Take a look at the docs.

Also, if you want to create a sqlite file, you should create an engine with a file database, not in-memory:

engine = sqlalchemy.create_engine("sqlite:///mydb.db")  # relative path to db
df.to_sql("my_table", engine)

Now there should be a file named mydb.db in the same directory where you run your application/script, with a table my_table containing the data in df.


问:
How to call an element in an 2D python array
I'm trying to change the value of a certain element in a 2D array.
the 2D array is a num1 by num2 matrix with every element as 0. I'm trying to change the Rth
row Cth column of the matrix to 1

```<code>matrix = []
def make_matrix(num1, num2):
    row = []
    for i in range(num1):
        row.append(0)
    for i in range(num2):
        matrix.append(row)

def change_to_one(R, C):
    matrix[R-1][C-1] = 1

make_matrix(3, 2)
change_to_one(2, 1)
print(matrix)
</code>```

it prints [[1, 0, 0], [1, 0, 0]] instead of [[0, 0, 0], [1, 0, 0]]

答:
There are two problems in your code:

You are using a reference to the original list when you do matrix.append(row[:]). This can be circumvented by just copying the elements of the list as row[:] instead of using row. Otherwise, whatever changes you do to the first row, will also be reflected in all the other rows.

You forgot to return after modifying the matrix. This is not a major problem in your case as the scope of your matrix is global.

```<code>matrix = []

def make_matrix(num1, num2):
    row = []
    for i in range(num1):
        row.append(0)
    for i in range(num2):
        matrix.append(row[:]) # <--- Use row[:] instead of row

def change_to_one(R, C):
    matrix[R-1][C-1] = 1
    return matrix # <---- return from here

make_matrix(3, 2)
matrix = change_to_one(2, 1) # <---- save the returned result in a variable
print(matrix)

# [[0, 0, 0], [1, 0, 0]]
</code>```

Body:
I'm trying to change the value of a certain element in a 2D array.
the 2D array is a num1 by num2 matrix with every element as 0. I'm trying to change the Rth
row Cth column of the matrix to 1

matrix = []
def make_matrix(num1, num2):
    row = []
    for i in range(num1):
        row.append(0)
    for i in range(num2):
        matrix.append(row)

def change_to_one(R, C):
    matrix[R-1][C-1] = 1

make_matrix(3, 2)
change_to_one(2, 1)
print(matrix)

it prints [[1, 0, 0], [1, 0, 0]] instead of [[0, 0, 0], [1, 0, 0]]

Body:
There are two problems in your code:

You are using a reference to the original list when you do matrix.append(row[:]). This can be circumvented by just copying the elements of the list as row[:] instead of using row. Otherwise, whatever changes you do to the first row, will also be reflected in all the other rows.

You forgot to return after modifying the matrix. This is not a major problem in your case as the scope of your matrix is global.

matrix = []

def make_matrix(num1, num2):
    row = []
    for i in range(num1):
        row.append(0)
    for i in range(num2):
        matrix.append(row[:]) # <--- Use row[:] instead of row

def change_to_one(R, C):
    matrix[R-1][C-1] = 1
    return matrix # <---- return from here

make_matrix(3, 2)
matrix = change_to_one(2, 1) # <---- save the returned result in a variable
print(matrix)

# [[0, 0, 0], [1, 0, 0]]


问:
Aggregation and Grouping with Pandas
I am trying to add a column of values based on account numbers and have the result show in a new column. Also, I'm identifying the first instance of the contract account as a Unique value and the others as duplicates.
For example:

```<code>Index   CA#   Duplicate?    $     $$
1      1101   True        440.4  880.80
2      1101   False       440.4  -
3      1102   True        440.8  440.80
4      1103   True        441.2  441.20
5      1106   True        442.4  1,327.20
6      1106   False       442.4  -
7      1106   False       442.4  -
</code>```

My first column 'CA#' are identifiers that I want to flag as True(or 1) if they're the first and only CA#, otherwise, I want them flagged as False(or 0).
For instance, CA# 1101 on Index 1 would receive a True and CA# 1101 on Index 2 would receive a False.

Then I'm trying to use that True flag to sum the total that each CA# is linked to on the $ column. In the CA#1101 case, the total $$ is 880.80.
So far I have only got as far as trying to generate a new column that has the boolean identifier for the unique values on the CA# column, but I get only True values on the new series that my code creates and I know that is wrong.

```<code>import pandas as pd
from pandas import DataFrame, Series
import numpy as np

file_name= ('A:\LEO\Documents\Mock data.xlsx')
sheet_name= ('Sheet1')
data = pd.read_excel(io= file_name, sheet= sheet_name)
data.sort_values('CA#', inplace= True)
data_ltd = DataFrame(data, columns=['CA#','$'])
bool_series = data_ltd['CA'].duplicated()
data_ltd ['bool_series'] = bool_series
print(data_ltd[bool_series].head(10))
</code>```

Title: Aggregation and Grouping with Pandas

Body:
I am trying to add a column of values based on account numbers and have the result show in a new column. Also, I'm identifying the first instance of the contract account as a Unique value and the others as duplicates.
For example:

Index   CA#   Duplicate?    $     $$
1      1101   True        440.4  880.80
2      1101   False       440.4  -
3      1102   True        440.8  440.80
4      1103   True        441.2  441.20
5      1106   True        442.4  1,327.20
6      1106   False       442.4  -
7      1106   False       442.4  -

My first column 'CA#' are identifiers that I want to flag as True(or 1) if they're the first and only CA#, otherwise, I want them flagged as False(or 0).
For instance, CA# 1101 on Index 1 would receive a True and CA# 1101 on Index 2 would receive a False.

Then I'm trying to use that True flag to sum the total that each CA# is linked to on the $ column. In the CA#1101 case, the total $$ is 880.80.
So far I have only got as far as trying to generate a new column that has the boolean identifier for the unique values on the CA# column, but I get only True values on the new series that my code creates and I know that is wrong.

import pandas as pd
from pandas import DataFrame, Series
import numpy as np

file_name= ('A:\LEO\Documents\Mock data.xlsx')
sheet_name= ('Sheet1')
data = pd.read_excel(io= file_name, sheet= sheet_name)
data.sort_values('CA#', inplace= True)
data_ltd = DataFrame(data, columns=['CA#','$'])
bool_series = data_ltd['CA'].duplicated()
data_ltd ['bool_series'] = bool_series
print(data_ltd[bool_series].head(10))

Body:
Use the inverse of duplicated:

~df.duplicated('CA#')

0     True
1    False
2     True
3     True
4     True
5    False
6    False
dtype: bool

df['Duplicate?'] = ~df.duplicated('CA#')

    CA#  Duplicate?      $        $$
0  1101        True  440.4    880.80
1  1101       False  440.4         -
2  1102        True  440.8    440.80
3  1103        True  441.2    441.20
4  1106        True  442.4  1,327.20
5  1106       False  442.4         -
6  1106       False  442.4         -

To get your $$ column, we can use groupby and np.where:

df['$$'] = df.groupby('CA#')['$'].transform('sum')
df['$$'] = np.where(df['$$'].duplicated(), '-', df['$$'])

    CA#  Duplicate?      $                  $$
0  1101        True  440.4               880.8
1  1101       False  440.4                   -
2  1102        True  440.8               440.8
3  1103        True  441.2               441.2
4  1106        True  442.4  1327.1999999999998
5  1106       False  442.4                   -
6  1106       False  442.4                   -


问:
monitor a program's memory usage in Linux
Are there any tools available in Linux which graphically or textually display memory usage for a program?  For example, if I write a C++ program and would like to verify that objects are being allocated and deallocated properly in memory, are there applications available that would visually show the objects being instantiated and deleted?  When I used to program in Visual Studio, I remember stepping through a program and using a debug pane to monitor memory usage and am looking for something similar to that in Linux.  </p>

答: I normally run top to keep an eye on overall memory usage.

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Nathan Fellman

OwnerDisplayName: anon


问:
Retrieving some values in array
Hi
I have an array of random question nos (ids). I have one form with a label for the question, a radiobutton list for their answers and a next button & checkbox to review that question. When I click the next button next(random from array) question appears. I want question id(array) those are checked for review.  How can I do this?
I used code as follows that calculates array (like this:10111) as i gives 1 value for checked & 0 for unchecked rather that this i want array of question ids those are checked :</p>

```<code>//Code gives array of checked values in terms of 1 & o
            int g;
            if (chkmark.Checked == true)
            {
                g = 1;
            }
            else
            {
                g = 0;
            }
            int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
            int[] temp1 = (int[])Session["arrofchk"];
            int k, no;

            if (temp1 == null)
                no = 0;
            else
                no = temp.Length;
            for (k = 0; k < no; k++)
            {
           chkarray[k] = temp1[k];
            }
            chkarray[j] = g;
</code>```

答:
I think you are generating the random questions correctly.

So when you click the next button you can check whether the checkbox for review question is checked or not. If its checked just save the corresponding id of question or save 0 into temp array and save it in session like you done.

Title: Retrieving some values in array

Body:
Hi
I have an array of random question nos (ids). I have one form with a label for the question, a radiobutton list for their answers and a next button & checkbox to review that question. When I click the next button next(random from array) question appears. I want question id(array) those are checked for review.  How can I do this?
I used code as follows that calculates array (like this:10111) as i gives 1 value for checked & 0 for unchecked rather that this i want array of question ids those are checked :

//Code gives array of checked values in terms of 1 & o
            int g;
            if (chkmark.Checked == true)
            {
                g = 1;
            }
            else
            {
                g = 0;
            }
            int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
            int[] temp1 = (int[])Session["arrofchk"];
            int k, no;

            if (temp1 == null)
                no = 0;
            else
                no = temp.Length;
            for (k = 0; k < no; k++)
            {
           chkarray[k] = temp1[k];
            }
            chkarray[j] = g;


问:
How to enable pagination on DRF GenericAPIView?
So I recently switched over from using APIView to GenericAPIView - hoping this would give me access to more DRF features - pagination being one of them.

My understanding was that I could just add this setting globally and pagination would just work on all GenericAPIViews

settings.py

```<code>REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 5
}
</code>```

This does not enable pagination.

So then I also defined pagination_class as a class attribute

```<code>class job(GenericAPIView):

    serializer_class = JobSerializer
    pagination_class = PageNumberPaginator
    def get_queryset(self):
        return Job.objects.all()

    def get(self, request, format=None):
        queryset = self.get_queryset()
        if queryset.exists():
            serializer = JobSerializer(queryset, many=True)
            return Response(serializer.data)
        else:
            return Response({"Returned empty queryset"}, status=status.HTTP_404_NOT_FOUND)
</code>```

Still no pagination.  This endpoint is returning over 100 records and adding string queries for ?page=1 or ?page=2 just returns the same 100+ list.

What am I doing wrong here?  I understand that I can just copy the DRF's paginator view methods inside my class - but I thought using GenericAPIView allowed me to easily leverage the built in pagination?

答:
Instead of returning Response object your should return self.get_paginated_response(...)

So the end of your code would be

```<code>return self.get_paginated_response(self.paginate_queryset(JobSerializer(queryset, many=True).data))
</code>```

Body:
So I recently switched over from using APIView to GenericAPIView - hoping this would give me access to more DRF features - pagination being one of them.

My understanding was that I could just add this setting globally and pagination would just work on all GenericAPIViews

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 5
}

This does not enable pagination.

So then I also defined pagination_class as a class attribute

class job(GenericAPIView):

    serializer_class = JobSerializer
    pagination_class = PageNumberPaginator
    def get_queryset(self):
        return Job.objects.all()

    def get(self, request, format=None):
        queryset = self.get_queryset()
        if queryset.exists():
            serializer = JobSerializer(queryset, many=True)
            return Response(serializer.data)
        else:
            return Response({"Returned empty queryset"}, status=status.HTTP_404_NOT_FOUND)

Still no pagination.  This endpoint is returning over 100 records and adding string queries for ?page=1 or ?page=2 just returns the same 100+ list.

What am I doing wrong here?  I understand that I can just copy the DRF's paginator view methods inside my class - but I thought using GenericAPIView allowed me to easily leverage the built in pagination?

Body:
Instead of returning Response object your should return self.get_paginated_response(...)

So the end of your code would be

return self.get_paginated_response(self.paginate_queryset(JobSerializer(queryset, many=True).data))


问:
How to use an Area in ASP.NET Core
How do I use an Area in ASP.NET Core?

I have an app that needs an Admin section. This section requires its Views to be placed in that area. All requests that start with Admin/ will need to be redirected to that area.

答:
Areas Implementation in Routing
First Create Area(Admin) using VS and add the following code into Startup.cs
First Way to Implement:-
Add Controller Login and Index Action and add Following Code, [Area(“Admin”)] is compulsory to add on controller level to perform asp.net areas Routing.
Startup.cs

```<code> app.UseMvc(routes =>
            {
                routes.MapRoute(
                  name: "areas",
                  template: "{area:exists}/{controller=Login}/{action=Index}/{id?}"
                );
            });
</code>```

Note: Area routing must be placed first with non area routing, area: exists is compulsory to add area  routing.

Controller Code:

```<code>[Area("Admin")]
    public class LoginController : Controller
    {
        public IActionResult Index()
        {
            return Content("Area Admin Login Controller and Index Action");
        }
    }
</code>```

This route may be called using http://localhost:111/Admin

Second Way to Implement Area Routing:-
Add Following code into startup.cs.

```<code>app.UseMvc(routes =>
            {
                routes.MapAreaRoute(
    name: "default",
    areaName: "Guest",
    template: "Guest/{controller}/{action}/{id?}",
    defaults: new { controller = "GuestLogin", action = "Index" });
            });
</code>```

Create an Area “Guest”, Add “GuestLogin” Controller and “Index” Action and add the following code into the newly created controller.

```<code>[Area("Guest")]
    public class GuestLoginController : Controller
    {
        public IActionResult Index()
        {
            return Content("Area Guest Login Controller and Index Action");
        }
    }
</code>```

This route may be called using http://localhost:111/Guest

Title: How to use an Area in ASP.NET Core

Body:
Areas Implementation in Routing
First Create Area(Admin) using VS and add the following code into Startup.cs
First Way to Implement:-
Add Controller Login and Index Action and add Following Code, [Area(“Admin”)] is compulsory to add on controller level to perform asp.net areas Routing.
Startup.cs

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                  name: "areas",
                  template: "{area:exists}/{controller=Login}/{action=Index}/{id?}"
                );
            });

Note: Area routing must be placed first with non area routing, area: exists is compulsory to add area  routing.

Controller Code:

[Area("Admin")]
    public class LoginController : Controller
    {
        public IActionResult Index()
        {
            return Content("Area Admin Login Controller and Index Action");
        }
    }

This route may be called using http://localhost:111/Admin

Second Way to Implement Area Routing:-
Add Following code into startup.cs.

app.UseMvc(routes =>
            {
                routes.MapAreaRoute(
    name: "default",
    areaName: "Guest",
    template: "Guest/{controller}/{action}/{id?}",
    defaults: new { controller = "GuestLogin", action = "Index" });
            });

Create an Area “Guest”, Add “GuestLogin” Controller and “Index” Action and add the following code into the newly created controller.

[Area("Guest")]
    public class GuestLoginController : Controller
    {
        public IActionResult Index()
        {
            return Content("Area Guest Login Controller and Index Action");
        }
    }

This route may be called using http://localhost:111/Guest


问:
Refer to a Property name using a Variable in Linq
I am trying to access a property "DailyQtyOrders_01" in my object using the first code below, this works ok.
but now i want to use it in a linq expression on the second line code, this works, but i want the property to be variable (3rd line code), this throws error. What is the method to do that?</p>

```<code>item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5);

productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().DailyQtyOrders_01 = 5;

productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5);
</code>```

答:
The problem lies in the last part of your third linq statement.

```<code>productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5);
</code>```

In the above code, you are assigning the value of "DailyQtyOrders_01" in an instance of "item". This is not the same instance of your linq query refers to, but the variable "item" you have created/referred above.

```<code>.GetProperty("DailyQtyOrders_01").SetValue(item, 5);
</code>```

What you need to do would be to split the query into two parts, and refer the instance on which you want the value to be set.

For example

```<code>var itemInstance =  productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().item;
itemInstance.GetType().GetProperty("DailyQtyOrders_01").SetValue(itemInstance, 5);
productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().item = itemInstance;
</code>```

Body:
I am trying to access a property "DailyQtyOrders_01" in my object using the first code below, this works ok.
but now i want to use it in a linq expression on the second line code, this works, but i want the property to be variable (3rd line code), this throws error. What is the method to do that?

item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5);

productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().DailyQtyOrders_01 = 5;

productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5);

Body:
The problem lies in the last part of your third linq statement.

productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().item.GetType().GetProperty("DailyQtyOrders_01").SetValue(item, 5);

In the above code, you are assigning the value of "DailyQtyOrders_01" in an instance of "item". This is not the same instance of your linq query refers to, but the variable "item" you have created/referred above.

.GetProperty("DailyQtyOrders_01").SetValue(item, 5);

What you need to do would be to split the query into two parts, and refer the instance on which you want the value to be set.

For example

var itemInstance =  productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().item;
itemInstance.GetType().GetProperty("DailyQtyOrders_01").SetValue(itemInstance, 5);
productsSales.Where(x => x.sellerId == item.sellerId).FirstOrDefault().item = itemInstance;


问:
String index out of range: -5
I have a problem when i test runQuery, the problem is String index out of range: -5 and i can't find the solution

```<code>@Test
void testRunQuery() throws FileNotFoundException, IOException, InterruptedException {
    final Answer answer = new Answer();
    String[] args = new String[5];

    final String year = "yyyy ";
    final String month = "mm ";
    final String day = "dd ";
    final String limit = "limit ";
    args[0] = year.substring(5);
    args[1] = month.substring(3);
    args[2] = day.substring(3);
    args[3] = null;
    args[4] = limit.substring(6);

    Job result = answer.runQuery(args);
    assertNotNull(result);

}
</code>```

And this is runQuery where i make the query

```<code>public  Job runQuery(final String[] args) throws InterruptedException {
    // Use standard SQL syntax for queries.
    // See: https://cloud.google.com/bigquery/sql-reference/
    // Variabili per le query
    final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE)),
            mm=Integer.valueOf(args[ONE].substring(THREE)),
            dd=Integer.valueOf(args[TWO].substring(THREE)),
            limit=Integer.valueOf(args[FOUR].substring(SIX));

final QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(
    "SELECT DISTINCT owner_user_id "
    + "FROM `bigquery-public-data.stackoverflow.posts_answers` "
    + "WHERE extract(year from creation_date) = @yyyy "
    + "AND extract(month from creation_date) = @mm "
    + "AND extract(day from creation_date) = @dd "
    + "AND owner_user_id is not null "
    + "AND owner_user_id > 0 "
    + "ORDER BY owner_user_id ASC LIMIT @limit ")
    .addNamedParameter("yyyy", QueryParameterValue.int64(yyyy))
    .addNamedParameter("mm", QueryParameterValue.int64(mm))
    .addNamedParameter("dd", QueryParameterValue.int64(dd))
    .addNamedParameter("limit", QueryParameterValue.int64(limit))
    .setUseLegacySql(false).build();

        // Create a job ID so that we can safely retry.
final JobId jobId = JobId.of(UUID.randomUUID().toString());
Job queryJob=bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

// Wait for the query to complete.
queryJob = queryJob.waitFor();

        // Check for errors
        if (queryJob == null) {
            throw new RuntimeException("Job no longer exists");
        } else if (queryJob.getStatus().getError() != null) {
            // You can also look at queryJob.getStatus().getExecutionErrors() for all
            // errors, not just the latest one.
            throw new RuntimeException(queryJob.getStatus().getError().toString());
        }
        return queryJob;
    }
</code>```

```<code>String index out of range: -5 at the line 93 of runQuery; this is the line:
final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE))
</code>```

答:
You have misunderstood what argument Java's String.substring function takes.

In short, you appear to think the argument takes the length of the substring.  It doesn't - rather, it specifies the "begin-index" - ie. where in the supplied string to start copying.

So when you say :

```<code>final String year = "yyyy ";
args[0] = year.substring(5);
</code>```

you are NOT actually setting args[0] to a 5-character string.  In stead, you are setting it to the part of string "yyyy " starting at position 5 - in other words, you are setting it to empty-string.

So when you subsequently say

```<code>final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE)),
</code>```

and assuming you have ZERO set to 0 and FIVE to 5, this will fail since you have args[0] as empty-string "", and you can't get a substring starting at position 5 from "".

To sum up, if you have

```<code>    String myString = "smiles";

    System.out.println("substring(0, 4) = <" + myString.substring(0, 4) + ">");
    System.out.println("substring(2, 4) = <" + myString.substring(2, 4) + ">");
    System.out.println("substring(4)    = <" + myString.substring(4) + ">");
</code>```

the output will be :

```<code>substring(0, 4) = <smil>
substring(2, 4) = <il>
substring(4)    = <es>
</code>```

In short, get rid of your ".substring" calls in both your test and your main code.

Check out the spec at https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)

Title: String index out of range: -5

Body:
I have a problem when i test runQuery, the problem is String index out of range: -5 and i can't find the solution

@Test
void testRunQuery() throws FileNotFoundException, IOException, InterruptedException {
    final Answer answer = new Answer();
    String[] args = new String[5];

    final String year = "yyyy ";
    final String month = "mm ";
    final String day = "dd ";
    final String limit = "limit ";
    args[0] = year.substring(5);
    args[1] = month.substring(3);
    args[2] = day.substring(3);
    args[3] = null;
    args[4] = limit.substring(6);

    Job result = answer.runQuery(args);
    assertNotNull(result);

}

And this is runQuery where i make the query

public  Job runQuery(final String[] args) throws InterruptedException {
    // Use standard SQL syntax for queries.
    // See: https://cloud.google.com/bigquery/sql-reference/
    // Variabili per le query
    final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE)),
            mm=Integer.valueOf(args[ONE].substring(THREE)),
            dd=Integer.valueOf(args[TWO].substring(THREE)),
            limit=Integer.valueOf(args[FOUR].substring(SIX));

final QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(
    "SELECT DISTINCT owner_user_id "
    + "FROM `bigquery-public-data.stackoverflow.posts_answers` "
    + "WHERE extract(year from creation_date) = @yyyy "
    + "AND extract(month from creation_date) = @mm "
    + "AND extract(day from creation_date) = @dd "
    + "AND owner_user_id is not null "
    + "AND owner_user_id > 0 "
    + "ORDER BY owner_user_id ASC LIMIT @limit ")
    .addNamedParameter("yyyy", QueryParameterValue.int64(yyyy))
    .addNamedParameter("mm", QueryParameterValue.int64(mm))
    .addNamedParameter("dd", QueryParameterValue.int64(dd))
    .addNamedParameter("limit", QueryParameterValue.int64(limit))
    .setUseLegacySql(false).build();

        // Create a job ID so that we can safely retry.
final JobId jobId = JobId.of(UUID.randomUUID().toString());
Job queryJob=bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

// Wait for the query to complete.
queryJob = queryJob.waitFor();

        // Check for errors
        if (queryJob == null) {
            throw new RuntimeException("Job no longer exists");
        } else if (queryJob.getStatus().getError() != null) {
            // You can also look at queryJob.getStatus().getExecutionErrors() for all
            // errors, not just the latest one.
            throw new RuntimeException(queryJob.getStatus().getError().toString());
        }
        return queryJob;
    }

String index out of range: -5 at the line 93 of runQuery; this is the line:
final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE))

Body:
You have misunderstood what argument Java's String.substring function takes.

In short, you appear to think the argument takes the length of the substring.  It doesn't - rather, it specifies the "begin-index" - ie. where in the supplied string to start copying.

So when you say :

final String year = "yyyy ";
args[0] = year.substring(5);

you are NOT actually setting args[0] to a 5-character string.  In stead, you are setting it to the part of string "yyyy " starting at position 5 - in other words, you are setting it to empty-string.

So when you subsequently say

final Integer yyyy=Integer.valueOf(args[ZERO].substring(FIVE)),

and assuming you have ZERO set to 0 and FIVE to 5, this will fail since you have args[0] as empty-string "", and you can't get a substring starting at position 5 from "".

To sum up, if you have

    String myString = "smiles";

    System.out.println("substring(0, 4) = <" + myString.substring(0, 4) + ">");
    System.out.println("substring(2, 4) = <" + myString.substring(2, 4) + ">");
    System.out.println("substring(4)    = <" + myString.substring(4) + ">");

the output will be :

substring(0, 4) = <smil>
substring(2, 4) = <il>
substring(4)    = <es>

In short, get rid of your ".substring" calls in both your test and your main code.

Check out the spec at https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)


问:
Do Self Hosted Agents require dedicated machines?
I am migrating XAML Builds to Azure Devops. Goal is to remove the dedicated Build Staging server to cut costs.

Following is the process:
1) Build ASP.NET Web Application.
2) Copy configs, assemblies, WebPackage from Build output to various folders in UNC share which will be later picked up by a Release Pipeline Job.

Since Microsoft Hosted Agents dont allow usage of UNC share, I wanted to use Self Hosted Agent.

Question:
Can I use a Self Hosted Agent without the necessity of a dedicated server to hold the Build Output in Image or Container which can then be copied to the UNC Share? I am new to Devops and hence the articles on MS confused me if I need a dedicated server or not.

Tried to set up a Self Hosted Agent pool, but the steps suggest that I require a machine where the Self Hosted Agent need to be setup. If this is the case then it means I will be requiring a dedicated machine like in XAML process. Am I blabbering? Please excuse if yes :-)

Expected Result: Run a Build Pipeline with Self Hosted Agents on Cloud without the requirement of a Dedicated Server.

答:
...Since Microsoft Hosted Agents dont allow usage of UNC share...

This is not a problem, there is no reason for you to use UNC shares.

You don't need to access UNC shares to store artifacts for later consumption; use the Publish Artifacts build activity. That will store your build outputs internally and make them available to downstream releases.


问:
Example code for jquery dialog
I need to create a jquery modal dialog with an image inside the modal box.
The dialog box should be closed only when user click on the image.

I never use jquery;Can someone provide me an example code?

答:
take a look at Jquery UI its the most common dialog box in the jquery world ;)

http://jqueryui.com/demos/dialog/

Try this:

html:

```<code>  <a href="#" id="target">derp</a>
    <div id="dialog"><img src="http://sstatic.net/stackoverflow/img/sprites.png?v=3"/></div>
</code>```

jquery

```<code>  $(document).ready(function() {
    $('#target').click(function() {

                 $('#dialog').dialog('open');

    return false;
    });

    $('img').click(function() {

         $('#dialog').dialog('close');

    });
    });
</code>```

Title: Example code for jquery dialog

Body:
take a look at Jquery UI its the most common dialog box in the jquery world ;)

http://jqueryui.com/demos/dialog/

Try this:

html:

  <a href="#" id="target">derp</a>
    <div id="dialog"><img src="http://sstatic.net/stackoverflow/img/sprites.png?v=3"/></div>

jquery

  $(document).ready(function() {
    $('#target').click(function() {

                 $('#dialog').dialog('open');

    return false;
    });

    $('img').click(function() {

         $('#dialog').dialog('close');

    });
    });


问:
Check if child component rendered - Jest, Enzyme
In my unit test, I want to test whether the parent component is successfully rendering its child component. Here is the code:

```<code>describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.find(Child).length).toEqual(1);
  });
});
</code>```

Parent:

```<code>const Parent = observer(({ store }) => {
  const bookList = toJS(store.planets);
  return (
    <div>
      <div className={style.planet_container}>
        {bookList.map(book => {
          return <Child key={book.name} name={book.name} />;
        })}
      </div>
    </div>
  );
});
</code>```

Above code is taken from here, but it's not working. I am getting the following error:

Expected 1, Received 0'

Where am I going wrong? I am using Enzyme 3.3 with Jest 23.1.0.

答:
Child is not rendering because you are not mocking the props (in this case the prop "store") correctly.

Try this:

it('renders Child component', () => {
  const wrapper = shallow( < Parent / > );
  wrapper.setProps({
    store: {
      planets: [{
          name: "name 1"
        }
      ]
    }
  });
  expect(wrapper.find(Child)).toHaveLength(1);
});```

Body:
In my unit test, I want to test whether the parent component is successfully rendering its child component. Here is the code:

describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.find(Child).length).toEqual(1);
  });
});

Parent:

const Parent = observer(({ store }) => {
  const bookList = toJS(store.planets);
  return (

        {bookList.map(book => {
          return <Child key={book.name} name={book.name} />;
        })}

  );
});

Above code is taken from here, but it's not working. I am getting the following error:

Expected 1, Received 0'

Where am I going wrong? I am using Enzyme 3.3 with Jest 23.1.0.


问:
Is it possible to run multiple animations with an overall rate_func?
The following is my current code:

from manimlib.imports import *

class ClockOrganization(VGroup):
  CONFIG = {
    "numbers" : 4,
    "radius" : 3.1,
    "color" : WHITE
  }

  def __init__(self, **kwargs):
    digest_config(self, kwargs, locals())
    self.generate_nodes()
    VGroup.__init__(self, *self.node_list,**kwargs)

  def generate_nodes(self):
    self.node_list = []
    for i in range(self.numbers):
      mobject = VMobject()
      number = TexMobject(str(i+1))
      circle = Circle(radius=0.4,color=self.color)
      mobject.add(number)
      mobject.add(circle)
      mobject.move_to(
        self.radius * np.cos((-TAU / self.numbers) * i + 17*TAU / 84) * RIGHT
        + self.radius * np.sin((-TAU / self.numbers) * i + 17*TAU / 84) * UP
      )
      self.node_list.append(mobject)

  def select_node(self, node):
    selected_node = self.node_list[node]
    selected_node.scale(1.2)
    selected_node.set_color(RED)

  def deselect_node(self, selected_node):
    node = self.node_list[selected_node]
    node.scale(0.8)
    node.set_color(self.color)

class Testing3(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    for i in range(10):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    for i in range(1,10):
      self.play(Transform(test, animation_steps[i]),run_time=0.3)
    self.wait()
```

<p>If you run it currently, it highlights 19, then revolves to 7 at a uniform pace. Is it possible to set a <code>rate_func</code> for this overall process, so it starts revolving slowly, speeds up halfway, then slows its way to 7, like the smooth <code>rate_func</code> but applied over the entire thing?</p>

<p>I have tried changing the above Scene class to</p>

<pre class="lang-py prettyprint-override"><code>class Testing3(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    for i in range(10):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    for i in range(1,10):
      if i in range(1,6):
        time_to_run=(sigmoid(10*(-i/4+.75))-sigmoid(-5))/(1-2*sigmoid(-5)+3)+.1
      if i in range(6,10):
        time_to_run=(sigmoid(10*(i/4-1.75))-sigmoid(-5))/(1-2*sigmoid(-5)+3)+.1
      self.play(Transform(test, animation_steps[i]),run_time=time_to_run)
    self.wait()
</code>```

and it comes close to what I'm going for, but the Transforms seem rather choppy.

答:
I don't know if you mean this:</p>

```<code>class Testing4(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    #animation_steps.append(test)
    num_circ=15
    for i in range(num_circ):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    test_normal=test.copy()
    test.save_state()
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    self.play(Restore(test))
    anims=[]
    for i in range(1,num_circ):
        test.node_list[(19+i)%test.numbers-1].generate_target()
        test.node_list[(19+i)%test.numbers-1].target.scale(1.2)
        test.node_list[(19+i)%test.numbers-1].target.set_color(RED)
        anims.append(MoveToTarget(test.node_list[(19+i)%test.numbers-1],rate_func=there_and_back))
    self.play(
        AnimationGroup(*anims,lag_ratio=0.1)
        )
    self.wait()
</code>```

Body:
The following is my current code:

from manimlib.imports import *

class ClockOrganization(VGroup):
  CONFIG = {
    "numbers" : 4,
    "radius" : 3.1,
    "color" : WHITE
  }

  def __init__(self, **kwargs):
    digest_config(self, kwargs, locals())
    self.generate_nodes()
    VGroup.__init__(self, *self.node_list,**kwargs)

  def generate_nodes(self):
    self.node_list = []
    for i in range(self.numbers):
      mobject = VMobject()
      number = TexMobject(str(i+1))
      circle = Circle(radius=0.4,color=self.color)
      mobject.add(number)
      mobject.add(circle)
      mobject.move_to(
        self.radius * np.cos((-TAU / self.numbers) * i + 17*TAU / 84) * RIGHT
        + self.radius * np.sin((-TAU / self.numbers) * i + 17*TAU / 84) * UP
      )
      self.node_list.append(mobject)

  def select_node(self, node):
    selected_node = self.node_list[node]
    selected_node.scale(1.2)
    selected_node.set_color(RED)

  def deselect_node(self, selected_node):
    node = self.node_list[selected_node]
    node.scale(0.8)
    node.set_color(self.color)

class Testing3(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    for i in range(10):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    for i in range(1,10):
      self.play(Transform(test, animation_steps[i]),run_time=0.3)
    self.wait()

If you run it currently, it highlights 19, then revolves to 7 at a uniform pace. Is it possible to set a rate_func for this overall process, so it starts revolving slowly, speeds up halfway, then slows its way to 7, like the smooth rate_func but applied over the entire thing?

I have tried changing the above Scene class to

class Testing3(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    for i in range(10):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    for i in range(1,10):
      if i in range(1,6):
        time_to_run=(sigmoid(10*(-i/4+.75))-sigmoid(-5))/(1-2*sigmoid(-5)+3)+.1
      if i in range(6,10):
        time_to_run=(sigmoid(10*(i/4-1.75))-sigmoid(-5))/(1-2*sigmoid(-5)+3)+.1
      self.play(Transform(test, animation_steps[i]),run_time=time_to_run)
    self.wait()

and it comes close to what I'm going for, but the Transforms seem rather choppy.

Body:
I don't know if you mean this:

class Testing4(Scene):
  def construct(self):
    test = ClockOrganization(numbers=21)
    self.play(Write(test), run_time=1.5)
    animation_steps=[]
    #animation_steps.append(test)
    num_circ=15
    for i in range(num_circ):
      thing = test.deepcopy()
      thing.select_node((19+i)%test.numbers-1)
      animation_steps.append(thing)
    test_normal=test.copy()
    test.save_state()
    self.play(Transform(test, animation_steps[0]))
    self.wait(2)
    self.play(Restore(test))
    anims=[]
    for i in range(1,num_circ):
        test.node_list[(19+i)%test.numbers-1].generate_target()
        test.node_list[(19+i)%test.numbers-1].target.scale(1.2)
        test.node_list[(19+i)%test.numbers-1].target.set_color(RED)
        anims.append(MoveToTarget(test.node_list[(19+i)%test.numbers-1],rate_func=there_and_back))
    self.play(
        AnimationGroup(*anims,lag_ratio=0.1)
        )
    self.wait()


答:
This has to do with pointers.
You first define row=[]
When you do this matrix.append(row) num2 times, you are appending the address of row, hence if you change row anytime, it will be broadcasted subsequently.

In other words, changing data in row will change data everywhere you appended row to which in your case is all rows of 2D matrix.

Try this code:

```<code>def make_matrix(num1, num2):
    for i in range(num2):
      row = []
      for i in range(num1):
          row.append(0)
      matrix.append(row)
</code>```

Here we create a new row everytime and then append it to our matrix, this way changes in any row will not be broadcasted.

Title: How to call an element in an 2D python array

Body:
This has to do with pointers.
You first define row=[]
When you do this matrix.append(row) num2 times, you are appending the address of row, hence if you change row anytime, it will be broadcasted subsequently.

In other words, changing data in row will change data everywhere you appended row to which in your case is all rows of 2D matrix.

Try this code:

def make_matrix(num1, num2):
    for i in range(num2):
      row = []
      for i in range(num1):
          row.append(0)
      matrix.append(row)

Here we create a new row everytime and then append it to our matrix, this way changes in any row will not be broadcasted.


问:
Regex to remove year from a string PHP
I have created a database of cigarette and trading cards. Each set title has a year associated with it. For example, 1943 or 2011. The year is always 4 characters long, but can be anywhere in the string.

Could someone please help me create a regex that will find the year in the string. I tried '/d{4}\b/' but it is failing.

答:
Here is a full solution:</p>

```<code>$stringWithYear = '1990 New York Marathon';
$stringNoYear = preg_replace('/(19|20)[0-9][0-9]/', '', $stringWithYear);
echo trim($stringNoYear);  // outputs 'New York Marathon'
</code>```

Title: Regex to remove year from a string PHP

Body:
Here is a full solution:

$stringWithYear = '1990 New York Marathon';
$stringNoYear = preg_replace('/(19|20)[0-9][0-9]/', '', $stringWithYear);
echo trim($stringNoYear);  // outputs 'New York Marathon'


问:
How to fix an OLE DB error in SQL Server Data Tools
I'm trying to transfer columns from database tables into a fact table in a data warehouse.

I'm using the following SQL command to retrieve data

```<code>SELECT employée.matricule, accident.[code accident], prestataire.[N°],
visite.[date visite], accident.[date accident] ,remboursement.[montant rem], visite.[Nbre Jours Acc]
FROM
    visite, employée, accident, prestataire, remboursement, bordereaux
WHERE
    employée.matricule=accident.matricule AND
    employée.matricule= visite.matricule AND
    prestataire.valeur = bordereaux.prestataire AND
    bordereaux.matricule = employée.matricule AND
    remboursement.[numéro du bulletin] = bodereaux.[numéro du bulletin]
</code>```

The column [numéro du bulletin] exists in the table "bodereaux" and "remboursement" but I don't understand why I keep getting this error

Error   2

Validation error. Data Flow Task OLE DB Source [48]: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80040E14.  An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80040E14  Description: "Statement(s) could not be prepared.".  An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80040E14  Description: "The multi-part identifier "bodereaux.numéro du bulletin" could not be bound.".    FaitAccident.dtsx   0   0

答:
Try using the following query:</p>

```<code>SELECT
    employée.matricule,
    accident.[code accident],
    prestataire.[N°],
    visite.[date visite],
    accident.[date accident],
    remboursement.[montant rem],
    visite.[Nbre Jours Acc]
FROM
    visite INNER JOIN employée ON employée.matricule = visite.matricule
           INNER JOIN accident ON employée.matricule = accident.matricule
           INNER JOIN bordereaux ON bordereaux.matricule = employée.matricule
           INNER JOIN remboursement ON remboursement.[numéro du bulletin] = bodereaux.[numéro du bulletin]
           INNER JOIN prestataire ON prestataire.valeur = bordereaux.prestataire
</code>```

Body:
I'm trying to transfer columns from database tables into a fact table in a data warehouse.

I'm using the following SQL command to retrieve data

SELECT employée.matricule, accident.[code accident], prestataire.[N°],
visite.[date visite], accident.[date accident] ,remboursement.[montant rem], visite.[Nbre Jours Acc]
FROM
    visite, employée, accident, prestataire, remboursement, bordereaux
WHERE
    employée.matricule=accident.matricule AND
    employée.matricule= visite.matricule AND
    prestataire.valeur = bordereaux.prestataire AND
    bordereaux.matricule = employée.matricule AND
    remboursement.[numéro du bulletin] = bodereaux.[numéro du bulletin]

The column [numéro du bulletin] exists in the table "bodereaux" and "remboursement" but I don't understand why I keep getting this error

Error   2

Validation error. Data Flow Task OLE DB Source [48]: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80040E14.  An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80040E14  Description: "Statement(s) could not be prepared.".  An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80040E14  Description: "The multi-part identifier "bodereaux.numéro du bulletin" could not be bound.".    FaitAccident.dtsx   0   0

Body:
Try using the following query:

SELECT
    employée.matricule,
    accident.[code accident],
    prestataire.[N°],
    visite.[date visite],
    accident.[date accident],
    remboursement.[montant rem],
    visite.[Nbre Jours Acc]
FROM
    visite INNER JOIN employée ON employée.matricule = visite.matricule
           INNER JOIN accident ON employée.matricule = accident.matricule
           INNER JOIN bordereaux ON bordereaux.matricule = employée.matricule
           INNER JOIN remboursement ON remboursement.[numéro du bulletin] = bodereaux.[numéro du bulletin]
           INNER JOIN prestataire ON prestataire.valeur = bordereaux.prestataire


问:
collectionView didSlectRow bug
Hello on a specific viewController of my project i have a UICollectionView with a custom class cell. But i have a big problem this that func :

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("tapped on a cell")
    }
```

when is click on a cell and instant realease (normal click) it does nothing, just nothing.

if i press and hold about 1s without release the finger it become grey, highlighted

And if i press and hold at least 3 seconds release the finger didSelectItemAt is executed correctly.
I tried to do the same on another project and that's work great but not on this VC and i really don't find the problem. The VC Bugged is of addTest clas in Main.storyboard

答:
The insight of Mojtaba Hosseini is very clever, but the answer given might not be quite correct.

It turns out that there is a UITapGestureRecognizer on the main view; if it recognizes before the tap on the cell, it prevents cell selection. But if you merely set cancelsTouchesInView to false on that gesture recognizer, then they both operate, and that seems unlikely to be what is wanted. We surely want the cell tap and not the tap gesture recognizer tap.

The correct solution is thus to give the tap gesture recognizer a delegate and implement gestureRecognizerShouldBegin. Here, we look to see where the tap is. If it is within the bounds of a cell, we return false; otherwise we return true. We thus mediate between the cell tap and gesture recognizer tap.

Here is a possible implementation, demonstrated in a highly simplified form:

```<code>extension UIView {
    func isDescendant(of whattype:UIView.Type) -> Bool {
        var sup : UIView? = self.superview
        while sup != nil {
            if (whattype == type(of:sup!)) {
                return true
            }
            sup = sup!.superview
        }
        return false
    }
}

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        let t = UITapGestureRecognizer(target: self, action: #selector(tap))
        self.view.addGestureRecognizer(t)
        t.delegate = self
    }

    @objc func tap(_:UIGestureRecognizer) {
        print("tap")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("select")
    }

    func gestureRecognizerShouldBegin(_ gr: UIGestureRecognizer) -> Bool {
        if let v = gr.view {
            let loc = gr.location(in: v)
            if let v2 = v.hitTest(loc, with: nil) {
                return !v2.isDescendant(of: UICollectionViewCell.self)
            }
        }
        return true
    }
}
</code>```

As you can see, we look to see whether the tap is inside a collection view cell; if it is, our gesture recognizer is prevented from recognizing, and the selection succeeds immediately.

Title: collectionView didSlectRow bug

Body:
Hello on a specific viewController of my project i have a UICollectionView with a custom class cell. But i have a big problem this that func :

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("tapped on a cell")
    }

when is click on a cell and instant realease (normal click) it does nothing, just nothing.

if i press and hold about 1s without release the finger it become grey, highlighted

And if i press and hold at least 3 seconds release the finger didSelectItemAt is executed correctly.
I tried to do the same on another project and that's work great but not on this VC and i really don't find the problem. The VC Bugged is of addTest clas in Main.storyboard

Body:
The insight of Mojtaba Hosseini is very clever, but the answer given might not be quite correct.

It turns out that there is a UITapGestureRecognizer on the main view; if it recognizes before the tap on the cell, it prevents cell selection. But if you merely set cancelsTouchesInView to false on that gesture recognizer, then they both operate, and that seems unlikely to be what is wanted. We surely want the cell tap and not the tap gesture recognizer tap.

The correct solution is thus to give the tap gesture recognizer a delegate and implement gestureRecognizerShouldBegin. Here, we look to see where the tap is. If it is within the bounds of a cell, we return false; otherwise we return true. We thus mediate between the cell tap and gesture recognizer tap.

Here is a possible implementation, demonstrated in a highly simplified form:

extension UIView {
    func isDescendant(of whattype:UIView.Type) -> Bool {
        var sup : UIView? = self.superview
        while sup != nil {
            if (whattype == type(of:sup!)) {
                return true
            }
            sup = sup!.superview
        }
        return false
    }
}

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        let t = UITapGestureRecognizer(target: self, action: #selector(tap))
        self.view.addGestureRecognizer(t)
        t.delegate = self
    }

    @objc func tap(_:UIGestureRecognizer) {
        print("tap")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("select")
    }

    func gestureRecognizerShouldBegin(_ gr: UIGestureRecognizer) -> Bool {
        if let v = gr.view {
            let loc = gr.location(in: v)
            if let v2 = v.hitTest(loc, with: nil) {
                return !v2.isDescendant(of: UICollectionViewCell.self)
            }
        }
        return true
    }
}

As you can see, we look to see whether the tap is inside a collection view cell; if it is, our gesture recognizer is prevented from recognizing, and the selection succeeds immediately.


问:
Xcode error kCFNumberFormatterCurrencyStyle
I'm trying to format $123,123 USA currency in an app displaying properties on a map. The number show $(null) should show the #

Incompatible integer to pointer conversion initializing 'NSInteger *' (aka 'long *') with an expression of type 'NSInteger' (aka 'long')

Implicit conversion from enumeration type 'enum CFNumberFormatterStyle' to different enumeration type 'NSNumberFormatterStyle' (aka 'enum NSNumberFormatterStyle')

```<code>cell.imgViewPropertyType.image = [UIImage imageNamed:@"for_sale"];
NSInteger *intPrice = [theProperty.priceSale integerValue];
NSNumber *tempPrice = [NSNumber numberWithInteger:intPrice];
NSString *price = [NSNumberFormatter localizedStringFromNumber:tempPrice numberStyle:kCFNumberFormatterCurrencyStyle];
</code>```

答:
Try with this. Note that intPrice is not a pointer and hence you need to declare as NSInteger intPrice instead of NSInteger *intPrice. That is the reason for the error which you are getting.

```<code>cell.imgViewPropertyType.image = [UIImage imageNamed:@"for_sale"];
NSInteger intPrice = [theProperty.priceSale integerValue];
NSNumber *tempPrice = [NSNumber numberWithInteger:intPrice];
</code>```

As rmaddy pointed below, you can also use below line.

```<code>NSNumber *tempPrice = @(intPrice);
</code>```

Regarding second error about CFNumberFormatterStyle, localizedStringFromNumber accepts NSNumberFormatterStyle and not type CFNumberFormatterStyle. You are trying to pass wrong type of style there. Try with NSNumberFormatterCurrencyStyle.

```<code>NSString *price = [NSNumberFormatter localizedStringFromNumber:tempPrice numberStyle:NSNumberFormatterCurrencyStyle];
</code>```

Body:
I'm trying to format $123,123 USA currency in an app displaying properties on a map. The number show $(null) should show the #

Incompatible integer to pointer conversion initializing 'NSInteger *' (aka 'long *') with an expression of type 'NSInteger' (aka 'long')

Implicit conversion from enumeration type 'enum CFNumberFormatterStyle' to different enumeration type 'NSNumberFormatterStyle' (aka 'enum NSNumberFormatterStyle')

cell.imgViewPropertyType.image = [UIImage imageNamed:@"for_sale"];
NSInteger *intPrice = [theProperty.priceSale integerValue];
NSNumber *tempPrice = [NSNumber numberWithInteger:intPrice];
NSString *price = [NSNumberFormatter localizedStringFromNumber:tempPrice numberStyle:kCFNumberFormatterCurrencyStyle];

Body:
Try with this. Note that intPrice is not a pointer and hence you need to declare as NSInteger intPrice instead of NSInteger *intPrice. That is the reason for the error which you are getting.

cell.imgViewPropertyType.image = [UIImage imageNamed:@"for_sale"];
NSInteger intPrice = [theProperty.priceSale integerValue];
NSNumber *tempPrice = [NSNumber numberWithInteger:intPrice];

As rmaddy pointed below, you can also use below line.

NSNumber *tempPrice = @(intPrice);

Regarding second error about CFNumberFormatterStyle, localizedStringFromNumber accepts NSNumberFormatterStyle and not type CFNumberFormatterStyle. You are trying to pass wrong type of style there. Try with NSNumberFormatterCurrencyStyle.

NSString *price = [NSNumberFormatter localizedStringFromNumber:tempPrice numberStyle:NSNumberFormatterCurrencyStyle];


问:
hg convert from Subversion on macOS -- could not load Subversion python bindings?
I want to convert a subversion repository to mercurial on macOS.  I've made a local copy of the svn repo.  Then I tried

```<code>hg convert --source-type svn --dest-type hg srcPath dstPath
</code>```

and got

```<code>could not load Subversion python bindings
abort: srcPath: missing or unsupported repository
</code>```

I found this page on the convert extension, which talks about needing Subversion python bindings.  One thing it says is

Bindings are included with the TortoiseHg distribution package and the Win32 InnoSetup (non-MSI) binaries for Mercurial, so if you install either of them you don't need to install additional packages.

Well, I installed TortoiseHG, which is an application on macOS, but I don't see how that helps.

It also says

For Mac OS X, the easiest way is to install the CollabNet Subversion build, and then copy the content of /opt/subversion/lib/svn-python to the site-package directory of the Python installation.

So I follow their link to the CollabNet Subversion build, and I see offerings for Windows, Linux, and Solaris, but nothing about macOS.

I also tried installing MacPorts and installing the subversion-python27bindings package.  Didn't help.  (In case it's not obvious, I'm not familiar with Python and have only the vaguest idea what bindings are.)

I'm lost.

答: I got it to work by using MacPorts to install the hgsubversion extension, and then using that to clone the svn repository, rather than using hg convert.

Body:
I want to convert a subversion repository to mercurial on macOS.  I've made a local copy of the svn repo.  Then I tried

hg convert --source-type svn --dest-type hg srcPath dstPath

and got

could not load Subversion python bindings
abort: srcPath: missing or unsupported repository

I found this page on the convert extension, which talks about needing Subversion python bindings.  One thing it says is

Bindings are included with the TortoiseHg distribution package and the Win32 InnoSetup (non-MSI) binaries for Mercurial, so if you install either of them you don't need to install additional packages.

Well, I installed TortoiseHG, which is an application on macOS, but I don't see how that helps.

It also says

For Mac OS X, the easiest way is to install the CollabNet Subversion build, and then copy the content of /opt/subversion/lib/svn-python to the site-package directory of the Python installation.

So I follow their link to the CollabNet Subversion build, and I see offerings for Windows, Linux, and Solaris, but nothing about macOS.

I also tried installing MacPorts and installing the subversion-python27bindings package.  Didn't help.  (In case it's not obvious, I'm not familiar with Python and have only the vaguest idea what bindings are.)

I'm lost.