问:
Image preprocessing of finetune in ResNet
I want to finetune ResNet50 ImageNet pretrained model, and I have a few question about image preprocessing of finetune.

In ImageNet preprocessing, we need to subtract the mean of pixel ([103.939, 116.779, 123.68]). When I use my dataset to finetune, should I subtract mean of ImageNet or subtract the mean of my data.

I do see many people rescale the data to [0,1], but the pretrained model(ImageNet) use image scale in [0,255]. Why do people do that? Is it reasonable?

答:
In my honest opinion people overstate the impact of image preprocessing. The only truly important thing is that the test data is similar in value scale to the training data. There are some theoretical benefits of having a pre normalized dataset, with the usage of batch normalization, but in practice it never made much of a difference (2-4% Accuracy).

If you have a running model and you are trying to get those last few % better accuracy without having to increase the amount of parameter than I would suggest tweaking this to your use-case.

In my opinion there is no single method that works for every use-case, but a good starting point is to use the same preprocessing as ImageNet, because the features will be similar to the ones produced for the imagenet classification.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
don't have function startAccelerometerUpdateQueue in Xcode
Does Someone know why in my xCode there isn't function startAccelerometerUpdateQueue? Here there is a screenshot of my xCode:
Screen1

I thought maybe the function was deprecated, so I selected the function starAccelerometerUpdate. But when i try to insert the NSOperationQueue.mainQueue(), xCode doesn't see that too (it suggests to change NSOperationQueue in OperationQueue, but i need the function mainQueue(). Screen2

答:
You're reading old documentation or an old tutorial. The method was renamed in Swift 3's "Grand Renaming". The second version you tried is close, (startAccelerometerUpdate(to: handler:)) but NSOperationQueue is now OperationQueue. It should look like this:

```<code>motionManager.startGyroUpdates(to: OperationQueue.main) { (data, error) in
    // Your handler code here
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You're reading old documentation or an old tutorial. The method was renamed in Swift 3's "Grand Renaming". The second version you tried is close, (startAccelerometerUpdate(to: handler:)) but NSOperationQueue is now OperationQueue. It should look like this:

motionManager.startGyroUpdates(to: OperationQueue.main) { (data, error) in
    // Your handler code here
}


问:
How to use if statement and perform the following operation?
How to use if loops and perform the following condition:

for example if i have the following datatype,

```<code>id    count A    count B    variable A     variable    sum
AAA    6           34         AA              AA        10
123    15          19         RA              RA        25
AAA    61          04         AA              AA        85
123    1           91         RS              RS        35
123    66          89         RA              RA        25
AAA    45          41         SP              SP        55
123    62          39         SS              SS        45
</code>```

For the same id, if variable A and variable B are same and not same, i would like to perform this operation.

if variable A = variable B

```<code>df = df.assign(result = np.where(df.sum < 50, df.shift(1).count A, df.count A))
</code>```

if variable A != variable B

```<code>df = df.assign(result = np.where(df.sum > 50, df.shift(1).count A, df.count A))
</code>```

答:
It seems you need add conditions with () and & (and):

```<code>m1 = (df['sum'] < 50)  & (df['variable A'] == df['variable B'])
df = df.assign(result = np.where(m1, df.shift(1)['count A'], df['count A']))

m2 = (df['sum'] > 50)  & (df['variable A'] != df['variable B'])
df = df.assign(result = np.where(m2, df.shift(1)['count A'], df['count A']))
</code>```

Body:
How to use if loops and perform the following condition:

for example if i have the following datatype,

id    count A    count B    variable A     variable    sum
AAA    6           34         AA              AA        10
123    15          19         RA              RA        25
AAA    61          04         AA              AA        85
123    1           91         RS              RS        35
123    66          89         RA              RA        25
AAA    45          41         SP              SP        55
123    62          39         SS              SS        45

For the same id, if variable A and variable B are same and not same, i would like to perform this operation.

if variable A = variable B

df = df.assign(result = np.where(df.sum < 50, df.shift(1).count A, df.count A))

if variable A != variable B

df = df.assign(result = np.where(df.sum > 50, df.shift(1).count A, df.count A))

Body:
It seems you need add conditions with () and & (and):

m1 = (df['sum'] < 50)  & (df['variable A'] == df['variable B'])
df = df.assign(result = np.where(m1, df.shift(1)['count A'], df['count A']))

m2 = (df['sum'] > 50)  & (df['variable A'] != df['variable B'])
df = df.assign(result = np.where(m2, df.shift(1)['count A'], df['count A']))


问:
Add images in ListView in Fragment - Navigation Drawer
In my app i am using Navigation Drawer with ListView in Fragment. And i successfully implemented the list view inside Fragment. but now i want to do add image in this list.How to do it. Need some example

This is my Vegall.java file

```<code>import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Vegall extends Fragment {
    private ListView lv;
    private static String[] vegalllist = {"Vegetables1", "Vegetables2"};

    public static Vegall newInstance()
    {
        Vegall vegall =new Vegall();
        return vegall;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView=inflater.inflate(R.layout.vegall, null);

        lv = (ListView) rootView.findViewById(R.id.vegall_lv);

        lv.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, vegalllist));

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
                //Toast.makeText(getActivity(), vegcat[i], Toast.LENGTH_SHORT).show();
                selectItem(i);

            }
        });
        return rootView;
    }
    private void selectItem(int i){
        Fragment newFragment;
        FragmentTransaction transaction = getFragmentManager().beginTransaction();

        switch (i){
            case 0:
                newFragment = new Vegetables1();
                transaction.replace(R.id.containerID, newFragment);
                transaction.addToBackStack(null);
                transaction.commit();
                break;

            case 1:
                Intent intent = new Intent(getActivity(), Vegetables2.class);
                startActivity(intent);
                break;
        }
    }
    @Override
    public String toString(){
        return "Home";
    }

}
</code>```

This is my Vegall.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/vegall_lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
</code>```

答: insert image in the drawable folder and then link it to the xml file use the <imageview>

Body:
In my app i am using Navigation Drawer with ListView in Fragment. And i successfully implemented the list view inside Fragment. but now i want to do add image in this list.How to do it. Need some example

This is my Vegall.java file

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Vegall extends Fragment {
    private ListView lv;
    private static String[] vegalllist = {"Vegetables1", "Vegetables2"};

    public static Vegall newInstance()
    {
        Vegall vegall =new Vegall();
        return vegall;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView=inflater.inflate(R.layout.vegall, null);

        lv = (ListView) rootView.findViewById(R.id.vegall_lv);

        lv.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, vegalllist));

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
                //Toast.makeText(getActivity(), vegcat[i], Toast.LENGTH_SHORT).show();
                selectItem(i);

            }
        });
        return rootView;
    }
    private void selectItem(int i){
        Fragment newFragment;
        FragmentTransaction transaction = getFragmentManager().beginTransaction();

        switch (i){
            case 0:
                newFragment = new Vegetables1();
                transaction.replace(R.id.containerID, newFragment);
                transaction.addToBackStack(null);
                transaction.commit();
                break;

            case 1:
                Intent intent = new Intent(getActivity(), Vegetables2.class);
                startActivity(intent);
                break;
        }
    }
    @Override
    public String toString(){
        return "Home";
    }

}

This is my Vegall.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/vegall_lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


问:
JS: Group array by values in nested array
I have an array:

```<code>[
  {
    theme: "low battery",
    Number: "S-10",
    components: [ "hardware", "battery" ]
  },
  {
    theme: "bad sync",
    Number: "S-11",
    components: [ "software" ]
  },
  {
    theme: "misc troubles",
    Number: "S-12",
    components: [ "hardware", "software" ]
  }
]
</code>```

So i want to group this array by "components" values. In other words, i want to know, how many times does component occures in array. For example:

```<code>[
  {
    component: "hardware",
    amount: 2
  },
  {
    component: "software",
    amount: 2
  },
  {
    component: "battery",
    amount: 1
  }
]
</code>```

答:
You can create a map to store the count of each component in an efficient way (lookup complexity of O(1)):

