问:
spring data jpa query value in a Set
I have an entity class A which has a Set of entities of class B with a ManyToMany relationship (out of scope why I need this)

```<code>class A {

    @ManyToMany(cascade = CascadeType.ALL)
    Set<B> setOfB;
}
</code>```

Now, given an object of class B, how can I retrieve the object(s) of class A which has the B object in its Set??

I have tried in my class A repository with this:

```<code>interface Arepository extends JpaRepository<A, Long> {

    @Query("from A a where ?1 in a.setOfB")
    List<A> findByB(B b)
}
</code>```

But it gives me a SQLGrammarException, so which is the correct syntax?

Thank you for your help.

答:
Metamodel class:

```<code>@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(A.class)
public class A_ {
    public static volatile SetAttribute<A, B> bSet;
}
</code>```

Specification utils:

```<code>public class ASpecs {

    public static Specification<A> containsB(B b) {
        return (root, query, cb) -> {
            Expression<Set<B>> bSet = root.get(A_.bSet);
            return cb.isMember(b, bSet);
        };
    }
}
</code>```

Your repository:

```<code>public interface ARepository extends JpaRepository<A, Long>, JpaSpecificationExecutor<A> {
}
</code>```

Usage:

```<code>@Service
public class YourService {

    @Resource
    private ARepository repository;

    public List<A> getByB(B b) {
        return repository.findAll(ASpecs.containsB(b));
    }
}
</code>```

Title: spring data jpa query value in a Set

Body:
I have an entity class A which has a Set of entities of class B with a ManyToMany relationship (out of scope why I need this)

class A {

    @ManyToMany(cascade = CascadeType.ALL)
    Set setOfB;
}

Now, given an object of class B, how can I retrieve the object(s) of class A which has the B object in its Set??

I have tried in my class A repository with this:

interface Arepository extends JpaRepository {

    @Query("from A a where ?1 in a.setOfB")
    List findByB(B b)
}

But it gives me a SQLGrammarException, so which is the correct syntax?

Thank you for your help.

Body:
Metamodel class:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(A.class)
public class A_ {
    public static volatile SetAttribute<A, B> bSet;
}

Specification utils:

public class ASpecs {

    public static Specification<A> containsB(B b) {
        return (root, query, cb) -> {
            Expression<Set<B>> bSet = root.get(A_.bSet);
            return cb.isMember(b, bSet);
        };
    }
}

Your repository:

public interface ARepository extends JpaRepository<A, Long>, JpaSpecificationExecutor<A> {
}

Usage:

@Service
public class YourService {

    @Resource
    private ARepository repository;

    public List<A> getByB(B b) {
        return repository.findAll(ASpecs.containsB(b));
    }
}


来源: stackexchange

问:
After Intsall SSL on magento site
I installed SSL certificate for my magento store and set system config to:

Use Secure URLs in Frontend:yes

Use Secure URLs in Admin:yes

however when I review the page source some links have http:// instead of https://

I cleaned up the cache, but was not able to solve this issue, can any one help me?

答:
You will need to fix your theme's templates, styles and extensions.

Search in projectroot for href="http:// or src="http:// and replace by href="// and src="//

also make sure external resources support ssl

ContentLicense: CC BY-SA 4.0

Title: After Intsall SSL on magento site

ContentLicense: CC BY-SA 3.0


问:
Grant update to user Oracle
I would like to grant the right of update to a manager on a table custumer but only on the customers of which it is manager.

For example I have a table Custumer and I created a user "Jean" with the command CREATE USER, so I would like that "Jean" can modify all the customers of which it is manager.

答:
I found this example of RLS but It's too late to edit to meet your simple USER requirements. This example caters for users with many andvarious ROLES that may be inherited from an Organizational Tree. But I hope you get the idea?</p>

