问:
Multiple XML format from SQL Server single table
```<code>SELECT
    consent_type, state_code,
    suburb, sex_code, postcode,
    CarerPrimary, CarerResidence, CarerRelationship,
    service_type_outlet_codeno,
    last_service_date, service_hours,
    to_date, from_date
FROM
    TABLEX
</code>```

How can I get the following XML format from this single table? Most confusing is  CarerPrimary, CarerResidence, CarerRelationship part. This table contains information of multiple clients, so service_user part would appear once for each client. Thanks.

```<code><agency>
    <service_user consent_type="1" state_code="2" suburb="Croydon" sex_code="1" postcode="3136">
        <service_user_response value="1" question_fieldname="CarerPrimary"/>
        <service_user_response value="1" question_fieldname="CarerResidence"/>
        <service_user_response value="9" question_fieldname="CarerRelationship"/>
        <service_user_outlet service_type_outlet_codeno="8376784"  last_service_date="02/9/2016" >
            <service_hours service_hours="240" to_date="15/8/2016" from_date="09/8/2016"/>
            <service_hours service_hours="90" to_date="02/9/2016" from_date="02/9/2016"/>
        </service_user_outlet>
    </service_user>
    <service_user .... >
    </service_user>
</agency>
</code>```

New Code,

```<code>SELECT PostalCode AS [@Postcode]
      ,IIF (HC.HasCarer = 'true', 'Y', 'N') as [@has_carer_type]
      ,convert(date, [BirthDate], 111) AS [@BirthDate]
      ,'N' as [@birth_date_est_ind]
      ,IIF (new_gender = 6, 3, new_gender) AS [@sex_code]
      --SLK
      ,City AS [@Suburb]
      ,DEX.[dbo].[CRM2DEX]('State',[new_Address1State], 0) AS [@StateCode]
      ,'Y' as [@consent_type]

      --,CONCAT ([FirstName], ' ' + [MiddleName]) AS GivenName
   --   ,[LastName] AS FamilyName
   --   ,cb.new_ClientID AS ClientId

      /********service_user_response*******/
      ,HC.CarerPrimary AS [service_user_response/@value]
      ,'CarerPrimary' AS [service_user_response/@question_fieldname]
      ,HC.CarerResidence AS [service_user_response/@value]
      ,'CarerResidence' AS [service_user_response/@question_fieldname]
      ,dex.dbo.CRM2QDC('Relationship', default, HC.new_Relationship) AS [service_user_response/@value]
      ,'CarerRelationship' AS [service_user_response/@question_fieldname]
      --,IIF (new_CarerAgeGroup IS NULL, 99, new_CarerAgeGroup) AS CarerAgeGroup
      ,IIF (new_indigenoustatus = 9, NULL, new_indigenoustatus) AS [service_user_response/@value]
      ,'IndigenousStatus' AS [service_user_response/@question_fieldname]
      ,COALESCE (Country.[new_Code], '0003') AS [service_user_response/@value]
      ,'BirthCountry' AS [service_user_response/@question_fieldname]
      ,COALESCE (Lang.[new_Code], '0002') AS [service_user_response/@value]
      ,'Language' AS [service_user_response/@question_fieldname]
      ,new_interpreter AS [service_user_response/@value]
      ,'InterpreterServices' AS [service_user_response/@question_fieldname]
      ,new_communicationmethod AS [service_user_response/@value]
      ,'CommunicationMethod' AS [service_user_response/@question_fieldname]
      ,IIF (cb.new_livingarrangements = 9, 99, cb.new_livingarrangements) AS [service_user_response/@value]
      ,'LivingArrangements' AS [service_user_response/@question_fieldname]
      ,cb.new_residentialsetting AS [service_user_response/@value]
      ,'ResidentialSetting' AS [service_user_response/@question_fieldname]
      ,new_employmentstatus AS [service_user_response/@value]
      ,'LabourForceStatus' AS  [service_user_response/@question_fieldname]
      ,IIF (new_primaryincomesource = 7, 97, new_primaryincomesource) AS [service_user_response/@value]
      ,'IncomeSource' AS  [service_user_response/@question_fieldname]
      --,(SELECT IIF (Disability IS NULL, 'false', 'true') from HasDisablity where ClientID = CB.ContactId) AS HasDisabilities

      --,IIF (new_client is NULL, NULL, (select coalesce (new_name, null) FROM Health AS D where D.new_contact = CB.ContactId for xml path ('DisabilityCode'), type)) AS Disabilities
      --,(SELECT IIF (new_name IS NULL, NULL, (select H2.new_name from Health AS H2 where H2.new_contact = CB.ContactId
      --  for xml path ('DisabilityCode'), type)) FROM Health AS D where D.new_contact = CB.ContactId) AS Disabilities
--    ,DEX.[dbo].[CRM2DEX]('AccommodationType',C.new_residentialsetting, 0) AS AccommodationTypeCode
--    ,DEX.[dbo].[CRM2DEX]('DVACardStatus',[new_DVAentitlement], 0) AS DVACardStatusCode
      --,COALESCE (HasCarer, 'false') AS HasCarer

--    ,DEX.[dbo].[CRM2DEX]('HouseholdComposition', C.new_livingarrangements, 0) AS HouseholdCompositionCode

  FROM [FOCUSCRM_MSCRM].[dbo].[ContactBase] AS CB
  INNER JOIN
      (SELECT [ParentId]
             ,[Line1]
             ,[Line2]
             ,[City]
             ,[PostalCode]
      FROM [FOCUSCRM_MSCRM].[dbo].[CustomerAddressBase]
      WHERE addressNumber = 1 ) AS A ON CB.ContactId = A.ParentId

  LEFT OUTER JOIN
      (SELECT [new_countryId]
             ,[new_name]
             ,[new_Code]
      FROM [FOCUSCRM_MSCRM].[dbo].[new_countryBase]) AS Country ON CB.new_CountryofBirth = Country.new_countryId

  LEFT OUTER JOIN
      (SELECT [new_languageId]
             ,[new_name]
             ,[new_Code]
      FROM [FOCUSCRM_MSCRM].[dbo].[new_languageBase]) AS Lang ON CB.new_PreferredLanguage = Lang.new_languageId

  LEFT OUTER JOIN
      (SELECT new_ClientName, new_livingarrangements, new_residentialsetting
        FROM (
        SELECT [new_ClientName]
        ,row_number() over (Partition by new_ClientName ORDER BY ModifiedOn DESC) AS R
        ,new_AssessmentDate
        ,new_livingarrangements
        ,new_residentialsetting

        FROM [FOCUSCRM_MSCRM].[dbo].[new_assessmentBase] AS AB1
        WHERE statecode = 0
          ) AS T1

      WHERE R = 1) AS C ON CB.ContactId = C.new_ClientName

  LEFT OUTER JOIN HasCarer AS HC ON HC.new_clientname = cb.contactID

      WHERE CB.new_clientID IN (SELECT DISTINCT new_clientID from TS)
  and statecode = 0

  --) AS T GROUP BY ClientID having count(ClientId)>1

 FOR XML PATH('service_user'),ROOT('agency');
</code>```

答:
Without sample data it is a blind flight, but you might try something like this:

```<code>SELECT
    consent_type AS [@constent_type]
  , state_code AS [@state_code]
  , suburb AS [@suburb]
  , sex_code AS [@sex_code]
  , postcode AS [@postcode]
  , CarerPrimary AS [service_user_response/@value]
  ,'CarerPrimary' AS [service_user_response/@question_fieldname]
  , CarerResidence AS [service_user_response/@value]
  ,'CarerResidence' AS [service_user_response/@question_fieldname]
  , CarerRelationship AS [service_user_response/@value]
  ,'CarerRelationship' AS [service_user_response/@question_fieldname]
  , service_type_outlet_codeno AS [service_user_outlet/@service_type_outlet_codeno]
  , last_service_date AS [service_user_outlet/@last_service_date]
  , service_hours AS [service_user_outlet/service_hours/@service_hours]
  , to_date AS [service_user_outlet/service_hours/@to_date]
  , from_date AS [service_user_outlet/service_hours/@from_date]
FROM
    TABLEX
FOR XML PATH('service_user'),ROOT('agency');
</code>```

FOR XML PATH allows to define the XPath as column alias. attributes are marked with a @ sign.

The service_hours in your example look as if they were 1:n, but the query does not look as such.

Body:
SELECT
    consent_type, state_code,
    suburb, sex_code, postcode,
    CarerPrimary, CarerResidence, CarerRelationship,
    service_type_outlet_codeno,
    last_service_date, service_hours,
    to_date, from_date
FROM
    TABLEX

How can I get the following XML format from this single table? Most confusing is  CarerPrimary, CarerResidence, CarerRelationship part. This table contains information of multiple clients, so service_user part would appear once for each client. Thanks.

<agency>
    <service_user consent_type="1" state_code="2" suburb="Croydon" sex_code="1" postcode="3136">
        <service_user_response value="1" question_fieldname="CarerPrimary"/>
        <service_user_response value="1" question_fieldname="CarerResidence"/>
        <service_user_response value="9" question_fieldname="CarerRelationship"/>
        <service_user_outlet service_type_outlet_codeno="8376784"  last_service_date="02/9/2016" >
            <service_hours service_hours="240" to_date="15/8/2016" from_date="09/8/2016"/>
            <service_hours service_hours="90" to_date="02/9/2016" from_date="02/9/2016"/>
        </service_user_outlet>
    </service_user>
    <service_user .... >
    </service_user>
</agency>

New Code,