var items = [
  {
    theme: "low battery",
    Number: "S-10",
    components: [ "hardware", "battery" ]
  },
  {
    theme: "bad sync",
    Number: "S-11",
    components: [ "software" ]
  },
  {
    theme: "misc troubles",
    Number: "S-12",
    components: [ "hardware", "software" ]
  }
];

var componentMap = new Map();

items.forEach((item) => {
  item.components.forEach((component) => {
    if (componentMap.has(component)) {
      componentMap.set(component, componentMap.get(component) + 1);
    }
    else {
      componentMap.set(component, 1);
    }
  });
});

var componentCount = [];

componentMap.forEach((value, key) => {
  componentCount.push({
    component: key,
    amount: value
  });
});

console.log(componentCount);```

Body:
I have an array:

[
  {
    theme: "low battery",
    Number: "S-10",
    components: [ "hardware", "battery" ]
  },
  {
    theme: "bad sync",
    Number: "S-11",
    components: [ "software" ]
  },
  {
    theme: "misc troubles",
    Number: "S-12",
    components: [ "hardware", "software" ]
  }
]

So i want to group this array by "components" values. In other words, i want to know, how many times does component occures in array. For example:

[
  {
    component: "hardware",
    amount: 2
  },
  {
    component: "software",
    amount: 2
  },
  {
    component: "battery",
    amount: 1
  }
]


问:
GraphQL on top of REST API
Morning guys, I'm currently working on writing GraphQL on top of REST API in it. Say that a JSON response is an object 'user' that contains elements such as id, name, email and an 'address' which is an object consisting of street, suite, city, and zipcode. How should I declare the type in the schema for this 'address' field, which contains multiple elements inside. I have seen the documentation and could not understand what would be the correct type for my scenario.

The snippet of the schema related is below:

```<code>export default new GraphQLObjectType({
    name: 'User',
    description: 'User(s) object in JSONPlaceholder Fake API',
    fields: () => ({
        id: {
            type: GraphQLID
        },
        name: {
            type: GraphQLString
        },
        username: {
            type: GraphQLString
        },
        email: {
            type: GraphQLString
        },
        address: {
            type: (?)
        }
    })
})
</code>```

Below is my JSON API which I target.

```<code>{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}
</code>```

I think of creating separate objects and creating resolver to only fetch that particular 'address' object, but that means I'm querying twice. I assume there might be some workaround to avoid this.

Thanks in advance!

答:
As you mentioned you should create a new GraphQLObjectType to represent the address object and its fields and then set this as the type of address. In this case as the field names match the JSON payload there is no requirement for a custom resolver.

If you think you might end up making duplicate calls to a REST API you may find dataloaders library from facebook helpful. You can use it to ensure that a given request to a REST API is made only once per request. It can also help out with other tings like batching.

You code would look something like this -

```<code>const AddressType = new GraphQLObjectType({
    name: 'AddressType',
    description: 'Address',
    fields: () => ({
        // then add all the fields on address
    })
})

export default new GraphQLObjectType({
    name: 'User',
    description: 'User(s) object in JSONPlaceholder Fake API',
    fields: () => ({
        id: {
            type: GraphQLID
        },
        name: {
            type: GraphQLString
        },
        username: {
            type: GraphQLString
        },
        email: {
            type: GraphQLString
        },
        address: {
            type: AddressType
        }
    })
})
</code>```

Title: GraphQL on top of REST API

Body:
Morning guys, I'm currently working on writing GraphQL on top of REST API in it. Say that a JSON response is an object 'user' that contains elements such as id, name, email and an 'address' which is an object consisting of street, suite, city, and zipcode. How should I declare the type in the schema for this 'address' field, which contains multiple elements inside. I have seen the documentation and could not understand what would be the correct type for my scenario.

The snippet of the schema related is below:

export default new GraphQLObjectType({
    name: 'User',
    description: 'User(s) object in JSONPlaceholder Fake API',
    fields: () => ({
        id: {
            type: GraphQLID
        },
        name: {
            type: GraphQLString
        },
        username: {
            type: GraphQLString
        },
        email: {
            type: GraphQLString
        },
        address: {
            type: (?)
        }
    })
})

Below is my JSON API which I target.

{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}

I think of creating separate objects and creating resolver to only fetch that particular 'address' object, but that means I'm querying twice. I assume there might be some workaround to avoid this.

Thanks in advance!

Body:
As you mentioned you should create a new GraphQLObjectType to represent the address object and its fields and then set this as the type of address. In this case as the field names match the JSON payload there is no requirement for a custom resolver.

If you think you might end up making duplicate calls to a REST API you may find dataloaders library from facebook helpful. You can use it to ensure that a given request to a REST API is made only once per request. It can also help out with other tings like batching.

You code would look something like this -

const AddressType = new GraphQLObjectType({
    name: 'AddressType',
    description: 'Address',
    fields: () => ({
        // then add all the fields on address
    })
})

export default new GraphQLObjectType({
    name: 'User',
    description: 'User(s) object in JSONPlaceholder Fake API',
    fields: () => ({
        id: {
            type: GraphQLID
        },
        name: {
            type: GraphQLString
        },
        username: {
            type: GraphQLString
        },
        email: {
            type: GraphQLString
        },
        address: {
            type: AddressType
        }
    })
})


问:
how i i can transparent background on android studio?
i want to design a layout exactly like image below.

when i put my linear layout alpha as transparent , all icons inside it also become transparent and its completely normal. but i want a way to just have transparent background not all items !

i want a transparent layout like this:

but my layout shows like this :

here is my code :

```<code>    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="100dp"
    android:background="@color/colorPrimary"
    android:orientation="vertical"
    android:alpha="0.5"
    >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:alpha="1"
        >

        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333"
            android:padding="10dp"
            >

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333"
            android:padding="10dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333"
            android:padding="10dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
    </LinearLayout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
    </LinearLayout>

</LinearLayout>
</code>```

答:
You can try like this if you want to adjust the transparent change the alpha in color I gave as #55000000 you can change the alpha value(55) whatever you want. if you wish black transparency you can use #55FFFFFF</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/colorPrimary"
              android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:background="#55000000"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="3"
            >

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="3"
            >

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>
</code>```

Body:
i want to design a layout exactly like image below.

when i put my linear layout alpha as transparent , all icons inside it also become transparent and its completely normal. but i want a way to just have transparent background not all items !

i want a transparent layout like this:

but my layout shows like this :

here is my code :

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="100dp"
    android:background="@color/colorPrimary"
    android:orientation="vertical"
    android:alpha="0.5"
    >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:alpha="1"
        >

        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333"
            android:padding="10dp"
            >

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333"
            android:padding="10dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333"
            android:padding="10dp">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
    </LinearLayout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
        <RelativeLayout
            android:layout_width="1dip"
            android:layout_height="fill_parent"
            android:layout_weight="0.333">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@mipmap/consert"
                android:layout_gravity="center_horizontal"
                />

        </RelativeLayout>
    </LinearLayout>

</LinearLayout>

Body:
You can try like this if you want to adjust the transparent change the alpha in color I gave as #55000000 you can change the alpha value(55) whatever you want. if you wish black transparency you can use #55FFFFFF

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/colorPrimary"
              android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:background="#55000000"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="3"
            >

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="3"
            >

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:padding="10dp"
                >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@mipmap/ic_launcher"
                    />

            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>

</LinearLayout>


问:
RecyclerView ItemTouchHelper Buttons on Swipe
I am trying to port some iOS functionality to Android.

I intent to create a table where on swipe to the left shows 2 button: Edit and Delete.

I have been playing with it and I know I am very close. The secret really lies on the method OnChildDraw.

I would like to Draw a Rect that fits the text Delete then draw the Edit text besides it with their respective background color. The remaining white space when clicked should restore the row to its initial position.

I have managed to paint the background while the user is swiping to the sides but I don't know how to add the listeners and once it is swiped to the side, the dragging function begins to misbehave.

I am working on Xamarin but pure java solutions also are accepted as I can easily port them to c#.