```<code>BEGIN
  DBMS_RLS.DROP_POLICY (object_schema    => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_READ');

  DBMS_RLS.DROP_POLICY (object_schema    => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_WRITE');

  DBMS_RLS.DROP_POLICY (object_schema    => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_REGISTER');

END;

CREATE OR REPLACE PACKAGE chs_security_policies AS

    ROLE_CRUM            CONSTANT VARCHAR2(5) := 'CRUM';
    ROLE_CRUO            CONSTANT VARCHAR2(5) := 'CRUO';
    ROLE_HOU             CONSTANT VARCHAR2(5) := 'HOU';
    ROLE_DCO             CONSTANT VARCHAR2(5) := 'DCO';
    ROLE_SA              CONSTANT VARCHAR2(5) := 'SA';
    ROLE_CA              CONSTANT VARCHAR2(5) := 'CA';
    CHS_ORG_TREE         CONSTANT CHAR(5)     := 'CHS01';
    READ_ACCESS          CONSTANT INTEGER     :=   63;
    WRITE_ACCESS         CONSTANT INTEGER     :=   42;
    INSERT_ACCESS        CONSTANT INTEGER     :=   64;
    ORG_CASCADE          CONSTANT INTEGER     := 2060;
    CASE_SPECIFIC        CONSTANT INTEGER     :=   48;
    QUARANTINED_ACCESS   CONSTANT INTEGER     :=  128;
    FINALISED_ACCESS     CONSTANT INTEGER     :=  256;
    READ_ONLY            CONSTANT INTEGER     :=   21;
    READ_CASE_ORG_UNITS  CONSTANT INTEGER     :=   16;
    READ_GROUP_ORG_UNITS CONSTANT INTEGER     :=    4;
    READ_WORLD_ORG_UNITS CONSTANT INTEGER     :=    1;

    FUNCTION case_file_read     (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2;

    FUNCTION case_file_write    (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2;

    FUNCTION case_file_register (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2;

    FUNCTION case_file_filter   (i_schema IN VARCHAR2, i_object IN VARCHAR2, i_access_requested INTEGER)
      RETURN VARCHAR2;

    FUNCTION check_case_access  (i_case_file_id IN INTEGER, i_mgr_org_unit IN INTEGER, i_dco_person_id in varchar2)
      RETURN INTEGER
      DETERMINISTIC;

    FUNCTION default_priv_mask  (i_person_id in varchar2)
      RETURN INTEGER
      DETERMINISTIC;

    FUNCTION decode_role        (i_case_file_id IN INTEGER, i_mgr_org_unit IN INTEGER, i_dco_person_id in varchar2)
      RETURN VARCHAR2
      DETERMINISTIC;

    FUNCTION check_proxy_access (i_case_file_id         IN case_file.case_file_id%type
                               , i_dco_person_id        IN case_file.dco_person_id%type
                               , i_mgr_org_unit         IN case_file.mgr_org_unit%type
                               , i_proxy_person_id      IN case_file.dco_person_id%type)
      RETURN INTEGER
      DETERMINISTIC;

END chs_security_policies;

CREATE OR REPLACE PACKAGE BODY chs_security_policies AS

    FUNCTION case_file_read (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2
    IS

    BEGIN

      RETURN case_file_filter(i_schema, i_object, READ_ACCESS);

    END case_file_read;

    FUNCTION case_file_write (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2
    IS

    BEGIN

      RETURN case_file_filter(i_schema, i_object, WRITE_ACCESS);

    END case_file_write;

    FUNCTION case_file_register (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2
    IS

    BEGIN

      RETURN case_file_filter(i_schema, i_object, INSERT_ACCESS);

    END case_file_register;

    FUNCTION case_file_filter (i_schema IN VARCHAR2, i_object IN VARCHAR2, i_access_requested INTEGER)
      RETURN VARCHAR2
    IS

      o_filter_predicate VARCHAR2(200) := '';

    BEGIN

      CASE lower(i_object)
      WHEN 'case_file' THEN
        o_filter_predicate :=
          'BITAND(chs_security_policies.check_case_access(case_file_id, mgr_org_unit, dco_person_id), '||i_access_requested||') <> 0 ';
      WHEN 'case_file_h' THEN
        o_filter_predicate :=
          'BITAND(chs_security_policies.check_case_access(case_file_id, mgr_org_unit, dco_person_id), '||i_access_requested||') <> 0 ';
      END CASE;

      RETURN o_filter_predicate;

    END case_file_filter;

    FUNCTION check_proxy_access (i_case_file_id         IN case_file.case_file_id%type
                               , i_dco_person_id        IN case_file.dco_person_id%type
                               , i_mgr_org_unit         IN case_file.mgr_org_unit%type
                               , i_proxy_person_id      IN case_file.dco_person_id%type)
      RETURN INTEGER
      DETERMINISTIC
    IS
      o_has_access       INTEGER     := 0;
      v_prev_person      varchar2(8) := SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER');

    BEGIN

      dbms_session.set_identifier(i_proxy_person_id);

      IF BITAND(check_case_access(i_case_file_id, i_mgr_org_unit, i_dco_person_id), READ_ACCESS) <> 0
      THEN
        o_has_access := 1;
      END IF;

      dbms_session.set_identifier(v_prev_person);

      RETURN o_has_access;

    END check_proxy_access;

    FUNCTION check_case_access(i_case_file_id in INTEGER, i_mgr_org_unit in INTEGER, i_dco_person_id in varchar2)
      RETURN INTEGER
      DETERMINISTIC
    IS

      o_access_granted   INTEGER     := 0;
      v_curr_person      varchar2(8) := SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER');
      v_single_priv      INTEGER     := 0;
      v_profile_org_unit INTEGER     := 0;
      v_quarantine_ok    varchar2(1);
      v_finalise_ok      varchar2(1);
      v_is_participant   varchar2(1);
      v_local_role       access_role.role_code%type;

      cursor user_privs is
        select
               d.priv_id,
               b.org_unit_id,
               c.role_code
        from
               access_user      a
              ,access_profile   b
              ,access_role      c
              ,access_role_priv d
              ,access_priv      e
        where
               a.person_id      = v_curr_person
          and  a.active_flag    = 'Y'
          and  b.person_id      = a.person_id
          and  c.role_code      = b.role_code
          and  d.role_code      = b.role_code
          and  e.priv_id        = d.priv_id
      ;

    BEGIN

      IF v_curr_person is null
      THEN
          RETURN 0;
      END IF;

      select
        case
           when exists
              (select
                      *
                 from
                      complainant a
                where
                      a.case_file_id      = i_case_file_id
                  and a.person_id         = v_curr_person
                  and a.active_flag       = 'Y'
              )
           then  'Y'
           else  'N'
        end
      into
        v_is_participant
      from
        dual
      ;

      IF v_is_participant = 'Y'
      THEN
          RETURN 0;
      END IF;

      select
        case
           when exists
              (select
                      *
                 from
                      respondent a
                where
                      a.case_file_id      = i_case_file_id
                  and a.person_id         = v_curr_person
                  and a.person_type      <> 'U'
                  and a.active_flag       = 'Y'
              )
           then  'Y'
           else  'N'
        end
      into
        v_is_participant
      from
        dual
      ;

      IF v_is_participant = 'Y'
      THEN
          RETURN 0;
      END IF;

      v_quarantine_ok := 'N';
      v_finalise_ok   := 'N';

      open user_privs;

      loop
          fetch user_privs into v_single_priv,
                                v_profile_org_unit,
                                v_local_role;

          exit when user_privs%notfound;

          IF v_single_priv = QUARANTINED_ACCESS
          THEN
               v_quarantine_ok := 'Y';
               continue;
          END IF;

          IF v_single_priv = FINALISED_ACCESS
          THEN
               v_finalise_ok := 'Y';
               continue;
          END IF;

          IF bitand(v_single_priv, ORG_CASCADE) <> 0
          THEN
              select
                case
                  when i_mgr_org_unit in (
                    select
                      a.org_unit_child
                    from
                      org_rel a
                    connect by nocycle
                      a.org_rel_type_code = CHS_ORG_TREE and
                    prior
                      a.org_unit_child = a.org_unit_parent
                    start with
                      a.org_unit_child = v_profile_org_unit
                  and a.org_rel_type_code = CHS_ORG_TREE)
                  then v_single_priv
                  else 0
                end
              into
                v_single_priv
              from
                dual
              ;

          END IF;

          IF bitand(v_single_priv, CASE_SPECIFIC) <> 0
          THEN
              IF v_local_role = 'CA'
              THEN
                select
                  case
                    when exists
                        (select
                                *
                           from
                                case_assistant a
                          where
                                a.case_file_id      = i_case_file_id
                            and a.case_assistant_id = v_curr_person
                            and sysdate between       a.access_from and a.access_to
                          )
                    then  v_single_priv
                    else  0
                    end
                into
                  v_single_priv
                from
                  dual
                ;
                IF v_single_priv <> 0
                THEN
                    v_quarantine_ok := 'Y';
                END IF;
              ELSE
                  IF v_curr_person <> i_dco_person_id
                  THEN
                      v_single_priv := 0;
                  END IF;
              END IF;
          END IF;

          o_access_granted := (o_access_granted + v_single_priv - bitand(o_access_granted, v_single_priv));

      end loop;

      close user_privs;

      IF o_access_granted = 0 THEN
        RETURN o_access_granted;
      END IF;

      IF (v_quarantine_ok = 'N' AND (i_dco_person_id <> v_curr_person
                                 OR  BITAND(o_access_granted,CASE_SPECIFIC) = 0)) THEN
        select
          case
            when exists
                (select
                        *
                   from
                        quarantine a
                  where
                        a.case_file_id      = i_case_file_id
                    and a.active_flag       = 'Y'
                  )
            then  0
            else  o_access_granted
          end
        into
          o_access_granted
        from
          dual
        ;
      END IF;

      IF o_access_granted = 0 THEN
        RETURN o_access_granted;
      END IF;

      IF v_finalise_ok = 'N' THEN
        select
          case
            when exists
                (select
                        *
                   from
                        finalise a
                  where
                        a.case_file_id      = i_case_file_id
                  )
            then  0
            else  o_access_granted
          end
        into
          o_access_granted
        from
          dual
        ;

      END IF;

      IF v_finalise_ok = 'Y' THEN
        select
          case
            when exists
                (select
                        *
                   from
                        finalise a
                  where
                        a.case_file_id      = i_case_file_id
                  )
            then  BITAND(o_access_granted, READ_ONLY)
            else  o_access_granted
          end
        into
          o_access_granted
        from
          dual
        ;

      END IF;

      RETURN o_access_granted;

    END check_case_access;

    FUNCTION decode_role(i_case_file_id IN INTEGER, i_mgr_org_unit IN INTEGER, i_dco_person_id in varchar2)
      RETURN VARCHAR2
      DETERMINISTIC
    IS

      v_curr_person      varchar2(8) := SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER');
      v_access_granted   INTEGER     := 0;
      o_role_used        access_role.role_code%type;

    BEGIN

      v_access_granted := check_case_access(i_case_file_id, i_mgr_org_unit, i_dco_person_id);

      IF BITAND(v_access_granted, READ_CASE_ORG_UNITS ) <> 0 THEN
          IF v_curr_person = i_dco_person_id THEN
              o_role_used := ROLE_DCO;
          ELSE
              o_role_used := ROLE_CA;
          END IF;
      ELSE
          IF BITAND(v_access_granted, READ_GROUP_ORG_UNITS) <> 0 THEN
              o_role_used := ROLE_HOU;
          ELSE
              IF BITAND(v_access_granted, READ_WORLD_ORG_UNITS) <> 0 THEN
                  select
                    case
                    when exists
                        (select
                                *
                           from
                                access_profile a
                          where
                                a.person_id       = v_curr_person
                            and a.role_code       = ROLE_CRUM
                          )
                    then  ROLE_CRUM
                    else  ROLE_CRUO
                  end
                into
                  o_role_used
                from
                  dual
                ;
              END IF;
          END IF;
      END IF;

      RETURN o_role_used;

    END decode_role;

    FUNCTION default_priv_mask(i_person_id in varchar2)
      RETURN INTEGER
      DETERMINISTIC
    IS

      o_access_available INTEGER     := 0;
      v_single_priv      INTEGER     := 0;

      cursor user_privs is
        select
               d.priv_id
        from
               access_user      a
              ,access_profile   b
              ,access_role      c
              ,access_role_priv d
              ,access_priv      e
        where
               a.person_id      = i_person_id
          and  a.active_flag    = 'Y'
          and  b.person_id      = a.person_id
          and  c.role_code      = b.role_code
          and  d.role_code      = b.role_code
          and  e.priv_id        = d.priv_id
      ;

    BEGIN

      open user_privs;

      loop
          fetch user_privs into v_single_priv;

          exit when user_privs%notfound;

          o_access_available := (o_access_available + v_single_priv - bitand(o_access_available, v_single_priv));

      end loop;

      close user_privs;

      RETURN o_access_available;

    END default_priv_mask;

END chs_security_policies;

/

BEGIN
  DBMS_RLS.ADD_POLICY (object_schema     => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_READ',
                       function_schema   => 'CHS',
                       statement_types   => 'SELECT',
                       policy_function   => 'chs_security_policies.case_file_read');

  DBMS_RLS.ADD_POLICY (object_schema     => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_WRITE',
                       function_schema   => 'CHS',
                       statement_types   => 'UPDATE,DELETE',
                       policy_function   => 'chs_security_policies.case_file_write');

  DBMS_RLS.ADD_POLICY (object_schema     => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_REGISTER',
                       function_schema   => 'CHS',
                       statement_types   => 'INSERT',
                       policy_function   => 'chs_security_policies.case_file_register');
END;
</code>```

Title: Grant update to user Oracle

Body:
I found this example of RLS but It's too late to edit to meet your simple USER requirements. This example caters for users with many andvarious ROLES that may be inherited from an Organizational Tree. But I hope you get the idea?