SELECT PostalCode AS [@Postcode]
      ,IIF (HC.HasCarer = 'true', 'Y', 'N') as [@has_carer_type]
      ,convert(date, [BirthDate], 111) AS [@BirthDate]
      ,'N' as [@birth_date_est_ind]
      ,IIF (new_gender = 6, 3, new_gender) AS [@sex_code]
      --SLK
      ,City AS [@Suburb]
      ,DEX.[dbo].[CRM2DEX]('State',[new_Address1State], 0) AS [@StateCode]
      ,'Y' as [@consent_type]

      --,CONCAT ([FirstName], ' ' + [MiddleName]) AS GivenName
   --   ,[LastName] AS FamilyName
   --   ,cb.new_ClientID AS ClientId

      /********service_user_response*******/
      ,HC.CarerPrimary AS [service_user_response/@value]
      ,'CarerPrimary' AS [service_user_response/@question_fieldname]
      ,HC.CarerResidence AS [service_user_response/@value]
      ,'CarerResidence' AS [service_user_response/@question_fieldname]
      ,dex.dbo.CRM2QDC('Relationship', default, HC.new_Relationship) AS [service_user_response/@value]
      ,'CarerRelationship' AS [service_user_response/@question_fieldname]
      --,IIF (new_CarerAgeGroup IS NULL, 99, new_CarerAgeGroup) AS CarerAgeGroup
      ,IIF (new_indigenoustatus = 9, NULL, new_indigenoustatus) AS [service_user_response/@value]
      ,'IndigenousStatus' AS [service_user_response/@question_fieldname]
      ,COALESCE (Country.[new_Code], '0003') AS [service_user_response/@value]
      ,'BirthCountry' AS [service_user_response/@question_fieldname]
      ,COALESCE (Lang.[new_Code], '0002') AS [service_user_response/@value]
      ,'Language' AS [service_user_response/@question_fieldname]
      ,new_interpreter AS [service_user_response/@value]
      ,'InterpreterServices' AS [service_user_response/@question_fieldname]
      ,new_communicationmethod AS [service_user_response/@value]
      ,'CommunicationMethod' AS [service_user_response/@question_fieldname]
      ,IIF (cb.new_livingarrangements = 9, 99, cb.new_livingarrangements) AS [service_user_response/@value]
      ,'LivingArrangements' AS [service_user_response/@question_fieldname]
      ,cb.new_residentialsetting AS [service_user_response/@value]
      ,'ResidentialSetting' AS [service_user_response/@question_fieldname]
      ,new_employmentstatus AS [service_user_response/@value]
      ,'LabourForceStatus' AS  [service_user_response/@question_fieldname]
      ,IIF (new_primaryincomesource = 7, 97, new_primaryincomesource) AS [service_user_response/@value]
      ,'IncomeSource' AS  [service_user_response/@question_fieldname]
      --,(SELECT IIF (Disability IS NULL, 'false', 'true') from HasDisablity where ClientID = CB.ContactId) AS HasDisabilities

      --,IIF (new_client is NULL, NULL, (select coalesce (new_name, null) FROM Health AS D where D.new_contact = CB.ContactId for xml path ('DisabilityCode'), type)) AS Disabilities
      --,(SELECT IIF (new_name IS NULL, NULL, (select H2.new_name from Health AS H2 where H2.new_contact = CB.ContactId
      --  for xml path ('DisabilityCode'), type)) FROM Health AS D where D.new_contact = CB.ContactId) AS Disabilities
--    ,DEX.[dbo].[CRM2DEX]('AccommodationType',C.new_residentialsetting, 0) AS AccommodationTypeCode
--    ,DEX.[dbo].[CRM2DEX]('DVACardStatus',[new_DVAentitlement], 0) AS DVACardStatusCode
      --,COALESCE (HasCarer, 'false') AS HasCarer

--    ,DEX.[dbo].[CRM2DEX]('HouseholdComposition', C.new_livingarrangements, 0) AS HouseholdCompositionCode

  FROM [FOCUSCRM_MSCRM].[dbo].[ContactBase] AS CB
  INNER JOIN
      (SELECT [ParentId]
             ,[Line1]
             ,[Line2]
             ,[City]
             ,[PostalCode]
      FROM [FOCUSCRM_MSCRM].[dbo].[CustomerAddressBase]
      WHERE addressNumber = 1 ) AS A ON CB.ContactId = A.ParentId

  LEFT OUTER JOIN
      (SELECT [new_countryId]
             ,[new_name]
             ,[new_Code]
      FROM [FOCUSCRM_MSCRM].[dbo].[new_countryBase]) AS Country ON CB.new_CountryofBirth = Country.new_countryId

  LEFT OUTER JOIN
      (SELECT [new_languageId]
             ,[new_name]
             ,[new_Code]
      FROM [FOCUSCRM_MSCRM].[dbo].[new_languageBase]) AS Lang ON CB.new_PreferredLanguage = Lang.new_languageId

  LEFT OUTER JOIN
      (SELECT new_ClientName, new_livingarrangements, new_residentialsetting
        FROM (
        SELECT [new_ClientName]
        ,row_number() over (Partition by new_ClientName ORDER BY ModifiedOn DESC) AS R
        ,new_AssessmentDate
        ,new_livingarrangements
        ,new_residentialsetting

        FROM [FOCUSCRM_MSCRM].[dbo].[new_assessmentBase] AS AB1
        WHERE statecode = 0
          ) AS T1

      WHERE R = 1) AS C ON CB.ContactId = C.new_ClientName

  LEFT OUTER JOIN HasCarer AS HC ON HC.new_clientname = cb.contactID

      WHERE CB.new_clientID IN (SELECT DISTINCT new_clientID from TS)
  and statecode = 0

  --) AS T GROUP BY ClientID having count(ClientId)>1

 FOR XML PATH('service_user'),ROOT('agency');

Body:
Without sample data it is a blind flight, but you might try something like this:

SELECT
    consent_type AS [@constent_type]
  , state_code AS [@state_code]
  , suburb AS [@suburb]
  , sex_code AS [@sex_code]
  , postcode AS [@postcode]
  , CarerPrimary AS [service_user_response/@value]
  ,'CarerPrimary' AS [service_user_response/@question_fieldname]
  , CarerResidence AS [service_user_response/@value]
  ,'CarerResidence' AS [service_user_response/@question_fieldname]
  , CarerRelationship AS [service_user_response/@value]
  ,'CarerRelationship' AS [service_user_response/@question_fieldname]
  , service_type_outlet_codeno AS [service_user_outlet/@service_type_outlet_codeno]
  , last_service_date AS [service_user_outlet/@last_service_date]
  , service_hours AS [service_user_outlet/service_hours/@service_hours]
  , to_date AS [service_user_outlet/service_hours/@to_date]
  , from_date AS [service_user_outlet/service_hours/@from_date]
FROM
    TABLEX
FOR XML PATH('service_user'),ROOT('agency');

FOR XML PATH allows to define the XPath as column alias. attributes are marked with a @ sign.

The service_hours in your example look as if they were 1:n, but the query does not look as such.


来源: stackexchange

问:
JXTreeTable RowFilter implementation
I'll try to implement RowFilter for JXTreeTable, but it does not work. My implementation is smth like this:

```<code>public class CustomRowFilter extends RowFilter<TableModel, Integer> {
@Override
public boolean include(Entry entry) {
    if (entry.getValueCount() == 3) {
        Integervalue1 = (Integer) entry.getValue(1);
        Integervalue2 = (Integer) entry.getValue(2);
        if (value1.equals(value2)) {
            return true;
        }
    }
    return false;
}
</code>```

}

Can somebody tell me where is my mistake? May be JXTreeTable does not support filtering?

Thnx in advance

答:
sorting/filtering is not supported in JXTreeTable

https://community.oracle.com/thread/2167209?tstart=0

ContentLicense: CC BY-SA 3.0

Title: JXTreeTable RowFilter implementation

Body:
I'll try to implement RowFilter for JXTreeTable, but it does not work. My implementation is smth like this:

public class CustomRowFilter extends RowFilter<TableModel, Integer> {
@Override
public boolean include(Entry entry) {
    if (entry.getValueCount() == 3) {
        Integervalue1 = (Integer) entry.getValue(1);
        Integervalue2 = (Integer) entry.getValue(2);
        if (value1.equals(value2)) {
            return true;
        }
    }
    return false;
}

}

Can somebody tell me where is my mistake? May be JXTreeTable does not support filtering?

Thnx in advance


问:
Docker Licensing a product
Apart from docker environment we used to look MAC address as unique key for licensing. For Docker MAC Address is changes on Reboot. What We can Look in docker for licensing ?</p>

答:
Docker start assigning always the same mac 02:42:ac:11:00:02 for the first container and then is increasing by one each mac for each different container.

It seems 02:42:ac doesn't match any real vendor in oui databases. Look at the official documentation about this. They say:

The MAC address is generated using the IP address allocated to the container to avoid ARP collisions, using a range from 02:42:ac:11:00:00 to 02:42:ac:11:ff:ff

Anyway, you can set any mac address on container generation using --mac-address parameter on the docker run command. For example doing a command like this docker run -ti --mac-address 00:00:00:00:00:11 ubuntu:trusty. So you can control the mac of each container for licensing.

I copied my own answer on a similar question here.

Hope it helps.

Title: Docker Licensing a product


问:
Prevent the run tool window from popping up everytime I run my tests
I run my tests a lot, most of the time all I need is the little balloon tip that pops up saying "12 tests passed" or "1 test failed".

That's all I need, but the run tab demands attention, and sometimes takes focus, which is very annoying when I'm typing.

I know I can hit escape when it takes focus, but I want to ignore the test results unless too many pass/fail.

So, is there anyway to bury the run window until I want to see the results, or run the test in the background (but not outside of the IDE)?

答: I'm afraid that there is no way to keep it completely hidden when running tests. Feel free to submit a feature request.</p>

ContentLicense: CC BY-SA 2.5


问:
How to create a CocoaPod with swift?
I create a swift cocoa touch framework according to create cocoapod with siwft

and it works fine, But there is another problem, my framework will dependency on other framework, such as SwiftyJSON.

And I try add

```<code>s.dependency "SwiftyJSON", "~> 2.3"
</code>```

into the .podspec file.
But when I try to build my 'Example', still error happens :

'No such module SwiftyJSON'

答:
Open your terminal and goto to your folder project. Then follow this step. Type this command in your terminal.

```<code>open -a TextEdit Podfile
</code>```

Then copy this pod 'SwiftyJSON', :git =>'https://github.com/SwiftyJSON/SwiftyJSON.git'

put into Podfile. Then save it. And type this command in your terminal.

```<code>pod install
</code>```

Hope it will help you.

Title: How to create a CocoaPod with swift?

Body:
I create a swift cocoa touch framework according to create cocoapod with siwft

and it works fine, But there is another problem, my framework will dependency on other framework, such as SwiftyJSON.

And I try add

s.dependency "SwiftyJSON", "~> 2.3"

into the .podspec file.
But when I try to build my 'Example', still error happens :

'No such module SwiftyJSON'

Body:
Open your terminal and goto to your folder project. Then follow this step. Type this command in your terminal.

open -a TextEdit Podfile

Then copy this pod 'SwiftyJSON', :git =>'https://github.com/SwiftyJSON/SwiftyJSON.git'

put into Podfile. Then save it. And type this command in your terminal.

pod install

Hope it will help you.


问:
rpmbuild install dependency
I'm new to rpmbuild + spec files and I tried the following tutorial to build the "hello world" example.