```<code>    public class SavedPlacesItemTouchHelper : ItemTouchHelper.SimpleCallback
    {
        private SavedPlacesRecyclerviewAdapter adapter;
        private Paint paint = new Paint();
        private Context context;

        public SavedPlacesItemTouchHelper(Context context, SavedPlacesRecyclerviewAdapter adapter) : base(ItemTouchHelper.ActionStateIdle, ItemTouchHelper.Left)
        {
            this.context = context;
            this.adapter = adapter;
        }

        public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
        {
            return false;
        }

        public override void OnSwiped(RecyclerView.ViewHolder viewHolder, int direction)
        {
        }

        public override void OnChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
        {
            float translationX = dX;
            View itemView = viewHolder.ItemView;
            float height = (float)itemView.Bottom - (float)itemView.Top;

            if (actionState == ItemTouchHelper.ActionStateSwipe && dX <= 0) // Swiping Left
            {
                 translationX = -Math.Min(-dX, height * 2);
                paint.Color = Color.Red;
                RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
                c.DrawRect(background, paint);

                //viewHolder.ItemView.TranslationX = translationX;
            }
            else if (actionState == ItemTouchHelper.ActionStateSwipe && dX > 0) // Swiping Right
            {
                translationX = Math.Min(dX, height * 2);
                paint.Color = Color.Red;
                RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
                c.DrawRect(background, paint);
            }

            base.OnChildDraw(c, recyclerView, viewHolder, translationX, dY, actionState, isCurrentlyActive);
        }
    }
}
</code>```

This is what I currently have.

If you know how to add listeners or any suggestions please leave a comment!

UPDATE:

I just realized that on double tap on the white remaining space of the row already restore the row to its initial state. Not a single tap though :(

答:
I wanted to use this touch gesture in my app too, after working too much with Itemtouchhelper I decided to write my own touch handler:

```<code>    private class TouchHelper : Java.Lang.Object, View.IOnTouchListener
    {
        ViewHolder vh;
        public TouchHelper(ViewHolder vh)
        { this.vh = vh;  }

        float DownX, DownY; bool isSliding;
        TimeSpan tsDown;
        public bool OnTouch(View v, MotionEvent e)
        {
            switch (e.Action)
            {
                case MotionEventActions.Down:
                    DownX = e.GetX(); DownY = e.GetY();
                    tsDown = TimeSpan.Now;
                    break;
                case MotionEventActions.Move:
                    float deltaX = e.GetX() - DownX, deltaY = e.GetX() - DownY;
                    if (Math.Abs(deltaX) >= Values.ScreenWidth / 20 || Math.Abs(deltaY) >= Values.ScreenWidth / 20)
                        isSliding = Math.Abs(deltaX) > Math.Abs(deltaY);

                    //TextsPlace is the layout that moves with touch
                    if(isSliding)
                        vh.TextsPlace.TranslationX = deltaX / 2;

                    break;
                case MotionEventActions.Cancel:
                case MotionEventActions.Up:
                    //handle if touch was for clicking
                    if (Math.Abs(deltaX) <= 50 && (TimeSpan.Now - tsDown).TotalMilliseconds <= 400)
                        vh.OnTextsPlaceClick(vh.TextsPlace, null);
                    break;
            }
            return true;
        }
    }
</code>```

Note: Set this as ontouchlistener of your viewholder content when creating the viewholder. You can add your animations to return the item to its first place.

You can also write your custom layoutmanager to block vertical scroll while item is sliding.

Body:
I am trying to port some iOS functionality to Android.

I intent to create a table where on swipe to the left shows 2 button: Edit and Delete.

I have been playing with it and I know I am very close. The secret really lies on the method OnChildDraw.

I would like to Draw a Rect that fits the text Delete then draw the Edit text besides it with their respective background color. The remaining white space when clicked should restore the row to its initial position.

I have managed to paint the background while the user is swiping to the sides but I don't know how to add the listeners and once it is swiped to the side, the dragging function begins to misbehave.

I am working on Xamarin but pure java solutions also are accepted as I can easily port them to c#.

    public class SavedPlacesItemTouchHelper : ItemTouchHelper.SimpleCallback
    {
        private SavedPlacesRecyclerviewAdapter adapter;
        private Paint paint = new Paint();
        private Context context;

        public SavedPlacesItemTouchHelper(Context context, SavedPlacesRecyclerviewAdapter adapter) : base(ItemTouchHelper.ActionStateIdle, ItemTouchHelper.Left)
        {
            this.context = context;
            this.adapter = adapter;
        }

        public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
        {
            return false;
        }

        public override void OnSwiped(RecyclerView.ViewHolder viewHolder, int direction)
        {
        }

        public override void OnChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
        {
            float translationX = dX;
            View itemView = viewHolder.ItemView;
            float height = (float)itemView.Bottom - (float)itemView.Top;

            if (actionState == ItemTouchHelper.ActionStateSwipe && dX <= 0) // Swiping Left
            {
                 translationX = -Math.Min(-dX, height * 2);
                paint.Color = Color.Red;
                RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
                c.DrawRect(background, paint);

                //viewHolder.ItemView.TranslationX = translationX;
            }
            else if (actionState == ItemTouchHelper.ActionStateSwipe && dX > 0) // Swiping Right
            {
                translationX = Math.Min(dX, height * 2);
                paint.Color = Color.Red;
                RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
                c.DrawRect(background, paint);
            }

            base.OnChildDraw(c, recyclerView, viewHolder, translationX, dY, actionState, isCurrentlyActive);
        }
    }
}

This is what I currently have.

If you know how to add listeners or any suggestions please leave a comment!

UPDATE:

I just realized that on double tap on the white remaining space of the row already restore the row to its initial state. Not a single tap though :(

Body:
I wanted to use this touch gesture in my app too, after working too much with Itemtouchhelper I decided to write my own touch handler:

    private class TouchHelper : Java.Lang.Object, View.IOnTouchListener
    {
        ViewHolder vh;
        public TouchHelper(ViewHolder vh)
        { this.vh = vh;  }

        float DownX, DownY; bool isSliding;
        TimeSpan tsDown;
        public bool OnTouch(View v, MotionEvent e)
        {
            switch (e.Action)
            {
                case MotionEventActions.Down:
                    DownX = e.GetX(); DownY = e.GetY();
                    tsDown = TimeSpan.Now;
                    break;
                case MotionEventActions.Move:
                    float deltaX = e.GetX() - DownX, deltaY = e.GetX() - DownY;
                    if (Math.Abs(deltaX) >= Values.ScreenWidth / 20 || Math.Abs(deltaY) >= Values.ScreenWidth / 20)
                        isSliding = Math.Abs(deltaX) > Math.Abs(deltaY);

                    //TextsPlace is the layout that moves with touch
                    if(isSliding)
                        vh.TextsPlace.TranslationX = deltaX / 2;

                    break;
                case MotionEventActions.Cancel:
                case MotionEventActions.Up:
                    //handle if touch was for clicking
                    if (Math.Abs(deltaX) <= 50 && (TimeSpan.Now - tsDown).TotalMilliseconds <= 400)
                        vh.OnTextsPlaceClick(vh.TextsPlace, null);
                    break;
            }
            return true;
        }
    }

Note: Set this as ontouchlistener of your viewholder content when creating the viewholder. You can add your animations to return the item to its first place.

You can also write your custom layoutmanager to block vertical scroll while item is sliding.


问:
Merge two table based on row name
I need to merge two table into one based on Row name, each table has 172 rows and 172 columns example of my data look

```<code>#table 1
A B C
1 2 3
2 3 4
5 6 7

#table 2
A B C
1 3 8
2 4 6
5 4 2
</code>```

I want my output like this

```<code>A B C
1 2 3
1 3 8
2 3 4
2 4 6
5 6 7
5 4 2
</code>```

Title: Merge two table based on row name

Body:
I need to merge two table into one based on Row name, each table has 172 rows and 172 columns example of my data look

#table 1
A B C
1 2 3
2 3 4
5 6 7

#table 2
A B C
1 3 8
2 4 6
5 4 2

I want my output like this

A B C
1 2 3
1 3 8
2 3 4
2 4 6
5 6 7
5 4 2

Body:
You can use mapply,

mapply(rbind, table1, table2)

#     A B C
#[1,] 1 2 3
#[2,] 1 3 8
#[3,] 2 3 4
#[4,] 2 4 6
#[5,] 5 6 7
#[6,] 5 4 2


问:
How can i delete particular item stored inside local storage?
Values stored inside local storage

```<code>{"10":true,"11":true,"16":false}
</code>```

I want to delete a particular data stored inside local storage e.g. 10

```<code>var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};

$.each(checkboxValues, function(key, value) {
                if(value===true) {
                    delete checkboxValues[key];
                    }
                }
            });
</code>```

I stored all checkboxes id and value during onload, and want to remove those checkboxes id with true value when user submit the form.

With the method used above, I unable to delete the data. Is anything wrong with my code?

答:
In order to delete an item from localStorage you have to use removeItem() function but in your case you actually need to update it. So first so you have to overwrite the existing value. See the code below. Here is a Fiddle

//set the value for first time suppose
localStorage.setItem("checkboxValues", JSON.stringify({
  "10": true,
  "11": true,
  "16": false
}));
   //get the value and update
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};
$.each(checkboxValues, function(key, value) {
  if (value === true) {
    delete checkboxValues[key];
  }
})
   //store the updated value back to localStorage
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
console.log(JSON.stringify(checkboxValues));//logs {"16":false}
console.log(JSON.parse(localStorage.getItem('checkboxValues')));
// logs an object with only one property {16:false}```