BEGIN
  DBMS_RLS.DROP_POLICY (object_schema    => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_READ');

  DBMS_RLS.DROP_POLICY (object_schema    => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_WRITE');

  DBMS_RLS.DROP_POLICY (object_schema    => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_REGISTER');

END;

CREATE OR REPLACE PACKAGE chs_security_policies AS

    ROLE_CRUM            CONSTANT VARCHAR2(5) := 'CRUM';
    ROLE_CRUO            CONSTANT VARCHAR2(5) := 'CRUO';
    ROLE_HOU             CONSTANT VARCHAR2(5) := 'HOU';
    ROLE_DCO             CONSTANT VARCHAR2(5) := 'DCO';
    ROLE_SA              CONSTANT VARCHAR2(5) := 'SA';
    ROLE_CA              CONSTANT VARCHAR2(5) := 'CA';
    CHS_ORG_TREE         CONSTANT CHAR(5)     := 'CHS01';
    READ_ACCESS          CONSTANT INTEGER     :=   63;
    WRITE_ACCESS         CONSTANT INTEGER     :=   42;
    INSERT_ACCESS        CONSTANT INTEGER     :=   64;
    ORG_CASCADE          CONSTANT INTEGER     := 2060;
    CASE_SPECIFIC        CONSTANT INTEGER     :=   48;
    QUARANTINED_ACCESS   CONSTANT INTEGER     :=  128;
    FINALISED_ACCESS     CONSTANT INTEGER     :=  256;
    READ_ONLY            CONSTANT INTEGER     :=   21;
    READ_CASE_ORG_UNITS  CONSTANT INTEGER     :=   16;
    READ_GROUP_ORG_UNITS CONSTANT INTEGER     :=    4;
    READ_WORLD_ORG_UNITS CONSTANT INTEGER     :=    1;

    FUNCTION case_file_read     (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2;

    FUNCTION case_file_write    (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2;

    FUNCTION case_file_register (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2;

    FUNCTION case_file_filter   (i_schema IN VARCHAR2, i_object IN VARCHAR2, i_access_requested INTEGER)
      RETURN VARCHAR2;

    FUNCTION check_case_access  (i_case_file_id IN INTEGER, i_mgr_org_unit IN INTEGER, i_dco_person_id in varchar2)
      RETURN INTEGER
      DETERMINISTIC;

    FUNCTION default_priv_mask  (i_person_id in varchar2)
      RETURN INTEGER
      DETERMINISTIC;

    FUNCTION decode_role        (i_case_file_id IN INTEGER, i_mgr_org_unit IN INTEGER, i_dco_person_id in varchar2)
      RETURN VARCHAR2
      DETERMINISTIC;

    FUNCTION check_proxy_access (i_case_file_id         IN case_file.case_file_id%type
                               , i_dco_person_id        IN case_file.dco_person_id%type
                               , i_mgr_org_unit         IN case_file.mgr_org_unit%type
                               , i_proxy_person_id      IN case_file.dco_person_id%type)
      RETURN INTEGER
      DETERMINISTIC;

END chs_security_policies;

CREATE OR REPLACE PACKAGE BODY chs_security_policies AS

    FUNCTION case_file_read (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2
    IS

    BEGIN

      RETURN case_file_filter(i_schema, i_object, READ_ACCESS);

    END case_file_read;

    FUNCTION case_file_write (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2
    IS

    BEGIN

      RETURN case_file_filter(i_schema, i_object, WRITE_ACCESS);

    END case_file_write;

    FUNCTION case_file_register (i_schema IN VARCHAR2, i_object IN VARCHAR2)
      RETURN VARCHAR2
    IS

    BEGIN

      RETURN case_file_filter(i_schema, i_object, INSERT_ACCESS);

    END case_file_register;

    FUNCTION case_file_filter (i_schema IN VARCHAR2, i_object IN VARCHAR2, i_access_requested INTEGER)
      RETURN VARCHAR2
    IS

      o_filter_predicate VARCHAR2(200) := '';

    BEGIN

      CASE lower(i_object)
      WHEN 'case_file' THEN
        o_filter_predicate :=
          'BITAND(chs_security_policies.check_case_access(case_file_id, mgr_org_unit, dco_person_id), '||i_access_requested||') <> 0 ';
      WHEN 'case_file_h' THEN
        o_filter_predicate :=
          'BITAND(chs_security_policies.check_case_access(case_file_id, mgr_org_unit, dco_person_id), '||i_access_requested||') <> 0 ';
      END CASE;

      RETURN o_filter_predicate;

    END case_file_filter;

    FUNCTION check_proxy_access (i_case_file_id         IN case_file.case_file_id%type
                               , i_dco_person_id        IN case_file.dco_person_id%type
                               , i_mgr_org_unit         IN case_file.mgr_org_unit%type
                               , i_proxy_person_id      IN case_file.dco_person_id%type)
      RETURN INTEGER
      DETERMINISTIC
    IS
      o_has_access       INTEGER     := 0;
      v_prev_person      varchar2(8) := SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER');

    BEGIN

      dbms_session.set_identifier(i_proxy_person_id);

      IF BITAND(check_case_access(i_case_file_id, i_mgr_org_unit, i_dco_person_id), READ_ACCESS) <> 0
      THEN
        o_has_access := 1;
      END IF;

      dbms_session.set_identifier(v_prev_person);

      RETURN o_has_access;

    END check_proxy_access;

    FUNCTION check_case_access(i_case_file_id in INTEGER, i_mgr_org_unit in INTEGER, i_dco_person_id in varchar2)
      RETURN INTEGER
      DETERMINISTIC
    IS

      o_access_granted   INTEGER     := 0;
      v_curr_person      varchar2(8) := SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER');
      v_single_priv      INTEGER     := 0;
      v_profile_org_unit INTEGER     := 0;
      v_quarantine_ok    varchar2(1);
      v_finalise_ok      varchar2(1);
      v_is_participant   varchar2(1);
      v_local_role       access_role.role_code%type;

      cursor user_privs is
        select
               d.priv_id,
               b.org_unit_id,
               c.role_code
        from
               access_user      a
              ,access_profile   b
              ,access_role      c
              ,access_role_priv d
              ,access_priv      e
        where
               a.person_id      = v_curr_person
          and  a.active_flag    = 'Y'
          and  b.person_id      = a.person_id
          and  c.role_code      = b.role_code
          and  d.role_code      = b.role_code
          and  e.priv_id        = d.priv_id
      ;

    BEGIN

      IF v_curr_person is null
      THEN
          RETURN 0;
      END IF;

      select
        case
           when exists
              (select
                      *
                 from
                      complainant a
                where
                      a.case_file_id      = i_case_file_id
                  and a.person_id         = v_curr_person
                  and a.active_flag       = 'Y'
              )
           then  'Y'
           else  'N'
        end
      into
        v_is_participant
      from
        dual
      ;

      IF v_is_participant = 'Y'
      THEN
          RETURN 0;
      END IF;

      select
        case
           when exists
              (select
                      *
                 from
                      respondent a
                where
                      a.case_file_id      = i_case_file_id
                  and a.person_id         = v_curr_person
                  and a.person_type      <> 'U'
                  and a.active_flag       = 'Y'
              )
           then  'Y'
           else  'N'
        end
      into
        v_is_participant
      from
        dual
      ;

      IF v_is_participant = 'Y'
      THEN
          RETURN 0;
      END IF;

      v_quarantine_ok := 'N';
      v_finalise_ok   := 'N';

      open user_privs;

      loop
          fetch user_privs into v_single_priv,
                                v_profile_org_unit,
                                v_local_role;

          exit when user_privs%notfound;

          IF v_single_priv = QUARANTINED_ACCESS
          THEN
               v_quarantine_ok := 'Y';
               continue;
          END IF;

          IF v_single_priv = FINALISED_ACCESS
          THEN
               v_finalise_ok := 'Y';
               continue;
          END IF;

          IF bitand(v_single_priv, ORG_CASCADE) <> 0
          THEN
              select
                case
                  when i_mgr_org_unit in (
                    select
                      a.org_unit_child
                    from
                      org_rel a
                    connect by nocycle
                      a.org_rel_type_code = CHS_ORG_TREE and
                    prior
                      a.org_unit_child = a.org_unit_parent
                    start with
                      a.org_unit_child = v_profile_org_unit
                  and a.org_rel_type_code = CHS_ORG_TREE)
                  then v_single_priv
                  else 0
                end
              into
                v_single_priv
              from
                dual
              ;

          END IF;

          IF bitand(v_single_priv, CASE_SPECIFIC) <> 0
          THEN
              IF v_local_role = 'CA'
              THEN
                select
                  case
                    when exists
                        (select
                                *
                           from
                                case_assistant a
                          where
                                a.case_file_id      = i_case_file_id
                            and a.case_assistant_id = v_curr_person
                            and sysdate between       a.access_from and a.access_to
                          )
                    then  v_single_priv
                    else  0
                    end
                into
                  v_single_priv
                from
                  dual
                ;
                IF v_single_priv <> 0
                THEN
                    v_quarantine_ok := 'Y';
                END IF;
              ELSE
                  IF v_curr_person <> i_dco_person_id
                  THEN
                      v_single_priv := 0;
                  END IF;
              END IF;
          END IF;

          o_access_granted := (o_access_granted + v_single_priv - bitand(o_access_granted, v_single_priv));

      end loop;

      close user_privs;

      IF o_access_granted = 0 THEN
        RETURN o_access_granted;
      END IF;

      IF (v_quarantine_ok = 'N' AND (i_dco_person_id <> v_curr_person
                                 OR  BITAND(o_access_granted,CASE_SPECIFIC) = 0)) THEN
        select
          case
            when exists
                (select
                        *
                   from
                        quarantine a
                  where
                        a.case_file_id      = i_case_file_id
                    and a.active_flag       = 'Y'
                  )
            then  0
            else  o_access_granted
          end
        into
          o_access_granted
        from
          dual
        ;
      END IF;

      IF o_access_granted = 0 THEN
        RETURN o_access_granted;
      END IF;

      IF v_finalise_ok = 'N' THEN
        select
          case
            when exists
                (select
                        *
                   from
                        finalise a
                  where
                        a.case_file_id      = i_case_file_id
                  )
            then  0
            else  o_access_granted
          end
        into
          o_access_granted
        from
          dual
        ;

      END IF;

      IF v_finalise_ok = 'Y' THEN
        select
          case
            when exists
                (select
                        *
                   from
                        finalise a
                  where
                        a.case_file_id      = i_case_file_id
                  )
            then  BITAND(o_access_granted, READ_ONLY)
            else  o_access_granted
          end
        into
          o_access_granted
        from
          dual
        ;

      END IF;

      RETURN o_access_granted;

    END check_case_access;

    FUNCTION decode_role(i_case_file_id IN INTEGER, i_mgr_org_unit IN INTEGER, i_dco_person_id in varchar2)
      RETURN VARCHAR2
      DETERMINISTIC
    IS

      v_curr_person      varchar2(8) := SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER');
      v_access_granted   INTEGER     := 0;
      o_role_used        access_role.role_code%type;

    BEGIN

      v_access_granted := check_case_access(i_case_file_id, i_mgr_org_unit, i_dco_person_id);

      IF BITAND(v_access_granted, READ_CASE_ORG_UNITS ) <> 0 THEN
          IF v_curr_person = i_dco_person_id THEN
              o_role_used := ROLE_DCO;
          ELSE
              o_role_used := ROLE_CA;
          END IF;
      ELSE
          IF BITAND(v_access_granted, READ_GROUP_ORG_UNITS) <> 0 THEN
              o_role_used := ROLE_HOU;
          ELSE
              IF BITAND(v_access_granted, READ_WORLD_ORG_UNITS) <> 0 THEN
                  select
                    case
                    when exists
                        (select
                                *
                           from
                                access_profile a
                          where
                                a.person_id       = v_curr_person
                            and a.role_code       = ROLE_CRUM
                          )
                    then  ROLE_CRUM
                    else  ROLE_CRUO
                  end
                into
                  o_role_used
                from
                  dual
                ;
              END IF;
          END IF;
      END IF;

      RETURN o_role_used;

    END decode_role;

    FUNCTION default_priv_mask(i_person_id in varchar2)
      RETURN INTEGER
      DETERMINISTIC
    IS

      o_access_available INTEGER     := 0;
      v_single_priv      INTEGER     := 0;

      cursor user_privs is
        select
               d.priv_id
        from
               access_user      a
              ,access_profile   b
              ,access_role      c
              ,access_role_priv d
              ,access_priv      e
        where
               a.person_id      = i_person_id
          and  a.active_flag    = 'Y'
          and  b.person_id      = a.person_id
          and  c.role_code      = b.role_code
          and  d.role_code      = b.role_code
          and  e.priv_id        = d.priv_id
      ;

    BEGIN

      open user_privs;

      loop
          fetch user_privs into v_single_priv;

          exit when user_privs%notfound;

          o_access_available := (o_access_available + v_single_priv - bitand(o_access_available, v_single_priv));

      end loop;

      close user_privs;

      RETURN o_access_available;

    END default_priv_mask;

END chs_security_policies;

/

BEGIN
  DBMS_RLS.ADD_POLICY (object_schema     => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_READ',
                       function_schema   => 'CHS',
                       statement_types   => 'SELECT',
                       policy_function   => 'chs_security_policies.case_file_read');

  DBMS_RLS.ADD_POLICY (object_schema     => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_WRITE',
                       function_schema   => 'CHS',
                       statement_types   => 'UPDATE,DELETE',
                       policy_function   => 'chs_security_policies.case_file_write');

  DBMS_RLS.ADD_POLICY (object_schema     => 'CHS',
                       object_name       => 'CASE_FILE',
                       policy_name       => 'CASE_FILE_REGISTER',
                       function_schema   => 'CHS',
                       statement_types   => 'INSERT',
                       policy_function   => 'chs_security_policies.case_file_register');
END;


问:
Problem with access to Mongodb on Amazon EC2
i've got another question for you.
I have Amazon EC2 instance with mondodb installed.
It works great except one thing - i can't access (connect to) it from outside (my PC).
I think the problem with Security Groups. It's some sort of default firewall.
Does anyone know how to configure EC2 instance to have access to mongodb?
Thanks in advance.</p>

答:
Think carefully before doing this. If you open the ports, make sure you restrict the IP numbers that can access it, otherwise anyone will be able to access your database. You can enable authentication in MongoDB, but it's not particularly safe, just a username and password. You should not have your database open to the internet, it is not a good idea.

A better way than opening up ports in the EC2 firewall is to open an SSH tunnel an forward the port, this makes sure that only you can access the database, and only while the SSH tunnel is active.

Open up a new terminal and run this command (replacing user and host with the user you use when SSH'ing to your server and the name of the server):

```<code>ssh user@host -N -L 27017:127.0.0.1:27017
</code>```

The command will forward the port 27017 on your computer to the same port on the server. To connect to the MongoDB instance simply run mongo in a terminal (if that doesn't work, try mongo --host 127.0.0.1 or even mongo --host 127.0.0.1 --port 27017).

If you run MongoDB on your local machine you will have to change the first port, since the local server is already using it. In that case run this command instead:

```<code>ssh user@host -N -L 27018:127.0.0.1:27017
</code>```

and then connect with

```<code>mongo --port 27018
</code>```

(possibly adding --host 127.0.0.1 if it doesn't work).

When you're done working with the database, exit mongo and press ctrl-C in the terminal with the SSH command.

ContentLicense: CC BY-SA 2.5

Body:
Think carefully before doing this. If you open the ports, make sure you restrict the IP numbers that can access it, otherwise anyone will be able to access your database. You can enable authentication in MongoDB, but it's not particularly safe, just a username and password. You should not have your database open to the internet, it is not a good idea.

A better way than opening up ports in the EC2 firewall is to open an SSH tunnel an forward the port, this makes sure that only you can access the database, and only while the SSH tunnel is active.

Open up a new terminal and run this command (replacing user and host with the user you use when SSH'ing to your server and the name of the server):

ssh user@host -N -L 27017:127.0.0.1:27017

The command will forward the port 27017 on your computer to the same port on the server. To connect to the MongoDB instance simply run mongo in a terminal (if that doesn't work, try mongo --host 127.0.0.1 or even mongo --host 127.0.0.1 --port 27017).

If you run MongoDB on your local machine you will have to change the first port, since the local server is already using it. In that case run this command instead:

ssh user@host -N -L 27018:127.0.0.1:27017

and then connect with

mongo --port 27018

(possibly adding --host 127.0.0.1 if it doesn't work).

When you're done working with the database, exit mongo and press ctrl-C in the terminal with the SSH command.


问:
How does the indexing work to find MIN() or MAX() value for a specific indexed column and sort a table in following scenario?
Following is the text from MySQL Documentation :

To find the MIN() or MAX() value for a specific indexed column
  key_col. This is optimized by a preprocessor that checks whether you
  are using WHERE key_part_N = constant on all key parts that occur
  before key_col in the index. In this case, MySQL does a single key
  lookup for each MIN() or MAX() expression and replaces it with a
  constant. If all expressions are replaced with constants, the query
  returns at once. For example:

```<code>SELECT MIN(key_part2),MAX(key_part2)
  FROM tbl_name WHERE key_part1=10;
</code>```

To sort or group a table if the sorting or grouping is done on a
  leftmost prefix of a usable index (for example, ORDER BY key_part1,
  key_part2). If all key parts are followed by DESC, the key is read in
  reverse order.

In some cases, a query can be optimized to retrieve values without
  consulting the data rows. (An index that provides all the necessary
  results for a query is called a covering index.) If a query uses from
  a table only columns that are included in some index, the selected
  values can be retrieved from the index tree for greater speed:

```<code>SELECT key_part3 FROM tbl_name
  WHERE key_part1=1
</code>```

I'm not at all able to understand these points and the respective code from the MySQL Documentation.

Someone please make the things easy in order to clarify the things to make me understand.

I am not asking what is Indexing and how does work, etc. etc.

I just want to understand what these sentences are trying to say and what's happening out there in the code?

What are key_par_N and what's the purpose of using them here?

What does actually mean by the term key part in this context?

What does mean by all key parts that occur before key_col in the index?

Where is the column key_col of which we are supposed to fine MIN() and MAX() values (See the first line : To find the MIN() or MAX() value for a specific indexed column key_col.)?

Someone please make me clear everything.

Note : I've already seen this question which is asking the same thing but it has received a generalized answer which is not specific to the explanation and code given in the manual. So, I'm asking this question to get precise and specific answer. So, please don't mark my question duplicate.

答:
In SQL you can create an index in order to index multiple columns e.g., create index idx on t1 (key_colX, key_colY). Now key_part1 is key_colX and key_part2 is key_colY. The order is important!

Let´s say we use a bTree as an index structure, then elements are organized according to key_part1 first, if key_part1 of two elements is equal then according to key_part2. Now if you issue a query and set key_part1 = 10 to a (constant) value, the DB can quickly find the subtree of the bTree where key_part1 = 10. All elements in this subtree are organized according to key_part2 which makes a Min() or Max() very efficient.

If you try the query the other way

```<code>SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name WHERE key_part2=10;
</code>```

then the index cannot be utilized.

So the above basically says you can answer queries more efficiently if your query can utilize the order of the indexed columns.

Body:
Following is the text from MySQL Documentation :

To find the MIN() or MAX() value for a specific indexed column
  key_col. This is optimized by a preprocessor that checks whether you
  are using WHERE key_part_N = constant on all key parts that occur
  before key_col in the index. In this case, MySQL does a single key
  lookup for each MIN() or MAX() expression and replaces it with a
  constant. If all expressions are replaced with constants, the query
  returns at once. For example:

SELECT MIN(key_part2),MAX(key_part2)
  FROM tbl_name WHERE key_part1=10;

To sort or group a table if the sorting or grouping is done on a
  leftmost prefix of a usable index (for example, ORDER BY key_part1,
  key_part2). If all key parts are followed by DESC, the key is read in
  reverse order.

In some cases, a query can be optimized to retrieve values without
  consulting the data rows. (An index that provides all the necessary
  results for a query is called a covering index.) If a query uses from
  a table only columns that are included in some index, the selected
  values can be retrieved from the index tree for greater speed:

SELECT key_part3 FROM tbl_name
  WHERE key_part1=1

I'm not at all able to understand these points and the respective code from the MySQL Documentation.

Someone please make the things easy in order to clarify the things to make me understand.

I am not asking what is Indexing and how does work, etc. etc.

I just want to understand what these sentences are trying to say and what's happening out there in the code?

What are key_par_N and what's the purpose of using them here?

What does actually mean by the term key part in this context?

What does mean by all key parts that occur before key_col in the index?

Where is the column key_col of which we are supposed to fine MIN() and MAX() values (See the first line : To find the MIN() or MAX() value for a specific indexed column key_col.)?

Someone please make me clear everything.

Note : I've already seen this question which is asking the same thing but it has received a generalized answer which is not specific to the explanation and code given in the manual. So, I'm asking this question to get precise and specific answer. So, please don't mark my question duplicate.

Body:
In SQL you can create an index in order to index multiple columns e.g., create index idx on t1 (key_colX, key_colY). Now key_part1 is key_colX and key_part2 is key_colY. The order is important!

Let´s say we use a bTree as an index structure, then elements are organized according to key_part1 first, if key_part1 of two elements is equal then according to key_part2. Now if you issue a query and set key_part1 = 10 to a (constant) value, the DB can quickly find the subtree of the bTree where key_part1 = 10. All elements in this subtree are organized according to key_part2 which makes a Min() or Max() very efficient.

If you try the query the other way

SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name WHERE key_part2=10;

then the index cannot be utilized.

So the above basically says you can answer queries more efficiently if your query can utilize the order of the indexed columns.


问:
How to get data passed from PUT method
I am creating an API for Laravel. I use the PUT method for updating data.

I send data with Postman using the PUT method. In my controller, I got an empty array. How to access the passed data?

In my route, I have:

```<code>Route::put('vehicletypes/{id}','API\VehicletypeController@update');
</code>```

In my controller:

```<code>public function update(Request $request, $id){

print_r($request->all()); exit;

}
</code>```

How to get the data passed in PUT method?

答:
You are getting empty response because PHP have some security restrictions against PUT. But Laravel have a workaround for this.

So, to solve this you have to send a POST request from Postman instead, with a POST param _method with value PUT. And that should work.

Title: How to get data passed from PUT method

Body:
I am creating an API for Laravel. I use the PUT method for updating data.

I send data with Postman using the PUT method. In my controller, I got an empty array. How to access the passed data?

In my route, I have:

Route::put('vehicletypes/{id}','API\VehicletypeController@update');

In my controller:

public function update(Request $request, $id){

print_r($request->all()); exit;

}

How to get the data passed in PUT method?


问:
What is a Rust systest?
I sometimes see that a Rust crate has a folder called systest. I guess that the name stands for "system test", but I can't find any documentation of this.

My questions are:

What is the purpose of a systest? Just testing that a crate compiles fine, or also testing that some code in another crate runs fine?

What are the rules to follow when writing a systest? Is it just a crate in a folder called systest?

Why does the lib.rs in systest/src seem to always include a file all.rs generated from build.rs?

答:
systest is not a standard name used in Rust or Cargo. However, it is the name suggested by the documentation for ctest, which performs automated testing for FFI bindings. build.rs uses ctest to generate the all.rs file which contains the tests, and this is included from the main file.

According to the documentation, the tests generate include ensuring that all function signatures, constant values, struct layout/alignment, type size/alignment, etc., all match their C equivalent.

Title: What is a Rust systest?


问:
Mongo Aggregation Project add property to all in Array
Im using mongo 2.6 and as part of a aggregations pipeline I need to add a an object to all entries in an array. Since I use mongo 2.6 i cant use $addFields.

My data looks like:

```<code>{
"_id" : ObjectId("5a290637e4b08ddd7334e541"),
"placeName" : "Caspeco Mobile Order",
"created" : ISODate("2017-12-07T09:13:27.248Z"),
"currency" : "SEK",
"isCredit" : false,
"costCenter" : {
    "name" : "Test Restaurangen",
    "number" : "800"
},
"debitAccounts" : [
    {
        "name" : "CASH",
        "number" : "1915",
        "amount" : 189.0
    }
],
"creditAccounts" : [
    {
        "name" : "Mat",
        "number" : "3120",
        "amount" : 168.749984741211
    }
],
"taxAccounts" : [
    {
        "name" : "Moms 12%",
        "number" : "2621",
        "amount" : 20.2500076293945
    }
],
"credit" : false
</code>```

}

And as first step in aggregations I need to add the costCenter object to all potential creditAccounts

Doing something like:

```<code>{$project: {'creditAccounts'{'costCentre':'$costCenter.name','costCentreAccount':'$costCenter.number','name':'$creditAccounts.name','number':'$creditAccounts.number','amount':'$creditAccounts.amount'}, document: '$$ROOT'}}
</code>```

Doent work since it generates a array of names and numbers...

答:
Found the solution to be $map:

```<code>creditAccounts:{$map:{input:'$creditAccounts', as:'creditAcccount', in : {name:'$$creditAcccount.name',number:'$$creditAcccount.name',amount:'$$creditAcccount.amount', costCentre:'$costCenter.name',costCentreAccount:'$costCenter.number'}}}
</code>```

Even though its really ugly.

Body:
Im using mongo 2.6 and as part of a aggregations pipeline I need to add a an object to all entries in an array. Since I use mongo 2.6 i cant use $addFields.

My data looks like:

{
"_id" : ObjectId("5a290637e4b08ddd7334e541"),
"placeName" : "Caspeco Mobile Order",
"created" : ISODate("2017-12-07T09:13:27.248Z"),
"currency" : "SEK",
"isCredit" : false,
"costCenter" : {
    "name" : "Test Restaurangen",
    "number" : "800"
},
"debitAccounts" : [
    {
        "name" : "CASH",
        "number" : "1915",
        "amount" : 189.0
    }
],
"creditAccounts" : [
    {
        "name" : "Mat",
        "number" : "3120",
        "amount" : 168.749984741211
    }
],
"taxAccounts" : [
    {
        "name" : "Moms 12%",
        "number" : "2621",
        "amount" : 20.2500076293945
    }
],
"credit" : false

}

And as first step in aggregations I need to add the costCenter object to all potential creditAccounts

Doing something like:

{$project: {'creditAccounts'{'costCentre':'$costCenter.name','costCentreAccount':'$costCenter.number','name':'$creditAccounts.name','number':'$creditAccounts.number','amount':'$creditAccounts.amount'}, document: '$$ROOT'}}

Doent work since it generates a array of names and numbers...

Body:
Found the solution to be $map:

creditAccounts:{$map:{input:'$creditAccounts', as:'creditAcccount', in : {name:'$$creditAcccount.name',number:'$$creditAcccount.name',amount:'$$creditAcccount.amount', costCentre:'$costCenter.name',costCentreAccount:'$costCenter.number'}}}

Even though its really ugly.


问:
Reorder control isn't displayed on table view
I created an iOS application based on navigation-based application template, the application is backed by Core Data framework.

When clicking on Edit button, I want the rows to be reorder-able and delete-able.

When constructing cells, I added this line:

```<code>cell.showsReorderControl = YES;
</code>```

And tableView:canMoveRowAtIndexPath: method returns YES.

But the reorder control isn't displayed in the row, Am I missing something?

答:
The UITableView also has to be in editing mode, which it's not in by default. Usually you use a button or some other control to toggle between editing mode. To put the table view in editing mode (we assume you have a UITableViewController and your tableView property is properly set, if not, adjust for your environment):</p>

```<code>// This line somewhere inside the UITableViewController will
// animate in the various editing controls and make sure they
// show up on your table.
[[self tableView] setEditing:YES animated:YES];
</code>```

Body:
I created an iOS application based on navigation-based application template, the application is backed by Core Data framework.

When clicking on Edit button, I want the rows to be reorder-able and delete-able.

When constructing cells, I added this line:

cell.showsReorderControl = YES;

And tableView:canMoveRowAtIndexPath: method returns YES.

But the reorder control isn't displayed in the row, Am I missing something?

Body:
The UITableView also has to be in editing mode, which it's not in by default. Usually you use a button or some other control to toggle between editing mode. To put the table view in editing mode (we assume you have a UITableViewController and your tableView property is properly set, if not, adjust for your environment):

// This line somewhere inside the UITableViewController will
// animate in the various editing controls and make sure they
// show up on your table.
[[self tableView] setEditing:YES animated:YES];


问:
Contact phone numbers Lync SDK 2013
Hello                                                                               I'm using Lync SDK 2013, to display number phones from contact in ListBox, and use the Items (phone number) to call this number by my API.                                So i did a WPF application, that contains just a ListBox, and 2 buttons (Call - Hang up). My apllication is added as custom command in Lync, in RightClick in the contact. and it doesn't have any Lync Controls. So what i want to do is: if i Right Click on the contact, my application launches and gives me the number phone List in the ListBox.                                                                I did it with a WPF that contains the controls: ContactSearchInputBox (to search a contact) and ContactSearchResultList and it works very Well, I don't know how to do it without controls.
Any One Can Help Me !!!! :(</p>

答:
```<code>public partial class ChoosePhoneNumber : Window
    {
        LyncClient lync_client;
        Contact contact;
        ContactSubscription contact_subscription;
        List<ContactInformationType> contact_information_list;
        ContactManager contact_manager;

        public ChoosePhoneNumber()
        {
            InitializeComponent();

            connect_lync();
            get_subscribed_contact(this.contact);
        }
    }
        private void connect_lync()
        {
            try
            {
                lync_client = LyncClient.GetClient();
                contact_manager = lync_client.ContactManager;
            }
            catch (ClientNotFoundException)
            {
                MessageBox.Show("Client is ot running", "Error While GetClient", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void get_subscribed_contact(Contact contact)
        {
            List<object> contact_phone_numbers_list = new List<object>();
            contact_information_list = new List<ContactInformationType>();
            contact_information_list.Add(ContactInformationType.ContactEndpoints);
            contact_information_list.Add(ContactInformationType.DisplayName);

            contact = contact_manager.GetContactByUri("number"); // I put here the number phone of a contact in my list
            contact_subscription = LyncClient.GetClient().ContactManager.CreateSubscription();
            contact_subscription.AddContact(contact);
            contact.ContactInformationChanged += Contact_ContactInformationChanged;
            contact_subscription.Subscribe(ContactSubscriptionRefreshRate.High, contact_information_list);

            List<object> endpoints = (List<object>)contact.GetContactInformation(ContactInformationType.ContactEndpoints);

            var phone_numbers_list = endpoints.Where<object>(N => ((ContactEndpoint)N).Type == ContactEndpointType.HomePhone ||
            ((ContactEndpoint)N).Type == ContactEndpointType.MobilePhone || ((ContactEndpoint)N).Type == ContactEndpointType.OtherPhone
            || ((ContactEndpoint)N).Type == ContactEndpointType.WorkPhone).ToList<object>();
            var name = contact.GetContactInformation(ContactInformationType.DisplayName);

            if (phone_numbers_list != null)
            {
                foreach (var phone_number in phone_numbers_list)
                {
                    contact_phone_numbers_list.Add(((ContactEndpoint)phone_number).DisplayName);
                }
                conboboxPhoneNumbers.ItemsSource = contact_phone_numbers_list;
            }
        }

        private void Contact_ContactInformationChanged(object sender, ContactInformationChangedEventArgs e)
        {
            var contact = (Contact)sender;
            if (e.ChangedContactInformation.Contains(ContactInformationType.ContactEndpoints))
            {
                update_endpoints(contact);
            }
        }

        private void update_endpoints(Contact contact)
        {
            if ((lync_client != null) && (lync_client.State == ClientState.SignedIn))
            {
                ContactEndpoint endpoints = (ContactEndpoint)contact.GetContactInformation(ContactInformationType.ContactEndpoints);
            }
        }
</code>```

Title: Contact phone numbers Lync SDK 2013


问:
Authentication of different types of user of same name in django?
I have a model of teacher and student . If I created a Student and again create a teacher with same name and email and stuffs, It gets created .. Can't be a teacher and student of same people in a college. How to apply in rest api? </p>

答:
There are several way to solve this, depending on your requirements and preference.

One way would be at database level with constraints. In this case you'd have to create model with all people regardless of their status and add additional boolean field that differentiates between Students and Teachers. This would look like this:

```<code>class People(models.Model):

    email = models.EmailField(unique=True)
    is_teacher = models.BooleanField()
</code>```

unique means that email must be unique throughout the table and if you try to add another person with the same email, IntegrityError will be raised.

There is also a possibility to use unique over several fields with unique_together like this.

```<code>class People(models.Model):

    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

    class Meta:
        unique_together = (('first_name', 'last_name'),)
</code>```

This means that first_name and last_name together must be unique.

Another approach would be to check if student or teacher is already in one or the other table before saving with filter() and exists().

```<code>teacher_exists = Teacher.objects.filter(teacher=something).exists()
student_exists = Teacher.objects.filter(student=something).exists()
</code>```

exists() returns True if the QuerySet contains any results, and False if not.

Body:
There are several way to solve this, depending on your requirements and preference.

One way would be at database level with constraints. In this case you'd have to create model with all people regardless of their status and add additional boolean field that differentiates between Students and Teachers. This would look like this:

class People(models.Model):

    email = models.EmailField(unique=True)
    is_teacher = models.BooleanField()

unique means that email must be unique throughout the table and if you try to add another person with the same email, IntegrityError will be raised.

There is also a possibility to use unique over several fields with unique_together like this.

class People(models.Model):

    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)

    class Meta:
        unique_together = (('first_name', 'last_name'),)

This means that first_name and last_name together must be unique.

Another approach would be to check if student or teacher is already in one or the other table before saving with filter() and exists().

teacher_exists = Teacher.objects.filter(teacher=something).exists()
student_exists = Teacher.objects.filter(student=something).exists()

exists() returns True if the QuerySet contains any results, and False if not.


问:
Check if string contains a 3 character long substring of another string
I need a regex pattern to check whether characters present in a string consecutively repeats 3 character in another string. Eg:

```<code>var string1 = "HelloWorld";
var string2 = "Work";
</code>```

Here the letters "Wor" in string1 repeats in string2, so it should return true.

Any help on this

答:
Code from https://www.garysieling.com/blog/javascript-function-find-overlap-two-strings:

function findOverlap(a, b) {
  if (b.length === 0) {
    return '';
  }

  if (a.endsWith(b)) {
    return b;
  }

  if (a.indexOf(b) >= 0) {
    return b;
  }

  return findOverlap(a, b.substring(0, b.length - 1));
}
```

<p>Some test cases:</p>

<pre class="lang-js prettyprint-override"><code>findOverlap("12345", "aaa") // ""
findOverlap("12345", "12") // "12"
findOverlap("12345", "345") // "345"
findOverlap("12345", "3456") // "345"
findOverlap("12345", "111") // "1"
</code>```

To solve your particular problem you could:

const haveOverlap = (string1, string2) => findOverlap(string1, string2).length >= 3;
console.log(haveOverlap('HelloWorld', 'Work')); // true
```

Body:
I need a regex pattern to check whether characters present in a string consecutively repeats 3 character in another string. Eg:

var string1 = "HelloWorld";
var string2 = "Work";

Here the letters "Wor" in string1 repeats in string2, so it should return true.

Any help on this

Body:
Code from https://www.garysieling.com/blog/javascript-function-find-overlap-two-strings:

function findOverlap(a, b) {
  if (b.length === 0) {
    return '';
  }

  if (a.endsWith(b)) {
    return b;
  }

  if (a.indexOf(b) >= 0) {
    return b;
  }

  return findOverlap(a, b.substring(0, b.length - 1));
}

Some test cases:

findOverlap("12345", "aaa") // ""
findOverlap("12345", "12") // "12"
findOverlap("12345", "345") // "345"
findOverlap("12345", "3456") // "345"
findOverlap("12345", "111") // "1"

To solve your particular problem you could:

const haveOverlap = (string1, string2) => findOverlap(string1, string2).length >= 3;
console.log(haveOverlap('HelloWorld', 'Work')); // true


问:
Showing more text with jquery
I am looking for a way to show more or less text. I want to show 600 characters by default and if show more is clicked it will show 600 more characters and then if clicked again shows 600 more until there are no more characters. I also would like a show less button to collapse the text back to its default 600 characters. I have pages with 5000+ words and this would make reading much easier and make it look nicer. Right now I am using this to show the first 600 chars and when show more is clicked it expands all the way.

```<code>$(document).ready(function() {
var showChar = 600;
var ellipsestext = "...";
var moretext = "View more";
var lesstext = "View less";
$('.more').each(function() {
    var content = $(this).html();

    if(content.length > showChar) {

        var c = content.substr(0, showChar);
        var h = content.substr(showChar-1, content.length - showChar);

        var html = c + '<span class="moreelipses">'+ellipsestext+'</span> <span class="morecontent"><span>' + h + '  </span><a rel="nofollow" href="" class="morelink">'+moretext+'</a></span>';

        $(this).html(html);
    }

});

$(".morelink").click(function(){
    if($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
});
});
</code>```

Could somebody please edit this code to work like this or help me to achieve this any other way? I would really like to make my pages more presentable and readable and this would definitely do the trick. Thanks.

答:
I knocked up the following code to show you how to elicit information from the viewer concerning the number of lines:

The HTML:

```<code><div style="height: 6em; overflow: auto; line-height: 1.5em">
    <p> Number of lines to display  (optional) <input type="text" value="4" style="width: 3em"><button type="button" class="scrollLength">change</button></p>
    <p>
        This is a huge load of text<br>
        line 2<br>
        line 3<br>
        line 4<br>
        ...etc....
    </p>
</div>
</code>```

The jQuery code:

```<code>$('button.scrollLength').each(function(){
    var $this = $(this);
    $this.click(
        function(){
            var myParent      = $this.parent();
            var numberOfLines = myParent.children('input').attr('value');
            var displayArea    = myParent.parent();
            if (numberOfLines > 0) {
                var lineHeight  = displayArea.css('lineHeight');
                var heightUnits = lineHeight.replace(/[0-9]./g, '');
                displayArea.css({height: (numberOfLines * parseFloat(lineHeight)) + heightUnits});
            }
        }
    );
});
</code>```

Regards
      Neil

Title: Showing more text with jquery

Body:
I am looking for a way to show more or less text. I want to show 600 characters by default and if show more is clicked it will show 600 more characters and then if clicked again shows 600 more until there are no more characters. I also would like a show less button to collapse the text back to its default 600 characters. I have pages with 5000+ words and this would make reading much easier and make it look nicer. Right now I am using this to show the first 600 chars and when show more is clicked it expands all the way.

$(document).ready(function() {
var showChar = 600;
var ellipsestext = "...";
var moretext = "View more";
var lesstext = "View less";
$('.more').each(function() {
    var content = $(this).html();

    if(content.length > showChar) {

        var c = content.substr(0, showChar);
        var h = content.substr(showChar-1, content.length - showChar);

        var html = c + ''+ellipsestext+' ' + h + '  '+moretext+'';

        $(this).html(html);
    }

});

$(".morelink").click(function(){
    if($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
});
});

Could somebody please edit this code to work like this or help me to achieve this any other way? I would really like to make my pages more presentable and readable and this would definitely do the trick. Thanks.

Body:
I knocked up the following code to show you how to elicit information from the viewer concerning the number of lines:

The HTML:

<div style="height: 6em; overflow: auto; line-height: 1.5em">
    <p> Number of lines to display  (optional) <input type="text" value="4" style="width: 3em"><button type="button" class="scrollLength">change</button></p>
    <p>
        This is a huge load of text<br>
        line 2<br>
        line 3<br>
        line 4<br>
        ...etc....
    </p>
</div>

The jQuery code:

$('button.scrollLength').each(function(){
    var $this = $(this);
    $this.click(
        function(){
            var myParent      = $this.parent();
            var numberOfLines = myParent.children('input').attr('value');
            var displayArea    = myParent.parent();
            if (numberOfLines > 0) {
                var lineHeight  = displayArea.css('lineHeight');
                var heightUnits = lineHeight.replace(/[0-9]./g, '');
                displayArea.css({height: (numberOfLines * parseFloat(lineHeight)) + heightUnits});
            }
        }
    );
});

Regards
      Neil


问:
Should Private/Protected methods be under unit test?
In TDD development, the first thing you typically do is to create your interface and then begin writing your unit tests against that interface. As you progress through the TDD process you would end-up creating a class that implements the interface and then at some point your unit test would pass.

Now my question is about the private and protected methods that I might have to write in my class in support of the methods/properties exposed by the interface:

Should the private methods in the class have their own unit tests?

Should the protected methods in the class have their own unit tests?

My thoughts:

Especially because I am coding to interfaces, I shouldn't worry about protected/private methods as they are black boxes.

Because I am using interfaces, I am writing unit tests to validate that the contract defined is properly implemented by the different classes implementing the interface, so again I shouldnt worry about the private/protected methods and they should be exercised via unit tests that call the methods/properties defined by the interface.

If my code-coverage does not show that the protected/private methods are being hit, then I don't have the right unit-tests or I have code thats not being used and should be removed.

答:
A good design means splitting the application into multiple testable units. After doing this, some units are exposed to the public API, but some others may not be. Also, the interaction points between exposed units and these "internal" units are also not a part of the pubic API.

I think once we have the identifiable unit, is would benefit from the unit tests, regardless if exposed via public API or not.


问:
Gradle flyway script to update multiple databases
I have a Gradle script which uses the flyway plugin to create some database tables, and now I need to update the script so that it can work with 2 separate sets of flyway scripts, each of which updates a separate database.

In the single-database version of the script I simply do this:

```<code>flyway {
    url = 'jdbc:edb://localhost:5432/mydb'
    schemas = ['my_schema']
    user = 'my_user'
    password = 'my_pass'
    locations = ['filesystem:src/main/resources/db/flyway/my_db']
}
</code>```

I've been experimenting with declaring a new task to run the scripts for the second db:

```<code>task flywayMigrate2 << {
    ext {
        flyway {
            url = 'jdbc:edb://localhost:5432/mydb2'
            schemas = ['my_schema2']
            user = 'my_user2'
            password = 'my_pass2'
            locations = ['filesystem:src/main/resources/db/flyway/my_db2']
        }
    }
}

flywayMigrate2.finalizedBy flywayMigrate
</code>```

My Gradle skills are poor, but I know this isn't the right way to do it - my understanding is that the ext block overwrites the original flyway configuration, so if I wanted to run flywayMigrate after flywayMigrate2 it would continue to use the second set of config values rather than reverting to the original set.

I can't be the first person to need to do this, but I'm struggling to find a decent approach, can anyone help?

答:
The flyway { ... } extension object is for configuring properties which are common to all flyway tasks. Each task also has properties which can be configured, my guess is that task level properties override properties configured on the flyway { ... } extension object.

I think you'd just configure two FlywayMigrateTask instances in your build.gradle

```<code>import org.flywaydb.gradle.task.*

task migrate1(type: FlywayMigrateTask) {
    url = 'jdbc:edb://localhost:5432/mydb1'
    user = 'user1'
    locations = ['filesystem:src/main/flyway/db1/migration']
    // etc
}

task migrate2(type: FlywayMigrateTask) {
    url = 'jdbc:edb://localhost:5432/mydb2'
    user = 'user2'
    locations = ['filesystem:src/main/flyway/db2/migration']
    // etc
}
</code>```

See also AbstractFlywayTask.java

Body:
I have a Gradle script which uses the flyway plugin to create some database tables, and now I need to update the script so that it can work with 2 separate sets of flyway scripts, each of which updates a separate database.

In the single-database version of the script I simply do this:

flyway {
    url = 'jdbc:edb://localhost:5432/mydb'
    schemas = ['my_schema']
    user = 'my_user'
    password = 'my_pass'
    locations = ['filesystem:src/main/resources/db/flyway/my_db']
}

I've been experimenting with declaring a new task to run the scripts for the second db:

task flywayMigrate2 << {
    ext {
        flyway {
            url = 'jdbc:edb://localhost:5432/mydb2'
            schemas = ['my_schema2']
            user = 'my_user2'
            password = 'my_pass2'
            locations = ['filesystem:src/main/resources/db/flyway/my_db2']
        }
    }
}

flywayMigrate2.finalizedBy flywayMigrate

My Gradle skills are poor, but I know this isn't the right way to do it - my understanding is that the ext block overwrites the original flyway configuration, so if I wanted to run flywayMigrate after flywayMigrate2 it would continue to use the second set of config values rather than reverting to the original set.

I can't be the first person to need to do this, but I'm struggling to find a decent approach, can anyone help?

Body:
The flyway { ... } extension object is for configuring properties which are common to all flyway tasks. Each task also has properties which can be configured, my guess is that task level properties override properties configured on the flyway { ... } extension object.

I think you'd just configure two FlywayMigrateTask instances in your build.gradle

import org.flywaydb.gradle.task.*

task migrate1(type: FlywayMigrateTask) {
    url = 'jdbc:edb://localhost:5432/mydb1'
    user = 'user1'
    locations = ['filesystem:src/main/flyway/db1/migration']
    // etc
}

task migrate2(type: FlywayMigrateTask) {
    url = 'jdbc:edb://localhost:5432/mydb2'
    user = 'user2'
    locations = ['filesystem:src/main/flyway/db2/migration']
    // etc
}

See also AbstractFlywayTask.java


问:
Find position of MenuItem dynamically
I have a menu with all items' showAsAction set to ifRoom. Now I want to get the exact position (x,y) of the center of any of these menu items.

I first thought of getting this information from the underlying views, but I don't know how to reliably access the view of a specific menu item.

In onCreateOptionsMenu:

```<code>MenuItem someItem = menu.findItem(R.id.some_action);
// someItem.getX();
// someItem.getY();
</code>```

I'd expect these coordinates to be relative to the application's Toolbar. In this case I also need access to someItem.get{Width,Height}() to calculate the center coordinates.

An example menu:

```<code><menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_search"
    android:title="@string/action_search"
    android:icon="@drawable/ic_search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="ifRoom|collapseActionView" />

<item
    android:id="@+id/action_example"
    android:title="@string/action_example"
    android:icon="@drawable/ic_example"
    app:showAsAction="ifRoom" />

</menu>
</code>```

答:
The solution is to use the underlying activity to find the instanciated view.

```<code>View menuItemView = getActivity().findViewById(R.id.action_search);
</code>```

Then the position can be extracted relative to the toolbar by using View.getLocationInWindow(intArr), which returns (x,y) relative to the view's window.

```<code>int[] itemWindowLocation = new int[2];
menuItemView.getLocationInWindow(itemWindowLocation);

int[] toolbarWindowLocation = new int[2];
toolbar.getLocationInWindow(toolbarWindowLocation);

int itemX = itemWindowLocation[0] - toolbarWindowLocation[0];
int itemY = itemWindowLocation[1] - toolbarWindowLocation[1];
int centerX = itemX + menuItemView.getWidth() / 2;
int centerY = itemY + menuItemView.getHeight() / 2;
</code>```

Title: Find position of MenuItem dynamically

Body:
I have a menu with all items' showAsAction set to ifRoom. Now I want to get the exact position (x,y) of the center of any of these menu items.

I first thought of getting this information from the underlying views, but I don't know how to reliably access the view of a specific menu item.

In onCreateOptionsMenu:

MenuItem someItem = menu.findItem(R.id.some_action);
// someItem.getX();
// someItem.getY();

I'd expect these coordinates to be relative to the application's Toolbar. In this case I also need access to someItem.get{Width,Height}() to calculate the center coordinates.

An example menu:

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_search"
    android:title="@string/action_search"
    android:icon="@drawable/ic_search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="ifRoom|collapseActionView" />

<item
    android:id="@+id/action_example"
    android:title="@string/action_example"
    android:icon="@drawable/ic_example"
    app:showAsAction="ifRoom" />

</menu>

Body:
The solution is to use the underlying activity to find the instanciated view.

View menuItemView = getActivity().findViewById(R.id.action_search);

Then the position can be extracted relative to the toolbar by using View.getLocationInWindow(intArr), which returns (x,y) relative to the view's window.

int[] itemWindowLocation = new int[2];
menuItemView.getLocationInWindow(itemWindowLocation);

int[] toolbarWindowLocation = new int[2];
toolbar.getLocationInWindow(toolbarWindowLocation);

int itemX = itemWindowLocation[0] - toolbarWindowLocation[0];
int itemY = itemWindowLocation[1] - toolbarWindowLocation[1];
int centerX = itemX + menuItemView.getWidth() / 2;
int centerY = itemY + menuItemView.getHeight() / 2;


问:
looping through an array backwards from current position
I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.

What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?

Question Class

```<code>// This file contains questions from QuestionBank
class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}
</code>```

Main Activity.java

```<code>     public class MainActivityextends AppCompatActivity {
                private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
                private int mQuestionNumber = 1; // current question number
            //initialising navigation buttons
                private Button mPrevious;
                private Button mNext;
            private TextView mQuestionText;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_beginner_review);
                    mPrevious = (Button) findViewById(R.id.previous);
                    mNext = (Button) findViewById(R.id.next);
  mQuestionText = (TextView) findViewById(R.id.txtQuestion);
                    // receive the current question number from last activity by Intent

        Intent intent = getIntent();
             currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
                    mNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
    // checking against total number of questions the user has attempted instead of total number of questions from Question Class
    if (mQuestionNumber < currentQuestionNumber) {
             updateQuestion();
                        }
                    });
                    mPrevious.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
            // i want it to loop backwards from here
                        }
                    });

            // logic to update question from array
                private void updateQuestion() {
                    if (mQuestionNumber < mQuestionLibrary.getLength()) {
                        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
                        mQuestionNumber++;
                    }
                }

            }
</code>```

答:
Here's a solution accounting for bounds</p>

```<code>mNext.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View view) {
        showNextQuestion();
    }
});
mPrevious.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View view) {
        showPreviousQuestion();
    }
});

private void showNextQuestion() {
    showQuestion(1);
}

private void showPreviousQuestion() {
    showQuestion(-1);
}

private void showQuestion(int increment) {
    int newQuestionNumber = mQuestionNumber + increment;
    if (newQuestionNumber >= 0 && newQuestionNumber < mQuestionLibrary.getLength()) {
        mQuestionNumber = newQuestionNumber;
        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
    }
}
</code>```

Body:
I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.

What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?

Question Class

// This file contains questions from QuestionBank
class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}

Main Activity.java

     public class MainActivityextends AppCompatActivity {
                private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
                private int mQuestionNumber = 1; // current question number
            //initialising navigation buttons
                private Button mPrevious;
                private Button mNext;
            private TextView mQuestionText;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_beginner_review);
                    mPrevious = (Button) findViewById(R.id.previous);
                    mNext = (Button) findViewById(R.id.next);
  mQuestionText = (TextView) findViewById(R.id.txtQuestion);
                    // receive the current question number from last activity by Intent

        Intent intent = getIntent();
             currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
                    mNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
    // checking against total number of questions the user has attempted instead of total number of questions from Question Class
    if (mQuestionNumber < currentQuestionNumber) {
             updateQuestion();
                        }
                    });
                    mPrevious.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
            // i want it to loop backwards from here
                        }
                    });

            // logic to update question from array
                private void updateQuestion() {
                    if (mQuestionNumber < mQuestionLibrary.getLength()) {
                        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
                        mQuestionNumber++;
                    }
                }

            }

Body:
Here's a solution accounting for bounds

mNext.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View view) {
        showNextQuestion();
    }
});
mPrevious.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(final View view) {
        showPreviousQuestion();
    }
});

private void showNextQuestion() {
    showQuestion(1);
}

private void showPreviousQuestion() {
    showQuestion(-1);
}

private void showQuestion(int increment) {
    int newQuestionNumber = mQuestionNumber + increment;
    if (newQuestionNumber >= 0 && newQuestionNumber < mQuestionLibrary.getLength()) {
        mQuestionNumber = newQuestionNumber;
        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
    }
}


问:
App size increased in Release build compared to debug build
In all my previous projects debug build always bigger & release build smaller.

But strange issue occur for me.
When I build the debug APK it have 1085KB

If I build the release APK it have 2432KB

Any one give me solution for this issue.

My dependencies in build.gradle :

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "ranjih.kotlinandroid"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 5
        versionName "1.3"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-config:10.2.1'
    compile 'com.google.firebase:firebase-messaging:10.2.1'
    compile 'com.google.android.gms:play-services-ads:10.2.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true;
    }
    testCompile 'junit:junit:4.12'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile project(path: ':lib')
}

apply plugin: 'com.google.gms.google-services'
repositories {
    maven {
        url "https://jitpack.io"
    }
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
}

apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}
buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        // These docs use an open ended version so that our plugin
        // can be updated quickly in response to Android tooling updates

        // We recommend changing it to the latest version from our changelog:
        // https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
</code>```

答:
In case of a large png files existed try to use next:</p>

```<code>android {
    …
    buildTypes {
        release {
            crunchPngs true // or false
        }
    }
}
</code>```

Body:
In all my previous projects debug build always bigger & release build smaller.

But strange issue occur for me.
When I build the debug APK it have 1085KB

If I build the release APK it have 2432KB

Any one give me solution for this issue.

My dependencies in build.gradle :

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "ranjih.kotlinandroid"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 5
        versionName "1.3"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-config:10.2.1'
    compile 'com.google.firebase:firebase-messaging:10.2.1'
    compile 'com.google.android.gms:play-services-ads:10.2.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true;
    }
    testCompile 'junit:junit:4.12'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile project(path: ':lib')
}

