问:
yairEO/tagify same event when tag added on script load and on user added tag by himself
Im using jquery and nice library from github yairEO/tagify

I need to separate two events when tag is added by user and when tag is added by script on load:

```<code>tagify.on('add', function(e, tagName){
    console.log('added', tagName)
});
</code>```

It is neccesary to ajax update, delete tags and add new. When I use javascript above i have log from console on load page and on tag add.

Need help ;)

答:
I got my own solution.
Its not perfect but it work well !
(after pick tag from dropdown)</p>

```<code>tagify.on('add', function(e){
    if(tagify.listeners.dropdown){
        var tag_id = e.detail.data.code;
        //do my code
    }
});
</code>```

Body:
Im using jquery and nice library from github yairEO/tagify

I need to separate two events when tag is added by user and when tag is added by script on load:

tagify.on('add', function(e, tagName){
    console.log('added', tagName)
});

It is neccesary to ajax update, delete tags and add new. When I use javascript above i have log from console on load page and on tag add.

Need help ;)

Body:
I got my own solution.
Its not perfect but it work well !
(after pick tag from dropdown)

tagify.on('add', function(e){
    if(tagify.listeners.dropdown){
        var tag_id = e.detail.data.code;
        //do my code
    }
});


来源: stackexchange

问:
Overloading input the base class inside overloading input derived class
I want to reuse a overloading input functions from Base class inside Derived class.

```<code>class Base
{
private:
    int m_value;

public:
    Base(int value)
        : m_value(value)
    {
    }

    friend std::istream& operator>> (std::istream &in,Base &b)
    {

        in>>b.m_value;
        return in;
    }
};

class Derived : public Base
{
    std::string id;
public:
    Derived(int value,std::string id)
        : Base(value),id(id)
    {
    }

    friend std::istream& operator>> (std::istream &in,Derived &d)
    {
        in>>static_cast<Base>(d);//not work
        in>>d.id;
        return in;
    }
};
</code>```

What wrong with my code when I write in>>static_cast<Base>(d)?

答:
In order to get the Base part of d, you need to cast to Base&.

What you get with your cast is a temporary Base object, which can't be passed as a non-const reference argument.

Note that this cast will still not make everything work as you would expect – for instance,

```<code>Derived d;
Base &b = d;
std::cin >> b;
</code>```

will use the Base& overload, since overloading is based on the static type of b.

A common way to overload >> (and <<) for a hierarchy is to have only one overload, which just delegates to a virtual member function.

Then you can override the member function in the derived classes and let dynamic dispatch take care of selecting the appropriate function.

```<code>struct Base
{
    virtual void read(std::istream& is) { ... }
};

std::istream& operator>> (std::istream &in, Base &b)
{
    b.read(in);
    return in;
}

struct Derived: Base
{
    void read(std::istream& is) override { Base::read(is); ... }
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to reuse a overloading input functions from Base class inside Derived class.

class Base
{
private:
    int m_value;

public:
    Base(int value)
        : m_value(value)
    {
    }

    friend std::istream& operator>> (std::istream &in,Base &b)
    {

        in>>b.m_value;
        return in;
    }
};

class Derived : public Base
{
    std::string id;
public:
    Derived(int value,std::string id)
        : Base(value),id(id)
    {
    }

    friend std::istream& operator>> (std::istream &in,Derived &d)
    {
        in>>static_cast<Base>(d);//not work
        in>>d.id;
        return in;
    }
};

What wrong with my code when I write in>>static_cast<Base>(d)?

Body:
In order to get the Base part of d, you need to cast to Base&.

What you get with your cast is a temporary Base object, which can't be passed as a non-const reference argument.

Note that this cast will still not make everything work as you would expect – for instance,

Derived d;
Base &b = d;
std::cin >> b;

will use the Base& overload, since overloading is based on the static type of b.

A common way to overload >> (and <<) for a hierarchy is to have only one overload, which just delegates to a virtual member function.

Then you can override the member function in the derived classes and let dynamic dispatch take care of selecting the appropriate function.

struct Base
{
    virtual void read(std::istream& is) { ... }
};

std::istream& operator>> (std::istream &in, Base &b)
{
    b.read(in);
    return in;
}

struct Derived: Base
{
    void read(std::istream& is) override { Base::read(is); ... }
};


问:
Ansible: How to extract values from a dictionary of lists
I'm trying to fetch the values from list of dict but unable to get the exact output, which is required

Using Linux server with installed versions of ansible 2.7.5 & jinja2 2.7.2 .

The below one is the list of dict value.

```<code>DOMAIN_GROUPS_ASSIGNMENT:

CACHE01:
    - domain_group: DG1
      is_active: true
    - domain_group: DG2
      is_active: true
    - domain_group: DG3
      is_active: true
  CACHE02:
    - domain_group: DG4
      is_active: true
    - domain_group: DG5
      is_active: true
    - domain_group: DG6
      is_active: true

  SCACHE01:
    - domain_group: DG1
      is_active: false
    - domain_group: DG2
      is_active: false
    - domain_group: DG3
      is_active: true
  SCACHE02:
    - domain_group: DG4
      is_active: false
    - domain_group: DG5
      is_active: false
    - domain_group: DG6
      is_active: false
</code>```

So far trying with the below code:

```<code>- debug:
      msg: "KEY: {{ item.key }}, VALUE: {{ item.value }}"
    loop: "{{ lookup('dict', DOMAIN_GROUPS_ASSIGNMENT) }}"
</code>```

Output which I'm getting is:

```<code>TASK [debug] ************************************************************************************************************************************************
task path: /u02/netcracker/reir1015_test/singlesite/test.yml:7
Friday 31 May 2019  08:54:59 -0400 (0:00:00.058)       0:00:00.897 ************
ok: [localhost] => (item={'key': u'CACHE01', 'value': [{u'is_active': True, u'domain_group': u'DG1'}, {u'is_active': True, u'domain_group': u'DG2'}, {u'is_active': True, u'domain_group': u'DG3'}]}) => {}

MSG:

KEY: CACHE01, VALUE: [{u'domain_group': u'DG1', u'is_active': True}, {u'domain_group': u'DG2', u'is_active': True}, {u'domain_group': u'DG3', u'is_active': True}]

ok: [localhost] => (item={'key': u'SCACHE02', 'value': [{u'is_active': False, u'domain_group': u'DG4'}, {u'is_active': False, u'domain_group': u'DG5'}, {u'is_active': False, u'domain_group': u'DG6'}]}) => {}

MSG:

KEY: SCACHE02, VALUE: [{u'domain_group': u'DG4', u'is_active': False}, {u'domain_group': u'DG5', u'is_active': False}, {u'domain_group': u'DG6', u'is_active': False}]

ok: [localhost] => (item={'key': u'SCACHE01', 'value': [{u'is_active': False, u'domain_group': u'DG1'}, {u'is_active': False, u'domain_group': u'DG2'}, {u'is_active': True, u'domain_group': u'DG3'}]}) => {}

MSG:

KEY: SCACHE01, VALUE: [{u'domain_group': u'DG1', u'is_active': False}, {u'domain_group': u'DG2', u'is_active': False}, {u'domain_group': u'DG3', u'is_active': True}]

ok: [localhost] => (item={'key': u'CACHE02', 'value': [{u'is_active': True, u'domain_group': u'DG4'}, {u'is_active': True, u'domain_group': u'DG5'}, {u'is_active': True, u'domain_group': u'DG6'}]}) => {}

MSG:

KEY: CACHE02, VALUE: [{u'domain_group': u'DG4', u'is_active': True}, {u'domain_group': u'DG5', u'is_active': True}, {u'domain_group': u'DG6', u'is_active': True}]
</code>```

Required output:

Result should be in dict format and should be stored in one variable.

I expect something like below in list or dict format:

CACHE01: True ,CACHE02: True, SCACHE01:False, SCACHE02: False

The above values should get stored in one variable.

答:
You have to select the right value for your result:

```<code>tasks:
- name: DEBUG
  debug:
    msg: 'KEY: {{ item.key }}, VALUE: {{ item.value.0.is_active }}'
  loop: '{{ lookup("dict", DOMAIN_GROUPS_ASSIGNMENT) }}'