Body:
Values stored inside local storage

{"10":true,"11":true,"16":false}

I want to delete a particular data stored inside local storage e.g. 10

var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};

$.each(checkboxValues, function(key, value) {
                if(value===true) {
                    delete checkboxValues[key];
                    }
                }
            });

I stored all checkboxes id and value during onload, and want to remove those checkboxes id with true value when user submit the form.

With the method used above, I unable to delete the data. Is anything wrong with my code?


问:
Drag selection of elements not in group in konvajs
Is there a way in KonvaJs for dragging multiple elements at once without grouping them ?</p>

答:
The idea is: listen to dragmove event, apply position diff for all other objects that you need to move.

```<code>let oldX, oldY;
layer.on('dragstart', (e) => {
   oldX = e.target.x();
   oldY = e.target.y();
});
layer.on('dragmove', (e) => {
   const diffX = e.target.x() - oldX;
   const diffY = e.target.y() - oldY;

   // move everyone
   layer.children.each((child) => {
     // skip draggable circle
     if (child === e.target) {
       return;
     }
     // move other nodes
     child.x(child.x() + diffX);
     child.y(child.y() + diffY);
   });
   oldX = e.target.x();
   oldY = e.target.y();
});
</code>```

Demo: http://jsbin.com/babasibudi/1/edit?js,output

Body:
The idea is: listen to dragmove event, apply position diff for all other objects that you need to move.

let oldX, oldY;
layer.on('dragstart', (e) => {
   oldX = e.target.x();
   oldY = e.target.y();
});
layer.on('dragmove', (e) => {
   const diffX = e.target.x() - oldX;
   const diffY = e.target.y() - oldY;

   // move everyone
   layer.children.each((child) => {
     // skip draggable circle
     if (child === e.target) {
       return;
     }
     // move other nodes
     child.x(child.x() + diffX);
     child.y(child.y() + diffY);
   });
   oldX = e.target.x();
   oldY = e.target.y();
});

Demo: http://jsbin.com/babasibudi/1/edit?js,output


问:
onclick action not calling javascript function
I am expecting that the on button click action should popup the alert message. But I am unable to figure out the root cause that code doesn't work as expected.

Here is my code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>

<script type="text/javascript">
function click() {
alert("this is an alert");
}
</script>

<form>
<input type="button" value="Click Here" onclick="click()" />
</form>