apply plugin: 'com.google.gms.google-services'
repositories {
    maven {
        url "https://jitpack.io"
    }
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
}

apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}
buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        // These docs use an open ended version so that our plugin
        // can be updated quickly in response to Android tooling updates

        // We recommend changing it to the latest version from our changelog:
        // https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
        classpath 'io.fabric.tools:gradle:1.+'
    }
}

Body:
In case of a large png files existed try to use next:

android {
    …
    buildTypes {
        release {
            crunchPngs true // or false
        }
    }
}


问:
Git clone "fatal: I don't handle protocol 'ssh'"
I've created a repository in my local machine and asked a colleague to clone it, but it's saying it can't handle the SSH protocol. In my computer the repository is at /devel/scripts.git, and there's an user called devel with access to that folder. Another guy could clone it normally, using git clone ssh://devel@192.168.0.7/devel/scripts.git.

We are all using Ubuntu, me and the problematic machine are at 12.04 (I could push from another folder using the same URL as remote) and the other guy is using 13.04.

Finally, the machine that got the issue can access that user via SSH normally.

答: I had similar issue when trying from windows Git GUI. I executed the command via Git Bash and it worked for me without this error.


问:
git pre-commit hook file
I tried to add the pre-commit hook file gitlab server side. I know pre-commit hook is client side hook. I just want to add the pre-commit hook file in all the project's .git/hooks folder.

What I tried:-
I edited all the pre-commit.sample file in my gitlab server machine and created the new project. But I did not found that edited sample hook file in my local (windows) after cloned the repo.

Is there any way to add the pre-commit hook in all the project's git folder by server side? Because we have more than 500 projects.

答:
You can't do that, from the documentation at https://git-scm.com/book/gr/v2/Customizing-Git-Git-Hooks

It’s important to note that client-side hooks are not copied when you clone a repository. If your intent with these scripts is to enforce a policy, you’ll probably want to do that on the server side

Title: git pre-commit hook file