Manage to get it working, but I wanted to learn how dependencies/requires works. Therefore, I tried to duplicate another "hello world 2" example and link it as a dependency to the first in the spec file below.

However I keep getting the error below. Is there a way that yum install will pick up the helloworld1 and install automatically when i yum install helloworld2 ?

Any example for me learn from?

SPEC FILE

```<code>Name:           helloworld2
Version:        2.0
Release:        1%{?dist}
Summary:        A hello world program

License:        GPLv3+
URL:            https://blog.packagecloud.io
Source0:        helloworld2-2.0.tar.gz

#BuildRequires: helloworld1
Requires(preun):  helloworld1
#PreReq: testYW

%description
A helloworld program from the packagecloud.io blog!

%prep
%setup

%build
make PREFIX=/usr %{?_smp_mflags}

%install
make PREFIX=/usr DESTDIR=%{?buildroot} install
echo %{?buildroot}

%clean
rm -rf %{buildroot}

%files
%{_bindir}/helloworld2
</code>```

ERORR

COMMAND >> yum install RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm

```<code>Loaded plugins: product-id, search-disabled-repos, security, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
Setting up Install Process
Examining RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm: helloworld2-2.0-1.el6.x86_64
Marking RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package helloworld2.x86_64 0:2.0-1.el6 will be installed
--> Processing Dependency: helloworld1 for package: helloworld2-2.0-1.el6.x86_64
--> Finished Dependency Resolution
Error: Package: helloworld2-2.0-1.el6.x86_64 (/helloworld2-2.0-1.el6.x86_64)
           Requires: helloworld1
 You could try using --skip-broken to work around the problem
</code>```

答: since helloworld2 requires helloworld1; you should either install helloworld1 first; either install both together. Since helloworld2 depends on helloworld1; you cannot install him without installing helloworld1 first (or at the same time).</p>

Title: rpmbuild install dependency

Body:
I'm new to rpmbuild + spec files and I tried the following tutorial to build the "hello world" example.

Manage to get it working, but I wanted to learn how dependencies/requires works. Therefore, I tried to duplicate another "hello world 2" example and link it as a dependency to the first in the spec file below.

However I keep getting the error below. Is there a way that yum install will pick up the helloworld1 and install automatically when i yum install helloworld2 ?

Any example for me learn from?

SPEC FILE

Name:           helloworld2
Version:        2.0
Release:        1%{?dist}
Summary:        A hello world program

License:        GPLv3+
URL:            https://blog.packagecloud.io
Source0:        helloworld2-2.0.tar.gz

#BuildRequires: helloworld1
Requires(preun):  helloworld1
#PreReq: testYW

%description
A helloworld program from the packagecloud.io blog!

%prep
%setup

%build
make PREFIX=/usr %{?_smp_mflags}

%install
make PREFIX=/usr DESTDIR=%{?buildroot} install
echo %{?buildroot}

%clean
rm -rf %{buildroot}

%files
%{_bindir}/helloworld2

ERORR

COMMAND >> yum install RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm

Loaded plugins: product-id, search-disabled-repos, security, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
Setting up Install Process
Examining RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm: helloworld2-2.0-1.el6.x86_64
Marking RPMS/x86_64/helloworld2-2.0-1.el6.x86_64.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package helloworld2.x86_64 0:2.0-1.el6 will be installed
--> Processing Dependency: helloworld1 for package: helloworld2-2.0-1.el6.x86_64
--> Finished Dependency Resolution
Error: Package: helloworld2-2.0-1.el6.x86_64 (/helloworld2-2.0-1.el6.x86_64)
           Requires: helloworld1
 You could try using --skip-broken to work around the problem


问:
Segmentation fault during resizing two-dimensional dynamically allocated table
I`ve got two-dimensional, dynamically allocated table. Resize the table.

1) Create new one.

2) Delete previous pointer, allocated memory.

3) Assign new pointer.

Code:

```<code>#include <stdio.h>
#include <stdlib.h>

int** create(int rows, int columns)
{
    int **tab = (int**)malloc(rows * sizeof(int*));
    int i=0;
    for(;i<rows; ++i)
    {
        tab[i] = (int*)malloc(columns * sizeof(int));   /* tab[i] = (int*)calloc(columns , sizeof(int)); */
    }

    return tab;
}
void deleteTab(int **tab, int rows)
{
    int i=0;
    for(;i<rows;++i)
    {
        free(tab[i]);
    }
    free(tab);
}
void resize(int **tab, int oldRows, int newRows, int newColumns)
{
    int **newTab=create(newRows, newColumns);
    deleteTab(tab, oldRows);
    tab=newTab;
}
void printTab(int **tab, int rows, int columns)
{
    int i=0, j=0;
    for(i=0;i<rows;++i, printf("\n"))
    {
        for(j=0;j<columns;++j)
        {
            printf("%i ", tab[i][j]);
        }
    }
}
int main()
{
    int **tab=create(4,7);
    resize(tab,4,8,9);
    int i=0, j=0;
    for(i=0;i<8;++i)
    {
        for(j=0;j<9;++j)
        {
            tab[i][j]=3;
        }
    }
    printTab(tab,8,9);
}
</code>```

Output:
Segmentation fault.

Is it a good way/algorithm to resize the table? How to omit segmentation fault error?

答:
resize must return newtab. the parameter is passed by value. or you can make tab as a pointer of your table and change your code like this

```<code>void resize(int ***tab, int oldRows, int newRows, int newColumns)
{
    int **newTab=create(newRows, newColumns);
    deleteTab(*tab, oldRows);
    *tab=newTab;
}
</code>```

and call it like this:

```<code>int main()
{
    int **tab=create(4,7);
    resize(&tab,4,8,9); //note 'tab' now pass-by-pointer
    //...
}
</code>```

Body:
I`ve got two-dimensional, dynamically allocated table. Resize the table.

1) Create new one.

2) Delete previous pointer, allocated memory.

3) Assign new pointer.

Code:

#include <stdio.h>
#include <stdlib.h>

int** create(int rows, int columns)
{
    int **tab = (int**)malloc(rows * sizeof(int*));
    int i=0;
    for(;i<rows; ++i)
    {
        tab[i] = (int*)malloc(columns * sizeof(int));   /* tab[i] = (int*)calloc(columns , sizeof(int)); */
    }

    return tab;
}
void deleteTab(int **tab, int rows)
{
    int i=0;
    for(;i<rows;++i)
    {
        free(tab[i]);
    }
    free(tab);
}
void resize(int **tab, int oldRows, int newRows, int newColumns)
{
    int **newTab=create(newRows, newColumns);
    deleteTab(tab, oldRows);
    tab=newTab;
}
void printTab(int **tab, int rows, int columns)
{
    int i=0, j=0;
    for(i=0;i<rows;++i, printf("\n"))
    {
        for(j=0;j<columns;++j)
        {
            printf("%i ", tab[i][j]);
        }
    }
}
int main()
{
    int **tab=create(4,7);
    resize(tab,4,8,9);
    int i=0, j=0;
    for(i=0;i<8;++i)
    {
        for(j=0;j<9;++j)
        {
            tab[i][j]=3;
        }
    }
    printTab(tab,8,9);
}

Output:
Segmentation fault.

Is it a good way/algorithm to resize the table? How to omit segmentation fault error?

Body:
resize must return newtab. the parameter is passed by value. or you can make tab as a pointer of your table and change your code like this

void resize(int ***tab, int oldRows, int newRows, int newColumns)
{
    int **newTab=create(newRows, newColumns);
    deleteTab(*tab, oldRows);
    *tab=newTab;
}

and call it like this:

int main()
{
    int **tab=create(4,7);
    resize(&tab,4,8,9); //note 'tab' now pass-by-pointer
    //...
}


问:
Send notification to everybody but user who triggered it?
I'm using Firebase Messaging to send out notifications to users of my iPhone app. My database is structured like this:

```<code>- Users
    - user1
    - user2
- Groups
    - group1
        - members
            - user1
            - user2
</code>```

When a user joins a group they get subscribed to a topic corresponding to that group. I have a cloud function that listens for writes in that group, and sends a notification to the groups topic when a write happens:

```<code>exports.sendNotifs = functions.database
    .ref('pets/{petId}/events/{eventId}').onWrite(event => {
        const pet_Id = event.params.petId;

        const payload = {
              'notification': {
                'title': `${toTitleCase(name)} just logged an event`,
                'body': `${events[eventType]} for ${toTitleCase(petName)}`,
                'sound': 'default',
              }
            };

        admin.messaging().sendToTopic(pet_Id, payload);
    });
</code>```

However, this results in everybody getting a notification including the person who did the write that triggered the notification. I only want other people in the group to display a notification since the triggering user doesn't need to see one. I tried appending the sending user's uid as extra data of the notification and only displaying the notification if the recieving user's uid doesn't match the notification data's uid. This works when the application is in the foreground but not if its in the background, so if the user writes then closes the application before he receives the notification it'll display for him when he receives it, something I'm trying to avoid.

How can I make sure only other members of a group get a notification? Are messaging topics not good for this?

答:
If you use Topics it's not possible to send to everyone except one.

If you are Ok sending to everyone, and then filtering on the client, you will need to use the data messages, and not notification messages, to avoid the problem with background/foreground you described.
https://firebase.google.com/docs/cloud-messaging/concept-options

Body:
I'm using Firebase Messaging to send out notifications to users of my iPhone app. My database is structured like this:

- Users
    - user1
    - user2
- Groups
    - group1
        - members
            - user1
            - user2

When a user joins a group they get subscribed to a topic corresponding to that group. I have a cloud function that listens for writes in that group, and sends a notification to the groups topic when a write happens:

exports.sendNotifs = functions.database
    .ref('pets/{petId}/events/{eventId}').onWrite(event => {
        const pet_Id = event.params.petId;

        const payload = {
              'notification': {
                'title': `${toTitleCase(name)} just logged an event`,
                'body': `${events[eventType]} for ${toTitleCase(petName)}`,
                'sound': 'default',
              }
            };

        admin.messaging().sendToTopic(pet_Id, payload);
    });

However, this results in everybody getting a notification including the person who did the write that triggered the notification. I only want other people in the group to display a notification since the triggering user doesn't need to see one. I tried appending the sending user's uid as extra data of the notification and only displaying the notification if the recieving user's uid doesn't match the notification data's uid. This works when the application is in the foreground but not if its in the background, so if the user writes then closes the application before he receives the notification it'll display for him when he receives it, something I'm trying to avoid.

How can I make sure only other members of a group get a notification? Are messaging topics not good for this?