</code>```

Body:
I'm trying to fetch the values from list of dict but unable to get the exact output, which is required

Using Linux server with installed versions of ansible 2.7.5 & jinja2 2.7.2 .

The below one is the list of dict value.

DOMAIN_GROUPS_ASSIGNMENT:

CACHE01:
    - domain_group: DG1
      is_active: true
    - domain_group: DG2
      is_active: true
    - domain_group: DG3
      is_active: true
  CACHE02:
    - domain_group: DG4
      is_active: true
    - domain_group: DG5
      is_active: true
    - domain_group: DG6
      is_active: true

  SCACHE01:
    - domain_group: DG1
      is_active: false
    - domain_group: DG2
      is_active: false
    - domain_group: DG3
      is_active: true
  SCACHE02:
    - domain_group: DG4
      is_active: false
    - domain_group: DG5
      is_active: false
    - domain_group: DG6
      is_active: false

So far trying with the below code:

- debug:
      msg: "KEY: {{ item.key }}, VALUE: {{ item.value }}"
    loop: "{{ lookup('dict', DOMAIN_GROUPS_ASSIGNMENT) }}"

Output which I'm getting is:

TASK [debug] ************************************************************************************************************************************************
task path: /u02/netcracker/reir1015_test/singlesite/test.yml:7
Friday 31 May 2019  08:54:59 -0400 (0:00:00.058)       0:00:00.897 ************
ok: [localhost] => (item={'key': u'CACHE01', 'value': [{u'is_active': True, u'domain_group': u'DG1'}, {u'is_active': True, u'domain_group': u'DG2'}, {u'is_active': True, u'domain_group': u'DG3'}]}) => {}

MSG:

KEY: CACHE01, VALUE: [{u'domain_group': u'DG1', u'is_active': True}, {u'domain_group': u'DG2', u'is_active': True}, {u'domain_group': u'DG3', u'is_active': True}]

ok: [localhost] => (item={'key': u'SCACHE02', 'value': [{u'is_active': False, u'domain_group': u'DG4'}, {u'is_active': False, u'domain_group': u'DG5'}, {u'is_active': False, u'domain_group': u'DG6'}]}) => {}

MSG:

KEY: SCACHE02, VALUE: [{u'domain_group': u'DG4', u'is_active': False}, {u'domain_group': u'DG5', u'is_active': False}, {u'domain_group': u'DG6', u'is_active': False}]

ok: [localhost] => (item={'key': u'SCACHE01', 'value': [{u'is_active': False, u'domain_group': u'DG1'}, {u'is_active': False, u'domain_group': u'DG2'}, {u'is_active': True, u'domain_group': u'DG3'}]}) => {}

MSG:

KEY: SCACHE01, VALUE: [{u'domain_group': u'DG1', u'is_active': False}, {u'domain_group': u'DG2', u'is_active': False}, {u'domain_group': u'DG3', u'is_active': True}]

ok: [localhost] => (item={'key': u'CACHE02', 'value': [{u'is_active': True, u'domain_group': u'DG4'}, {u'is_active': True, u'domain_group': u'DG5'}, {u'is_active': True, u'domain_group': u'DG6'}]}) => {}

MSG:

KEY: CACHE02, VALUE: [{u'domain_group': u'DG4', u'is_active': True}, {u'domain_group': u'DG5', u'is_active': True}, {u'domain_group': u'DG6', u'is_active': True}]

Required output:

Result should be in dict format and should be stored in one variable.

I expect something like below in list or dict format:

CACHE01: True ,CACHE02: True, SCACHE01:False, SCACHE02: False

The above values should get stored in one variable.

Body:
You have to select the right value for your result:

tasks:
- name: DEBUG
  debug:
    msg: 'KEY: {{ item.key }}, VALUE: {{ item.value.0.is_active }}'
  loop: '{{ lookup("dict", DOMAIN_GROUPS_ASSIGNMENT) }}'


问:
Compare two multi-element attributes in XACML policy
Consider a subject and object both having a label defined as follows:

subject/object label = [i1, i2, ..., in],  where i is some subjectId of another subject.

In a policy (ALFA/XACML), how can I perform a comparison against the subject and object label such that no elements in either list are the same.

For example:

```<code>subject_label = [i2, i4, i9]
object_label  = [i1, i3, i7, i9]
</code>```

The resulting decision would be DENY as both labels contain i9. If no match was found in any list, then the access result would be PERMIT.

答:
What you are looking to use is stringAtLeastOneMemberOf (or equivalent for other datatypes). This function takes in 2 parameters:

a bag of type string

a bag of type string

It returns true if there is at least one value in the first bag equal to one value in the second bag. For strings, the comparison is case-sensitive.

```<code>namespace com.axiomatics{
    /**
     * Ths policy will checks the contents of the user label and the the resource label.
     * It will deny access if there is at least one value in the user label equal to at least
     * one value in the resource label.
     */
    policy denyIfSameContent{
        apply firstApplicable
        /**
         * This rule will deny access is user.label contains at least 1 value that is also present
         * in object.label
         */
        rule denyIfSameContent{
            deny
            condition stringAtLeastOneMemberOf(user.label, object.label)
        }
    }
}
</code>```

And here is the XACML/XML representation:

```<code><?xml version="1.0" encoding="UTF-8"?><!--This file was generated by the
    ALFA Plugin for Eclipse from Axiomatics AB (http://www.axiomatics.com). --><!--Any modification to this file will
    be lost upon recompilation of the source ALFA file -->
<xacml3:Policy
    xmlns:xacml3="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
    PolicyId="http://axiomatics.com/alfa/identifier/com.axiomatics.denyIfSameContent"
    RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"
    Version="1.0">
    <xacml3:Description>Ths policy will checks the contents of the user
        label and the the resource label.
        It will deny access if there is at least one value in the user label
        equal to at least
        one value in the resource label.
    </xacml3:Description>
    <xacml3:PolicyDefaults>
        <xacml3:XPathVersion>http://www.w3.org/TR/1999/REC-xpath-19991116
        </xacml3:XPathVersion>
    </xacml3:PolicyDefaults>
    <xacml3:Target />
    <xacml3:Rule Effect="Deny"
        RuleId="com.axiomatics.denyIfSameContent.denyIfSameContent">
        <xacml3:Description>This rule will deny access is user.label contains
            at least 1 value that is also present
            in object.label
        </xacml3:Description>
        <xacml3:Target />
        <xacml3:Condition>
            <xacml3:Apply
                FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                <xacml3:AttributeDesignator
                    AttributeId="com.axiomatics.user.label"
                    Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"
                    DataType="http://www.w3.org/2001/XMLSchema#string"
                    MustBePresent="false" />
                <xacml3:AttributeDesignator
                    AttributeId="com.axiomatics.object.label"
                    Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"
                    DataType="http://www.w3.org/2001/XMLSchema#string"
                    MustBePresent="false" />
            </xacml3:Apply>
        </xacml3:Condition>
    </xacml3:Rule>
</xacml3:Policy>
</code>```

Body:
Consider a subject and object both having a label defined as follows:

subject/object label = [i1, i2, ..., in],  where i is some subjectId of another subject.

In a policy (ALFA/XACML), how can I perform a comparison against the subject and object label such that no elements in either list are the same.

For example:

subject_label = [i2, i4, i9]
object_label  = [i1, i3, i7, i9]

The resulting decision would be DENY as both labels contain i9. If no match was found in any list, then the access result would be PERMIT.

Body:
What you are looking to use is stringAtLeastOneMemberOf (or equivalent for other datatypes). This function takes in 2 parameters:

a bag of type string

a bag of type string

It returns true if there is at least one value in the first bag equal to one value in the second bag. For strings, the comparison is case-sensitive.

namespace com.axiomatics{
    /**
     * Ths policy will checks the contents of the user label and the the resource label.
     * It will deny access if there is at least one value in the user label equal to at least
     * one value in the resource label.
     */
    policy denyIfSameContent{
        apply firstApplicable
        /**
         * This rule will deny access is user.label contains at least 1 value that is also present
         * in object.label
         */
        rule denyIfSameContent{
            deny
            condition stringAtLeastOneMemberOf(user.label, object.label)
        }
    }
}

And here is the XACML/XML representation:

<?xml version="1.0" encoding="UTF-8"?><!--This file was generated by the
    ALFA Plugin for Eclipse from Axiomatics AB (http://www.axiomatics.com). --><!--Any modification to this file will
    be lost upon recompilation of the source ALFA file -->
<xacml3:Policy
    xmlns:xacml3="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
    PolicyId="http://axiomatics.com/alfa/identifier/com.axiomatics.denyIfSameContent"
    RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"
    Version="1.0">
    <xacml3:Description>Ths policy will checks the contents of the user
        label and the the resource label.&#13;
        It will deny access if there is at least one value in the user label
        equal to at least&#13;
        one value in the resource label.
    </xacml3:Description>
    <xacml3:PolicyDefaults>
        <xacml3:XPathVersion>http://www.w3.org/TR/1999/REC-xpath-19991116
        </xacml3:XPathVersion>
    </xacml3:PolicyDefaults>
    <xacml3:Target />
    <xacml3:Rule Effect="Deny"
        RuleId="com.axiomatics.denyIfSameContent.denyIfSameContent">
        <xacml3:Description>This rule will deny access is user.label contains
            at least 1 value that is also present&#13;
            in object.label
        </xacml3:Description>
        <xacml3:Target />
        <xacml3:Condition>
            <xacml3:Apply
                FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-at-least-one-member-of">
                <xacml3:AttributeDesignator
                    AttributeId="com.axiomatics.user.label"
                    Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"
                    DataType="http://www.w3.org/2001/XMLSchema#string"
                    MustBePresent="false" />
                <xacml3:AttributeDesignator
                    AttributeId="com.axiomatics.object.label"
                    Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"
                    DataType="http://www.w3.org/2001/XMLSchema#string"
                    MustBePresent="false" />
            </xacml3:Apply>
        </xacml3:Condition>
    </xacml3:Rule>
</xacml3:Policy>


问:
React Native - useRef warning on function components
I have a simple function component that needs to use input refs in order to set correct focuses on submitting:

```<code>import React, { useRef } from 'react'
import { View, TextInput } from 'react-native'

export default function Login() {
  let usernameRef = useRef(null)
  let passwordRef = useRef(null)

  return (
    <View>
      <TextInput ref={usernameRef} />
      <TextInput ref={passwordRef} />
    </View>
  )
}
</code>```

The problem is that using ref with new Hooks API still alerting a warn:

Warning: Function components cannot be given refs. Attempts to access
  this ref will fail. Did you mean to use React.forwardRef()?

I don't want to use classes. Tried using "forwardRef" and the warning still there:

```<code>import React, { createRef, forwardRef } from 'react'
import { View, TextInput } from 'react-native'

export default function Login() {
  let usernameRef = createRef()
  let passwordRef = createRef()
  const Input = forwardRef((props, ref) => (
    <TextInput ref={ref} {...props} />
  ))

  return (
    <View>
      <Input ref={usernameRef} />
      <Input ref={passwordRef} />
    </View>
  )
}
</code>```

What I'm doing wrong?

答:
```<code>import React from 'react'
import { View, TextInput } from 'react-native'

const usernameRef = React.createRef();
const passwordRef = React.createRef();

export default function Login() {
  return (
    <View style={{flex: 1 , justifyContent: "center", alignItems: "center"}}>
      <TextInput ref={usernameRef} onSubmitEditing={() => passwordRef.current.focus()} placeholder="First" />
      <TextInput ref={passwordRef} placeholder="second" />
    </View>
  )
}
</code>```

Snack here

Body:
I have a simple function component that needs to use input refs in order to set correct focuses on submitting:

import React, { useRef } from 'react'
import { View, TextInput } from 'react-native'

export default function Login() {
  let usernameRef = useRef(null)
  let passwordRef = useRef(null)

  return (
    <View>
      <TextInput ref={usernameRef} />
      <TextInput ref={passwordRef} />
    </View>
  )
}

The problem is that using ref with new Hooks API still alerting a warn:

Warning: Function components cannot be given refs. Attempts to access
  this ref will fail. Did you mean to use React.forwardRef()?

I don't want to use classes. Tried using "forwardRef" and the warning still there:

import React, { createRef, forwardRef } from 'react'
import { View, TextInput } from 'react-native'

export default function Login() {
  let usernameRef = createRef()
  let passwordRef = createRef()
  const Input = forwardRef((props, ref) => (
    <TextInput ref={ref} {...props} />
  ))

  return (
    <View>
      <Input ref={usernameRef} />
      <Input ref={passwordRef} />
    </View>
  )
}

What I'm doing wrong?

Body:
import React from 'react'
import { View, TextInput } from 'react-native'

const usernameRef = React.createRef();
const passwordRef = React.createRef();

export default function Login() {
  return (
    <View style={{flex: 1 , justifyContent: "center", alignItems: "center"}}>
      <TextInput ref={usernameRef} onSubmitEditing={() => passwordRef.current.focus()} placeholder="First" />
      <TextInput ref={passwordRef} placeholder="second" />
    </View>
  )
}

Snack here


问:
Cannot add(any of) global git configurations in .gitconfig file
I recently tried to add a configuration for git as global configuration. For example git config --global core-editor "vim". I got the error as given below.

error: could not write config file /home/admin/.gitconfig: Operation not permitted

Like wise I also tried to add git config --global color.ui always. For this also the above error is thrown in the terminal.

Please help me.

答:
Check if immutable(i) attribute has been set for that file. When this attribute is enabled, we cannot alter, rename or delete file. Try the below command.

```<code>sudo chattr -i .gitconfig
</code>```

Please visit this link for more details.

Body:
Check if immutable(i) attribute has been set for that file. When this attribute is enabled, we cannot alter, rename or delete file. Try the below command.

sudo chattr -i .gitconfig

Please visit this link for more details.


问:
How to play audio file in asp.net
i have a grid in my page...

grid consists of 2 columns like Songname and play(linkbutton column)

when i click play of the particular row, it should play that particular song in other web page

the song should play with the help of object tag(means it should have all options like next, prev,seek in the player)

i took a small above example to explain my problem overall the senario explained above matches in my project

Please help iam stuck up eith this problem from pat one week, i googled many times, iam not getting the exact answer

sorry for bad english

Thank you in advance

答:
    background-color:aqua;
    background: url("farm.jpg") no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>ImageButton1.Attributes.Add("onmouseover", "zvukkonj()");
            ImageButton1.Attributes.Add("onclick", "opiskonj()");</code>```

ContentLicense: CC BY-SA 3.0

Title: How to play audio file in asp.net

Body:
    background-color:aqua;
    background: url("farm.jpg") no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

ImageButton1.Attributes.Add("onmouseover", "zvukkonj()");
            ImageButton1.Attributes.Add("onclick", "opiskonj()");


问:
Django Models: Create custom User model when I create a normal User
I have a model called 'User profiles' that is a custom user, it takes a user in a OneToOneField and also has additional fields like 'age', 'is_teacher', 'is_location'.

My Problem is that when I create a normal user, this 'User Profiles' dosen't create a new User. How do I make that happen?

I know that I have to do something like this with a receiver (Where do I add the receiver?):

```<code>from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_user_data(sender, update_fields, created, instance, **kwargs):
if created:
    # Create your user data
    pass
</code>```

These are my models:

```<code>from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class UserProfile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  age = models.IntegerField(default=18)
  description = models.CharField(max_length=300)
  is_student = models.BooleanField(default=False)
  is_teacher = models.BooleanField(default=False)

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

答:
So you're almost there!

a signal is function that executes after something happens, in the case a User model gets saved to the database, it in turn calls every function that's decorated with @receiver and that model as a sender it can find.

What you need to do is check if its a new or updated user, and if its a new one you create the users profile. Something like:

```<code>@receiver(post_save, sender=User)
def create_user_data(sender, update_fields, created, instance, **kwargs):
    if created:
        user  = instance
        profile = UserProfile.objects.create(user=user, age=12)
</code>```

Now, this only works if the User itself contains enough information to create the profile!

Body:
I have a model called 'User profiles' that is a custom user, it takes a user in a OneToOneField and also has additional fields like 'age', 'is_teacher', 'is_location'.

My Problem is that when I create a normal user, this 'User Profiles' dosen't create a new User. How do I make that happen?

I know that I have to do something like this with a receiver (Where do I add the receiver?):

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_user_data(sender, update_fields, created, instance, **kwargs):
if created:
    # Create your user data
    pass

These are my models:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class UserProfile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  age = models.IntegerField(default=18)
  description = models.CharField(max_length=300)
  is_student = models.BooleanField(default=False)
  is_teacher = models.BooleanField(default=False)

  def __str__(self):
    return self.user.username

Body:
So you're almost there!

a signal is function that executes after something happens, in the case a User model gets saved to the database, it in turn calls every function that's decorated with @receiver and that model as a sender it can find.

What you need to do is check if its a new or updated user, and if its a new one you create the users profile. Something like:

@receiver(post_save, sender=User)
def create_user_data(sender, update_fields, created, instance, **kwargs):
    if created:
        user  = instance
        profile = UserProfile.objects.create(user=user, age=12)

Now, this only works if the User itself contains enough information to create the profile!


问:
Display marks from least to high
I'm trying to display the marks from least to high from user input.The code gets the array of students name and array of marks.Then it has to show the output from least to high marks along with student name.I'm struck at displaying the name of student.The code just shows the marks from least to high.</p>

```<code>int n = 5;//total no of students
Scanner in = new Scanner(System.in);
System.out.println("Enter Students name:");
String[] s = new String[n];
for (int i = 0; i<s.length; i++)
{
  s[i] = in.nextLine();
}
System.out.println("Enter marks:");
int array[] = new int[n];
for (int i = 0; i<n; i++)
{
 array[i] = in.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < array.length; i++)
{
  System.out.println(array[i]);
}
</code>```

答:
This should work for you </p>

```<code>// Class student
public class Student implements Comparable {
    public String Name;
    public double Mark;

    // Should implement comparable to be able to compare it via Marks
    @Override
    public int compareTo(Student per) {
        if(this.Mark == per.Mark)
            return 0;
        else
            return this.Mark > per.Mark ? 1 : -1;
    }
}

//total no of students
int n = 5;
// list of students and their marks
Student[] s = new Student[n];
// Scanner
Scanner in = new Scanner(System.in);

// Get student names and their marks
for (int i = 0; i<s.length; i++)
{
    s[i] = new Student();
    System.out.println("Enter Student #" + i + " name :");
    s[i].Name = in.nextLine();

    System.out.println("Enter Student #" + i + " mark :");
    s[i].mark = in.nextDouble();
}

Arrays.sort(s);
for (int i = 0; i < s.length; i++)
{
    System.out.println(s[i].Name + " : " + s[i].Mark);
}
</code>```

Title: Display marks from least to high

Body:
I'm trying to display the marks from least to high from user input.The code gets the array of students name and array of marks.Then it has to show the output from least to high marks along with student name.I'm struck at displaying the name of student.The code just shows the marks from least to high.

int n = 5;//total no of students
Scanner in = new Scanner(System.in);
System.out.println("Enter Students name:");
String[] s = new String[n];
for (int i = 0; i<s.length; i++)
{
  s[i] = in.nextLine();
}
System.out.println("Enter marks:");
int array[] = new int[n];
for (int i = 0; i<n; i++)
{
 array[i] = in.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < array.length; i++)
{
  System.out.println(array[i]);
}

Body:
This should work for you

// Class student
public class Student implements Comparable {
    public String Name;
    public double Mark;

    // Should implement comparable to be able to compare it via Marks
    @Override
    public int compareTo(Student per) {
        if(this.Mark == per.Mark)
            return 0;
        else
            return this.Mark > per.Mark ? 1 : -1;
    }
}

//total no of students
int n = 5;
// list of students and their marks
Student[] s = new Student[n];
// Scanner
Scanner in = new Scanner(System.in);

// Get student names and their marks
for (int i = 0; i<s.length; i++)
{
    s[i] = new Student();
    System.out.println("Enter Student #" + i + " name :");
    s[i].Name = in.nextLine();

    System.out.println("Enter Student #" + i + " mark :");
    s[i].mark = in.nextDouble();
}

Arrays.sort(s);
for (int i = 0; i < s.length; i++)
{
    System.out.println(s[i].Name + " : " + s[i].Mark);
}


问:
UIButton.isSelected can't Observable
I want to check the isSelected state of some UIButtons in order to feed the isEnabled state of another button. I wanted the latter button enabled only when one of the other buttons isSelected state is set to true.
However I saw that you have chosen to keep the isSelected property only as an Observer.

```<code>@IBAction func checkBoxButtonTaped(sender: UIButton) {
    sender.rx.isSelected.onNext(!sender.isSelected)
}
</code>```

Or

```<code>@IBAction func checkBoxButtonTaped(sender: UIButton) {
    sender.isSelected = !sender.isSelected
}
</code>```

Observable Code:

```<code>let state = Observable.just(true)
state.bindTo(checkBoxButton.rx.isSelected)
    .disposed(by: disposeBag)
state.bindTo(loginButton.rx.isEnabled)
    .disposed(by: disposeBag)
</code>```

By two code snippets, Observable can't work.

答:
Or you can simply use scan:

```<code>checkBoxButton.rx.tap
    .scan(false) { lastValue, _ in
        return !lastValue
    }
    .bind(to: loginButton.rx.isEnabled)
    .disposed(by: disposeBag)
</code>```

Here is a more detailed explanation of how scan works.

Title: UIButton.isSelected can't Observable

Body:
I want to check the isSelected state of some UIButtons in order to feed the isEnabled state of another button. I wanted the latter button enabled only when one of the other buttons isSelected state is set to true.
However I saw that you have chosen to keep the isSelected property only as an Observer.

@IBAction func checkBoxButtonTaped(sender: UIButton) {
    sender.rx.isSelected.onNext(!sender.isSelected)
}

Or

@IBAction func checkBoxButtonTaped(sender: UIButton) {
    sender.isSelected = !sender.isSelected
}

Observable Code:

let state = Observable.just(true)
state.bindTo(checkBoxButton.rx.isSelected)
    .disposed(by: disposeBag)
state.bindTo(loginButton.rx.isEnabled)
    .disposed(by: disposeBag)

By two code snippets, Observable can't work.

Body:
Or you can simply use scan:

checkBoxButton.rx.tap
    .scan(false) { lastValue, _ in
        return !lastValue
    }
    .bind(to: loginButton.rx.isEnabled)
    .disposed(by: disposeBag)

Here is a more detailed explanation of how scan works.


问:
Render partial last in Razor page, despite being logically first
I have a situation like so:

```<code>@{ Html.RenderPartial("Header"); }

@{ Html.RenderPartial("ArbitraryView"); }
</code>```

The ArbitraryView partial sets ViewData["Test"] in its view.

The Header partial prints ViewData["Test"].

Is it possible to tell razor to render the ArbitraryView partial first in order for it to set ViewData["Test"], then the Header last in order to read that value, without changing the order they're displayed on the page?

I am incapable of using RenderBody, which would achieve this desired result.

答:
Instead of using RenderPartial you could use Partial and keep the results in variables. You can then output the results in the order you want:

```<code>@{
    var arbitraryView = Html.Partial("ArbitraryView");
    var header = Html.Partial("Header");
}

@header
@arbitraryView
</code>```

Body:
I have a situation like so:

@{ Html.RenderPartial("Header"); }

@{ Html.RenderPartial("ArbitraryView"); }

The ArbitraryView partial sets ViewData["Test"] in its view.

The Header partial prints ViewData["Test"].

Is it possible to tell razor to render the ArbitraryView partial first in order for it to set ViewData["Test"], then the Header last in order to read that value, without changing the order they're displayed on the page?

I am incapable of using RenderBody, which would achieve this desired result.

Body:
Instead of using RenderPartial you could use Partial and keep the results in variables. You can then output the results in the order you want:

@{
    var arbitraryView = Html.Partial("ArbitraryView");
    var header = Html.Partial("Header");
}

@header
@arbitraryView


问:
How to create a SFX ZIP with SevenZipSharp?
I have been looking at SevenZipSharp to create a self extracting zip file. The project page says that they have a special class SevenZipSfx that does this. However I have searched the object explorer and the documentation for version 0.64 and I cant find any reference to it.

Does anyone know if the class is missing or if there is a different meaning to "Special Class" that I'm missing?

答:
It looks like the Sfx class isn't built by default. Grab the source code from Codeplex (or check out the trunk code) and add conditional compile constant SFX to the project settings and rebuild. Annoyingly the signing isn't in their source control so you'll have to disable code signing for the assembly.

Alternatively if this is a one-off SFX then you can build it yourself using the files in the SevenZip\sfx directory. If you look at the SevenZipSfx soruce you'll see it simply prepends one of those files taken from the assembly resources to the .7z archive.


问:
What is the better way to create React components when there's a View and Edit functionalities?
I have a use case where I need Edit and View functionality of a Content. Let's take user and admin where user can just view the information and admin can edit the fields (mostly dropdown and text) to show to the user. I have a MainComponent which calls either Edit or View based on the person logging in. View and Edit have separate APIs for my purpose. View just fetches the selected information whereas Edit fetches both the selected and the options available. For example, let's take Difficulty Level: It can be Easy, Medium or Hard. View fetches only value which was selected by Admin whereas Admin fetches all the available options for him(Easy, Medium and Hard) and his previously selected value.

The real situation I have is much more complex with 5-10 API calls (with 10 Dropdowns) in Edit Page whereas View has only 10 Dropdowns and a single API call and its selected values by admin.

I want to know whether my way of splitting component is correct.

Another approach I had in my mind is not to have 2 separate components for View and Edit respectively and have a common Component and use if else case to show either view or edit fields and do API calls based on selection(Edit or View). But I don't have a clear idea on this type of implementation.

The downside of my approach is, if I want to add a new field, I need to do it in 2 places, both Edit and View but good thing here is, Edit looks cleaner and my concern is Edit itself is bulky now and having a common one will make it even more bulkier and unwanted things might load for View(I think).

The downside of my another approach is if in future I want a field, I have to add it both in View and Edit Components.

I am new to react and I want to know which way is better or is there an even better approach. Any suggestion on this would be helpful.

PS: Due to confidentiality reasons, I cannot post the code here.

答:
As I understand, your two components are too different to be the same with some if cases to tweak it around depending if it is a user or an admin connected.

What I would recommend is to have a single higher order component rendering two different dummy component for each type of viewer.

That way, if there are some logic or data that are specific to a single entity, you can just pass it to single dummy component or both if it's generic data.

Your dummy components can also inherit from another components such as you can have: HOComp => GenericDummyComp => SpecificComp

Like that if you want to add a new field, you just have to add it in the Generic component and it will be rendered in both generic and specific components.


问:
Filtering some data from Spark dataframe based on CSV records
I have a CSV file containing some words. Total no. of words in csv file won't exceed 50k records.

I have a Spark Dataframe created from a JSON file having keywords column. What I need to do is filter out the records from dataframe whose keywords column value matches with the value present in CSV file. Here, Matches means if the word in csv file appears in dataframe column.

Taking an example, let's say there is a word "baby toys" in csv file and spark dataframe looks like this

```<code>***Keywords***
new baby toys
baby toys for all
costly baby toys price
baby has toys
</code>```

In the above first 3 rows should be filtered out as all having the word baby toys in sequence.

To implement, I am doing something like this.

```<code>1. Reading csv file and creating a dataframe.

2. Collecting all the words as an array of strings from dataframe created above as
val negativeKeywords = csvDF.distinct.map(x => x.getString(0)).collect()

3. Creating a UDF to match the words - one from negative list created above and other from Spark dataframe(created in step 4)
 val udfmatch= udf((x: String) => {
      val loop = new Breaks
      var check = false
      loop.breakable{
        for(s <- negativeKeywords){
          if(x.contains(s)){
            check = true
            loop.break
          }
        }
      }
      check
  })

4. Created spark dataframe from JSON file.
5. Filter from the above JSON dataframe using UDF defined above.
   sparkDf.filter(udfmatch(col("keyword_text")))
</code>```

In the above, I am iterating over the entire csv words list(until I find it) for every keyword present in Spark dataframe, which i think is not right and time consuming.
Can someone please suggest a better way.

答:
Let's start with a Seq of keywords that are coming from csv; we can use fold left and use contains like below code:

```<code>val conds= seq(("new toys")).toList
val result = conds.foldLeft(yourJsonDf){(newdf,conds)=>
 newdf.filter(!col("yourJsonColumnToFitlerOn").contains(conds))}
</code>```

This will get you the rows that do not match  your list.  if you want to have those filtered rows only.  you can simply join on your "yourJsonColumntoFilteron" back to your original DF and use leftanti join
something like below code

```<code>val filteredResults = originalDf.join(result ,Seq("yourJsonColumnToFilterOn"),"leftanti")
filteredResults.show()
</code>```

Per you question of returning null DF is due to the nature of spark processing of foldLeft.  it does not break the loop over the iteration of items in your list. or Simply put foldleft does not get executed N times based on elements in your List. the execution is only 1 time which saves you a lot of time and resources and does not have to worry on GC cleanup.   hope the above changes in the Answer meets your request.
Cheers,

Body:
I have a CSV file containing some words. Total no. of words in csv file won't exceed 50k records.

I have a Spark Dataframe created from a JSON file having keywords column. What I need to do is filter out the records from dataframe whose keywords column value matches with the value present in CSV file. Here, Matches means if the word in csv file appears in dataframe column.

Taking an example, let's say there is a word "baby toys" in csv file and spark dataframe looks like this

***Keywords***
new baby toys
baby toys for all
costly baby toys price
baby has toys

In the above first 3 rows should be filtered out as all having the word baby toys in sequence.

To implement, I am doing something like this.

1. Reading csv file and creating a dataframe.

2. Collecting all the words as an array of strings from dataframe created above as
val negativeKeywords = csvDF.distinct.map(x => x.getString(0)).collect()

3. Creating a UDF to match the words - one from negative list created above and other from Spark dataframe(created in step 4)
 val udfmatch= udf((x: String) => {
      val loop = new Breaks
      var check = false
      loop.breakable{
        for(s <- negativeKeywords){
          if(x.contains(s)){
            check = true
            loop.break
          }
        }
      }
      check
  })

4. Created spark dataframe from JSON file.
5. Filter from the above JSON dataframe using UDF defined above.
   sparkDf.filter(udfmatch(col("keyword_text")))

In the above, I am iterating over the entire csv words list(until I find it) for every keyword present in Spark dataframe, which i think is not right and time consuming.
Can someone please suggest a better way.

Body:
Let's start with a Seq of keywords that are coming from csv; we can use fold left and use contains like below code:

val conds= seq(("new toys")).toList
val result = conds.foldLeft(yourJsonDf){(newdf,conds)=>
 newdf.filter(!col("yourJsonColumnToFitlerOn").contains(conds))}

This will get you the rows that do not match  your list.  if you want to have those filtered rows only.  you can simply join on your "yourJsonColumntoFilteron" back to your original DF and use leftanti join
something like below code

val filteredResults = originalDf.join(result ,Seq("yourJsonColumnToFilterOn"),"leftanti")
filteredResults.show()

Per you question of returning null DF is due to the nature of spark processing of foldLeft.  it does not break the loop over the iteration of items in your list. or Simply put foldleft does not get executed N times based on elements in your List. the execution is only 1 time which saves you a lot of time and resources and does not have to worry on GC cleanup.   hope the above changes in the Answer meets your request.
Cheers,


问:
Set a custom identity value on a auto increment field
I have in my DB (Sql server 2008) a id column with auto numeric set on.
I'm using EF and linq2entities

In some specific scenario I would like to be able to set a custom Id number (obviously I'm totally sure this value is not repeated), for example I would use it to "fill" missing Id numbers caused by deletions.  I want to keep the auto increment prop in database, the problem is that when I do the linq sentence, the database assign the next Id number, not the one that I like.

Maybe it's a little weird but is it possible to do using linq2entities ?

Thanks in advance!

答:
I don't like to say flat-out that it's impossible, but this is pretty inside baseball for L2E. But it's a pretty simple INSERT trigger. You'll get the inserted row via INSERTED (Google will explain), and then you update that row with whatever crazy logic you want.

I think you can bang your head against L2E for hours trying to figure it out, or do it inside of twenty minutes with a trigger.


问:
Unable to get SBT to download itself from behind Artifactory Pro corporate proxy
I've configured my local repositories file ~/.sbt/repositories as follows:

```<code>[repositories]
local
my-ivy-proxy-releases: http://ourinternalartifactoryaddress.com/artifactory/scala-ivy/, [organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext]
my-maven-proxy-releases: http://ourinternalartifactoryaddress.com/artifactory/mvn-all
</code>```

Resolution from the mvn-all virtual repo seems to work well - this is proxying maven-central as well as a number of internal standard maven repos.  Resolution from scala-ivy (a virtual repo) works well for the sbt-plugins remote repo, but it is not working for resolving things like SBT itself.

The Setup

scala-ivy - virtual repo (package type Ivy) proxying 3 remote repositories:

maven-central-mirror - (http://central.maven.org/maven2
)`, this is where sbt should be downloading itself from, package type 'Maven'

typesafe-ivy-releases - the jcenter repo ( https://dl.bintray.com/typesafe/ivy-releases/
) that houses sbt versions before the 1.x line and a number of Scala artifacts, package type 'Ivy'

scala-sbt - (https://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/
), package type 'SBT'

Question is - what's wrong with this setup/what am I missing on boot?

答:
I'm not sure if this ended up being a transient issue, but was surprised this morning to see SBT downloading itself from our mvn-all virtual repo in Artifactory when historically SBT was in an Ivy repo.

I'm happy to bump up an answer from one of the maintainers on where artifacts live today to help other people setting up.

Body:
I've configured my local repositories file ~/.sbt/repositories as follows:

[repositories]
local
my-ivy-proxy-releases: http://ourinternalartifactoryaddress.com/artifactory/scala-ivy/, [organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext]
my-maven-proxy-releases: http://ourinternalartifactoryaddress.com/artifactory/mvn-all

Resolution from the mvn-all virtual repo seems to work well - this is proxying maven-central as well as a number of internal standard maven repos.  Resolution from scala-ivy (a virtual repo) works well for the sbt-plugins remote repo, but it is not working for resolving things like SBT itself.

The Setup

scala-ivy - virtual repo (package type Ivy) proxying 3 remote repositories:

maven-central-mirror - (http://central.maven.org/maven2
)`, this is where sbt should be downloading itself from, package type 'Maven'

typesafe-ivy-releases - the jcenter repo ( https://dl.bintray.com/typesafe/ivy-releases/
) that houses sbt versions before the 1.x line and a number of Scala artifacts, package type 'Ivy'

scala-sbt - (https://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/
), package type 'SBT'

Question is - what's wrong with this setup/what am I missing on boot?


问:
View not re-rendering after onPress
I'm trying to change the backgroundColor of a React Native Card component when onPress event is triggered. Although I'm seeing the change of the state on componentDidUpdate, I'm not visualising it.

I'm changing the value of the itemsPressed array when the onPress event is triggered. If the pressed item id is already in the array it removes it else it adds it into the array.

```<code>export default class Popular extends Component {

 constructor(props) {
    super(props);
    this.togglePressed = this.togglePressed.bind(this);

    this.state = {
     categories: [],
     itemsPressed: []
   }
 }

 togglePressed = item => {
    const id = item.id;
    this.setState(({ itemsPressed }) => ({
      itemsPressed: this.isItemPressed(item)
      ? itemsPressed.filter(a => a != id)
      : [...itemsPressed, id],
    }))
 };

 isItemPressed = item => {
  const id = item.id;
  return this.state.itemsPressed.includes(id);
 };

 componentDidMount() {
   this.setState({
     categories:this.props.categories,
   });
 }

 componentDidUpdate(){
  console.log(this.state.itemsPressed);
 }

 renderTabItem = ({ item,index }) => (
  <TouchableOpacity
   style={styles.category}
   key={index}
   onPress={() => this.togglePressed(item)}
  >
   <Card center
    style={[styles.card,{backgroundColor:
          this.isItemPressed(item)
          ? item.color
          : 'gray'
     }]}>
     <Image source={item.icon} style={styles.categoryIcon}/>
   </Card>
   <Text size={12} center style={styles.categoryName}
     medium color='black'
    >
    {item.name.toLowerCase()}
   </Text>
 </TouchableOpacity>
 );

renderTab(){
  const {categories} = this.state;
  return (
    <FlatList
    horizontal = {true}
    pagingEnabled = {true}
    scrollEnabled = {true}
    showsHorizontalScrollIndicator={false}
    scrollEventThrottle={16}
    snapToAlignment='center'
    data={categories}
    keyExtractor={(item) => `${item.id}`}
    renderItem={this.renderTabItem}
   />
 )
}
  render() {
    return (
       <ScrollView>
        {this.renderTab()}
       </ScrollView>
   );
  }
 }
</code>```

I expected a visual change but I couldn't re render the renderTab().

Thank you!

答:
Your FlatList has the property category as data source, so it only re-renders the cells if it detects a change in the category property. Your code however is only changing itemsPressed, so no cell is re-rendered.

You can tell the FlatList to listen for changes state.itemsPressed by specifying it in the extraData property:

```<code>extraData={this.state.itemsPressed}
</code>```

Title: View not re-rendering after onPress

Body:
I'm trying to change the backgroundColor of a React Native Card component when onPress event is triggered. Although I'm seeing the change of the state on componentDidUpdate, I'm not visualising it.

I'm changing the value of the itemsPressed array when the onPress event is triggered. If the pressed item id is already in the array it removes it else it adds it into the array.

export default class Popular extends Component {

 constructor(props) {
    super(props);
    this.togglePressed = this.togglePressed.bind(this);

    this.state = {
     categories: [],
     itemsPressed: []
   }
 }

 togglePressed = item => {
    const id = item.id;
    this.setState(({ itemsPressed }) => ({
      itemsPressed: this.isItemPressed(item)
      ? itemsPressed.filter(a => a != id)
      : [...itemsPressed, id],
    }))
 };

 isItemPressed = item => {
  const id = item.id;
  return this.state.itemsPressed.includes(id);
 };

 componentDidMount() {
   this.setState({
     categories:this.props.categories,
   });
 }

 componentDidUpdate(){
  console.log(this.state.itemsPressed);
 }

 renderTabItem = ({ item,index }) => (
  <TouchableOpacity
   style={styles.category}
   key={index}
   onPress={() => this.togglePressed(item)}
  >
   <Card center
    style={[styles.card,{backgroundColor:
          this.isItemPressed(item)
          ? item.color
          : 'gray'
     }]}>
     <Image source={item.icon} style={styles.categoryIcon}/>
   </Card>
   <Text size={12} center style={styles.categoryName}
     medium color='black'
    >
    {item.name.toLowerCase()}
   </Text>
 </TouchableOpacity>
 );

renderTab(){
  const {categories} = this.state;
  return (
    <FlatList
    horizontal = {true}
    pagingEnabled = {true}
    scrollEnabled = {true}
    showsHorizontalScrollIndicator={false}
    scrollEventThrottle={16}
    snapToAlignment='center'
    data={categories}
    keyExtractor={(item) => `${item.id}`}
    renderItem={this.renderTabItem}
   />
 )
}
  render() {
    return (
       <ScrollView>
        {this.renderTab()}
       </ScrollView>
   );
  }
 }

I expected a visual change but I couldn't re render the renderTab().

Thank you!

Body:
Your FlatList has the property category as data source, so it only re-renders the cells if it detects a change in the category property. Your code however is only changing itemsPressed, so no cell is re-rendered.

You can tell the FlatList to listen for changes state.itemsPressed by specifying it in the extraData property:

extraData={this.state.itemsPressed}


问:
Why does this fail in Firefox and Chrome?
This is a common piece of JavaScript used to show a customer splash screen in Silverlight:

```<code>function onSourceDownloadProgressChanged(sender, eventArgs) {
            var myHost = document.getElementById("Xaml1");
            var rectBar = myHost.content.findName("rectBar");
            var rectBorder = myHost.content.findName("rectBorder");
            if (eventArgs.progress)
                rectBar.Width = eventArgs.progress * rectBorder.Width;
            else
                rectBar.Width = eventArgs.get_progress() * rectBorder.Width;
        }
</code>```

For some reason, Firefox and Chrome get errors on this line:

```<code>var rectBar = myHost.content.findName("rectBar");
</code>```

They complain that "myHost is null".

This works fine in Internet Explorer, but in Firefox and Chrome the progress bar is never updated because of this error.

The key portion it is traversing looks like this:

```<code><div id="silverlightControlHost">
        <object id="xaml1" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
          <param name="source" value="ClientBin/MyApp.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="4.0.50826.0" />
          <param name="autoUpgrade" value="true" />
          <param name="splashscreensource" value="ClientBin/SplashScreen.xaml" />
          <param name="onSourceDownloadProgressChanged" value="onSourceDownloadProgressChanged" />
          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
              <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
          </a>
        </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
</code>```

答: because the other browsers are case-sensitive. "Xaml1" != "xaml1"</p>

Body:
This is a common piece of JavaScript used to show a customer splash screen in Silverlight:

function onSourceDownloadProgressChanged(sender, eventArgs) {
            var myHost = document.getElementById("Xaml1");
            var rectBar = myHost.content.findName("rectBar");
            var rectBorder = myHost.content.findName("rectBorder");
            if (eventArgs.progress)
                rectBar.Width = eventArgs.progress * rectBorder.Width;
            else
                rectBar.Width = eventArgs.get_progress() * rectBorder.Width;
        }

For some reason, Firefox and Chrome get errors on this line:

var rectBar = myHost.content.findName("rectBar");

They complain that "myHost is null".

This works fine in Internet Explorer, but in Firefox and Chrome the progress bar is never updated because of this error.

The key portion it is traversing looks like this:

        <object id="xaml1" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
          <param name="source" value="ClientBin/MyApp.xap"/>
          <param name="onError" value="onSilverlightError" />
          <param name="background" value="white" />
          <param name="minRuntimeVersion" value="4.0.50826.0" />
          <param name="autoUpgrade" value="true" />
          <param name="splashscreensource" value="ClientBin/SplashScreen.xaml" />
          <param name="onSourceDownloadProgressChanged" value="onSourceDownloadProgressChanged" />

        </object>


问:
Programmatically change sorting order in Perl
I'd like to give the user the possibility to change the sorting order (asc / desc) in a data structure. As far as I know, this is done changing the order of $a and $bin the code, but I'd like to programmatically change this to avoid redundant code.

I made a working example:

use 5.018;
use warnings;

# Supply any argument to change sorting order
my $sorting_direction = $ARGV[0];

my $data = {
          'item1' => {
                         'min'  => 4,
                         'size' => 825,
                         'max'  => 256,
                       },
          'item2' => {
                         'min'  => 4,
                         'size' => 130,
                         'max'  => 65,
                       },
        };

if (defined $sorting_direction) {
    foreach my $item (sort { $$data{$a}{'size'} <=> $$data{$b}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
} else {
    foreach my $item (sort { $$data{$b}{'size'} <=> $$data{$a}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
}
```

Giving any parameter will change the sorting_direction. Can I do this without the if conditional?

答:
While it's always going to be slower because it's a full extra operation, if performance is not as much a concern as code cleanliness you could just reverse the list when the opposite sorting direction is chosen. Note that this would be slightly different in the case of sorting equal elements, as sort in Perl is normally stable (equal elements stay in the same order they originally were).</p>

```<code>my @sorted = sort { $$data{$a}{'size'} <=> $$data{$b}{'size'} } keys %{$data};
@sorted = reverse @sorted if $reverse;
</code>```

Body:
I'd like to give the user the possibility to change the sorting order (asc / desc) in a data structure. As far as I know, this is done changing the order of $a and $bin the code, but I'd like to programmatically change this to avoid redundant code.

I made a working example:

use 5.018;
use warnings;

# Supply any argument to change sorting order
my $sorting_direction = $ARGV[0];

my $data = {
          'item1' => {
                         'min'  => 4,
                         'size' => 825,
                         'max'  => 256,
                       },
          'item2' => {
                         'min'  => 4,
                         'size' => 130,
                         'max'  => 65,
                       },
        };

if (defined $sorting_direction) {
    foreach my $item (sort { $$data{$a}{'size'} <=> $$data{$b}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
} else {
    foreach my $item (sort { $$data{$b}{'size'} <=> $$data{$a}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
}

Giving any parameter will change the sorting_direction. Can I do this without the if conditional?

Body:
While it's always going to be slower because it's a full extra operation, if performance is not as much a concern as code cleanliness you could just reverse the list when the opposite sorting direction is chosen. Note that this would be slightly different in the case of sorting equal elements, as sort in Perl is normally stable (equal elements stay in the same order they originally were).

my @sorted = sort { $$data{$a}{'size'} <=> $$data{$b}{'size'} } keys %{$data};
@sorted = reverse @sorted if $reverse;


问:
Generate counts of records for each day in a week
I use SQL Server 2014 for my project. I have the following code to produce the number of registrations of each day:

```<code>SELECT
    DATEADD(DAY, DATEDIFF(DAY, 0, createTime), 0) AS createdOn,
    COUNT(*) AS Count
FROM
    Registration
GROUP BY
    DATEADD(DAY, DATEDIFF(DAY, 0, createTime), 0)
ORDER BY
    createdOn
</code>```

Now I would like to get the numbers for each day in a week (so there will be max 7 rows in output). How can I do it?

Here is the solution I have based on George's comment. Thank you, George!

```<code>SELECT
    DATEPART(weekday, createTime) AS createdOn,
    COUNT(*) AS Count
FROM
    Registration
GROUP BY
    DATEPART(weekday, createTime)
ORDER BY
    createdOn
</code>```

答:
One way to return all days within a range returned with your data joined on matching days is to use a "calendar" table and LEFT JOIN your data by date.</p>

```<code>DECLARE @StartDate DATETIME = '01/01/2015'
DECLARE @EndDate DATETIME = '12/01/2016'

//By Day In Year
;WITH Calender as
(
    SELECT CalendarDate = @StartDate
    UNION ALL
    SELECT CalendarDate = DATEADD(DAY, 1, CalendarDate)
    FROM Calender WHERE DATEADD (DAY, 1, CalendarDate) <= @EndDate
)

SELECT
    C.CalendarDate,
    COUNT(*) AS Count
FROM
    Calender C
    LEFT JOIN Regsitration R ON R.createdOn = C.CalendarDate
GROUP BY
    C.CalendarDate
OPTION (MAXRECURSION 0)

//By Week In Year

;WITH Calender as
(
    SELECT CalendarDate = @StartDate, WeekNumber=DATEPART(WEEK, @StartDate)
    UNION ALL
    SELECT CalendarDate = DATEADD(WEEK, 1, CalendarDate), WeekNumber=DATEPART(WEEK, @StartDate)
    FROM Calender WHERE DATEADD (WEEK, 1, CalendarDate) <= @EndDate
)

SELECT
    C.WeekNumber,
    COUNT(*) AS Count
FROM
    Calender C
    LEFT JOIN Regsitration R ON DATEPART(WEEK,R.createdOn) = C.WeekNumber
GROUP BY
    C.WeekNumber
OPTION (MAXRECURSION 0)
</code>```

Body:
I use SQL Server 2014 for my project. I have the following code to produce the number of registrations of each day:

SELECT
    DATEADD(DAY, DATEDIFF(DAY, 0, createTime), 0) AS createdOn,
    COUNT(*) AS Count
FROM
    Registration
GROUP BY
    DATEADD(DAY, DATEDIFF(DAY, 0, createTime), 0)
ORDER BY
    createdOn

Now I would like to get the numbers for each day in a week (so there will be max 7 rows in output). How can I do it?

Here is the solution I have based on George's comment. Thank you, George!

SELECT
    DATEPART(weekday, createTime) AS createdOn,
    COUNT(*) AS Count
FROM
    Registration
GROUP BY
    DATEPART(weekday, createTime)
ORDER BY
    createdOn

Body:
One way to return all days within a range returned with your data joined on matching days is to use a "calendar" table and LEFT JOIN your data by date.

DECLARE @StartDate DATETIME = '01/01/2015'
DECLARE @EndDate DATETIME = '12/01/2016'

//By Day In Year
;WITH Calender as
(
    SELECT CalendarDate = @StartDate
    UNION ALL
    SELECT CalendarDate = DATEADD(DAY, 1, CalendarDate)
    FROM Calender WHERE DATEADD (DAY, 1, CalendarDate) <= @EndDate
)

SELECT
    C.CalendarDate,
    COUNT(*) AS Count
FROM
    Calender C
    LEFT JOIN Regsitration R ON R.createdOn = C.CalendarDate
GROUP BY
    C.CalendarDate
OPTION (MAXRECURSION 0)

//By Week In Year

;WITH Calender as
(
    SELECT CalendarDate = @StartDate, WeekNumber=DATEPART(WEEK, @StartDate)
    UNION ALL
    SELECT CalendarDate = DATEADD(WEEK, 1, CalendarDate), WeekNumber=DATEPART(WEEK, @StartDate)
    FROM Calender WHERE DATEADD (WEEK, 1, CalendarDate) <= @EndDate
)

SELECT
    C.WeekNumber,
    COUNT(*) AS Count
FROM
    Calender C
    LEFT JOIN Regsitration R ON DATEPART(WEEK,R.createdOn) = C.WeekNumber
GROUP BY
    C.WeekNumber
OPTION (MAXRECURSION 0)


问:
How to wait for a single event in C#, with timeout and cancellation
So my requirement is to have my function wait for the first instance an event Action<T> coming from another class and another thread, and handle it on my thread, allowing the wait to be interrupted by either timeout or CancellationToken.

I want to create a generic function I can reuse.  I managed to create a couple options that do (I think) what I need, but both seem more complicated than I'd imagine it should have to be.

Usage

Just to be clear, a sample use of this function would look like this, where serialDevice is spitting out events on a separate thread:

```<code>var eventOccurred = Helper.WaitForSingleEvent<StatusPacket>(
    cancellationToken,
    statusPacket => OnStatusPacketReceived(statusPacket),
    a => serialDevice.StatusPacketReceived += a,
    a => serialDevice.StatusPacketReceived -= a,
    5000,
    () => serialDevice.RequestStatusPacket());
</code>```

Option 1—ManualResetEventSlim

This option isn't bad, but the Dispose handling of the ManualResetEventSlim is messier than it seems like it should be.  It gives ReSharper fits that I'm accessing modified/disposed things within the closure, and it's genuinely hard to follow so I'm not even sure it's correct.  Maybe there's something I'm missing that can clean this up, which would be my preference, but I don't see it offhand.  Here's the code.

```<code>public static bool WaitForSingleEvent<TEvent>(this CancellationToken token, Action<TEvent> handler, Action<Action<TEvent>> subscribe, Action<Action<TEvent>> unsubscribe, int msTimeout, Action initializer = null)
{
    var eventOccurred = false;
    var eventResult = default(TEvent);
    var o = new object();
    var slim = new ManualResetEventSlim();
    Action<TEvent> setResult = result =>
    {
        lock (o) // ensures we get the first event only
        {
            if (!eventOccurred)
            {
                eventResult = result;
                eventOccurred = true;
                // ReSharper disable AccessToModifiedClosure
                // ReSharper disable AccessToDisposedClosure
                if (slim != null)
                {
                    slim.Set();
                }
                // ReSharper restore AccessToDisposedClosure
                // ReSharper restore AccessToModifiedClosure
            }
        }
    };
    subscribe(setResult);
    try
    {
        if (initializer != null)
        {
            initializer();
        }
        slim.Wait(msTimeout, token);
    }
    finally // ensures unsubscription in case of exception
    {
        unsubscribe(setResult);
        lock(o) // ensure we don't access slim
        {
            slim.Dispose();
            slim = null;
        }
    }
    lock (o) // ensures our variables don't get changed in middle of things
    {
        if (eventOccurred)
        {
            handler(eventResult);
        }
        return eventOccurred;
    }
}
</code>```

Option 2—polling without a WaitHandle

The WaitForSingleEvent function here is much cleaner.  I'm able to use ConcurrentQueue and thus don't even need a lock.  But I just don't like the polling function Sleep, and I don't see any way around it with this approach.  I'd like to pass in a WaitHandle instead of a Func<bool> to clean up Sleep, but the second I do that I've got the whole Dispose mess to clean up again.

```<code>public static bool WaitForSingleEvent<TEvent>(this CancellationToken token, Action<TEvent> handler, Action<Action<TEvent>> subscribe, Action<Action<TEvent>> unsubscribe, int msTimeout, Action initializer = null)
{
    var q = new ConcurrentQueue<TEvent>();
    subscribe(q.Enqueue);
    try
    {
        if (initializer != null)
        {
            initializer();
        }
        token.Sleep(msTimeout, () => !q.IsEmpty);
    }
    finally // ensures unsubscription in case of exception
    {
        unsubscribe(q.Enqueue);
    }
    TEvent eventResult;
    var eventOccurred = q.TryDequeue(out eventResult);
    if (eventOccurred)
    {
        handler(eventResult);
    }
    return eventOccurred;
}

public static void Sleep(this CancellationToken token, int ms, Func<bool> exitCondition)
{
    var start = DateTime.Now;
    while ((DateTime.Now - start).TotalMilliseconds < ms && !exitCondition())
    {
        token.ThrowIfCancellationRequested();
        Thread.Sleep(1);
    }
}
</code>```

The question

I don't particularly care for either of these solutions, nor am I 100% sure either of them are 100% correct.  Is either one of these solutions better than the other (idiomaticity, efficiency, etc), or is there an easier way or built-in function to meet what I need to do here?

Update: Best answer so far

A modification of the TaskCompletionSource solution below.  No long closures, locks, or anything required.  Seems pretty straightforward.  Any errors here?

```<code>public static bool WaitForSingleEvent<TEvent>(this CancellationToken token, Action<TEvent> onEvent, Action<Action<TEvent>> subscribe, Action<Action<TEvent>> unsubscribe, int msTimeout, Action initializer = null)
{
    var tcs = new TaskCompletionSource<TEvent>();
    Action<TEvent> handler = result => tcs.TrySetResult(result);
    var task = tcs.Task;
    subscribe(handler);
    try
    {
        if (initializer != null)
        {
            initializer();
        }
        task.Wait(msTimeout, token);
    }
    finally
    {
        unsubscribe(handler);
        // Do not dispose task http://blogs.msdn.com/b/pfxteam/archive/2012/03/25/10287435.aspx
    }
    if (task.Status == TaskStatus.RanToCompletion)
    {
        onEvent(task.Result);
        return true;
    }
    return false;
}
</code>```

Update 2: Another great solution

Turns out that BlockingCollection works just like ConcurrentQueue but also has methods accepting a timeout and cancellation token.  One nice thing about this solution is that it can be updated to make a WaitForNEvents fairly easily:

```<code>public static bool WaitForSingleEvent<TEvent>(this CancellationToken token, Action<TEvent> handler, Action<Action<TEvent>> subscribe, Action<Action<TEvent>> unsubscribe, int msTimeout, Action initializer = null)
{
    var q = new BlockingCollection<TEvent>();
    Action<TEvent> add = item => q.TryAdd(item);
    subscribe(add);
    try
    {
        if (initializer != null)
        {
            initializer();
        }
        TEvent eventResult;
        if (q.TryTake(out eventResult, msTimeout, token))
        {
            handler(eventResult);
            return true;
        }
        return false;
    }
    finally
    {
        unsubscribe(add);
        q.Dispose();
    }
}
</code>```

答:
Why not just use
ManualResetEventSlim.Wait (int millisecondsTimeout, CancellationToken cancellationToken)
?

Body:
So my requirement is to have my function wait for the first instance an event Action<T> coming from another class and another thread, and handle it on my thread, allowing the wait to be interrupted by either timeout or CancellationToken.

I want to create a generic function I can reuse.  I managed to create a couple options that do (I think) what I need, but both seem more complicated than I'd imagine it should have to be.

Usage

Just to be clear, a sample use of this function would look like this, where serialDevice is spitting out events on a separate thread:

var eventOccurred = Helper.WaitForSingleEvent<StatusPacket>(
    cancellationToken,
    statusPacket => OnStatusPacketReceived(statusPacket),
    a => serialDevice.StatusPacketReceived += a,
    a => serialDevice.StatusPacketReceived -= a,
    5000,
    () => serialDevice.RequestStatusPacket());

Option 1—ManualResetEventSlim

This option isn't bad, but the Dispose handling of the ManualResetEventSlim is messier than it seems like it should be.  It gives ReSharper fits that I'm accessing modified/disposed things within the closure, and it's genuinely hard to follow so I'm not even sure it's correct.  Maybe there's something I'm missing that can clean this up, which would be my preference, but I don't see it offhand.  Here's the code.

public static bool WaitForSingleEvent<TEvent>(this CancellationToken token, Action<TEvent> handler, Action<Action<TEvent>> subscribe, Action<Action<TEvent>> unsubscribe, int msTimeout, Action initializer = null)
{
    var eventOccurred = false;
    var eventResult = default(TEvent);
    var o = new object();
    var slim = new ManualResetEventSlim();
    Action<TEvent> setResult = result =>
    {
        lock (o) // ensures we get the first event only
        {
            if (!eventOccurred)
            {
                eventResult = result;
                eventOccurred = true;
                // ReSharper disable AccessToModifiedClosure
                // ReSharper disable AccessToDisposedClosure
                if (slim != null)
                {
                    slim.Set();
                }
                // ReSharper restore AccessToDisposedClosure
                // ReSharper restore AccessToModifiedClosure
            }
        }
    };
    subscribe(setResult);
    try
    {
        if (initializer != null)
        {
            initializer();
        }
        slim.Wait(msTimeout, token);
    }
    finally // ensures unsubscription in case of exception
    {
        unsubscribe(setResult);
        lock(o) // ensure we don't access slim
        {
            slim.Dispose();
            slim = null;
        }
    }
    lock (o) // ensures our variables don't get changed in middle of things
    {
        if (eventOccurred)
        {
            handler(eventResult);
        }
        return eventOccurred;
    }
}

Option 2—polling without a WaitHandle

The WaitForSingleEvent function here is much cleaner.  I'm able to use ConcurrentQueue and thus don't even need a lock.  But I just don't like the polling function Sleep, and I don't see any way around it with this approach.  I'd like to pass in a WaitHandle instead of a Func<bool> to clean up Sleep, but the second I do that I've got the whole Dispose mess to clean up again.

public static bool WaitForSingleEvent<TEvent>(this CancellationToken token, Action<TEvent> handler, Action<Action<TEvent>> subscribe, Action<Action<TEvent>> unsubscribe, int msTimeout, Action initializer = null)
{
    var q = new ConcurrentQueue<TEvent>();
    subscribe(q.Enqueue);
    try
    {
        if (initializer != null)
        {
            initializer();
        }
        token.Sleep(msTimeout, () => !q.IsEmpty);
    }
    finally // ensures unsubscription in case of exception
    {
        unsubscribe(q.Enqueue);
    }
    TEvent eventResult;
    var eventOccurred = q.TryDequeue(out eventResult);
    if (eventOccurred)
    {
        handler(eventResult);
    }
    return eventOccurred;
}

public static void Sleep(this CancellationToken token, int ms, Func<bool> exitCondition)
{
    var start = DateTime.Now;
    while ((DateTime.Now - start).TotalMilliseconds < ms && !exitCondition())
    {
        token.ThrowIfCancellationRequested();
        Thread.Sleep(1);
    }
}

The question

I don't particularly care for either of these solutions, nor am I 100% sure either of them are 100% correct.  Is either one of these solutions better than the other (idiomaticity, efficiency, etc), or is there an easier way or built-in function to meet what I need to do here?

Update: Best answer so far

A modification of the TaskCompletionSource solution below.  No long closures, locks, or anything required.  Seems pretty straightforward.  Any errors here?

public static bool WaitForSingleEvent<TEvent>(this CancellationToken token, Action<TEvent> onEvent, Action<Action<TEvent>> subscribe, Action<Action<TEvent>> unsubscribe, int msTimeout, Action initializer = null)
{
    var tcs = new TaskCompletionSource<TEvent>();
    Action<TEvent> handler = result => tcs.TrySetResult(result);
    var task = tcs.Task;
    subscribe(handler);
    try
    {
        if (initializer != null)
        {
            initializer();
        }
        task.Wait(msTimeout, token);
    }
    finally
    {
        unsubscribe(handler);
        // Do not dispose task http://blogs.msdn.com/b/pfxteam/archive/2012/03/25/10287435.aspx
    }
    if (task.Status == TaskStatus.RanToCompletion)
    {
        onEvent(task.Result);
        return true;
    }
    return false;
}

Update 2: Another great solution

Turns out that BlockingCollection works just like ConcurrentQueue but also has methods accepting a timeout and cancellation token.  One nice thing about this solution is that it can be updated to make a WaitForNEvents fairly easily:

public static bool WaitForSingleEvent<TEvent>(this CancellationToken token, Action<TEvent> handler, Action<Action<TEvent>> subscribe, Action<Action<TEvent>> unsubscribe, int msTimeout, Action initializer = null)
{
    var q = new BlockingCollection<TEvent>();
    Action<TEvent> add = item => q.TryAdd(item);
    subscribe(add);
    try
    {
        if (initializer != null)
        {
            initializer();
        }
        TEvent eventResult;
        if (q.TryTake(out eventResult, msTimeout, token))
        {
            handler(eventResult);
            return true;
        }
        return false;
    }
    finally
    {
        unsubscribe(add);
        q.Dispose();
    }
}


问:
Entity framework core relationship collection is empty
I did do a database first approach, and I did make my database. I use relationship and I have two tables:

```<code>users
-------------
id PK int(11)
username UNIQUE varchar(20)

rooms
-------------
id PK int(11)
name VARCHAR(30) NOT NULL
owner_id INDEX int(11) -> FK to users.id
</code>```

When I do a scaffold, the models look a little like this:

User.cs:

```<code>public User()
{
    Rooms = new HashSet<Room>();
}

public int Id { get; set; }
public string Username { get; set; }
public virtual ICollection<Room> Rooms { get; set; }
</code>```

Room.cs:

```<code>public int Id { get; set; }
public string Name { get; set; }
public int? OwnerId { get; set; }

public virtual User Owner { get; set; }
</code>```

(the OwnerId is nullable since system rooms don't have an assigned owner)

The problem is, if I have my user object obtained when logging in, and I view user.Rooms, the collection is always empty, even though the database has an entry.

I know include fixes this, but that makes me have to load ALL rooms from the database, which is a terrible idea when there's like 1000+ rooms being loaded on start of the program.

Why is the collection always empty even though the relationships are setup correctly?

答:
Setting up relationsips are different from loading related entities on memory.
There are 4 different loading mechanisms you can choose according to your needs.

Eager(Include and ThenInclude)

Explicit

Lazy Loading(EF Core 2.1)

Select Loading

You can use select loading to filter which related entites must be loaded. So you do not need to load all related entitites.

Body:
I did do a database first approach, and I did make my database. I use relationship and I have two tables:

users
-------------
id PK int(11)
username UNIQUE varchar(20)

rooms
-------------
id PK int(11)
name VARCHAR(30) NOT NULL
owner_id INDEX int(11) -> FK to users.id

When I do a scaffold, the models look a little like this:

User.cs:

public User()
{
    Rooms = new HashSet<Room>();
}

public int Id { get; set; }
public string Username { get; set; }
public virtual ICollection<Room> Rooms { get; set; }

Room.cs:

public int Id { get; set; }
public string Name { get; set; }
public int? OwnerId { get; set; }

public virtual User Owner { get; set; }

(the OwnerId is nullable since system rooms don't have an assigned owner)

The problem is, if I have my user object obtained when logging in, and I view user.Rooms, the collection is always empty, even though the database has an entry.

I know include fixes this, but that makes me have to load ALL rooms from the database, which is a terrible idea when there's like 1000+ rooms being loaded on start of the program.

Why is the collection always empty even though the relationships are setup correctly?


问:
Why does not SetByteArrayRegion corrupt memory?
The SetByteArrayRegion function is implemented as

```<code>JNI_ENTRY(void, \
jni_Set##Result##ArrayRegion(JNIEnv *env, ElementType##Array array, jsize start, \
             jsize len, const ElementType *buf)) \
  JNIWrapper("Set" XSTR(Result) "ArrayRegion"); \
  DTRACE_PROBE5(hotspot_jni, Set##Result##ArrayRegion__entry, env, array, start, len, buf);\
  DT_VOID_RETURN_MARK(Set##Result##ArrayRegion); \
  typeArrayOop dst = typeArrayOop(JNIHandles::resolve_non_null(array)); \
  if (start < 0 || len < 0 || ((unsigned int)start + (unsigned int)len > (unsigned int)dst->length())) { \
    THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); \
  } else { \
    if (len > 0) { \
      int sc = TypeArrayKlass::cast(dst->klass())->log2_element_size(); \
      memcpy((u_char*) dst->Tag##_at_addr(start), \
             (u_char*) buf, \
             len << sc);    \
    } \
  } \
JNI_END
</code>```

As can be observed it calls memcpy on a native pointer to the java heap array: dst->Tag##_at_addr(start). memcpy itself is not atomic so I concluded that nothing stops GC from moving the array in the middle of memcpy call.

Moreover the array can be moved somwhere right after the dst->Tag##_at_addr(start) again causing memory corruption.

By contract, "critical" methods employ the GC_locker::lock_critical(thread);.

So why are SetArrayRegion methods safe? What did I miss?

答:
As you can see, the function is wrapped in JNI_ENTRY macro, which in turn performs ThreadInVMfromNative state transition. This means, a Java thread executing SetByteArrayRegion is guaranteed to be in _thread_in_vm state.

Non-concurrent compacting collectors can move objects only at the global safepoint. A safepoint implies that all Java thread are either blocked or running native code (_thread_in_native state).

So, if a safepoint is requested while SetByteArrayRegion is running, JVM will wait until all threads complete current VM operation. Сontrariwise, if SetByteArrayRegion is executed while GC is running, the thread will block at state transition until GC completes.

Body:
The SetByteArrayRegion function is implemented as

JNI_ENTRY(void, \
jni_Set##Result##ArrayRegion(JNIEnv *env, ElementType##Array array, jsize start, \
             jsize len, const ElementType *buf)) \
  JNIWrapper("Set" XSTR(Result) "ArrayRegion"); \
  DTRACE_PROBE5(hotspot_jni, Set##Result##ArrayRegion__entry, env, array, start, len, buf);\
  DT_VOID_RETURN_MARK(Set##Result##ArrayRegion); \
  typeArrayOop dst = typeArrayOop(JNIHandles::resolve_non_null(array)); \
  if (start < 0 || len < 0 || ((unsigned int)start + (unsigned int)len > (unsigned int)dst->length())) { \
    THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); \
  } else { \
    if (len > 0) { \
      int sc = TypeArrayKlass::cast(dst->klass())->log2_element_size(); \
      memcpy((u_char*) dst->Tag##_at_addr(start), \
             (u_char*) buf, \
             len << sc);    \
    } \
  } \
JNI_END

As can be observed it calls memcpy on a native pointer to the java heap array: dst->Tag##_at_addr(start). memcpy itself is not atomic so I concluded that nothing stops GC from moving the array in the middle of memcpy call.

Moreover the array can be moved somwhere right after the dst->Tag##_at_addr(start) again causing memory corruption.

By contract, "critical" methods employ the GC_locker::lock_critical(thread);.

So why are SetArrayRegion methods safe? What did I miss?


问:
How to scroll to the bottom after clicking a button in shiny data tables
I have a simple Shiny app that shows me a load of pictures within a data table in shiny. I have 20,000 images and I want to delete ones I dont like. At the moment when I delete a row the app then takes me to the top of the data table which is not useful for this number of images.

As a simple solution I thought I could make sure the app returned to the image above the one I had just deleted. I imagine this would be managed by a javascript function but I don't know how to implement this. I imagine it should be placed in the section of the code below tags$script. Can someone show me how/ give me guidance on how to implement this functionality

Here is the code for my app:

server

```<code>library(shiny)
library(shinydashboard)
library(data.table)
library(DT)
server<-shinyServer(function(input, output) {
  vals<-reactiveValues(myTabData = data.table(NULL))

  vals$Data<-data.table(Endo_Endoscopist=DT$Endo_Endoscopist,
                        PatientID=DT$PatientID,
                        NBIorWLorFICE=DT$NBIorWLorFICE,
                        url=DT$url)

  output$MainBody<-renderUI({
    fluidPage(
      box(width=12,
          h3(strong("Actions on datatable with buttons"),align="center"),
          hr(),
          column(12,dataTableOutput("Main_table")),
          tags$script("$(document).on('click', '#Main_table button', function () {
                      Shiny.onInputChange('lastClickId',this.id);
                      Shiny.onInputChange('lastClick', Math.random())
  });")

      )
      )
  })

  output$Main_table<-renderDataTable({
    DT=vals$Data

    DT[["Actions"]]<-
      paste0('
             <div class="btn-group" role="group" aria-label="Basic example">
             <button type="button" class="btn btn-secondary delete" id=delete_',1:nrow(vals$Data),'>Delete</button>
             <button type="button" class="btn btn-secondary modify"id=modify_',1:nrow(vals$Data),'>Modify</button>
             </div>

             ')
    datatable(DT,
              escape=F)}
      )

  output$downloadData <- downloadHandler(
    filename = function() {
      "Main_table.csv"
    },
    content = function(file) {
      write.csv(vals$Data, file, row.names = FALSE)

      # Warning: Error in write.table: unimplemented type 'list' in 'EncodeElement'
      # write.csv(vals$Data, file, row.names = FALSE)
    }
  )

  ##Managing in row deletion
  modal_modify<-modalDialog(
    fluidPage(
      h3(strong("Row modification"),align="center"),
      hr(),
      dataTableOutput('row_modif'),
      actionButton("save_changes","Save changes"),

      tags$script(HTML("$(document).on('click', '#save_changes', function () {
                       var list_value=[]
                       for (i = 0; i < $( '.new_input' ).length; i++)
                       {
                       list_value.push($( '.new_input' )[i].value)
                       }
                       Shiny.onInputChange('newValue', list_value)
  });"))
    ),
    size="l"
      )

  observeEvent(input$lastClick,
               {
                 if (input$lastClickId%like%"delete")
                 {
                   row_to_del=as.numeric(gsub("delete_","",input$lastClickId))
                   vals$Data=vals$Data[-row_to_del]
                 }
                 else if (input$lastClickId%like%"modify")
                 {
                   showModal(modal_modify)
                 }
               }
  )

  output$row_modif<-renderDataTable({
    selected_row=as.numeric(gsub("modify_","",input$lastClickId))
    old_row=vals$Data[selected_row]
    row_change=list()
    for (i in colnames(old_row))
    {
      if (is.numeric(vals$Data[[i]]))
      {
        row_change[[i]]<-paste0('<input class="new_input" type="number" id=new_',i,'><br>')
      }
      else
        row_change[[i]]<-paste0('<input class="new_input" type="text" id=new_',i,'><br>')
    }
    row_change=as.data.table(row_change)
    setnames(row_change,colnames(old_row))
    browser()
    DT=rbind(old_row,row_change)
    rownames(DT)<-c("Current values","New values")
    DT

  },escape=F,options=list(dom='t',ordering=F),selection="none"
  )

  observeEvent(input$newValue,
               {
                 newValue=lapply(input$newValue, function(col) {
                   if (suppressWarnings(all(!is.na(as.numeric(as.character(col)))))) {
                     as.numeric(as.character(col))
                   } else {
                     col
                   }
                 })
                 DF=data.frame(lapply(newValue, function(x) t(data.frame(x))))
                 colnames(DF)=colnames(vals$Data)
                 vals$Data[as.numeric(gsub("modify_","",input$lastClickId))]<-DF

               }
  )

  })
</code>```

ui

```<code>library(shiny)
library(shinydashboard)

ui<-fluidPage(dashboardBody(uiOutput("MainBody"),
                            downloadLink("downloadData", "Download"))
)
</code>```

答:
Here is a way to delete rows without re-rendering the table. I hope this helps.

```<code>library(DT)
library(shiny)

dat <- iris[1:5, 1:2]
dat$Action <-
  paste0(
    '<button type="button" class="btn btn-secondary delete" id="delete_',
    1:nrow(dat)-1,
    '" onclick="deleteRow(this.id);">Delete</button>')
dat$rowId <- paste0("row_", 1:nrow(dat)-1)

js <- paste0(
  c(
    "function deleteRow(id){",
    "  var rowNum = id.split('_')[1];",
    "  var table = $('#mytable').find('table').DataTable();",
    "  var nrows = table.rows().count();",
    "  for(var i=0; i < nrows; ++i){",
    "    if(table.row(i).id() == 'row_' + rowNum){",
    "      table.row(i).remove().draw(false);",
    "      break;",
    "    }",
    "  }",
    "}"
  ),
  collapse = "\n"
)

ui <- fluidPage(
  tags$head(tags$script(HTML(js))),
  DTOutput("mytable")
)

server <- function(input, output){
  output[["mytable"]] <- renderDT({
    datatable(dat, escape = FALSE, selection = "none",
              options = list(
                columnDefs = list(
                  list(targets = ncol(dat), visible = FALSE)
                ),
                rowId = JS(sprintf("function(data){return data[%d];}", ncol(dat)))))
  }, server = FALSE)
}

shinyApp(ui, server)
</code>```

Or, simpler:

```<code>dat <- iris[1:5, 1:2]
dat$Action <-
  '<button type="button" class="btn btn-secondary delete">Delete</button>'

callback <- c(
  "table.on('click', 'button.delete', function(){",
  "  var tr = $(this).closest('tr');",
  "  table.row(tr[0]).remove().draw(false);",
  "});"
)

ui <- fluidPage(
  DTOutput("mytable")
)

server <- function(input, output){
  output[["mytable"]] <- renderDT({
    datatable(dat, escape = -ncol(dat)-1, selection = "none",
              callback = JS(callback))
  }, server = FALSE)
}

shinyApp(ui, server)
</code>```

Body:
I have a simple Shiny app that shows me a load of pictures within a data table in shiny. I have 20,000 images and I want to delete ones I dont like. At the moment when I delete a row the app then takes me to the top of the data table which is not useful for this number of images.

As a simple solution I thought I could make sure the app returned to the image above the one I had just deleted. I imagine this would be managed by a javascript function but I don't know how to implement this. I imagine it should be placed in the section of the code below tags$script. Can someone show me how/ give me guidance on how to implement this functionality

Here is the code for my app:

server

library(shiny)
library(shinydashboard)
library(data.table)
library(DT)
server<-shinyServer(function(input, output) {
  vals<-reactiveValues(myTabData = data.table(NULL))

  vals$Data<-data.table(Endo_Endoscopist=DT$Endo_Endoscopist,
                        PatientID=DT$PatientID,
                        NBIorWLorFICE=DT$NBIorWLorFICE,
                        url=DT$url)

  output$MainBody<-renderUI({
    fluidPage(
      box(width=12,
          h3(strong("Actions on datatable with buttons"),align="center"),
          hr(),
          column(12,dataTableOutput("Main_table")),
          tags$script("$(document).on('click', '#Main_table button', function () {
                      Shiny.onInputChange('lastClickId',this.id);
                      Shiny.onInputChange('lastClick', Math.random())
  });")

      )
      )
  })

  output$Main_table<-renderDataTable({
    DT=vals$Data

    DT[["Actions"]]<-
      paste0('

             <button type="button" class="btn btn-secondary delete" id=delete_',1:nrow(vals$Data),'>Delete</button>
             <button type="button" class="btn btn-secondary modify"id=modify_',1:nrow(vals$Data),'>Modify</button>

             ')
    datatable(DT,
              escape=F)}
      )

  output$downloadData <- downloadHandler(
    filename = function() {
      "Main_table.csv"
    },
    content = function(file) {
      write.csv(vals$Data, file, row.names = FALSE)

      # Warning: Error in write.table: unimplemented type 'list' in 'EncodeElement'
      # write.csv(vals$Data, file, row.names = FALSE)
    }
  )

  ##Managing in row deletion
  modal_modify<-modalDialog(
    fluidPage(
      h3(strong("Row modification"),align="center"),
      hr(),
      dataTableOutput('row_modif'),
      actionButton("save_changes","Save changes"),

      tags$script(HTML("$(document).on('click', '#save_changes', function () {
                       var list_value=[]
                       for (i = 0; i < $( '.new_input' ).length; i++)
                       {
                       list_value.push($( '.new_input' )[i].value)
                       }
                       Shiny.onInputChange('newValue', list_value)
  });"))
    ),
    size="l"
      )

  observeEvent(input$lastClick,
               {
                 if (input$lastClickId%like%"delete")
                 {
                   row_to_del=as.numeric(gsub("delete_","",input$lastClickId))
                   vals$Data=vals$Data[-row_to_del]
                 }
                 else if (input$lastClickId%like%"modify")
                 {
                   showModal(modal_modify)
                 }
               }
  )

  output$row_modif<-renderDataTable({
    selected_row=as.numeric(gsub("modify_","",input$lastClickId))
    old_row=vals$Data[selected_row]
    row_change=list()
    for (i in colnames(old_row))
    {
      if (is.numeric(vals$Data[[i]]))
      {
        row_change[[i]]<-paste0('<input class="new_input" type="number" id=new_',i,'>
')
      }
      else
        row_change[[i]]<-paste0('<input class="new_input" type="text" id=new_',i,'>
')
    }
    row_change=as.data.table(row_change)
    setnames(row_change,colnames(old_row))
    browser()
    DT=rbind(old_row,row_change)
    rownames(DT)<-c("Current values","New values")
    DT

  },escape=F,options=list(dom='t',ordering=F),selection="none"
  )

  observeEvent(input$newValue,
               {
                 newValue=lapply(input$newValue, function(col) {
                   if (suppressWarnings(all(!is.na(as.numeric(as.character(col)))))) {
                     as.numeric(as.character(col))
                   } else {
                     col
                   }
                 })
                 DF=data.frame(lapply(newValue, function(x) t(data.frame(x))))
                 colnames(DF)=colnames(vals$Data)
                 vals$Data[as.numeric(gsub("modify_","",input$lastClickId))]<-DF

               }
  )

  })

ui

library(shiny)
library(shinydashboard)

ui<-fluidPage(dashboardBody(uiOutput("MainBody"),
                            downloadLink("downloadData", "Download"))
)

Body:
Here is a way to delete rows without re-rendering the table. I hope this helps.

library(DT)
library(shiny)

dat <- iris[1:5, 1:2]
dat$Action <-
  paste0(
    '<button type="button" class="btn btn-secondary delete" id="delete_',
    1:nrow(dat)-1,
    '" onclick="deleteRow(this.id);">Delete</button>')
dat$rowId <- paste0("row_", 1:nrow(dat)-1)

js <- paste0(
  c(
    "function deleteRow(id){",
    "  var rowNum = id.split('_')[1];",
    "  var table = $('#mytable').find('table').DataTable();",
    "  var nrows = table.rows().count();",
    "  for(var i=0; i < nrows; ++i){",
    "    if(table.row(i).id() == 'row_' + rowNum){",
    "      table.row(i).remove().draw(false);",
    "      break;",
    "    }",
    "  }",
    "}"
  ),
  collapse = "\n"
)

ui <- fluidPage(
  tags$head(tags$script(HTML(js))),
  DTOutput("mytable")
)

server <- function(input, output){
  output[["mytable"]] <- renderDT({
    datatable(dat, escape = FALSE, selection = "none",
              options = list(
                columnDefs = list(
                  list(targets = ncol(dat), visible = FALSE)
                ),
                rowId = JS(sprintf("function(data){return data[%d];}", ncol(dat)))))
  }, server = FALSE)
}

shinyApp(ui, server)

Or, simpler:

dat <- iris[1:5, 1:2]
dat$Action <-
  '<button type="button" class="btn btn-secondary delete">Delete</button>'

callback <- c(
  "table.on('click', 'button.delete', function(){",
  "  var tr = $(this).closest('tr');",
  "  table.row(tr[0]).remove().draw(false);",
  "});"
)

ui <- fluidPage(
  DTOutput("mytable")
)

server <- function(input, output){
  output[["mytable"]] <- renderDT({
    datatable(dat, escape = -ncol(dat)-1, selection = "none",
              callback = JS(callback))
  }, server = FALSE)
}

shinyApp(ui, server)


问:
How get properties from object in Laravel
I am beginner in Laravel. I use Laravel 5.8 in my project.

I have this object:

```<code>NominatimAddress {#1146 ▼
  -attribution: "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright"
  -category: "building"
  -displayName: "99, 9 Maja, Janowo, Olsztyn, powiat pomorski, pomorskie, "
  -osmType: "way"
  -osmId: 142789154
  -type: "yes"
  -coordinates: Coordinates {#1147 ▼
    -latitude: 51.51171143
    -longitude: 11.4023121
  }
  -bounds: Bounds {#1148 ▶}
  -adminLevels: AdminLevelCollection {#1149 ▶}
  -country: Country {#1152 ▶}
  -timezone: null
  -providedBy: "nominatim"
}
</code>```

How can I get latitude and longitude from this object?

答:
```<code>$lat = $object->coordinates->latitude;
$long = $object->coordinates->longitude;
</code>```

Body:
I am beginner in Laravel. I use Laravel 5.8 in my project.

I have this object:

NominatimAddress {#1146 ▼
  -attribution: "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright"
  -category: "building"
  -displayName: "99, 9 Maja, Janowo, Olsztyn, powiat pomorski, pomorskie, "
  -osmType: "way"
  -osmId: 142789154
  -type: "yes"
  -coordinates: Coordinates {#1147 ▼
    -latitude: 51.51171143
    -longitude: 11.4023121
  }
  -bounds: Bounds {#1148 ▶}
  -adminLevels: AdminLevelCollection {#1149 ▶}
  -country: Country {#1152 ▶}
  -timezone: null
  -providedBy: "nominatim"
}

How can I get latitude and longitude from this object?