</body>
</html>
</code>```

答:
There is click() function corresponding to button in JavaScript. Try using window.click()

```<code><input type="button" onclick="window.click()" value="click me"/>
</code>```

Body:
I am expecting that the on button click action should popup the alert message. But I am unable to figure out the root cause that code doesn't work as expected.

Here is my code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<form>
<input type="button" value="Click Here" onclick="click()" />
</form>

Body:
There is click() function corresponding to button in JavaScript. Try using window.click()

<input type="button" onclick="window.click()" value="click me"/>


问:
Parallel.Foreach + BackgroundWorker.ReportProgress
I am looking for feedback in case there are any known reasons I shouldn't do something like this: putting a ReportProgress within a Parallel foreach statement.  Are there any similar ways to achieve the same thing but are considered safer or better?

Code example:

```<code>        int iterations = 0;
        int count = items.Count;
        Parallel.ForEach(items, new ParallelOptions() { MaxDegreeOfParallelism = 5 }, item =>
        {
            iterations++;
            int percentComplete = (iterations/count) * 100;
            backgroundWorker.ReportProgress(percentComplete);
        };
</code>```

Additional info:

I have a Windows Form program that needs to do a specific task of managing items. Utilizing multi threading has made it much faster. However it needs to report to a progress bar on the form the overall progress completed so the end user doesn't wonder if the program frozen up. The overall job can take hours in some cases. So, having a progress bar is mandatory.

答:
I think Harald is on the money with his answer.
I've used the example shown at this link in the instance of having one background worker.

You get a good feel for how it works with the following snippet (copied from the link above). I think you could maybe use that as a base to allow a collection of DoWorkEventHandler delegates and create a BackgroundWorker for each.

```<code>      private void button4_Click(object sender, EventArgs e)
      {
         // Create dialog.
         ProgressWithCancel dlgProgress = new ProgressWithCancel( "Testing progress", LongOperation);

         // Show dialog with Synchronous/blocking call.
         // LongOperation() is called by dialog.
         dlgProgress.ShowDialog(); // Synchronous/blocking call.
      }

      private void LongOperation(object sender, DoWorkEventArgs e)
      {
         BackgroundWorker worker = sender as BackgroundWorker;

         int max = 20;
         for (int i = 0; i < max; i++)
         {
            if (worker.CancellationPending) // See if cacel button was pressed.
            {
               System.Threading.Thread.Sleep(2000); // Similate time for clean-up.
               break;
            }

            int percent = i * 100 / max;

            string userState = percent.ToString(); // render a string to display on the progress dialog.

            // Append to string just to show multi-line user-status info.
            if (percent >= 45 && percent <= 55) { userState += "Half way"; }
            if (percent >= 85) { userState += "Almost done"; }

            worker.ReportProgress(percent, userState); // Report percent and user-status info to dialog.

            System.Threading.Thread.Sleep(800); // Simulate time-consuming operation
         }
      }

// Implementation (in ProgressWithCancel.cs)

namespace ProgressWithCancel
{
   public partial class ProgressWithCancel : Form
   {
      public ProgressWithCancel(string whyWeAreWaiting, DoWorkEventHandler work)
      {
         InitializeComponent();
         this.Text = whyWeAreWaiting; // Show in title bar
         backgroundWorker1.DoWork += work; // Event handler to be called in context of new thread.
      }

      private void btnCancel_Click(object sender, EventArgs e)
      {
         label1.Text = "Cancel pending";
         backgroundWorker1.CancelAsync(); // Tell worker to abort.
         btnCancel.Enabled = false;
      }

      private void Progress_Load(object sender, EventArgs e)
      {
         backgroundWorker1.RunWorkerAsync();
      }

      private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
      {
         progressBar1.Value = e.ProgressPercentage;
         label1.Text = e.UserState as string;
      }

      private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
      {
         Close();
      }

   }
}
</code>```

Body:
I am looking for feedback in case there are any known reasons I shouldn't do something like this: putting a ReportProgress within a Parallel foreach statement.  Are there any similar ways to achieve the same thing but are considered safer or better?

Code example:

        int iterations = 0;
        int count = items.Count;
        Parallel.ForEach(items, new ParallelOptions() { MaxDegreeOfParallelism = 5 }, item =>
        {
            iterations++;
            int percentComplete = (iterations/count) * 100;
            backgroundWorker.ReportProgress(percentComplete);
        };

Additional info:

I have a Windows Form program that needs to do a specific task of managing items. Utilizing multi threading has made it much faster. However it needs to report to a progress bar on the form the overall progress completed so the end user doesn't wonder if the program frozen up. The overall job can take hours in some cases. So, having a progress bar is mandatory.

Body:
I think Harald is on the money with his answer.
I've used the example shown at this link in the instance of having one background worker.

You get a good feel for how it works with the following snippet (copied from the link above). I think you could maybe use that as a base to allow a collection of DoWorkEventHandler delegates and create a BackgroundWorker for each.

      private void button4_Click(object sender, EventArgs e)
      {
         // Create dialog.
         ProgressWithCancel dlgProgress = new ProgressWithCancel( "Testing progress", LongOperation);

         // Show dialog with Synchronous/blocking call.
         // LongOperation() is called by dialog.
         dlgProgress.ShowDialog(); // Synchronous/blocking call.
      }

      private void LongOperation(object sender, DoWorkEventArgs e)
      {
         BackgroundWorker worker = sender as BackgroundWorker;

         int max = 20;
         for (int i = 0; i < max; i++)
         {
            if (worker.CancellationPending) // See if cacel button was pressed.
            {
               System.Threading.Thread.Sleep(2000); // Similate time for clean-up.
               break;
            }

            int percent = i * 100 / max;

            string userState = percent.ToString(); // render a string to display on the progress dialog.

            // Append to string just to show multi-line user-status info.
            if (percent >= 45 && percent <= 55) { userState += "Half way"; }
            if (percent >= 85) { userState += "Almost done"; }

            worker.ReportProgress(percent, userState); // Report percent and user-status info to dialog.

            System.Threading.Thread.Sleep(800); // Simulate time-consuming operation
         }
      }

// Implementation (in ProgressWithCancel.cs)

namespace ProgressWithCancel
{
   public partial class ProgressWithCancel : Form
   {
      public ProgressWithCancel(string whyWeAreWaiting, DoWorkEventHandler work)
      {
         InitializeComponent();
         this.Text = whyWeAreWaiting; // Show in title bar
         backgroundWorker1.DoWork += work; // Event handler to be called in context of new thread.
      }

      private void btnCancel_Click(object sender, EventArgs e)
      {
         label1.Text = "Cancel pending";
         backgroundWorker1.CancelAsync(); // Tell worker to abort.
         btnCancel.Enabled = false;
      }

      private void Progress_Load(object sender, EventArgs e)
      {
         backgroundWorker1.RunWorkerAsync();
      }

      private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
      {
         progressBar1.Value = e.ProgressPercentage;
         label1.Text = e.UserState as string;
      }

      private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
      {
         Close();
      }

   }
}


问:
ERROR:Exception in request: org.apache.http.conn.HttpHostConnectException: Connection to http://********:80 refused
When I use SoapUI for testing SOAP project, I met an error, it pop up ERROR:Exception in request: org.apache.http.conn.HttpHostConnectException: Connection to http://(my website):80 refused. Does anyone know why this happen? I actually post my web app and database to AWS, those are on cloud now. Anyone met similar before? Thanks</p>

答:
If you go through a proxy, try to disable it :
Looks at the soapui toolbar</p>


问:
Filling a one2many inside a one2many in onchange
Using an on_change method I am trying to send default values to a one2many field using the concept of (0,0, {list values}; even there it works fine but inside that one2many there is also a one2many field to which I must also send values to implement In my code the same concept of (0,0, {list values}, but I did not get success.

Could you help me?.

Attached fragment of my code

class hc(models.Model):
    _name = 'hc'
    laboratorios_ids = fields.One2many(
        string='Laboratorios', comodel_name='resullab',
        inverse_name='hc_id')

    def cargar_pool_labs(self):
        labs = []
        pool = self.env['mymodel'].sudo().search([])
        for laboratorio in pool:
            analitos = [(0, 0, {'analito': line.analito,
                                'resultado': line.resultado ,
                                'resultado2': line.resultado2 ,
                                'unidades': line.unidades })
                            for line in laboratorio.analitos_ids]
            labs.append((0,0,{
            'nombre_examen' : laboratorio.nombre_examen,
            'cups' : laboratorio.cups,
            'laboratorio_id': laboratorio.laboratorio_id,
            'analitos_ids' : analitos
            }))
        self.laboratorios_ids = labs
```

<p><em>Note: the analitos_ids field is the one2many field that is inside the laboratorios_ids field which is also one2many.</em></p>

<p>The others models extructure</p>

<pre class="lang-py prettyprint-override"><code>class resullab(models.Model):
    _name = 'resullab'
    analitos_ids = fields.One2many('analito','laboratorio_id',
                                   'Analitos Lab', ondelete='cascade')

class labs_analito(models.Model):
    _name = 'analito'
    laboratorio_id = fields.Many2one('laboratorios', 'Lab Parent')
</code>```

Thanks for help!

答:
sorry about my english.

1- onchange is a method called from the client side on the server this
   method will return a value to the client side (javascript).

2- so when the client receive this data will fillup the fields so in the current
   view that you are in (form) if the field is not there the value will be
   ignored.

3- so when you pass the values of the second o2m field in the view this field is not there
   because it's in the form that will be opened by clicking on additem or
   on the item to edit.
   and this is why the value are not shown in the the form when you open the item.

There is no way to do this in onchange event because there is no way to pass the list
of the field to the tree of the first o2m.
what i mean is :

```<code>        o2m1_id            o2m2_id
model.1 -------> model.2 --------> model.3(field1, field2)
</code>```

in the view of model.1 you can create a special tree for o2m1_id and put the field o2m2_id there.
but this is useless because when you open the form fo o2m1_id you will find that the o2m2_id contains
records but with empty (field1, field2). and this is because values of field1, field2 returned by onchange event
are ignored, this two field are not in the view of model.1 that receives them.

Body:
Using an on_change method I am trying to send default values to a one2many field using the concept of (0,0, {list values}; even there it works fine but inside that one2many there is also a one2many field to which I must also send values to implement In my code the same concept of (0,0, {list values}, but I did not get success.

Could you help me?.

Attached fragment of my code

class hc(models.Model):
    _name = 'hc'
    laboratorios_ids = fields.One2many(
        string='Laboratorios', comodel_name='resullab',
        inverse_name='hc_id')

    def cargar_pool_labs(self):
        labs = []
        pool = self.env['mymodel'].sudo().search([])
        for laboratorio in pool:
            analitos = [(0, 0, {'analito': line.analito,
                                'resultado': line.resultado ,
                                'resultado2': line.resultado2 ,
                                'unidades': line.unidades })
                            for line in laboratorio.analitos_ids]
            labs.append((0,0,{
            'nombre_examen' : laboratorio.nombre_examen,
            'cups' : laboratorio.cups,
            'laboratorio_id': laboratorio.laboratorio_id,
            'analitos_ids' : analitos
            }))
        self.laboratorios_ids = labs

Note: the analitos_ids field is the one2many field that is inside the laboratorios_ids field which is also one2many.

The others models extructure

class resullab(models.Model):
    _name = 'resullab'
    analitos_ids = fields.One2many('analito','laboratorio_id',
                                   'Analitos Lab', ondelete='cascade')

class labs_analito(models.Model):
    _name = 'analito'
    laboratorio_id = fields.Many2one('laboratorios', 'Lab Parent')

Thanks for help!

Body:
sorry about my english.

1- onchange is a method called from the client side on the server this
   method will return a value to the client side (javascript).

2- so when the client receive this data will fillup the fields so in the current
   view that you are in (form) if the field is not there the value will be
   ignored.

3- so when you pass the values of the second o2m field in the view this field is not there
   because it's in the form that will be opened by clicking on additem or
   on the item to edit.
   and this is why the value are not shown in the the form when you open the item.

There is no way to do this in onchange event because there is no way to pass the list
of the field to the tree of the first o2m.
what i mean is :

        o2m1_id            o2m2_id
model.1 -------> model.2 --------> model.3(field1, field2)

in the view of model.1 you can create a special tree for o2m1_id and put the field o2m2_id there.
but this is useless because when you open the form fo o2m1_id you will find that the o2m2_id contains
records but with empty (field1, field2). and this is because values of field1, field2 returned by onchange event
are ignored, this two field are not in the view of model.1 that receives them.


问:
Are there any prototype-based languages with a whole development cycle?
Are there any real-world prototype-based programming languages with a whole development cycle?

"A whole development cycle" like Ruby and Python: web frameworks, scripting/interacting with the system, tools for debugging, profiling, etc.

Thank you

A brief note on PBPLs: (let's call these languages PBPL : prototype-based programming language)

There are some PBPLs out there. Some are being widely used like JavaScript (which Node.js may bring it into the field - or may not!). One other language is ActionScript which is also a PBPL but tightly bound to Flash VM (is it correct to say so?).

From less known ones I can speak of Lua which has a strong reputation in game development (mostly spread by WOW) but never took off as a full language. Lua has a table concept which can provide you some sort of prototype based programming facility.

There is also JScript (Windows scripting tool) which is already pointless by the newcomer PowerShell (I have used JScript to manipulate IIS but I never understood what is JScript!).

Others can be named like io (indeed very very neat, you will fall in love with it; absolutely impossible to use) and REBOL (What is this all about? A proprietary scripting tool? You must be kidding!) and newLISP (Which is actually a full language, but no one ever heard about it).

For sure there are much more to list here but either I do not remember or I did not understood them as a real world thing, like Self).

答:
I did not found one and the only candidate (JavaScript) is still spending very first steps (like Node.js).

Still one other valid candidate would be JavaScript! There is a .NET based implementation named IronJS which is implemented in F# and is going pretty well. This way one can have whole .NET development cycle at his toolbox. It is based on DLR and can be used in both .NET and Mono!

ContentLicense: CC BY-SA 2.5


问:
update is not firing in aframe component
I read from the aframe docs that whenever we update the position or any other value the update of the attached component would fire I am just trying to fire the update on every position change.

This is the component:-

```<code>        AFRAME.registerComponent('checking', {
          init: function(){
            console.log("initialized");
          },
          update: function(){
            console.log("valueUpdated: "+this.el.id);
          },
          tick: function(){

          }
        });
</code>```

update is being fired once with the init when the doc is loaded but not when I am doing this from the console like obj.setAttribute("position","4 6 7");
acc to the documentation it should happen right or I am making some very basic mistake?

Thanks...

答:
I think You are confusing a component with an entity. The entity is a container, which behavior and appearance are defined via components.
So the update function is firing at the beginning + when you change the component, like via setAttribute('checking','newValue').

You can do Your check either by:

including a listener for the 'componentChanged' event:

```<code>  this.el.addEventListener('componentChanged',function(e){
       if(e.detail.name==='position'){
          console.log(e.detail.newData);
       }
    });
</code>```

checking if the position changed on tick, but that seems highly inneficient:

```<code>   init(){
     this.pos = this.el.getAttribute('position');
   }
   tick: function(){
     if( this.el.getAttribute('position') != this.pos ){
         this.pos = this.el.getAttribute('position');
     }
   }
</code>```

Body:
I read from the aframe docs that whenever we update the position or any other value the update of the attached component would fire I am just trying to fire the update on every position change.

This is the component:-

        AFRAME.registerComponent('checking', {
          init: function(){
            console.log("initialized");
          },
          update: function(){
            console.log("valueUpdated: "+this.el.id);
          },
          tick: function(){

          }
        });

update is being fired once with the init when the doc is loaded but not when I am doing this from the console like obj.setAttribute("position","4 6 7");
acc to the documentation it should happen right or I am making some very basic mistake?

Thanks...

Body:
I think You are confusing a component with an entity. The entity is a container, which behavior and appearance are defined via components.
So the update function is firing at the beginning + when you change the component, like via setAttribute('checking','newValue').

You can do Your check either by:

including a listener for the 'componentChanged' event:

  this.el.addEventListener('componentChanged',function(e){
       if(e.detail.name==='position'){
          console.log(e.detail.newData);
       }
    });

checking if the position changed on tick, but that seems highly inneficient:

   init(){
     this.pos = this.el.getAttribute('position');
   }
   tick: function(){
     if( this.el.getAttribute('position') != this.pos ){
         this.pos = this.el.getAttribute('position');
     }
   }


问:
Binding to vm breaks reference
Extending controller binded to var vm = this fails to read binded values from component bindings

In example the difference is in (clicking the button displays entity)

```<code>app.controller('ThisBasicCtrl', function() {
  this.click = function() {
    this.text = this.entity;
  };
});
</code>```

```<code>app.controller('VmBasicCtrl', function() {
  var vm = this;
  vm.click = function() {
    vm.text = vm.entity; // here entity is undefined
  };

  vm.clickThatWorks = function() {
    this.text = this.entity // 'NOT really VM but shows the value';
  }
});
</code>```

var app = angular.module('app', []);

app.controller('MainCtrl', function() {
  var vm = this;
  vm.entity = {
    name: 'test'
  };
});

app.controller('ThisBasicCtrl', function() {
  this.click = function() {
    this.text = this.entity;
  };
});

app.component('thisExtendedComponent', {
  template: '<button ng-click="vm.click()">This controller</button>
{{vm.text}}
',
  controller: 'ExtendedCtrl',
  controllerAs: 'vm',
  bindings: {
    entity: '<'
  }
});

app.controller('ExtendedCtrl', function($controller) {
  angular.extend(this, $controller('ThisBasicCtrl'));
});

app.controller('VmBasicCtrl', function() {
  var vm = this;
  vm.click = function() {
    vm.text = vm.entity; // here entity is undefined
  };

  vm.clickThatWorks = function() {
    this.text = this.entity // 'NOT really VM but shows the value';
  }
});

app.component('vmExtendedComponent', {
  template: '<button ng-click="vm.click()">VM controller</button>
{{vm.text}}
',
  controller: 'VmExtendedCtrl',
  controllerAs: 'vm',
  bindings: {
    entity: '<'
  }
});

app.controller('VmExtendedCtrl', function($controller) {
  angular.extend(this, $controller('VmBasicCtrl'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl as vm">
  <div style="border: 1px solid;">
    <h5>
Extends <i style="color:orange">this</i> controller
</h5>
    <this-extended-component entity="vm.entity"></this-extended-component>
  </div>
  <br>
  <div style="border: 1px solid;">
    <h5>
Extends <i style="color:orange">VM</i> controller
</h5>
    <vm-extended-component entity="vm.entity"></vm-extended-component>
  </div>
</div></code>```

答:
Extend will copy the referance in the function...

On your thisExtendedComponent component you are extending ThisBasicCtrl and its click function referancing ownself inside the function but
vmExtendedComponent component is extending VmBasicCtrl controller and inside of click function it is referancing VmBasicCtrl controller not ownself.

So when you run the function vm variable is vmExtendedComponent's referance but variable changing in VmBasicCtrl.

DEMONSTRATION

In the example below there is a two component created with same controller. Controller has click and clickThatWorks functions. When you press the button component will log the ctrl variable on controller. The main difference is click func referancing a variable but clickThatWorks referancing ownself.

Run and see the result.

var app = angular.module('app', []);

app.controller('MainCtrl', function() {
  var vm = this;
  vm.entity = {
    name: 'test'
  };
});

app.controller('VmBasicCtrl', function() {
  var vm = this;
  vm.ctrl = 'vmbasic';
  vm.click = function() {
    console.log(vm.ctrl, vm.entity); // this is referancing vmBasic only
    vm.text = vm.entity; // here entity is undefined
  };

  vm.clickThatWorks = function() {
    console.log(this.ctrl, this.entity); // this is referancing ownself
    this.text = this.entity // 'NOT really VM but shows the value';
  }
});

app.component('vmExtendedComponent1', {
  template: 'click Example
<button ng-click="vm.click()">VM controller</button>
{{vm.text}}
',
  controller: 'VmExtendedCtrl',
  controllerAs: 'vm',
  bindings: {
    entity: '<'
  }
});

app.component('vmExtendedComponent2', {
  template: 'clickThatWorks Example
<button ng-click="vm.clickThatWorks()">VM controller</button>
{{vm.text}}
',
  controller: 'VmExtendedCtrl',
  controllerAs: 'vm',
  bindings: {
    entity: '<'
  }
});

app.controller('VmExtendedCtrl', function($controller) {
  angular.extend(this, $controller('VmBasicCtrl'));
  this.ctrl = 'vmextended';
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl as vm">
    <vm-extended-component1 entity="vm.entity"></vm-extended-component1>
    <vm-extended-component2 entity="vm.entity"></vm-extended-component2>
</div></code>```

Title: Binding to vm breaks reference

Body:
Extending controller binded to var vm = this fails to read binded values from component bindings

In example the difference is in (clicking the button displays entity)

app.controller('ThisBasicCtrl', function() {
  this.click = function() {
    this.text = this.entity;
  };
});

app.controller('VmBasicCtrl', function() {
  var vm = this;
  vm.click = function() {
    vm.text = vm.entity; // here entity is undefined
  };

  vm.clickThatWorks = function() {
    this.text = this.entity // 'NOT really VM but shows the value';
  }
});

var app = angular.module('app', []);

app.controller('MainCtrl', function() {
  var vm = this;
  vm.entity = {
    name: 'test'
  };
});

app.controller('ThisBasicCtrl', function() {
  this.click = function() {
    this.text = this.entity;
  };
});

app.component('thisExtendedComponent', {
  template: '<button ng-click="vm.click()">This controller</button>
{{vm.text}}
',
  controller: 'ExtendedCtrl',
  controllerAs: 'vm',
  bindings: {
    entity: '<'
  }
});

app.controller('ExtendedCtrl', function($controller) {
  angular.extend(this, $controller('ThisBasicCtrl'));
});

app.controller('VmBasicCtrl', function() {
  var vm = this;
  vm.click = function() {
    vm.text = vm.entity; // here entity is undefined
  };

  vm.clickThatWorks = function() {
    this.text = this.entity // 'NOT really VM but shows the value';
  }
});

app.component('vmExtendedComponent', {
  template: '<button ng-click="vm.click()">VM controller</button>
{{vm.text}}
',
  controller: 'VmExtendedCtrl',
  controllerAs: 'vm',
  bindings: {
    entity: '<'
  }
});

app.controller('VmExtendedCtrl', function($controller) {
  angular.extend(this, $controller('VmBasicCtrl'));
});

Extends this controller

    <this-extended-component entity="vm.entity"></this-extended-component>

Extends VM controller

    <vm-extended-component entity="vm.entity"></vm-extended-component>

Body:
Extend will copy the referance in the function...

On your thisExtendedComponent component you are extending ThisBasicCtrl and its click function referancing ownself inside the function but
vmExtendedComponent component is extending VmBasicCtrl controller and inside of click function it is referancing VmBasicCtrl controller not ownself.

So when you run the function vm variable is vmExtendedComponent's referance but variable changing in VmBasicCtrl.

DEMONSTRATION

In the example below there is a two component created with same controller. Controller has click and clickThatWorks functions. When you press the button component will log the ctrl variable on controller. The main difference is click func referancing a variable but clickThatWorks referancing ownself.

Run and see the result.

var app = angular.module('app', []);

app.controller('MainCtrl', function() {
  var vm = this;
  vm.entity = {
    name: 'test'
  };
});

app.controller('VmBasicCtrl', function() {
  var vm = this;
  vm.ctrl = 'vmbasic';
  vm.click = function() {
    console.log(vm.ctrl, vm.entity); // this is referancing vmBasic only
    vm.text = vm.entity; // here entity is undefined
  };

  vm.clickThatWorks = function() {
    console.log(this.ctrl, this.entity); // this is referancing ownself
    this.text = this.entity // 'NOT really VM but shows the value';
  }
});

app.component('vmExtendedComponent1', {
  template: '<span>click Example</span> <br><button ng-click="vm.click()">VM controller</button><div>{{vm.text}}</div>',
  controller: 'VmExtendedCtrl',
  controllerAs: 'vm',
  bindings: {
    entity: '<'
  }
});

app.component('vmExtendedComponent2', {
  template: '<span>clickThatWorks Example </span><br><button ng-click="vm.clickThatWorks()">VM controller</button><div>{{vm.text}}</div>',
  controller: 'VmExtendedCtrl',
  controllerAs: 'vm',
  bindings: {
    entity: '<'
  }
});

app.controller('VmExtendedCtrl', function($controller) {
  angular.extend(this, $controller('VmBasicCtrl'));
  this.ctrl = 'vmextended';
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl as vm">
    <vm-extended-component1 entity="vm.entity"></vm-extended-component1>
    <vm-extended-component2 entity="vm.entity"></vm-extended-component2>
</div>


问:
 larger break than usual?
This hasn't been a problem in the past, I don't know what has happened, but the
 element in my footer separates the text by like, 10px's. Wondering if I have some CSS or a tag I'm not aware of?

Here is my code:

.contentFake {
  background-color: #333;
  height: 200px;
}

.footer {
  width: 100%;
  position: fixed;
  margin-bottom: 0px;
  height: 80px;
  background-color: #1A1A1A;
  display: block;
}

.footerContent {
  width: 80%;
  margin: auto;
  padding: 20px;
  text-align: center;
  border-left: 1px solid #fff;
  border-right: 1px solid #fff;
  border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='contentFake'>
  <div class='footerContent'>
    <p>
      <font face="Helvetica" size="2" color="white">
        <font size="5" face="Indie Flower"><strong>THIS IS FOOTER</strong></font> <br />
        Home<br />
        Blog <br />
        Photo Feed <br />
        Vlogs <br />
        Farewell <br />
        BACK TO TOP <br /> © Jack Champions FOOTER All Rights Reserved 2017</font>
    </p>
  </div>
</div></code>```

jsfiddle: https://jsfiddle.net/gu1pdh5a/

The code  you run direct here, is the code I wish to see, yet on mine it turns up like this?

答:
use  margin and padding instead of
 tags.you can give padding top and bottom to the a tags.

Title: <br> larger break than usual?

Body:
This hasn't been a problem in the past, I don't know what has happened, but the
 element in my footer separates the text by like, 10px's. Wondering if I have some CSS or a tag I'm not aware of?

Here is my code:

.contentFake {
  background-color: #333;
  height: 200px;
}

.footer {
  width: 100%;
  position: fixed;
  margin-bottom: 0px;
  height: 80px;
  background-color: #1A1A1A;
  display: block;
}

.footerContent {
  width: 80%;
  margin: auto;
  padding: 20px;
  text-align: center;
  border-left: 1px solid #fff;
  border-right: 1px solid #fff;
  border: none;
}

        THIS IS FOOTER

        Home

        Blog

        Photo Feed

        Vlogs

        Farewell

        BACK TO TOP
 © Jack Champions FOOTER All Rights Reserved 2017

jsfiddle: https://jsfiddle.net/gu1pdh5a/

The code  you run direct here, is the code I wish to see, yet on mine it turns up like this?

Body: use  margin and padding instead of <br> tags.you can give padding top and bottom to the a tags.


问:
LINQ and column with Null
I have a DataSet, with a column, lets call it A, of type Int. I want to run a quiote simple LINQ query, using where on column A. The problem is, that column A can contain null values (at least in the T-SQL table from where i get it, I am not sure how these null values are translated in the TableAdapter). This results in an error when I try to run the following query:

```<code>MyTableDataTable dt =
    new MyTableDataTable();

MyTableTableAdapter ta =
     new MyTableTableAdapter();

        ta.Fill(dt);

// This is where the error occurs
var query = from  tbl in dt.AsEnumerable()
            where tbl.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };
</code>```

The error message it returns is this:

StrongTypingException was unhandled

An unhandled exception of type
   'System.Data.StrongTypingException' occurred in
  MyProgram.exe

Additional information: The value for column 'A' in
  table 'MyTable' is DBNull.

How should nullvalues be handed in a sceniario like this? I would like to do something like where A is not null, but I can't really find a way to do this...

答:
You must check null before  tbl.A == parentId ,and there are benefits check tbl.B

```<code>var query = from  tbl in dt.AsEnumerable()
        where tbl.A != null && tbl.A == parentId
        &&  tbl.B != null &&  tbl.B == languageId
        select new
        {
            tbl.A,
            tbl.B,
            tbl.C
        };
</code>```

Title: LINQ and column with Null

Body:
I have a DataSet, with a column, lets call it A, of type Int. I want to run a quiote simple LINQ query, using where on column A. The problem is, that column A can contain null values (at least in the T-SQL table from where i get it, I am not sure how these null values are translated in the TableAdapter). This results in an error when I try to run the following query:

MyTableDataTable dt =
    new MyTableDataTable();

MyTableTableAdapter ta =
     new MyTableTableAdapter();

        ta.Fill(dt);

// This is where the error occurs
var query = from  tbl in dt.AsEnumerable()
            where tbl.A == parentId
            &&    tbl.B == languageId
            select new
            {
                tbl.A,
                tbl.B,
                tbl.C
            };

The error message it returns is this:

StrongTypingException was unhandled

An unhandled exception of type
   'System.Data.StrongTypingException' occurred in
  MyProgram.exe

Additional information: The value for column 'A' in
  table 'MyTable' is DBNull.

How should nullvalues be handed in a sceniario like this? I would like to do something like where A is not null, but I can't really find a way to do this...

Body:
You must check null before  tbl.A == parentId ,and there are benefits check tbl.B

var query = from  tbl in dt.AsEnumerable()
        where tbl.A != null && tbl.A == parentId
        &&  tbl.B != null &&  tbl.B == languageId
        select new
        {
            tbl.A,
            tbl.B,
            tbl.C
        };


问:
escape special character json angular
Is there a built in way to escape json characters in angular (4)

here's my returned json -  I want to remove the   return symbols etc. A regex feels a bit hacky, prefer to use native / built in function.

EDIT: The {{ val }} expression are deliberate and I want to keep these.

```<code>"values": [
    "<p>value {{ val }} </p>\n\n<p><strong>value2 {{ val2 }}</strong></p>\n"
]
</code>```

答:
You need to use a regex, because those HTML characters are variable. But if you only want to remove the <code> </code>, simply do </p>

```<code>values = values.replace(' ', '');
</code>```

<p>For all characters : </p>

```<code>values = values.replace(new RegExp(/&[\w]{4};/, 'g', ''))
</code>```

Title: escape special character json angular

Body:
Is there a built in way to escape json characters in angular (4)

here's my returned json -  I want to remove the   return symbols etc. A regex feels a bit hacky, prefer to use native / built in function.

EDIT: The {{ val }} expression are deliberate and I want to keep these.

"values": [
    "
value {{ val }}
\n\n
value2 {{ val2 }}
\n"
]

Body:
You need to use a regex, because those HTML characters are variable. But if you only want to remove the &nbsp;, simply do

values = values.replace('&nbsp;', '');

For all characters :

values = values.replace(new RegExp(/&[\w]{4};/, 'g', ''))


问:
'didSelectRowAt' is not being called
i have a question about the UITableView delegate function didSelectRowAt. Everything is working fine but unfortunately the didSelectRowAt is not called. I read in some other stackoverflow question about the problem and tried some solutions out but none of them works for me. I made a subclass of the tableview which is the delegate himself:

```<code>class MyTableView : UITableView, UITableViewDelegate{

    override func awakeFromNib() {

        super.awakeFromNib()

        separatorStyle = .none

        backgroundView = nil
        backgroundColor = UIColor.clear

        isScrollEnabled = false

        delegate = self
        isEditing = false
        allowsSelection = true

    }

//    func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
//
//    this is working
//
//    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("not called")

    }

}
</code>```

So all subclasses of MyTableView will implement the datasource stuff and this also working fine (in case somehow will mentioned this).

The strange thing is that didHighlightRowAt is called, so the delegate somehow works. Only the didSelectRowAt which I want is not being called.

By the way there aren't any UITapGestureRecognizer.

Can somehow give me any advice here. Are there properties which are wrong?

答:
There might be the following issue

s:

You have not setup the delegate of the UITableView

```<code>self.tableview.delegate = self
</code>```

Check if the user-interaction is no disable for UITableView or UITableViewCell

```<code>self.tableview.isUserInteractionEnabled = true
</code>```

Check if the tableview selection style is not none

```<code>self.tableview.allowsSelection = true
</code>```

Check if any of the gestures are not enabled.

```<code>func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}
</code>```

Title: 'didSelectRowAt' is not being called

Body:
i have a question about the UITableView delegate function didSelectRowAt. Everything is working fine but unfortunately the didSelectRowAt is not called. I read in some other stackoverflow question about the problem and tried some solutions out but none of them works for me. I made a subclass of the tableview which is the delegate himself:

class MyTableView : UITableView, UITableViewDelegate{

    override func awakeFromNib() {

        super.awakeFromNib()

        separatorStyle = .none

        backgroundView = nil
        backgroundColor = UIColor.clear

        isScrollEnabled = false

        delegate = self
        isEditing = false
        allowsSelection = true

    }

//    func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
//
//    this is working
//
//    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("not called")

    }

}

So all subclasses of MyTableView will implement the datasource stuff and this also working fine (in case somehow will mentioned this).

The strange thing is that didHighlightRowAt is called, so the delegate somehow works. Only the didSelectRowAt which I want is not being called.

By the way there aren't any UITapGestureRecognizer.

Can somehow give me any advice here. Are there properties which are wrong?

Body:
There might be the following issue

s:

You have not setup the delegate of the UITableView

self.tableview.delegate = self

Check if the user-interaction is no disable for UITableView or UITableViewCell

self.tableview.isUserInteractionEnabled = true

Check if the tableview selection style is not none

self.tableview.allowsSelection = true

Check if any of the gestures are not enabled.

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}


问:
What essential design artifacts do you produce?
In the course of your software development lifecycle, what essential design artifacts do you produce? What makes them essential to your practice?

The project I'm currently on has been in production for more than 8 years. This web application has been actively enhanced and maintained over that time. While we have CMMI-based policies and processes in place, with portions of our practice being well defined, the design phase has been largely overlooked. What are the best practices?

答:
In our model (which is fairly specific to business process applications) the design artefacts include:

a domain data model, with comments on each entity and attribute

a properties file listing all the modify and create triggers on each entity, calculated attributes, validators and other business logic

a set of screen definitions (view model)

However do these really count as design artefacts? Our framework is such that these definitions are used to generate the actual code of the system, so maybe they go beyond design.

But the fact that they serve double duty is powerful because they are, by definition, up to date and synchronised with the code at all times.

OwnerDisplayName: Leigh Caldwell


问:
What is the difference between DoS and Brute Force attacks?
I was reading about DoS attacks on Apache servers but the "Brute Force" word pops up sometimes I know DoS attacks but "Brute Force" seems to be similar, is there a difference or it is just another word of DoS?</p>

答:
Brute force attacks use a technique of attempting to try every combination of passwords/keys to gain access to a particular system.  What the hacker does when they gain entry to the system depends on the motivation of the hacker.

DoS (Denial of Service) attacks describe cases where the motivation of the hacker is to bring down the system, causing maximum inconvenience to the users of the system.

They can't really be compared against each other, as brute force is a technique to gain entry, and DoS is a type of attack.  It is possible that an attack could be both brute force and DoS.

OwnerDisplayName: Sulaiman

LastEditorDisplayName: Jeremy Ruten

OwnerDisplayName: LeopardSkinPillBoxHat