问:
Update custom adapter with query results
i want to query results from custom adapter by comparing query text with list in RecycleView, it successfully gets results from query then i make list of results and update the existing adapter but it does not effect anything, i use below code fot that

```<code>combinationMessagesList = createCombinationMessagesList();
    combinationMessages = createCombinationMessagesList();

    combinationMessages.clear();

    for (int i = 0; i < combinationMessagesList.size(); i++) {

        CombinationMessage message = combinationMessagesList.get(i);
        if (message.getBody().toString().equals(search.getText().toString())){

            combinationMessages.add(combinationMessagesList.get(i));

        }
    }

    messagesAdapter.setList(combinationmessagesList);
    messagesAdapter.notifyDataSetChanged();

}
</code>```

PrivateDialogActivity

```<code>public class PrivateDialogActivity extends BaseDialogActivity {

private FriendOperationAction friendOperationAction;
private FriendObserver friendObserver;
private int operationItemPosition;
private final String TAG = "PrivateDialogActivity";

EditText search;

public static void start(Context context, User opponent, Dialog dialog) {
    Intent intent = new Intent(context, PrivateDialogActivity.class);
    intent.putExtra(QBServiceConsts.EXTRA_OPPONENT, opponent);
    intent.putExtra(QBServiceConsts.EXTRA_DIALOG, dialog);
    context.startActivity(intent);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initFields();

    context = this;

    if (dialog == null) {
        finish();
    }

    setUpActionBarWithUpButton();

    if (isNetworkAvailable()) {
        deleteTempMessages();
    }

    addObservers();

    initMessagesRecyclerView();

    search = (EditText) findViewById(R.id.search_edittext);
    Button button = (Button) findViewById(R.id.search);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showResult();
        }
    });

}

private void showResult() {

    combinationMessagesList = createCombinationMessagesList();
    combinationMessages = createCombinationMessagesList();

    combinationMessages.clear();

    for (int i = 0; i < combinationMessagesList.size(); i++) {

        CombinationMessage message = combinationMessagesList.get(i);
        if (message.getBody().toString().equals(search.getText().toString())){

            combinationMessages.add(combinationMessagesList.get(i));

        }
    }

    messagesAdapter.setList(combinationMessagesList);
    messagesAdapter.notifyDataSetChanged();

}

@Override
protected void addActions() {
    super.addActions();

    addAction(QBServiceConsts.ACCEPT_FRIEND_SUCCESS_ACTION, new AcceptFriendSuccessAction());
    addAction(QBServiceConsts.ACCEPT_FRIEND_FAIL_ACTION, failAction);

    addAction(QBServiceConsts.REJECT_FRIEND_SUCCESS_ACTION, new RejectFriendSuccessAction());
    addAction(QBServiceConsts.REJECT_FRIEND_FAIL_ACTION, failAction);

    updateBroadcastActionList();
}

@Override
protected void onResume() {
    super.onResume();

    checkForCorrectChat();

    if (isNetworkAvailable()) {
        startLoadDialogMessages();
    }

    checkMessageSendingPossibility();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    deleteObservers();
}

@Override
protected void updateActionBar() {
    setOnlineStatus(opponentUser);

    checkActionBarLogo(opponentUser.getAvatar(), R.drawable.placeholder_user);
}

@Override
protected void onConnectServiceLocally(QBService service) {
    onConnectServiceLocally();
    setOnlineStatus(opponentUser);
}

@Override
protected void onFileLoaded(QBFile file, String dialogId) {
    if(!dialogId.equals(dialog.getDialogId())){
        return;
    }

    try {
        privateChatHelper.sendPrivateMessageWithAttachImage(file, opponentUser.getUserId(), null, null);
    } catch (QBResponseException exc) {
        ErrorUtils.showError(this, exc);
    }
}

@Override
protected Bundle generateBundleToInitDialog() {
    Bundle bundle = new Bundle();
    bundle.putInt(QBServiceConsts.EXTRA_OPPONENT_ID, opponentUser.getUserId());
    return bundle;
}

@Override
protected void initMessagesRecyclerView() {
    super.initMessagesRecyclerView();
    messagesAdapter = new PrivateDialogMessagesAdapter(this, friendOperationAction, combinationMessagesList, this, dialog);
    messagesRecyclerView.addItemDecoration(
            new StickyRecyclerHeadersDecoration((StickyRecyclerHeadersAdapter) messagesAdapter));
    findLastFriendsRequest();

    messagesRecyclerView.setAdapter(messagesAdapter);
    scrollMessagesToBottom();
}

@Override
protected void updateMessagesList() {
    initActualExtras();
    checkForCorrectChat();

    int oldMessagesCount = messagesAdapter.getAllItems().size();

    this.combinationMessagesList = createCombinationMessagesList();
    Log.d(TAG, "combinationMessagesList = " + combinationMessagesList);
    messagesAdapter.setList(combinationMessagesList);
    findLastFriendsRequest();

    checkForScrolling(oldMessagesCount);
}

private void initActualExtras() {
    opponentUser = (User) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_OPPONENT);
    dialog = (Dialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG);
}

@Override
public void notifyChangedUserStatus(int userId, boolean online) {
    super.notifyChangedUserStatus(userId, online);

    if (opponentUser != null && opponentUser.getUserId() == userId) {
        setOnlineStatus(opponentUser);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.private_dialog_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    boolean isFriend = DataManager.getInstance().getFriendDataManager().getByUserId(
            opponentUser.getUserId()) != null;
    if (!isFriend && item.getItemId() != android.R.id.home) {
        ToastUtils.longToast(R.string.dialog_user_is_not_friend);
        return true;
    }
    switch (item.getItemId()) {
        case R.id.action_audio_call:
            callToUser(opponentUser, QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_AUDIO);
            break;
        case R.id.switch_camera_toggle:
            callToUser(opponentUser, QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO);
            break;
        default:
            super.onOptionsItemSelected(item);
    }
    return true;
}

@Override
protected void checkMessageSendingPossibility() {
    boolean enable = dataManager.getFriendDataManager().existsByUserId(opponentUser.getUserId()) && isNetworkAvailable();
    checkMessageSendingPossibility(enable);
}

@OnClick(R.id.toolbar)
void openProfile(View view) {
    UserProfileActivity.start(this, opponentUser.getUserId());
}

private void initFields() {
    chatHelperIdentifier = QBService.PRIVATE_CHAT_HELPER;
    friendOperationAction = new FriendOperationAction();
    friendObserver = new FriendObserver();
    initActualExtras();
//        opponentUser = (User)     getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_OPPONENT);
//        dialog = (Dialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG);
    combinationMessagesList = createCombinationMessagesList();
    title = opponentUser.getFullName();
}

private void addObservers() {
    dataManager.getFriendDataManager().addObserver(friendObserver);
}

private void deleteObservers() {
    dataManager.getFriendDataManager().deleteObserver(friendObserver);
}

private void findLastFriendsRequest() {
    ((PrivateDialogMessagesAdapter) messagesAdapter).findLastFriendsRequestMessagesPosition();
    messagesAdapter.notifyDataSetChanged();
}

private void setOnlineStatus(User user) {
    if (user != null) {
        if (friendListHelper != null) {
            String offlineStatus = getString(R.string.last_seen, DateUtils.toTodayYesterdayShortDateWithoutYear2(user.getLastLogin()),
                    DateUtils.formatDateSimpleTime(user.getLastLogin()));
            setActionBarSubtitle(
                    OnlineStatusUtils.getOnlineStatus(this, friendListHelper.isUserOnline(user.getUserId()), offlineStatus));
        }
    }
}

public void sendMessage(View view) {
    sendMessage(true);
}

private void callToUser(User user, QBRTCTypes.QBConferenceType qbConferenceType) {
    if (!isChatInitializedAndUserLoggedIn()) {
        ToastUtils.longToast(R.string.call_chat_service_is_initializing);
        return;
    }
    List<QBUser> qbUserList = new ArrayList<>(1);
    qbUserList.add(UserFriendUtils.createQbUser(user));
    CallActivity.start(PrivateDialogActivity.this, qbUserList, qbConferenceType, null);
}

private void acceptUser(final int userId) {
    if (isNetworkAvailable()) {
        if (!isChatInitializedAndUserLoggedIn()) {
            ToastUtils.longToast(R.string.call_chat_service_is_initializing);
            return;
        }

        showProgress();
        QBAcceptFriendCommand.start(this, userId);
    } else {
        ToastUtils.longToast(R.string.dlg_fail_connection);
        return;
    }
}

private void rejectUser(final int userId) {
    if (isNetworkAvailable()) {
        if (!isChatInitializedAndUserLoggedIn()) {
            ToastUtils.longToast(R.string.call_chat_service_is_initializing);
            return;
        }

        showRejectUserDialog(userId);
    } else {
        ToastUtils.longToast(R.string.dlg_fail_connection);
        return;
    }
}

private void showRejectUserDialog(final int userId) {
    User user = DataManager.getInstance().getUserDataManager().get(userId);
    if (user == null) {
        return;
    }

    TwoButtonsDialogFragment.show(getSupportFragmentManager(),
            getString(R.string.dialog_message_reject_friend, user.getFullName()),
            new MaterialDialog.ButtonCallback() {
                @Override
                public void onPositive(MaterialDialog dialog) {
                    super.onPositive(dialog);
                    showProgress();
                    QBRejectFriendCommand.start(PrivateDialogActivity.this, userId);
                }
            });
}

private void checkForCorrectChat() {
    Dialog updatedDialog = null;
    if (dialog != null) {
        updatedDialog = dataManager.getDialogDataManager().getByDialogId(dialog.getDialogId());
    } else {
        finish();
    }

    if (updatedDialog == null) {
        finish();
    } else {
        dialog = updatedDialog;
    }
}

private class FriendOperationAction implements FriendOperationListener {

    @Override
    public void onAcceptUserClicked(int position, int userId) {
        operationItemPosition = position;
        acceptUser(userId);
    }

    @Override
    public void onRejectUserClicked(int position, int userId) {
        operationItemPosition = position;
        rejectUser(userId);
    }
}

private class AcceptFriendSuccessAction implements Command {

    @Override
    public void execute(Bundle bundle) {
        ((PrivateDialogMessagesAdapter) messagesAdapter).clearLastRequestMessagePosition();
        messagesAdapter.notifyItemChanged(operationItemPosition);
        startLoadDialogMessages();
        hideProgress();
    }
}

private class RejectFriendSuccessAction implements Command {

    @Override
    public void execute(Bundle bundle) {
        ((PrivateDialogMessagesAdapter) messagesAdapter).clearLastRequestMessagePosition();
        messagesAdapter.notifyItemChanged(operationItemPosition);
        startLoadDialogMessages();
        hideProgress();
    }
}

private class FriendObserver implements Observer {

    @Override
    public void update(Observable observable, Object data) {
        if (data != null && data.equals(FriendDataManager.OBSERVE_KEY)) {
            checkForCorrectChat();
            checkMessageSendingPossibility();
        }
    }
}
}
</code>```

答:
it was my own mistake it code, i made the code work by changing messagesAdapter.setList(combinationmessagesList)
to
messagesAdapter.setList(combinationMessages);</p>

Body:
i want to query results from custom adapter by comparing query text with list in RecycleView, it successfully gets results from query then i make list of results and update the existing adapter but it does not effect anything, i use below code fot that

combinationMessagesList = createCombinationMessagesList();
    combinationMessages = createCombinationMessagesList();

    combinationMessages.clear();

    for (int i = 0; i < combinationMessagesList.size(); i++) {

        CombinationMessage message = combinationMessagesList.get(i);
        if (message.getBody().toString().equals(search.getText().toString())){

            combinationMessages.add(combinationMessagesList.get(i));

        }
    }

    messagesAdapter.setList(combinationmessagesList);
    messagesAdapter.notifyDataSetChanged();

}

PrivateDialogActivity

public class PrivateDialogActivity extends BaseDialogActivity {

private FriendOperationAction friendOperationAction;
private FriendObserver friendObserver;
private int operationItemPosition;
private final String TAG = "PrivateDialogActivity";

EditText search;

public static void start(Context context, User opponent, Dialog dialog) {
    Intent intent = new Intent(context, PrivateDialogActivity.class);
    intent.putExtra(QBServiceConsts.EXTRA_OPPONENT, opponent);
    intent.putExtra(QBServiceConsts.EXTRA_DIALOG, dialog);
    context.startActivity(intent);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initFields();

    context = this;

    if (dialog == null) {
        finish();
    }

    setUpActionBarWithUpButton();

    if (isNetworkAvailable()) {
        deleteTempMessages();
    }

    addObservers();

    initMessagesRecyclerView();

    search = (EditText) findViewById(R.id.search_edittext);
    Button button = (Button) findViewById(R.id.search);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showResult();
        }
    });

}

private void showResult() {

    combinationMessagesList = createCombinationMessagesList();
    combinationMessages = createCombinationMessagesList();

    combinationMessages.clear();

    for (int i = 0; i < combinationMessagesList.size(); i++) {

        CombinationMessage message = combinationMessagesList.get(i);
        if (message.getBody().toString().equals(search.getText().toString())){

            combinationMessages.add(combinationMessagesList.get(i));

        }
    }

    messagesAdapter.setList(combinationMessagesList);
    messagesAdapter.notifyDataSetChanged();

}

@Override
protected void addActions() {
    super.addActions();

    addAction(QBServiceConsts.ACCEPT_FRIEND_SUCCESS_ACTION, new AcceptFriendSuccessAction());
    addAction(QBServiceConsts.ACCEPT_FRIEND_FAIL_ACTION, failAction);

    addAction(QBServiceConsts.REJECT_FRIEND_SUCCESS_ACTION, new RejectFriendSuccessAction());
    addAction(QBServiceConsts.REJECT_FRIEND_FAIL_ACTION, failAction);

    updateBroadcastActionList();
}

@Override
protected void onResume() {
    super.onResume();

    checkForCorrectChat();

    if (isNetworkAvailable()) {
        startLoadDialogMessages();
    }

    checkMessageSendingPossibility();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    deleteObservers();
}

@Override
protected void updateActionBar() {
    setOnlineStatus(opponentUser);

    checkActionBarLogo(opponentUser.getAvatar(), R.drawable.placeholder_user);
}

@Override
protected void onConnectServiceLocally(QBService service) {
    onConnectServiceLocally();
    setOnlineStatus(opponentUser);
}

@Override
protected void onFileLoaded(QBFile file, String dialogId) {
    if(!dialogId.equals(dialog.getDialogId())){
        return;
    }

    try {
        privateChatHelper.sendPrivateMessageWithAttachImage(file, opponentUser.getUserId(), null, null);
    } catch (QBResponseException exc) {
        ErrorUtils.showError(this, exc);
    }
}

@Override
protected Bundle generateBundleToInitDialog() {
    Bundle bundle = new Bundle();
    bundle.putInt(QBServiceConsts.EXTRA_OPPONENT_ID, opponentUser.getUserId());
    return bundle;
}

@Override
protected void initMessagesRecyclerView() {
    super.initMessagesRecyclerView();
    messagesAdapter = new PrivateDialogMessagesAdapter(this, friendOperationAction, combinationMessagesList, this, dialog);
    messagesRecyclerView.addItemDecoration(
            new StickyRecyclerHeadersDecoration((StickyRecyclerHeadersAdapter) messagesAdapter));
    findLastFriendsRequest();

    messagesRecyclerView.setAdapter(messagesAdapter);
    scrollMessagesToBottom();
}

@Override
protected void updateMessagesList() {
    initActualExtras();
    checkForCorrectChat();

    int oldMessagesCount = messagesAdapter.getAllItems().size();

    this.combinationMessagesList = createCombinationMessagesList();
    Log.d(TAG, "combinationMessagesList = " + combinationMessagesList);
    messagesAdapter.setList(combinationMessagesList);
    findLastFriendsRequest();

    checkForScrolling(oldMessagesCount);
}

private void initActualExtras() {
    opponentUser = (User) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_OPPONENT);
    dialog = (Dialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG);
}

@Override
public void notifyChangedUserStatus(int userId, boolean online) {
    super.notifyChangedUserStatus(userId, online);

    if (opponentUser != null && opponentUser.getUserId() == userId) {
        setOnlineStatus(opponentUser);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.private_dialog_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    boolean isFriend = DataManager.getInstance().getFriendDataManager().getByUserId(
            opponentUser.getUserId()) != null;
    if (!isFriend && item.getItemId() != android.R.id.home) {
        ToastUtils.longToast(R.string.dialog_user_is_not_friend);
        return true;
    }
    switch (item.getItemId()) {
        case R.id.action_audio_call:
            callToUser(opponentUser, QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_AUDIO);
            break;
        case R.id.switch_camera_toggle:
            callToUser(opponentUser, QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO);
            break;
        default:
            super.onOptionsItemSelected(item);
    }
    return true;
}

@Override
protected void checkMessageSendingPossibility() {
    boolean enable = dataManager.getFriendDataManager().existsByUserId(opponentUser.getUserId()) && isNetworkAvailable();
    checkMessageSendingPossibility(enable);
}

@OnClick(R.id.toolbar)
void openProfile(View view) {
    UserProfileActivity.start(this, opponentUser.getUserId());
}

private void initFields() {
    chatHelperIdentifier = QBService.PRIVATE_CHAT_HELPER;
    friendOperationAction = new FriendOperationAction();
    friendObserver = new FriendObserver();
    initActualExtras();
//        opponentUser = (User)     getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_OPPONENT);
//        dialog = (Dialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG);
    combinationMessagesList = createCombinationMessagesList();
    title = opponentUser.getFullName();
}

private void addObservers() {
    dataManager.getFriendDataManager().addObserver(friendObserver);
}

private void deleteObservers() {
    dataManager.getFriendDataManager().deleteObserver(friendObserver);
}

private void findLastFriendsRequest() {
    ((PrivateDialogMessagesAdapter) messagesAdapter).findLastFriendsRequestMessagesPosition();
    messagesAdapter.notifyDataSetChanged();
}

private void setOnlineStatus(User user) {
    if (user != null) {
        if (friendListHelper != null) {
            String offlineStatus = getString(R.string.last_seen, DateUtils.toTodayYesterdayShortDateWithoutYear2(user.getLastLogin()),
                    DateUtils.formatDateSimpleTime(user.getLastLogin()));
            setActionBarSubtitle(
                    OnlineStatusUtils.getOnlineStatus(this, friendListHelper.isUserOnline(user.getUserId()), offlineStatus));
        }
    }
}

public void sendMessage(View view) {
    sendMessage(true);
}

private void callToUser(User user, QBRTCTypes.QBConferenceType qbConferenceType) {
    if (!isChatInitializedAndUserLoggedIn()) {
        ToastUtils.longToast(R.string.call_chat_service_is_initializing);
        return;
    }
    List<QBUser> qbUserList = new ArrayList<>(1);
    qbUserList.add(UserFriendUtils.createQbUser(user));
    CallActivity.start(PrivateDialogActivity.this, qbUserList, qbConferenceType, null);
}

private void acceptUser(final int userId) {
    if (isNetworkAvailable()) {
        if (!isChatInitializedAndUserLoggedIn()) {
            ToastUtils.longToast(R.string.call_chat_service_is_initializing);
            return;
        }

        showProgress();
        QBAcceptFriendCommand.start(this, userId);
    } else {
        ToastUtils.longToast(R.string.dlg_fail_connection);
        return;
    }
}

private void rejectUser(final int userId) {
    if (isNetworkAvailable()) {
        if (!isChatInitializedAndUserLoggedIn()) {
            ToastUtils.longToast(R.string.call_chat_service_is_initializing);
            return;
        }

        showRejectUserDialog(userId);
    } else {
        ToastUtils.longToast(R.string.dlg_fail_connection);
        return;
    }
}

private void showRejectUserDialog(final int userId) {
    User user = DataManager.getInstance().getUserDataManager().get(userId);
    if (user == null) {
        return;
    }

    TwoButtonsDialogFragment.show(getSupportFragmentManager(),
            getString(R.string.dialog_message_reject_friend, user.getFullName()),
            new MaterialDialog.ButtonCallback() {
                @Override
                public void onPositive(MaterialDialog dialog) {
                    super.onPositive(dialog);
                    showProgress();
                    QBRejectFriendCommand.start(PrivateDialogActivity.this, userId);
                }
            });
}

private void checkForCorrectChat() {
    Dialog updatedDialog = null;
    if (dialog != null) {
        updatedDialog = dataManager.getDialogDataManager().getByDialogId(dialog.getDialogId());
    } else {
        finish();
    }

    if (updatedDialog == null) {
        finish();
    } else {
        dialog = updatedDialog;
    }
}

private class FriendOperationAction implements FriendOperationListener {

    @Override
    public void onAcceptUserClicked(int position, int userId) {
        operationItemPosition = position;
        acceptUser(userId);
    }

    @Override
    public void onRejectUserClicked(int position, int userId) {
        operationItemPosition = position;
        rejectUser(userId);
    }
}

private class AcceptFriendSuccessAction implements Command {

    @Override
    public void execute(Bundle bundle) {
        ((PrivateDialogMessagesAdapter) messagesAdapter).clearLastRequestMessagePosition();
        messagesAdapter.notifyItemChanged(operationItemPosition);
        startLoadDialogMessages();
        hideProgress();
    }
}

private class RejectFriendSuccessAction implements Command {

    @Override
    public void execute(Bundle bundle) {
        ((PrivateDialogMessagesAdapter) messagesAdapter).clearLastRequestMessagePosition();
        messagesAdapter.notifyItemChanged(operationItemPosition);
        startLoadDialogMessages();
        hideProgress();
    }
}

private class FriendObserver implements Observer {

    @Override
    public void update(Observable observable, Object data) {
        if (data != null && data.equals(FriendDataManager.OBSERVE_KEY)) {
            checkForCorrectChat();
            checkMessageSendingPossibility();
        }
    }
}
}


问:
RadioButtons inside same RadioGroup but both buttons can be selected
I have two RadioButtons inside the same RadioGroup. But beside each RadioButton i want an ImageButton (info). Therefore my code is as below:

```<code><RadioGroup>
    <LinearLayout>     //Horizontal
        <RadioButton/>
        <ImageButton/>
    </LinearLayout>
    <LinearLayout>     //Horizontal
        <RadioButton/>
        <ImageButton/>
    </LinearLayout>
<RadioGroup/>
</code>```

But now the problem I am facing is fairly simple, both RadioButtons can be selected. I want only one to get selected at a time.

Plz ignore any typos. Bound to post this from phone.

答:
you can use radiobuttons only the child of a radio group

if u dont want this then use my code and remove radiogroup u can use custom radio buttons

```<code>  final RadioButton a1 = (RadioButton) findViewById(R.id.a1);
 final RadioButton a2 = (RadioButton) findViewById(R.id.a2);
 a1.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
      a2.setChecked(false);
      a1.setChecked(true);

  }
     });
   a2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    a1.setChecked(false);
    a2.setChecked(true);

}
});
</code>```

Body:
I have two RadioButtons inside the same RadioGroup. But beside each RadioButton i want an ImageButton (info). Therefore my code is as below:

<RadioGroup>
    <LinearLayout>     //Horizontal
        <RadioButton/>
        <ImageButton/>
    </LinearLayout>
    <LinearLayout>     //Horizontal
        <RadioButton/>
        <ImageButton/>
    </LinearLayout>
<RadioGroup/>

But now the problem I am facing is fairly simple, both RadioButtons can be selected. I want only one to get selected at a time.

Plz ignore any typos. Bound to post this from phone.

Body:
you can use radiobuttons only the child of a radio group

if u dont want this then use my code and remove radiogroup u can use custom radio buttons

  final RadioButton a1 = (RadioButton) findViewById(R.id.a1);
 final RadioButton a2 = (RadioButton) findViewById(R.id.a2);
 a1.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
      a2.setChecked(false);
      a1.setChecked(true);

  }
     });
   a2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    a1.setChecked(false);
    a2.setChecked(true);

}
});


问:
Convert CSV to XML when CSV contains both character and number data
From this thread, I got the basic info on how to parse CSV to create XML. Unfortunately, the text fields (all enclosed in quotes) sometimes contain commas, so line.split(',') gives me too many columns. I can't figure out how to parse the CSV so line.split(',') distinguishes between commas within a text field, and commas separating fields. Any thoughts on how to do that?

Thanks!

答:
Go grab this code: http://geekswithblogs.net/mwatson/archive/2004/09/04/10658.aspx

Then replace line.Split(",") with SplitCSV(line), like:

```<code>var lines = File.ReadAllLines(@"C:\text.csv");

var xml = new XElement("TopElement",
   lines.Select(line => new XElement("Item",
      SplitCSV(line)
          .Select((column, index) => new XElement("Column" + index, column)))));

xml.Save(@"C:\xmlout.xml");
</code>```

Note that the code at the link above is rather old, and probably could be cleaned up a bit using Linq, but it should do the trick.

Body:
Go grab this code: http://geekswithblogs.net/mwatson/archive/2004/09/04/10658.aspx

Then replace line.Split(",") with SplitCSV(line), like:

var lines = File.ReadAllLines(@"C:\text.csv");

var xml = new XElement("TopElement",
   lines.Select(line => new XElement("Item",
      SplitCSV(line)
          .Select((column, index) => new XElement("Column" + index, column)))));

xml.Save(@"C:\xmlout.xml");

Note that the code at the link above is rather old, and probably could be cleaned up a bit using Linq, but it should do the trick.


问:
Logstash MySQL JDBC LoadError: no such file to load -- <file-path>
I want to build Docker-ELK from this repository.

This is my logstash.conf file

```<code>input {
  jdbc {
    jdbc_driver_library => "/home/edsoft/IdeaProjects/docker-elk/resources/mysql-connector-java-5.1.36-bin.jar"
        jdbc_driver_class => "com.mysql.jdbc.Driver"
        jdbc_connection_string => "jdbc:mysql://localhost:3306/yazilimokulu"
        jdbc_user => "root"
        jdbc_password => "1"
        schedule => "* * * * *"
        statement => "select * from posts"
    }
    tcp {
        port => 5000
    }
}

## Add your filters / logstash plugins configuration here

output {
    elasticsearch {
        hosts => ["elasticsearch:9200"]
        index => "posts"
        document_type => "post"
        document_id => "%{id}" ## must be lower case
    }
}
</code>```

I run docker with docker-compose. Kibana and ElasticSearch start successfully but Logstash throw error

```<code>LoadError: no such file to load -- /home/edsoft/IdeaProjects/docker-elk/resources/mysql-connector-java-5.1.36-bin
logstash_1       |                   require at org/jruby/RubyKernel.java:1040
logstash_1       |                   require at /usr/share/logstash/vendor/bundle/jruby/1.9/gems/polyglot-0.3.5/lib/polyglot.rb:65
logstash_1       |              load_drivers at /usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-jdbc-4.1.3/lib/logstash/plugin_mixins/jdbc.rb:134
logstash_1       |                      each at org/jruby/RubyArray.java:1613
logstash_1       |              load_drivers at /usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-jdbc-4.1.3/lib/logstash/plugin_mixins/jdbc.rb:132
logstash_1       |   prepare_jdbc_connection at /usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-jdbc-4.1.3/lib/logstash/plugin_mixins/jdbc.rb:146
logstash_1       |                  register at /usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-jdbc-4.1.3/lib/logstash/inputs/jdbc.rb:191
logstash_1       |           register_plugin at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:282
logstash_1       |          register_plugins at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:293
logstash_1       |                      each at org/jruby/RubyArray.java:1613
logstash_1       |          register_plugins at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:293
logstash_1       |              start_inputs at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:436
logstash_1       |             start_workers at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:337
logstash_1       |                       run at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:232
logstash_1       |            start_pipeline at /usr/share/logstash/logstash-core/lib/logstash/agent.rb:387
</code>```

I write path ...bin.jar but error delete .jar from filename. I write ..bin.jar.jar error code is ..bin.jar but doesn't find the file.

Please help me

Thank you

答: The path you set for the jdbc_driver_library parameter doesn't exist within your container. You have to include the library file inside your Docker image or mount it from your host when you run the Logstash container.

Body:
I want to build Docker-ELK from this repository.

This is my logstash.conf file

input {
  jdbc {
    jdbc_driver_library => "/home/edsoft/IdeaProjects/docker-elk/resources/mysql-connector-java-5.1.36-bin.jar"
        jdbc_driver_class => "com.mysql.jdbc.Driver"
        jdbc_connection_string => "jdbc:mysql://localhost:3306/yazilimokulu"
        jdbc_user => "root"
        jdbc_password => "1"
        schedule => "* * * * *"
        statement => "select * from posts"
    }
    tcp {
        port => 5000
    }
}

## Add your filters / logstash plugins configuration here

output {
    elasticsearch {
        hosts => ["elasticsearch:9200"]
        index => "posts"
        document_type => "post"
        document_id => "%{id}" ## must be lower case
    }
}

I run docker with docker-compose. Kibana and ElasticSearch start successfully but Logstash throw error

LoadError: no such file to load -- /home/edsoft/IdeaProjects/docker-elk/resources/mysql-connector-java-5.1.36-bin
logstash_1       |                   require at org/jruby/RubyKernel.java:1040
logstash_1       |                   require at /usr/share/logstash/vendor/bundle/jruby/1.9/gems/polyglot-0.3.5/lib/polyglot.rb:65
logstash_1       |              load_drivers at /usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-jdbc-4.1.3/lib/logstash/plugin_mixins/jdbc.rb:134
logstash_1       |                      each at org/jruby/RubyArray.java:1613
logstash_1       |              load_drivers at /usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-jdbc-4.1.3/lib/logstash/plugin_mixins/jdbc.rb:132
logstash_1       |   prepare_jdbc_connection at /usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-jdbc-4.1.3/lib/logstash/plugin_mixins/jdbc.rb:146
logstash_1       |                  register at /usr/share/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-jdbc-4.1.3/lib/logstash/inputs/jdbc.rb:191
logstash_1       |           register_plugin at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:282
logstash_1       |          register_plugins at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:293
logstash_1       |                      each at org/jruby/RubyArray.java:1613
logstash_1       |          register_plugins at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:293
logstash_1       |              start_inputs at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:436
logstash_1       |             start_workers at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:337
logstash_1       |                       run at /usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:232
logstash_1       |            start_pipeline at /usr/share/logstash/logstash-core/lib/logstash/agent.rb:387

I write path ...bin.jar but error delete .jar from filename. I write ..bin.jar.jar error code is ..bin.jar but doesn't find the file.

Please help me

Thank you


问:
Is a global variable the only way to return the built AST in bison?
To return the fully built AST, I was told I should use a global variable in which I store it:

```<code>%{

AST::Root* root;

%}

%start program

%%

program:
    ...            { $$ = root = new AST::Root(...) }
    ...
    ;
</code>```

But is this the only way? Or is there a better way, maybe a way to return the AST directly from yyparse()?

答: You can use %parse-param for adding additional parameters to yyparse(). There is descrition

Body:
To return the fully built AST, I was told I should use a global variable in which I store it:

%{

AST::Root* root;

%}

%start program

%%

program:
    ...            { $$ = root = new AST::Root(...) }
    ...
    ;

But is this the only way? Or is there a better way, maybe a way to return the AST directly from yyparse()?


问:
Lower Case Certain Words R
I need to convert certain words to lower case. I am working with a list of movie titles, where prepositions and articles are normally lower case if they are not the first word in the title. If I have the vector:

movies = c('The Kings Of Summer', 'The Words', 'Out Of The Furnace', 'Me And Earl And The Dying Girl')

What I need is this:

movies_updated = c('The Kings of Summer', 'The Words', 'Out of the Furnace', 'Me and Earl and the Dying Girl')

Is there an elegant way to do this without using a long series of gsub(), as in:

```<code>movies_updated = gsub(' In ', ' in ', movies)
movies_updated = gsub(' In', ' in', movies_updated)
movies_updated = gsub(' Of ', ' of ', movies)
movies_updated = gsub(' Of', ' of', movies_updated)
movies_updated = gsub(' The ', ' the ', movies)
movies_updated = gsub(' the', ' the', movies_updated)
</code>```

And so on.

答:
Though I like @Konrad's answer for its succinctness, I'll offer an alternative that is more literal and manual.

```<code>movies = c('The Kings Of Summer', 'The Words', 'Out Of The Furnace',
           'Me And Earl And The Dying Girl')

gr <- gregexpr("(?<!^)\\b(of|in|the)\\b", movies, ignore.case = TRUE, perl = TRUE)
mat <- regmatches(movies, gr)
regmatches(movies, gr) <- lapply(mat, tolower)
movies
# [1] "The Kings of Summer"            "The Words"
# [3] "Out of the Furnace"             "Me And Earl And the Dying Girl"
</code>```

The tricks of the regular expression:

(?<!^) ensures we don't match a word at the beginning of a string. Without this, the first The of movies 1 and 2 will be down-cased.

\\b sets up word-boundaries, such that in in the middle of Dying will not match. This is slightly more robust than your use of space, since hyphens, commas, etc, will not be spaces but do indicate the beginning/end of a word.

(of|in|the) matches any one of of, in, or the. More patterns can be added with separating pipes |.

Once identified, it's as simple as replacing them with down-cased versions.

Title: Lower Case Certain Words R

Body:
I need to convert certain words to lower case. I am working with a list of movie titles, where prepositions and articles are normally lower case if they are not the first word in the title. If I have the vector:

movies = c('The Kings Of Summer', 'The Words', 'Out Of The Furnace', 'Me And Earl And The Dying Girl')

What I need is this:

movies_updated = c('The Kings of Summer', 'The Words', 'Out of the Furnace', 'Me and Earl and the Dying Girl')

Is there an elegant way to do this without using a long series of gsub(), as in:

movies_updated = gsub(' In ', ' in ', movies)
movies_updated = gsub(' In', ' in', movies_updated)
movies_updated = gsub(' Of ', ' of ', movies)
movies_updated = gsub(' Of', ' of', movies_updated)
movies_updated = gsub(' The ', ' the ', movies)
movies_updated = gsub(' the', ' the', movies_updated)

And so on.

Body:
Though I like @Konrad's answer for its succinctness, I'll offer an alternative that is more literal and manual.

movies = c('The Kings Of Summer', 'The Words', 'Out Of The Furnace',
           'Me And Earl And The Dying Girl')

gr <- gregexpr("(?<!^)\\b(of|in|the)\\b", movies, ignore.case = TRUE, perl = TRUE)
mat <- regmatches(movies, gr)
regmatches(movies, gr) <- lapply(mat, tolower)
movies
# [1] "The Kings of Summer"            "The Words"
# [3] "Out of the Furnace"             "Me And Earl And the Dying Girl"

The tricks of the regular expression:

(?<!^) ensures we don't match a word at the beginning of a string. Without this, the first The of movies 1 and 2 will be down-cased.

\\b sets up word-boundaries, such that in in the middle of Dying will not match. This is slightly more robust than your use of space, since hyphens, commas, etc, will not be spaces but do indicate the beginning/end of a word.

(of|in|the) matches any one of of, in, or the. More patterns can be added with separating pipes |.

Once identified, it's as simple as replacing them with down-cased versions.


问:
How to sort a mutable array with reference to Date which is saved as "object for key" in iphone?
I am new to iphone development .I have mutable array recent in which the values such as title,date,url and summary are stored as " object for key".The keys are myurl,mudate,mytitle,mysummary.I want to sort that mutable array in reference to date and print all the values according to that..How can i achieve that?Please help me out.Thanks.

```<code>            [item setObject:currentTitle forKey:@"title"];
            [item setObject:currentLink forKey:@"link"];
            [item setObject:currentSummary forKey:@"description"];
            [item setObject:currentDate forKey:@"pubDate"];//
            [item setObject:currentImage forKey:@"imagePath"];

            [recent addObject:[item copy]];
</code>```

All are xml parsed contents.

答:
Swift 3.0

```<code> let descriptor = NSSortDescriptor(key: "Your array KEY", ascending: false)

 yourArray.sort(using: [descriptor])
</code>```

for ascending sorting make it "true" and else make it "false".

Body:
I am new to iphone development .I have mutable array recent in which the values such as title,date,url and summary are stored as " object for key".The keys are myurl,mudate,mytitle,mysummary.I want to sort that mutable array in reference to date and print all the values according to that..How can i achieve that?Please help me out.Thanks.

            [item setObject:currentTitle forKey:@"title"];
            [item setObject:currentLink forKey:@"link"];
            [item setObject:currentSummary forKey:@"description"];
            [item setObject:currentDate forKey:@"pubDate"];//
            [item setObject:currentImage forKey:@"imagePath"];

            [recent addObject:[item copy]];

All are xml parsed contents.

Body:
Swift 3.0

 let descriptor = NSSortDescriptor(key: "Your array KEY", ascending: false)

 yourArray.sort(using: [descriptor])

for ascending sorting make it "true" and else make it "false".


问:
magick image resize
I am using magick library in R.

I am using the following command but it is not working correctly

```<code>shoe <- image_read('F:/photo.jpg')
image_scale(shoe,'382x509')

format width height colorspace filesize
JPEG   382    460       sRGB        0
</code>```

The width is set to 382 but not height. so I set height by following command

```<code>image_scale(shoe,'X509')

format width height colorspace filesize
JPEG   423    509       sRGB        0
</code>```

Now it changed the width. Is there any way to turn off the aspect ratio while resizing?

答:
Reading the original documentation here brings the solution:</p>

```<code>image_scale(shoe,"382x509!")
#  format width height colorspace filesize
#1   JPEG   382    509       sRGB        0
</code>```

Title: magick image resize

Body:
I am using magick library in R.

I am using the following command but it is not working correctly

shoe <- image_read('F:/photo.jpg')
image_scale(shoe,'382x509')

format width height colorspace filesize
JPEG   382    460       sRGB        0

The width is set to 382 but not height. so I set height by following command

image_scale(shoe,'X509')

format width height colorspace filesize
JPEG   423    509       sRGB        0

Now it changed the width. Is there any way to turn off the aspect ratio while resizing?

Body:
Reading the original documentation here brings the solution:

image_scale(shoe,"382x509!")
#  format width height colorspace filesize
#1   JPEG   382    509       sRGB        0


问:
Build failed with error Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc
I am using Xcode 8.2.1. I am also using CoreData in my project.
When I try to generate a build or when I archive I am seeing the following error. Files mentioned in the error also changes at times.

ERROR:

```<code><unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/StateRegionMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataProperties.swift'
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
</code>```

Here is how my CoreData Entities are configured:

Things I have Tried:

Check the location to see if files are actually missing, Files where present exactly at the same path.

I cleaned the build folder and removed derived data and build it again. Nothing helped.

Tried all the answers in this link. Nothing Worked.

Accepted Answer of this question doesn't seem to work either.

I am not sure why this error is coming. Any help is appreciated

EDIT

If I completely remove CoreData from my code then it Archives Successfully.

EDIT 2 :

When I change CodeGen to Manual/None and add files manually as suggested by @Anil . It builds successfully, But when I try to fetch the CoreData entity using :

```<code>let context = appDelegate.persistentContainer.viewContext
let buildingRoofMapping = BuildingRoofMapping(context:context)
</code>```

It gives me run time error.
Error :

```<code>'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'BuildingRoofMapping' must have a valid NSEntityDescription.'
</code>```

EDIT 3:
   Sample Code link. Run it in simulator. It crashes in fetchBasicPrice() of ViewController.swift file

答:
I am writing it as an answer because I am not allowed to comment yet.
From your comments I have assumed that you have cleaned the derived folder as well as deleted the app from simulator as well as from device while building on it.

Did you try setting Build Active Architecture Only flag to No in the Project settings tab? If not please do that as well.

While archiving, the app will be built for all targets. And thus some issue might surface which you would have missed by setting the flag to Yes during development.

Body:
I am using Xcode 8.2.1. I am also using CoreData in my project.
When I try to generate a build or when I archive I am seeing the following error. Files mentioned in the error also changes at times.

ERROR:

<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/BuildingRoofMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/Region+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/StateRegionMapping+CoreDataProperties.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataClass.swift'
<unknown>:0: error: no such file or directory: '/Users/anuragparashar/Library/Developer/Xcode/DerivedData/app-drgjxhipxxqdrcatqfdgpayyxnud/Build/Intermediates/app.build/Debug-iphoneos/app.build/DerivedSources/CoreDataGenerated/app/WalkingDoors+CoreDataProperties.swift'
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

Here is how my CoreData Entities are configured:

Things I have Tried:

Check the location to see if files are actually missing, Files where present exactly at the same path.

I cleaned the build folder and removed derived data and build it again. Nothing helped.

Tried all the answers in this link. Nothing Worked.

Accepted Answer of this question doesn't seem to work either.

I am not sure why this error is coming. Any help is appreciated

EDIT

If I completely remove CoreData from my code then it Archives Successfully.

EDIT 2 :

When I change CodeGen to Manual/None and add files manually as suggested by @Anil . It builds successfully, But when I try to fetch the CoreData entity using :

let context = appDelegate.persistentContainer.viewContext
let buildingRoofMapping = BuildingRoofMapping(context:context)

It gives me run time error.
Error :

'NSInvalidArgumentException', reason: 'An NSManagedObject of class 'BuildingRoofMapping' must have a valid NSEntityDescription.'

EDIT 3:
   Sample Code link. Run it in simulator. It crashes in fetchBasicPrice() of ViewController.swift file


问:
Hide footer view in ListView?
I have a ListView. The data behind it is fetched from the Internet, in sets of 10-30 items whenever the user scrolls all the way to the bottom. In order to indicate that it is loading more items, I used addFooterView() to add a simple view that displays a "Loading..." message and a spinner. Now, when I'm out of data (no more data to fetch), I want to hide that message. I tried to do:

```<code>loadingView.setVisibility(View.GONE);
</code>```

Unfortunately, while that does hide the view, it leaves space for it. I.e. I end up with a big blank space where the "Loading" message used to be. How can I go about properly hiding this view?

I can't use removeFooterView() because I may need to show it again, in which case I can't call addFooterView() again because an adapter has already been set on the ListView, and you can't call addHeaderView() / addFooterView() after setting an adapter.

答: Try setting the footer's height to 0px or 1px before hiding it. Alternatively, wrap the footer view in a wrap_content height FrameLayout and hide/show the inner view, leaving the FrameLayout visible; the height should wrap properly then.

Title: Hide footer view in ListView?

Body:
I have a ListView. The data behind it is fetched from the Internet, in sets of 10-30 items whenever the user scrolls all the way to the bottom. In order to indicate that it is loading more items, I used addFooterView() to add a simple view that displays a "Loading..." message and a spinner. Now, when I'm out of data (no more data to fetch), I want to hide that message. I tried to do:

loadingView.setVisibility(View.GONE);

Unfortunately, while that does hide the view, it leaves space for it. I.e. I end up with a big blank space where the "Loading" message used to be. How can I go about properly hiding this view?

I can't use removeFooterView() because I may need to show it again, in which case I can't call addFooterView() again because an adapter has already been set on the ListView, and you can't call addHeaderView() / addFooterView() after setting an adapter.


问:
Cannot repair Visual Studio after I canceled update
I cancelled updates installation for visual studio community 2017 RC.
Now, i cannot repair or open it. how resolve issue?

I need way to repair without uninstall/Reinstall ,because i have many packages installed on visual studio ,it would removed.

Note:When open visual studio,  i get error "The setup for this Installation was not Complete please run the Installer again to Correct the Issue"

答: The best way is to uninstall and then reinstall because you might mess up the files if try to fix it by yourself and there many reason as to why the updated didn't go as planned. Good Luck!</p>


问:
How much training data is needed for a speaker-dependent speech recognition system?
To implement a high-accuracy (< 15% WER) speaker-dependent ASR system, how much training data is needed from the speaker?

Also, are speaker-dependent models usually supplemented with a larger corpus of audio (from many speakers)? Or do they only use data from the single speaker?

答:
To implement a high-accuracy (< 15% WER) speaker-dependent ASR system, how much training data is needed from the speaker?

30-40 hours.

Also, are speaker-dependent models usually supplemented with a larger corpus of audio (from many speakers)?

Sometimes.

Or do they only use data from the single speaker?

It is possible to build speaker-dependent speaker from 1-2 hours of speaker data and 300+ hours of data from other speakers. It is less straightforward path than to collect single speaker data.


问:
NodeJS Express Async issue
I have this function which gets some data from my database but i'm having a trouble calling the function and getting the proper response

```<code>  function getEvents()
  {
    var x = [];
    var l = dbCollection['e'].find({}).forEach(function(y) {
    x.push(y);
  });

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

and another function which calls this function but it always returns undefined.
How can i make the function wait till mongoose has finished filling up the array?

Thanks for the help! My life

答:
dbCollection['e'].find is called non-blocking way so you are returning x before filling. You need to use callbacks or some mongoose promises. You can get all returning values from database like following snippet

```<code>function getEvents(callback) {
    dbCollection['e'].find({}, function(error, results) {
        // results is array.
        // if you need to filter results you can do it here
        return callback(error, results);
    })
}
</code>```

Whenever you need to call getEvents function you need to pass a callback to it.

```<code>getEvents(function(error, results) {
    console.log(results); // you have results here
})
</code>```

You should read mongoose docs for how queries work.

There is also support for promises in mongoose. You can check this url for more information about promises.

Title: NodeJS Express Async issue

Body:
I have this function which gets some data from my database but i'm having a trouble calling the function and getting the proper response

  function getEvents()
  {
    var x = [];
    var l = dbCollection['e'].find({}).forEach(function(y) {
    x.push(y);
  });

 return x;
});

and another function which calls this function but it always returns undefined.
How can i make the function wait till mongoose has finished filling up the array?

Thanks for the help! My life

Body:
dbCollection['e'].find is called non-blocking way so you are returning x before filling. You need to use callbacks or some mongoose promises. You can get all returning values from database like following snippet

function getEvents(callback) {
    dbCollection['e'].find({}, function(error, results) {
        // results is array.
        // if you need to filter results you can do it here
        return callback(error, results);
    })
}

Whenever you need to call getEvents function you need to pass a callback to it.

getEvents(function(error, results) {
    console.log(results); // you have results here
})

You should read mongoose docs for how queries work.

There is also support for promises in mongoose. You can check this url for more information about promises.


问:
Relative path not resolved in nodejs
I create a module named core that has core functionality of the project.
I also created a services project that used the core project in nodejs. This core module to be included as node_modules dependency (package.json) in service-app.

my service app call the core app and core app uses relative path:

```<code>//core-app -> logger.js

const loggerConfig = require('../../configs/logger-config.json');
</code>```

When service app start then it require core-app -> logger.js

```<code>const logger = require('core');
</code>```

than it prompt error

```<code>Error: Cannot find module '../../configs/logger-config.json
</code>```

Here ../../configs/logger-config.json is correct and it sometimes runnig on other system properly.

Now, I replace the relative path to,

```<code>//core-app -> logger.js
const path = require('path');
const loggerConfig = require(path.join(__dirname,'../../configs/logger-config.json'));
</code>```

then it is running.

I resolved error but not sure about code standard. For reference, I checked the other node_modules library and found they also used relative in the same manner but my case it prompts an error.

答: __dirname gives the current directory where the thread executes in nodejs. So, in place of relative path better to use through __dirname.

Title: Relative path not resolved in nodejs

Body:
I create a module named core that has core functionality of the project.
I also created a services project that used the core project in nodejs. This core module to be included as node_modules dependency (package.json) in service-app.

my service app call the core app and core app uses relative path:

//core-app -> logger.js

const loggerConfig = require('../../configs/logger-config.json');

When service app start then it require core-app -> logger.js

const logger = require('core');

than it prompt error

Error: Cannot find module '../../configs/logger-config.json

Here ../../configs/logger-config.json is correct and it sometimes runnig on other system properly.

Now, I replace the relative path to,

//core-app -> logger.js
const path = require('path');
const loggerConfig = require(path.join(__dirname,'../../configs/logger-config.json'));

then it is running.

I resolved error but not sure about code standard. For reference, I checked the other node_modules library and found they also used relative in the same manner but my case it prompts an error.


问:
Drupal default views versus Views contrib module
Drupal has some built in views that work without Views contrib module. We even can not manage or alter them. frontpage and taxonomy_term are two examples of such views. They are known as default views.

How can we generate our own views via module development?

My other question is about Views contrib module.

How views module enhances drupal's capabilities about views?

答:
Built-in list pages in Drupal (like the one listing all nodes) are strictly speaking not "views", because they are not powered by the Views module. After installing the Views module, you can replace the built-in list pages with your own views or add custom views for administrative tasks.

If you download version 3 (in alpha at the moment) of the admin_menu module you will also get the admin_views module, which can replace all built-in lists with 'real' views.

If you want to learn how to include a default view in your module, see this blog post.


问:
Error Login In My HMVC Code Igniter
i have a problem with my login in application . in my login authentication a create a library name is "auth" and i also was call "auth" in autoload but when i call a function in "auth" the error say

```<code>Message: Undefined property: Auth::$session
</code>```

here is my library "auth"

```<code>class Auth {
    public function cek_auth()
    {
        $this->ci =& get_instance();
        $this->sesi  = $this->ci->session->userdata('isLogin');
        $this->hak = $this->ci->session->userdata('stat');
        if($this->sesi != TRUE){
            $this->session->set_flashdata("pesan", "Sesi Login anda telah habis");
            redirect('user/login');
            exit();
        }

    }
    public function hak_akses($kecuali="")
    {
        if($this->hak==$kecuali){
            echo "<script>alert('Anda tidak berhak mengakses halaman ini!');</script>";
            redirect('dashboard');
        }elseif ($this->hak=="") {
            echo "<script>alert('Silahkan Login!');</script>";
            redirect('c_login','refresh');
        }else{

        }
    }
}
</code>```

my controller :
class Dashboard extends CI_Controller{

```<code>function __construct()
{
    parent::__construct();
    $this->auth->cek_auth(); //ngambil auth dari library
}
function index()
{
    $hak_akses = $this->session->userdata('lvl');
    if($hak_akses==1) {

        $data['content'] = 'dashboard';
        return $this->load->view('theme/index', $data);
    }

}
</code>```

}

and my autoload :

```<code>$autoload['libraries'] = array('database','form_validation','session','auth','parser');
</code>```

please give me a best solution , thanks

答:
If you are using session in your code then make sure to autoload in config.php file by setting an encryption key. If you don't autoload it then you can load it using $this->load->library('session'). But you must set encryption key in order to autoload or load session in controller functions.

Reference : Undefined property: CI::$session.

Hope this helps :)

Title: Error Login In My HMVC Code Igniter

Body:
i have a problem with my login in application . in my login authentication a create a library name is "auth" and i also was call "auth" in autoload but when i call a function in "auth" the error say

Message: Undefined property: Auth::$session

here is my library "auth"

class Auth {
    public function cek_auth()
    {
        $this->ci =& get_instance();
        $this->sesi  = $this->ci->session->userdata('isLogin');
        $this->hak = $this->ci->session->userdata('stat');
        if($this->sesi != TRUE){
            $this->session->set_flashdata("pesan", "Sesi Login anda telah habis");
            redirect('user/login');
            exit();
        }

    }
    public function hak_akses($kecuali="")
    {
        if($this->hak==$kecuali){
            echo "";
            redirect('dashboard');
        }elseif ($this->hak=="") {
            echo "";
            redirect('c_login','refresh');
        }else{

        }
    }
}

my controller :
class Dashboard extends CI_Controller{

function __construct()
{
    parent::__construct();
    $this->auth->cek_auth(); //ngambil auth dari library
}
function index()
{
    $hak_akses = $this->session->userdata('lvl');
    if($hak_akses==1) {

        $data['content'] = 'dashboard';
        return $this->load->view('theme/index', $data);
    }

}

}

and my autoload :

$autoload['libraries'] = array('database','form_validation','session','auth','parser');

please give me a best solution , thanks