问:
app:transformDexArchiveWithExternalLibsDexMergerForDebug
hi guys i get this error when i try to run my app

Error:Execution failed for task
':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

i don't know why!

I tried also to clean and rebuild project but i get always the same error!

Now i post my gradle:

```<code>android {
    compileSdkVersion 23
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.compscitutorials.basigarcia.navigationdrawervideotutorial"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'    }
}

dependencies {
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.1'
    compile 'de.hdodenhof:circleimageview:1.3.0'
    //noinspection GradleCompatible
    compile 'com.android.support:recyclerview-v7:26.1.0'
    //noinspection GradleCompatible
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.github.bumptech.glide:glide:3.8.0'
    //compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.exoplayer:exoplayer:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-core:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-dash:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-hls:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-ui:r2.4.0'
    compile 'com.facebook.android:facebook-android-sdk:3.21.1'
    //noinspection DuplicatePlatformClasses
    implementation 'org.apache.httpcomponents:httpclient:4.5.3'
}
</code>```

答:
Try this:-

Step1: Modify the app-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

```<code>android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 26
        multiDexEnabled true
    }

}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}
</code>```

Step 2: If you do override the Application class,

```<code>public class MyApplication extends Application {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}
</code>```

More info please check this link

Body:
hi guys i get this error when i try to run my app

Error:Execution failed for task
':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

i don't know why!

I tried also to clean and rebuild project but i get always the same error!

Now i post my gradle:

android {
    compileSdkVersion 23
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "com.compscitutorials.basigarcia.navigationdrawervideotutorial"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'    }
}

dependencies {
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.1'
    compile 'de.hdodenhof:circleimageview:1.3.0'
    //noinspection GradleCompatible
    compile 'com.android.support:recyclerview-v7:26.1.0'
    //noinspection GradleCompatible
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.github.bumptech.glide:glide:3.8.0'
    //compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.android.exoplayer:exoplayer:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-core:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-dash:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-hls:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-smoothstreaming:r2.4.0'
    compile 'com.google.android.exoplayer:exoplayer-ui:r2.4.0'
    compile 'com.facebook.android:facebook-android-sdk:3.21.1'
    //noinspection DuplicatePlatformClasses
    implementation 'org.apache.httpcomponents:httpclient:4.5.3'
}

Body:
Try this:-

Step1: Modify the app-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 26
        multiDexEnabled true
    }

}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

Step 2: If you do override the Application class,

public class MyApplication extends Application {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}

More info please check this link


来源: stackexchange

问:
mysql - compare data in different rows and columns in mysql
i have one table containing 3 columns. basically 2 but i have generated the 3rd one so i can compare it to the first column.

```
DATE       |TX  |PREV_WEEK
------------------------------
2017-12-05 |52  | 2017-05-28 |
2017-12-04 |95  | 2017-05-27 |
2017-12-03 |123 | 2017-05-26 |
2017-12-02 |20  | 2017-05-25 |
2017-12-01 |66  | 2017-05-24 |
2017-11-30 |2   | 2017-05-23 |
2017-05-29 |250 | 2017-05-22 |
2017-05-28 |28  | 2017-05-21 |
2017-05-27 |85  | 2017-05-20 |
```

what i need is to get a query/table to compare  current days' TX with the previous weeks TX. Therefore i need to add a column with the previous weeks' TX(PREV_TX)  next to PREV_WEEk.

Is there an easy way to perform this using mysql?.

答:
```<code>select tmp.date,
       tmp.tx,
       tmp.prev_week,
       tmp.prev_tx,
   // you can compare both tx here, like finding difference as follows
      coalesce(abs(tmp.prev_tx - tmp.tx),0) as diff
From
(
select t1.date,
       t1.tx,
       t1.prev_week,
       (select tx
        from table t2
        where t2.date = t1.prev_week
       ) as prev_tx
from table t1
group by t1.date
) tmp
;
</code>```

Hope it helps!

ContentLicense: CC BY-SA 3.0

Body:
i have one table containing 3 columns. basically 2 but i have generated the 3rd one so i can compare it to the first column.

DATE       |TX  |PREV_WEEK
------------------------------
2017-12-05 |52  | 2017-05-28 |
2017-12-04 |95  | 2017-05-27 |
2017-12-03 |123 | 2017-05-26 |
2017-12-02 |20  | 2017-05-25 |
2017-12-01 |66  | 2017-05-24 |
2017-11-30 |2   | 2017-05-23 |
2017-05-29 |250 | 2017-05-22 |
2017-05-28 |28  | 2017-05-21 |
2017-05-27 |85  | 2017-05-20 |

what i need is to get a query/table to compare  current days' TX with the previous weeks TX. Therefore i need to add a column with the previous weeks' TX(PREV_TX)  next to PREV_WEEk.

Is there an easy way to perform this using mysql?.

Body:
select tmp.date,
       tmp.tx,
       tmp.prev_week,
       tmp.prev_tx,
   // you can compare both tx here, like finding difference as follows
      coalesce(abs(tmp.prev_tx - tmp.tx),0) as diff
From
(
select t1.date,
       t1.tx,
       t1.prev_week,
       (select tx
        from table t2
        where t2.date = t1.prev_week
       ) as prev_tx
from table t1
group by t1.date
) tmp
;

Hope it helps!


问:
livy - server limit number of jobs
I am looking for some configuration in order to limit my livy server to not use more than X cores or number of jobs, I saw that someone already asked this in the Jira issues (https://issues.cloudera.org/browse/LIVY-74 ), and he got answered that Yarn is doing that, but I don't need yarn since I don't want to control my jobs / sessions per user and I don't have any other resources to manage except spark.

答:
You can take these properties as an example:</p>

```<code>livy.spark.driver.cores 1
livy.spark.driver.memory    512m
livy.spark.dynamicAllocation.cachedExecutorIdleTimeout
livy.spark.dynamicAllocation.enabled    true
livy.spark.dynamicAllocation.initialExecutors   1
livy.spark.dynamicAllocation.maxExecutors   5
livy.spark.dynamicAllocation.minExecutors   1
livy.spark.executor.cores   2
livy.spark.executor.instances   5
livy.spark.executor.memory  2G
</code>```

Title: livy - server limit number of jobs

Body:
You can take these properties as an example:

livy.spark.driver.cores 1
livy.spark.driver.memory    512m
livy.spark.dynamicAllocation.cachedExecutorIdleTimeout
livy.spark.dynamicAllocation.enabled    true
livy.spark.dynamicAllocation.initialExecutors   1
livy.spark.dynamicAllocation.maxExecutors   5
livy.spark.dynamicAllocation.minExecutors   1
livy.spark.executor.cores   2
livy.spark.executor.instances   5
livy.spark.executor.memory  2G


问:
Formula that deletes filtered results, but if nothing is found, deletes everything
```<code>Dim rng3 As Range

    Set rng3 = Range("J1").CurrentRegion

    rng3.AutoFilter Field:=10, Criteria1:="<>", Operator:=xlFilterValues

    With rng3
        With .Offset(1).Resize(.Rows.Count - 1)
            Application.DisplayAlerts = False
            .Rows.Delete
            Application.DisplayAlerts = True
        End With
    End With
</code>```

The above code (in theory) filters on "J1", anything that is other than blank ("<>") and then deletes the results. The problem is if there is already just blank data in column J it deletes everything.

答:
I've just tried and tested the following and it does as you expect:

```<code>Sub foo()
    Set rng3 = Range("J1").CurrentRegion
    rng3.AutoFilter Field:=10, Criteria1:="<>", Operator:=xlFilterValues

    With rng3.SpecialCells(xlCellTypeVisible)
            Application.DisplayAlerts = False
            NewAddress = Replace(rng3.Rows.Name, "A$1", "A$2")
            Range(NewAddress).Delete
            Application.DisplayAlerts = True
    End With
End Sub
</code>```

Or using a different approach:

```<code>Sub foo2()
LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row 'Find the last row with data on Column A

For i = 2 To LastRow 'Loop from Row 2 to the Last Row with data
    If Sheet1.Cells(i, 10).Value <> "" Then Sheet1.Rows(i).Delete 'Check Column J for any value, and if it has a value delete that row
Next i
End Sub
</code>```

Body:
Dim rng3 As Range

    Set rng3 = Range("J1").CurrentRegion

    rng3.AutoFilter Field:=10, Criteria1:="<>", Operator:=xlFilterValues

    With rng3
        With .Offset(1).Resize(.Rows.Count - 1)
            Application.DisplayAlerts = False
            .Rows.Delete
            Application.DisplayAlerts = True
        End With
    End With

The above code (in theory) filters on "J1", anything that is other than blank ("<>") and then deletes the results. The problem is if there is already just blank data in column J it deletes everything.

Body:
I've just tried and tested the following and it does as you expect:

Sub foo()
    Set rng3 = Range("J1").CurrentRegion
    rng3.AutoFilter Field:=10, Criteria1:="<>", Operator:=xlFilterValues

    With rng3.SpecialCells(xlCellTypeVisible)
            Application.DisplayAlerts = False
            NewAddress = Replace(rng3.Rows.Name, "A$1", "A$2")
            Range(NewAddress).Delete
            Application.DisplayAlerts = True
    End With
End Sub

Or using a different approach:

Sub foo2()
LastRow = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row 'Find the last row with data on Column A

For i = 2 To LastRow 'Loop from Row 2 to the Last Row with data
    If Sheet1.Cells(i, 10).Value <> "" Then Sheet1.Rows(i).Delete 'Check Column J for any value, and if it has a value delete that row
Next i
End Sub


问:
Python/SQL - WHERE clause not applying to all Rows
I am having a problem with the following code in a Python program I built. The program pulls data from a database and puts it into an Excel spreadsheet based on a list of reference numbers 'GrantRefNumber' that they input.

It works, but for some reason only the FIRST reference number has the 'a.reporting_period_id like 'none-' applied to it, the rest do not.

I am using a variable substitution in the SQL code to put the list of reference numbers into the string.

Any help would be much appreciated!

SQL:

```<code>"SELECT a.fa_reference as [GrantRefNumber],
a.fa_name as [Award Title],
a.location as [RO],
ISNULL(cat.grant_department_name, '') as [Department],
a.funding_start_date as [Start Date],
a.funding_end_date as [End Date],
a.[pi]    as [PI ID],
a.pi_initials  as [PI Name],
a.pi_surname as [PI Surname],
r1_2 as [Type],

DATEADD(s, cast(last_submitted_date as int), '1970-01-01 00:00:00') as [Submitted Date]

from keywordagreements a inner join entries_publications p on a.id =
p.agreement_id left outer join mrc_categories cat  on a.origid = cat.id and cat.centre not in ('2')

where a.[pi] NOT LIKE 'S%' and response_code not like 'Test' and Closed is null
and a.reporting_period_id like 'none-'
and a.funding_organisation not like '%UKSA%' and {}'

Order by [RO], [PI ID], [GrantRefNumber]".format(finalList)
</code>```

finalList (variable substitution):

The finalList is a list of Reference Numbers that I get from the user in Python called 'items'

```<code>items = dfCall['GrantRefNumber'].values.tolist()
refList = " OR ".join(["a.fa_reference LIKE '%s'" % num for num in items])
finalList = refList[:-1]
</code>```

I am using PYODBC to extract the data.

The SQL in my code looks like this (I removed the quote marks (and some of the columns) in the previous code to make it easier to read):

```<code>stringQ = "SELECT a.fa_reference as [GrantRefNumber], a.fa_name as [Award Title]," \
          " a.location  as [RO], ISNULL(cat.grant_department_name, '') as [Department]," \
          " a.funding_start_date as [Start Date], a.funding_end_date        as [End Date]," \
          " a.[pi]  as [PI ID], a.pi_initials   as [PI Name]," \
          " a.pi_surname as [PI Surname], " \
          " r1_2 as [Type], ISNULL(r1_2_1, '')  as [PubMed ID]," \
          " r1_2_2  as [Author], r1_2_3 as [Publication], ISNULL(r1_2_4, '') as [Journal]," \
          " ISNULL(r1_2_8, '') as [Month], ISNULL(r1_2_9, '') as [Year], ISNULL(r1_2_4_1, '') as [Conference]," \
          " ISNULL(r1_2_36, '') as [PubMed Central ID], ISNULL (r1_2_19, '') as [DOI]," \
          " case when nullif(r1_2_1,'') is not null then 'http://europepmc.org/abstract/MED/' + r1_2_1 else case when" \
          " nullif(r1_4,'') is not null then r1_4 else case when nullif(r1_2_19,'') is not null then" \
          " 'http://dx.doi.org/' + r1_2_19 else isnull(r1_2_1,'') end  end end as [URL], ISNULL(r1_2_21, '') " \
          "as [ISBN]," \
          " ISNULL(r1_2_30, '') as [ISBN (Electronic)], " \
          " ISNULL(r1_2_25, '') as [Chapter Number], " \
          "ISNULL(r1_2_26, '')" \
          " as [Chapter Title], ISNULL(r1_2_27, '') as [Chapter Author]," \
          " ISNULL(r1_2_29, '') as [ISSN (Print)], ISNULL(r1_2_32, '')  as [ISSN (Digital)], " \
          "ISNULL(r1_2_31, '')  as [Web of Science ID], ISNULL(r1_2_34, '') as [Scopus ID], " \
          "ISNULL(r1_2_35, '')  as [arXiv DepositID]," \
          " ISNULL(r1_2_38, '') as [Bibcode], ISNULL(r1_2_39, '') as [Ethos], ISNULL(r1_2_43, '')   as [NASA-ADS ID]," \
          " ISNULL(r1_2_46, '') as [Inspire], ISNULL(r1_2_40, '') as [PMC Manuscript ID], ISNULL(r1_2_45, '')" \
          " as [ORCID Work Putcode]," \
          " ISNULL(r1_2_61, '') as [OpenAire Access License], ISNULL(r1_2_52, '') " \
          "as [In EPMC?], ISNULL(r1_2_53, '') as [In PMC?]," \
          " ISNULL(r1_2_51, '') as [EPMC Open Access], " \
          " DATEADD(s, cast(last_submitted_date as int), '1970-01-01 00:00:00') as [Submitted Date] " \
          "from keywordagreements a inner join entries_publications p on a.id = " \
          "p.agreement_id left outer join mrc_categories cat " \
          "on a.origid = cat.id and cat.centre not in ('2') where a.[pi] NOT LIKE 'S%' and " \
          "response_code not like 'Test' and Closed is null " \
          "and a.reporting_period_id like 'none-' " \
          "and a.funding_organisation not like '%UKSA%' and {}' " \
          "Order by [RO], [PI ID], [GrantRefNumber]".format(finalList)
</code>```

答:
I'm not seeing where your format command substitutes. Here are a few examples of the format command:

```<code>'This is a {} string.'.format('formatted')
'This is a {0} {1}.'.format('formatted', 'string')
'This is a {replace_me} {replace_me_2}.'.format(replace_me='formatted', replace_me_2='string')
</code>```

Outputs This is a formatted string.

You'll need to modify you SQL to insert finalList into the SQL. Since we can't see your whole code, it also appear like you might want to use triple-quote formatting for multi-line support:

```<code>sql = """
    SELECT * FROM table
    WHERE blah = '{string_to_compare}'
""".format(string_to_compare='blah')
</code>```

Be very careful, you're open to SQL injection when using string substitution in any SQL query. Good luck!

Body:
I am having a problem with the following code in a Python program I built. The program pulls data from a database and puts it into an Excel spreadsheet based on a list of reference numbers 'GrantRefNumber' that they input.

It works, but for some reason only the FIRST reference number has the 'a.reporting_period_id like 'none-' applied to it, the rest do not.

I am using a variable substitution in the SQL code to put the list of reference numbers into the string.

Any help would be much appreciated!

SQL:

"SELECT a.fa_reference as [GrantRefNumber],
a.fa_name as [Award Title],
a.location as [RO],
ISNULL(cat.grant_department_name, '') as [Department],
a.funding_start_date as [Start Date],
a.funding_end_date as [End Date],
a.[pi]    as [PI ID],
a.pi_initials  as [PI Name],
a.pi_surname as [PI Surname],
r1_2 as [Type],

DATEADD(s, cast(last_submitted_date as int), '1970-01-01 00:00:00') as [Submitted Date]

from keywordagreements a inner join entries_publications p on a.id =
p.agreement_id left outer join mrc_categories cat  on a.origid = cat.id and cat.centre not in ('2')

where a.[pi] NOT LIKE 'S%' and response_code not like 'Test' and Closed is null
and a.reporting_period_id like 'none-'
and a.funding_organisation not like '%UKSA%' and {}'

Order by [RO], [PI ID], [GrantRefNumber]".format(finalList)

finalList (variable substitution):

The finalList is a list of Reference Numbers that I get from the user in Python called 'items'

items = dfCall['GrantRefNumber'].values.tolist()
refList = " OR ".join(["a.fa_reference LIKE '%s'" % num for num in items])
finalList = refList[:-1]

I am using PYODBC to extract the data.

The SQL in my code looks like this (I removed the quote marks (and some of the columns) in the previous code to make it easier to read):

stringQ = "SELECT a.fa_reference as [GrantRefNumber], a.fa_name as [Award Title]," \
          " a.location  as [RO], ISNULL(cat.grant_department_name, '') as [Department]," \
          " a.funding_start_date as [Start Date], a.funding_end_date        as [End Date]," \
          " a.[pi]  as [PI ID], a.pi_initials   as [PI Name]," \
          " a.pi_surname as [PI Surname], " \
          " r1_2 as [Type], ISNULL(r1_2_1, '')  as [PubMed ID]," \
          " r1_2_2  as [Author], r1_2_3 as [Publication], ISNULL(r1_2_4, '') as [Journal]," \
          " ISNULL(r1_2_8, '') as [Month], ISNULL(r1_2_9, '') as [Year], ISNULL(r1_2_4_1, '') as [Conference]," \
          " ISNULL(r1_2_36, '') as [PubMed Central ID], ISNULL (r1_2_19, '') as [DOI]," \
          " case when nullif(r1_2_1,'') is not null then 'http://europepmc.org/abstract/MED/' + r1_2_1 else case when" \
          " nullif(r1_4,'') is not null then r1_4 else case when nullif(r1_2_19,'') is not null then" \
          " 'http://dx.doi.org/' + r1_2_19 else isnull(r1_2_1,'') end  end end as [URL], ISNULL(r1_2_21, '') " \
          "as [ISBN]," \
          " ISNULL(r1_2_30, '') as [ISBN (Electronic)], " \
          " ISNULL(r1_2_25, '') as [Chapter Number], " \
          "ISNULL(r1_2_26, '')" \
          " as [Chapter Title], ISNULL(r1_2_27, '') as [Chapter Author]," \
          " ISNULL(r1_2_29, '') as [ISSN (Print)], ISNULL(r1_2_32, '')  as [ISSN (Digital)], " \
          "ISNULL(r1_2_31, '')  as [Web of Science ID], ISNULL(r1_2_34, '') as [Scopus ID], " \
          "ISNULL(r1_2_35, '')  as [arXiv DepositID]," \
          " ISNULL(r1_2_38, '') as [Bibcode], ISNULL(r1_2_39, '') as [Ethos], ISNULL(r1_2_43, '')   as [NASA-ADS ID]," \
          " ISNULL(r1_2_46, '') as [Inspire], ISNULL(r1_2_40, '') as [PMC Manuscript ID], ISNULL(r1_2_45, '')" \
          " as [ORCID Work Putcode]," \
          " ISNULL(r1_2_61, '') as [OpenAire Access License], ISNULL(r1_2_52, '') " \
          "as [In EPMC?], ISNULL(r1_2_53, '') as [In PMC?]," \
          " ISNULL(r1_2_51, '') as [EPMC Open Access], " \
          " DATEADD(s, cast(last_submitted_date as int), '1970-01-01 00:00:00') as [Submitted Date] " \
          "from keywordagreements a inner join entries_publications p on a.id = " \
          "p.agreement_id left outer join mrc_categories cat " \
          "on a.origid = cat.id and cat.centre not in ('2') where a.[pi] NOT LIKE 'S%' and " \
          "response_code not like 'Test' and Closed is null " \
          "and a.reporting_period_id like 'none-' " \
          "and a.funding_organisation not like '%UKSA%' and {}' " \
          "Order by [RO], [PI ID], [GrantRefNumber]".format(finalList)

Body:
I'm not seeing where your format command substitutes. Here are a few examples of the format command:

'This is a {} string.'.format('formatted')
'This is a {0} {1}.'.format('formatted', 'string')
'This is a {replace_me} {replace_me_2}.'.format(replace_me='formatted', replace_me_2='string')

Outputs This is a formatted string.

You'll need to modify you SQL to insert finalList into the SQL. Since we can't see your whole code, it also appear like you might want to use triple-quote formatting for multi-line support:

sql = """
    SELECT * FROM table
    WHERE blah = '{string_to_compare}'
""".format(string_to_compare='blah')

Be very careful, you're open to SQL injection when using string substitution in any SQL query. Good luck!


问:
What version control system should I use?
I'm working by myself on a project.  I'd like an easy to use, free, version control system that integrates with IntelliJ IDEA nicely.  I'd prefer if the whole repository was isolated to a single file, or folder, so that I could back it up on a USB stick easily and transfer it to another computer.</p>

答:
Take a look at Git. The whole repository is in the .git directory under your project root (by default) and I believe IntelliJ IDEA just integrated Git functionality recently.

Assuming you are going with the default (having the .git directory in the project root), then you can just copy your project to a USB stick and you have your project and repository to go.

ContentLicense: CC BY-SA 2.5


问:
How to set first N children height to its parent max-height jQuery or CSS(preferred)?
I have dynamically prepended divs (.class-row-notification) to another div (.class-append-con).

Now I want to set first 5 divs height to its parent's max-height (Including margin, padding, bottom-border etc.).

UPDATE

Addition of first five div class (.class-row-notification)(children div) == max-height of class(.class-append-con)(parent div)

How to do that ? If through CSS, it should be cross browser.

I tried it through jQuery but everytime it gives me same height as 11px for the div.class-row-notification

EDIT:-

I removed the commented code from snippet and tried again, its working here but not in my project why?

I have following html -

var notificationData = '[{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Shantaram :  Hello World !!!","notificationLink":"#","createdOn":1512640448139},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Spring : How are you, Shantaram ? !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Suyog :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Balasaheb :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Ravi :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Nilesh :  Hello World !!! Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!","notificationLink":"#","createdOn":1512640449140}]';

  notificationData = JSON.parse(notificationData);
//  console.log(notificationData);
//  console.log(notificationData.length);
  var len = notificationData.length - 5 ;
  var heightCon = 0;
  for( var i = 0; i < notificationData.length; ++i ) {
    contentText = jQuery(".class-notification-struct").clone(true);
    contentText.removeClass('class-notification-struct');
    /*contentText.find(".class-face-noti img").attr('src', notificationData.image);*/
    /*contentText.find(".class-name").html(notificationData[i].name);*/
    /*contentText.find(".class-notification-link").prop('href',notificationData[i].notificationLink);
    contentText.find(".class-notification-message").append(notificationData[i].message);
    var created_on_date = new  Date( notificationData[i].createdOn );
    contentText.find(".class-notification-time").append( created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString());
    */

    var created_on_date = new Date( notificationData[i].createdOn );
    var row_div =  "
"
                    +""
                      +""
                        +notificationData[i].message
                      +""
                      +""
                        +created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString()
                      +""
                    +""
                  +"
";
    jQuery(row_div).prependTo('.class-append-con');

//  if( len <= i ) {
//    heightCon += contentText.outerHeight( true );
//    alert(heightCon +" : "+contentText.outerHeight( true ));
//  }

}
  calculate_height();
function calculate_height(){
var h = 0;
    $('.class-append-con > .class-row-notification:lt(5)').each( function( i ){
      h += $(this).outerHeight( true );
      alert( "Height of "+(i+1)+" div     :-  " +$(this).outerHeight( true )+" \nHeight Addition   :-  "+ h );
    });
    $('.class-append-con').css('max-height', h);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.class-append-con {
  /* overflow: hidden; */
  overflow-y: auto;
}

.class-row-notification {
  padding: 5px 0px 5px 15px;
  background-color: #F0F0F0;
  border-bottom: 1px solid #C2D0DB;
  position: relative;
}

.class-notification-link {
  text-decoration: none;
}

.class-notification-message {
  width: 100%;
  display: block;
  font-size: 13px;
  /* margin-left: 9px; */
  vertical-align: top;
  color: #3F4B57;
  line-height: 15px;
  max-height: 30px;
  overflow: hidden;
}

.class-notification-time {
  font-size: 11px;
  display: block;
  color: #808080;
}</code>```

```

答:
I made a jQuery script to solve a similar problem some time ago. Mine was design to work with sibling elements, but it applies to parent-children elements too.

```<code>var maxHeight = Math.max.apply(null, $(".apply-max-height").map(function () {
    return $(this).height();
}).get());
$(".apply-max-height").height(maxHeight);
$(window).resize(function() {
    $(".apply-max-height").height("auto");
    var maxHeight = Math.max.apply(null, $(".apply-max-height").map(function() {
        return $(this).height();
    }).get());
    $(".apply-max-height").height(maxHeight);
});
</code>```

Updated for margin and other properties:

```<code>var maxHeight = Math.max.apply(null, $(".apply-max-height").map(function () {
    return $(this).height();
}).get());
$(".apply-max-height").height(maxHeight);
$('.children-element').css('margin', $('.parent-element').css('margin'));
$(window).resize(function() {
    $(".apply-max-height").height("auto");
    var maxHeight = Math.max.apply(null, $(".apply-max-height").map(function() {
        return $(this).height();
    }).get());
    $(".apply-max-height").height(maxHeight);
    $('.children-element').css('margin', $('.parent-element').css('margin'));
});
</code>```

This works on resizing too, add the properties that you want to "copy" the same way I did with margin and you should have no problems.

Add the "apply-max-height" class to all elements that you want and they will have the height of the tallest. Hope it works for you!

Body:
I have dynamically prepended divs (.class-row-notification) to another div (.class-append-con).

Now I want to set first 5 divs height to its parent's max-height (Including margin, padding, bottom-border etc.).

UPDATE

Addition of first five div class (.class-row-notification)(children div) == max-height of class(.class-append-con)(parent div)

How to do that ? If through CSS, it should be cross browser.

I tried it through jQuery but everytime it gives me same height as 11px for the div.class-row-notification

EDIT:-

I removed the commented code from snippet and tried again, its working here but not in my project why?

I have following html -

var notificationData = '[{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Shantaram :  Hello World !!!","notificationLink":"#","createdOn":1512640448139},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Spring : How are you, Shantaram ? !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Suyog :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Balasaheb :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Ravi :  Hello World !!!","notificationLink":"#","createdOn":1512640449140},{"notificationObjectId":null,"notificationId":null,"notifierId":null,"actorId":null,"entityId":null,"entityTypeId":null,"notifierName":null,"actorName":null,"message":"Nilesh :  Hello World !!! Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!Hello World !!!","notificationLink":"#","createdOn":1512640449140}]';

  notificationData = JSON.parse(notificationData);
//  console.log(notificationData);
//  console.log(notificationData.length);
  var len = notificationData.length - 5 ;
  var heightCon = 0;
  for( var i = 0; i < notificationData.length; ++i ) {
    contentText = jQuery(".class-notification-struct").clone(true);
    contentText.removeClass('class-notification-struct');
    /*contentText.find(".class-face-noti img").attr('src', notificationData.image);*/
    /*contentText.find(".class-name").html(notificationData[i].name);*/
    /*contentText.find(".class-notification-link").prop('href',notificationData[i].notificationLink);
    contentText.find(".class-notification-message").append(notificationData[i].message);
    var created_on_date = new  Date( notificationData[i].createdOn );
    contentText.find(".class-notification-time").append( created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString());
    */

    var created_on_date = new Date( notificationData[i].createdOn );
    var row_div =  "
"
                    +""
                      +""
                        +notificationData[i].message
                      +""
                      +""
                        +created_on_date.toDateString() +" at "+created_on_date.toLocaleTimeString()
                      +""
                    +""
                  +"
";
    jQuery(row_div).prependTo('.class-append-con');

//  if( len <= i ) {
//    heightCon += contentText.outerHeight( true );
//    alert(heightCon +" : "+contentText.outerHeight( true ));
//  }

}
  calculate_height();
function calculate_height(){
var h = 0;
    $('.class-append-con > .class-row-notification:lt(5)').each( function( i ){
      h += $(this).outerHeight( true );
      alert( "Height of "+(i+1)+" div     :-  " +$(this).outerHeight( true )+" \nHeight Addition   :-  "+ h );
    });
    $('.class-append-con').css('max-height', h);
}

.class-append-con {
  /* overflow: hidden; */
  overflow-y: auto;
}

.class-row-notification {
  padding: 5px 0px 5px 15px;
  background-color: #F0F0F0;
  border-bottom: 1px solid #C2D0DB;
  position: relative;
}

.class-notification-link {
  text-decoration: none;
}

.class-notification-message {
  width: 100%;
  display: block;
  font-size: 13px;
  /* margin-left: 9px; */
  vertical-align: top;
  color: #3F4B57;
  line-height: 15px;
  max-height: 30px;
  overflow: hidden;
}

.class-notification-time {
  font-size: 11px;
  display: block;
  color: #808080;
}

Body:
I made a jQuery script to solve a similar problem some time ago. Mine was design to work with sibling elements, but it applies to parent-children elements too.

var maxHeight = Math.max.apply(null, $(".apply-max-height").map(function () {
    return $(this).height();
}).get());
$(".apply-max-height").height(maxHeight);
$(window).resize(function() {
    $(".apply-max-height").height("auto");
    var maxHeight = Math.max.apply(null, $(".apply-max-height").map(function() {
        return $(this).height();
    }).get());
    $(".apply-max-height").height(maxHeight);
});

Updated for margin and other properties:

var maxHeight = Math.max.apply(null, $(".apply-max-height").map(function () {
    return $(this).height();
}).get());
$(".apply-max-height").height(maxHeight);
$('.children-element').css('margin', $('.parent-element').css('margin'));
$(window).resize(function() {
    $(".apply-max-height").height("auto");
    var maxHeight = Math.max.apply(null, $(".apply-max-height").map(function() {
        return $(this).height();
    }).get());
    $(".apply-max-height").height(maxHeight);
    $('.children-element').css('margin', $('.parent-element').css('margin'));
});

This works on resizing too, add the properties that you want to "copy" the same way I did with margin and you should have no problems.

Add the "apply-max-height" class to all elements that you want and they will have the height of the tallest. Hope it works for you!


问:
While parsing pdf with iText7 chars move on fixed interval (with Freeset font)
I'm trying to parse pdf that I have created with iText. In document I have two paragraphs:

"Имя" - ("name" from Russian) - font: Helvetica, size: 20.

"Фамилия" - ("surname" from Russian) - font: Freeset (I downloaded it here), size: 10.

When I finish parsing I get "Имя" properly encoded and "Ôàìèëèÿ" instead of "Фамилия". It is Unicode characters for "Фамилия" but moved 848 chars (10-based) left. (I mean that, for instance, instead of "Ф" (0x0424 in UTF-8) I get "Ô" (0x00d4) and difference between them is 848 (or 350 in hex))

I use this example to get text from pdf (but instead of filtering by font, I filter by equality to one of the Strings in the set ("Имя", "Фамилия")

I know that we are advised to store non-English charactes as sequence of Unicode symbols, but I'm creating pdf on the fly from incoming data so I can't manually retype it as separate Unicode symbols (if you know how to do it on the fly, please provide your approach).

Any ideas why this movement of character happen and how to avoid it are welcomed. Thank you in advance.

Here is the file I worked with.

Edit

I tried opening file in Acrobat Pro and everything is fine there. Acrobat also shows that all three fonts I've put in pdf are still in the document.

Here is the code I used to create pdf I'm processing:

```<code>private static void create() throws IOException {
    PdfDocument pdf = new PdfDocument(new PdfReader(srcPdf), new PdfWriter(targetPdf));
    PdfCanvas pdfCanvas = new PdfCanvas(pdf.getFirstPage());
    PdfFont freeset = getPdfFont(freesetPath);
    PdfFont helvetica = getPdfFont(helveticaPath);
    PdfFont circe = getPdfFont(circePath);
    pdfCanvas.beginText()
            .setFontAndSize(helvetica, 15)
            .setColor(Color.RED, true)
            .moveText(50, 300)
            .showText("Имя")
            .setFontAndSize(freeset, 10)
            .setColor(Color.GREEN, true)
            .moveText(0, -30)
            .showText("Фамилия")
            .setFontAndSize(circe, 20)
            .setColor(Color.BLUE, true)
            .moveText(0, -30)
            .showText("Должность")
            .endText();

    pdf.close();
}

private static PdfFont getPdfFont(String path) throws IOException {
    InputStream fontInputStream = new FileInputStream(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[2048];
    int a;
    while((a = fontInputStream.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, a);
    }
    baos.flush();
    return PdfFontFactory.createFont(baos.toByteArray(),
            PdfEncodings.IDENTITY_H, true);
}
</code>```

答:
iText 7 appears to have an issue with embedding the font in question. I don't know whether it's a bug in the font or in iText, though.

The "FreeSet" font is indeed embedded in the OP's sample document with a wrong ToUnicode map

```<code>...
6 beginbfrange
<009e> <009e> <00d4> <00aa> <00aa> <00e0> <00b2> <00b2> <00e8> <00b5> <00b5> <00eb> <00b6> <00b6> <00ec> <00c9> <00c9> <00ff> endbfrange
...
</code>```

which maps the glyphs used for "Фамилия" to 00d4, 00e0, 00e8, 00eb, 00ec, and 00ff.

This in turn explains why both iText and Adobe Reader extract unexpected text.

The issue can be reproduced like this:

```<code>PdfFont arial = PdfFontFactory.createFont(BYTES_OF_ARIAL_FONT, PdfEncodings.IDENTITY_H, true);
PdfFont freeSet = PdfFontFactory.createFont(BYTES_OF_FREESET_FONT, PdfEncodings.IDENTITY_H, true);

try (   OutputStream result = new FileOutputStream("cyrillicTextFreeSet.pdf");
        PdfWriter writer = new PdfWriter(result);
        PdfDocument pdfDocument = new PdfDocument(writer);
        Document doc = new Document(pdfDocument)    ) {
    doc.add(new Paragraph("Фамилия").setFont(arial));
    doc.add(new Paragraph("Фамилия").setFont(freeSet));
}
</code>```

(CreateCyrillicText test testCreateTextWithFreeSet)

The result looks ok:

When extracting / copying&pasting, though:

The embedded Arial subset has a proper ToUnicode map, the text in Arial is extracted as "Фамилия".

The embedded FreeSet subset has an incorrect ToUnicode map, the text in FreeSet is extracted as "Ôàìèëèÿ".

(Tested with the current iText 7.1.1-SNAPSHOT)

Apparently iText 7 does understand the FreeSet font program well enough to select the needed subset and reference the correct glyphs from the content but it has problems building an appropriate ToUnicode map. This is not a general problem, though, as the parallel test with Arial shows.

Body:
I'm trying to parse pdf that I have created with iText. In document I have two paragraphs:

"Имя" - ("name" from Russian) - font: Helvetica, size: 20.

"Фамилия" - ("surname" from Russian) - font: Freeset (I downloaded it here), size: 10.

When I finish parsing I get "Имя" properly encoded and "Ôàìèëèÿ" instead of "Фамилия". It is Unicode characters for "Фамилия" but moved 848 chars (10-based) left. (I mean that, for instance, instead of "Ф" (0x0424 in UTF-8) I get "Ô" (0x00d4) and difference between them is 848 (or 350 in hex))

I use this example to get text from pdf (but instead of filtering by font, I filter by equality to one of the Strings in the set ("Имя", "Фамилия")

I know that we are advised to store non-English charactes as sequence of Unicode symbols, but I'm creating pdf on the fly from incoming data so I can't manually retype it as separate Unicode symbols (if you know how to do it on the fly, please provide your approach).

Any ideas why this movement of character happen and how to avoid it are welcomed. Thank you in advance.

Here is the file I worked with.

Edit

I tried opening file in Acrobat Pro and everything is fine there. Acrobat also shows that all three fonts I've put in pdf are still in the document.

Here is the code I used to create pdf I'm processing:

private static void create() throws IOException {
    PdfDocument pdf = new PdfDocument(new PdfReader(srcPdf), new PdfWriter(targetPdf));
    PdfCanvas pdfCanvas = new PdfCanvas(pdf.getFirstPage());
    PdfFont freeset = getPdfFont(freesetPath);
    PdfFont helvetica = getPdfFont(helveticaPath);
    PdfFont circe = getPdfFont(circePath);
    pdfCanvas.beginText()
            .setFontAndSize(helvetica, 15)
            .setColor(Color.RED, true)
            .moveText(50, 300)
            .showText("Имя")
            .setFontAndSize(freeset, 10)
            .setColor(Color.GREEN, true)
            .moveText(0, -30)
            .showText("Фамилия")
            .setFontAndSize(circe, 20)
            .setColor(Color.BLUE, true)
            .moveText(0, -30)
            .showText("Должность")
            .endText();

    pdf.close();
}

private static PdfFont getPdfFont(String path) throws IOException {
    InputStream fontInputStream = new FileInputStream(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[2048];
    int a;
    while((a = fontInputStream.read(buffer, 0, buffer.length)) != -1) {
        baos.write(buffer, 0, a);
    }
    baos.flush();
    return PdfFontFactory.createFont(baos.toByteArray(),
            PdfEncodings.IDENTITY_H, true);
}

Body:
iText 7 appears to have an issue with embedding the font in question. I don't know whether it's a bug in the font or in iText, though.

The "FreeSet" font is indeed embedded in the OP's sample document with a wrong ToUnicode map

...
6 beginbfrange
<009e> <009e> <00d4> <00aa> <00aa> <00e0> <00b2> <00b2> <00e8> <00b5> <00b5> <00eb> <00b6> <00b6> <00ec> <00c9> <00c9> <00ff> endbfrange
...

which maps the glyphs used for "Фамилия" to 00d4, 00e0, 00e8, 00eb, 00ec, and 00ff.

This in turn explains why both iText and Adobe Reader extract unexpected text.

The issue can be reproduced like this:

PdfFont arial = PdfFontFactory.createFont(BYTES_OF_ARIAL_FONT, PdfEncodings.IDENTITY_H, true);
PdfFont freeSet = PdfFontFactory.createFont(BYTES_OF_FREESET_FONT, PdfEncodings.IDENTITY_H, true);

try (   OutputStream result = new FileOutputStream("cyrillicTextFreeSet.pdf");
        PdfWriter writer = new PdfWriter(result);
        PdfDocument pdfDocument = new PdfDocument(writer);
        Document doc = new Document(pdfDocument)    ) {
    doc.add(new Paragraph("Фамилия").setFont(arial));
    doc.add(new Paragraph("Фамилия").setFont(freeSet));
}

(CreateCyrillicText test testCreateTextWithFreeSet)

The result looks ok:

When extracting / copying&pasting, though:

The embedded Arial subset has a proper ToUnicode map, the text in Arial is extracted as "Фамилия".

The embedded FreeSet subset has an incorrect ToUnicode map, the text in FreeSet is extracted as "Ôàìèëèÿ".

(Tested with the current iText 7.1.1-SNAPSHOT)

Apparently iText 7 does understand the FreeSet font program well enough to select the needed subset and reference the correct glyphs from the content but it has problems building an appropriate ToUnicode map. This is not a general problem, though, as the parallel test with Arial shows.


问:
Program will print largest number and smallest number
I have some trouble when I try to code a program.

```<code>double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
    System.out.println("Give the " + (i + 1) + " number");
    array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
    if (array[i] > max) {
        max = array[i];
    }
    for (i = 0; i < 10; i++) {
        if (array[i] < min) {
            min = array[i];
        }
    }
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
</code>```

When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0

Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.

答:
Two simple corrections:

You just have to set initialized min and max to some values in array. (e.g. array[0] for your problem)

there is  no need to 3 for loops to find the min and max, just use one.

see below code:

```<code>int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;

System.out.println("Give the " + (1) + " number") ;
array[0] = input.nextDouble();

double max = array[0], min = array[0];

for (i = 1; i < 10; i++)
{
    System.out.println("Give the " + (i+1) + " number") ;
    array[i] = input.nextDouble();

    if(array[i] > max)
        max = array[i] ;

    if (array[i] < min)
        min = array[i];
}

System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
</code>```

Body:
I have some trouble when I try to code a program.

double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
    System.out.println("Give the " + (i + 1) + " number");
    array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
    if (array[i] > max) {
        max = array[i];
    }
    for (i = 0; i < 10; i++) {
        if (array[i] < min) {
            min = array[i];
        }
    }
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);

When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0

Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.

Body:
Two simple corrections:

You just have to set initialized min and max to some values in array. (e.g. array[0] for your problem)

there is  no need to 3 for loops to find the min and max, just use one.

see below code:

int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;

System.out.println("Give the " + (1) + " number") ;
array[0] = input.nextDouble();

double max = array[0], min = array[0];

for (i = 1; i < 10; i++)
{
    System.out.println("Give the " + (i+1) + " number") ;
    array[i] = input.nextDouble();

    if(array[i] > max)
        max = array[i] ;

    if (array[i] < min)
        min = array[i];
}

System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);


问:
Is it possible to extract inline CSS from HTML?
Using http://simplehtmldom.sourceforge.net/manual.htm, is it possible to extract the inline CSS of a HTML file?

This parser if pure html, assuming (just correct me if I'm wrong) it can't parse CSS tags.Is there any other way to extract inline CSS in the html file?

答:
Using a normal HTML parser:

Walk through all elements

If element's tag is style, get the element's content

If the element has an attribute style, get that attribute's value.


问:
When you send a message to a group from firebase console there is no statistics
I've created a group of devices (FCM Device Group)

And when I send a message from the console the Sent, Open, and Conversion statistics are always 0.

If I send a message to a single device the statistics works OK:

Is there any way I can get Sent, Opened an Conversion statistics of a message sent to a group?

Can I retrieve those statistics via API?

I need to retrieve the opened and conversion data of different messages (Topics don't fit our needs). I can make it one by one or by groups, but I don't find how can I get the data.

Thanks in advance.

答:
Well, I have confirmation from Google that Statistics won't show in your console.

You can do it by subscribing devices to topics, form server side you can add your devices to topics (documentation from Google)

Then just send the push to the topic from console and you will have statistics.

Note that new topics will take up to 1 day to be shown in console.

I hope that helps someone.


问:
slf4j log4j hello world problems
I tried searching for a solution to my error, however, due to similar questions being asked a lot, the swamp of results hasn't helped find an answer to my question.

I'm basically trying to get a simple "Hello World" in slf4j with log4j to work, so that I can later further customize it.

My Project is basically the maven hello world project, slightly adjusted:

App.java:

```<code>package xx.xxxx.logging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        System.out.println("Hello World!");

        LOGGER.info("Hello Logger!");
    }
}
</code>```

log4j2.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

        <Appenders>
                <Console name="STDOUT" target="System.out">
                        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
                </Console>
        </Appenders>

        <Loggers>
                <Root level="ALL">
                        <AppenderRef ref="STDOUT"/>
                </Root>
        </Loggers>

</Configuration>
</code>```

pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>xx.xxxx.logging</groupId>
  <artifactId>logging-test</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>

  <name>logging-test</name>

  <properties>
    <jdk.version>1.8</jdk.version>
    <java.version>1.8</java.version>

    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
    <sonar.java.source>${java.version}</sonar.java.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <version.sl4j>1.7.21</version.sl4j>
    <version.sl4j.log4j>2.0.1</version.sl4j.log4j>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${version.sl4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
  </dependencies>

</project>
</code>```

Trying to run App.java yields the following error:

```<code>2017-12-07 11:14:33,263 ERROR catching java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:133)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:744)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:683)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:675)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:349)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:150)
    at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:364)
    at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:422)
    at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:146)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:75)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:37)
    at org.apache.logging.log4j.LogManager.getContext(LogManager.java:263)
    at org.apache.logging.slf4j.Log4jLoggerFactory$PrivateManager.getContext(Log4jLoggerFactory.java:98)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getContext(Log4jLoggerFactory.java:84)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:44)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:358)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:383)
    at xx.xxxx.logging.App.<clinit>(App.java:8)
Caused by: java.lang.IllegalArgumentException: No enum constant org.apache.logging.log4j.core.appender.ConsoleAppender.Target.System.out
    at java.lang.Enum.valueOf(Enum.java:238)
    at org.apache.logging.log4j.core.appender.ConsoleAppender$Target.valueOf(ConsoleAppender.java:57)
    at org.apache.logging.log4j.core.appender.ConsoleAppender.createAppender(ConsoleAppender.java:98)
    ... 22 more

2017-12-07 11:14:33,268 ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.ConsoleAppender for element Console.
2017-12-07 11:14:33,269 ERROR Null object returned for Console in Appenders.
2017-12-07 11:14:33,275 ERROR Unable to locate appender STDOUT for logger
Hello World!
</code>```

Any leads on how to fix this would be greatly appreciated.

答:
Try this to follow log4j syntax according to https://logging.apache.org/log4j/2.x/manual/configuration.html</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
        <Appenders>
          <Console name="Console-Appender" target="SYSTEM_OUT">
             <PatternLayout>
               <pattern>
                   %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
               </pattern>
             </PatternLayout>
          </Console>
        </Appenders>

      <Loggers>
         <Root level="ALL">
             <AppenderRef ref="Console-Appender"/>
         </Root>
      </Loggers>
 </Configuration>
</code>```

Title: slf4j log4j hello world problems

Body:
I tried searching for a solution to my error, however, due to similar questions being asked a lot, the swamp of results hasn't helped find an answer to my question.

I'm basically trying to get a simple "Hello World" in slf4j with log4j to work, so that I can later further customize it.

My Project is basically the maven hello world project, slightly adjusted:

App.java:

package xx.xxxx.logging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        System.out.println("Hello World!");

        LOGGER.info("Hello Logger!");
    }
}

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

        <Appenders>
                <Console name="STDOUT" target="System.out">
                        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
                </Console>
        </Appenders>

        <Loggers>
                <Root level="ALL">
                        <AppenderRef ref="STDOUT"/>
                </Root>
        </Loggers>

</Configuration>

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>xx.xxxx.logging</groupId>
  <artifactId>logging-test</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>

  <name>logging-test</name>

  <properties>
    <jdk.version>1.8</jdk.version>
    <java.version>1.8</java.version>

    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
    <sonar.java.source>${java.version}</sonar.java.source>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <version.sl4j>1.7.21</version.sl4j>
    <version.sl4j.log4j>2.0.1</version.sl4j.log4j>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${version.sl4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${version.sl4j.log4j}</version>
    </dependency>
  </dependencies>

</project>

Trying to run App.java yields the following error:

2017-12-07 11:14:33,263 ERROR catching java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:133)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:744)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:683)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:675)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:349)
    at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:150)
    at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:364)
    at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:422)
    at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:146)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:75)
    at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:37)
    at org.apache.logging.log4j.LogManager.getContext(LogManager.java:263)
    at org.apache.logging.slf4j.Log4jLoggerFactory$PrivateManager.getContext(Log4jLoggerFactory.java:98)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getContext(Log4jLoggerFactory.java:84)
    at org.apache.logging.slf4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:44)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:358)
    at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:383)
    at xx.xxxx.logging.App.<clinit>(App.java:8)
Caused by: java.lang.IllegalArgumentException: No enum constant org.apache.logging.log4j.core.appender.ConsoleAppender.Target.System.out
    at java.lang.Enum.valueOf(Enum.java:238)
    at org.apache.logging.log4j.core.appender.ConsoleAppender$Target.valueOf(ConsoleAppender.java:57)
    at org.apache.logging.log4j.core.appender.ConsoleAppender.createAppender(ConsoleAppender.java:98)
    ... 22 more

2017-12-07 11:14:33,268 ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.ConsoleAppender for element Console.
2017-12-07 11:14:33,269 ERROR Null object returned for Console in Appenders.
2017-12-07 11:14:33,275 ERROR Unable to locate appender STDOUT for logger
Hello World!

Any leads on how to fix this would be greatly appreciated.

Body:
Try this to follow log4j syntax according to https://logging.apache.org/log4j/2.x/manual/configuration.html

<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
        <Appenders>
          <Console name="Console-Appender" target="SYSTEM_OUT">
             <PatternLayout>
               <pattern>
                   %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
               </pattern>
             </PatternLayout>
          </Console>
        </Appenders>

      <Loggers>
         <Root level="ALL">
             <AppenderRef ref="Console-Appender"/>
         </Root>
      </Loggers>
 </Configuration>


问:
golang format leading zeros with sign
I'd like to format an integer to an UTC offset formatted string

I tried it using the fmt package:

```<code>fmt.Sprintf("%+02d:00", utc)
</code>```

When utc is 1, I'd like it to print "+01:00", but I get "+1:00"

How can I combine the leading zeros flag, the sign flag and the width in one format string?

答:
width is the minimum number of runes to output

+01 is minimum width 3. For example,

```<code>package main

import (
    "fmt"
)

func main() {
    utc := 1
    s := fmt.Sprintf("%+03d:00", utc)
    fmt.Println(s)
}
</code>```

Playground: https://play.golang.org/p/Z0vBzzn-kp

Output:

```<code>+01:00
</code>```

Title: golang format leading zeros with sign

Body:
I'd like to format an integer to an UTC offset formatted string

I tried it using the fmt package:

fmt.Sprintf("%+02d:00", utc)

When utc is 1, I'd like it to print "+01:00", but I get "+1:00"

How can I combine the leading zeros flag, the sign flag and the width in one format string?

Body:
width is the minimum number of runes to output

+01 is minimum width 3. For example,

package main

import (
    "fmt"
)

func main() {
    utc := 1
    s := fmt.Sprintf("%+03d:00", utc)
    fmt.Println(s)
}

Playground: https://play.golang.org/p/Z0vBzzn-kp

Output:

+01:00


问:
if else condition of css in jQuery not working
I wrote below code to get my output.

```<code>$(document).ready(function(){
  if ($('.figure').css("left","702px")) {
    $('.level1').css("display", "inline-block");
  } else {
    $('.level1').css("display", "none");
  }
});
</code>```

What I want when my .figure is reach to left 702px. I want to show level1 icon. But now display none is not applying before 702px. That is level1 icon showing before reaching to 702px. Anything wrong ? please help. Even i want to add more conditions that is after some for example left 1500px of .figure then show level2 icon. Thanks.

答:
```<code>$('.figure').css("left","702px")
</code>```

This is used for setting the css value. Inside if condition, you need to do a check to match for value.

You can modify the condition line as below.

```<code>if ($('.figure').css("left") == "702px") {
</code>```

You should give !important while adding display inline-block to avoid the style being over-ridden.

So your code should look something like below.

```<code>$(document).ready(function(){
  if ($('.figure').css("left")== "702px") {
    $('.level1').css("display", "inline-block !important");
  } else {
    $('.level1').css("display", "none !important");
  }
});
</code>```

Body:
I wrote below code to get my output.

$(document).ready(function(){
  if ($('.figure').css("left","702px")) {
    $('.level1').css("display", "inline-block");
  } else {
    $('.level1').css("display", "none");
  }
});

What I want when my .figure is reach to left 702px. I want to show level1 icon. But now display none is not applying before 702px. That is level1 icon showing before reaching to 702px. Anything wrong ? please help. Even i want to add more conditions that is after some for example left 1500px of .figure then show level2 icon. Thanks.

Body:
$('.figure').css("left","702px")

This is used for setting the css value. Inside if condition, you need to do a check to match for value.

You can modify the condition line as below.

if ($('.figure').css("left") == "702px") {

You should give !important while adding display inline-block to avoid the style being over-ridden.

So your code should look something like below.

$(document).ready(function(){
  if ($('.figure').css("left")== "702px") {
    $('.level1').css("display", "inline-block !important");
  } else {
    $('.level1').css("display", "none !important");
  }
});


问:
VBA Editor broken - Excel 2016 OSX
I recently installed Excel 2016 for mac and when I launched the VBA editor the text was placed in a vertical way (line without any width) as shown in the following image. Any workaround for this?

答:
There has been a new release (15.39.0 build 17101000) for Office Excel for Mac.

It has been released on October 10. The VBA editor is improved a lot. Most probably this issues doesn't occur anymore.

See release notes

Title: VBA Editor broken - Excel 2016 OSX


问:
how to add available COM ports to ComboBox useing C#
i want to add available COM ports of the computer to combobox using C#. How can i do that? </p>

答: This might help you: SerialPort.GetPortNames


问:
Cygwin: Deleting file when handle is opened
I have a file which I want to delete, it's handle is held by system process so everytime I try to delete it it gives Access denied but for some reason cygwin is able to delete it.

I've downloaded the coreutils and investigated the source code of rm executable and found that it uses unlink function to achieve it. I've created a little test program which uses same function but it gives me Access denied anyway.

Then I found this article and guy describes how cygwin is able to delete a file which is the following:

Cygwin opens files always with all sharing flags
  set, so a file opened by a Cygwin process should not result in a sharing
  violation in another open call.  The exception is the first NtOpenFile
  in unlink_nt, which opens the file with FILE_SHARE_DELETE only to find
  out if the file has an open handle somewhere else.  In that case it gets
  a STATUS_SHARING_VIOLATION, the next NtOpenFile will open the file with
  all sharing flags set, and unlink_nt will try to delete the file or to
  rename it, or to move it to the recycle bin, dependent on its path.

Which makes sense, So I started to implement same thing. Here is my code:

```<code>HANDLE file;
PIO_STATUS_BLOCK stat;

UNICODE_STRING myUnicodeStr;
RtlInitUnicodeString(&myUnicodeStr, L"C:\\Program Files (x86)\\TSU\\bin\\TSU.sys");

POBJECT_ATTRIBUTES attr;
InitializeObjectAttributes (attr, &myUnicodeStr, OBJ_OPENIF, NULL, NULL);

NtOpenFile(&file, MAXIMUM_ALLOWED, attr, NULL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_DELETE_ON_CLOSE);

NtClose(file);
</code>```

As you can see I'm trying to open file with sharing flags set and also used FILE_DELETE_ON_CLOSE since I close the handle and I want it to be deleted afterwards.

The problem I have is Segmentation Fault(I'm using cygwin win10) for some reason. Little debugging showed that problem is in InitializeObjectAttributes function for some reason.

P.S
I know it's not the best solution to delete file when it's handle is held by some other process but the main goal is to mimic the rm.exe's behaviour in this way. Hope you can help. Thanks.

答:
under windows not always possible delete file. for example when some process mapping this file as an image

if try delete running EXE file with rm.exe - it first call ZwOpenFile with DesiredAccess = DELETE, ShareAccess = FILE_SHARE_DELETE and OpenOptions = FILE_OPEN_FOR_BACKUP_INTENT. this is ok. than called ZwSetInformationFile with FileDispositionInformation - the DeleteFile from FILE_DISPOSITION_INFORMATION set to TRUE. this call failed with status STATUS_CANNOT_DELETE.

filesystem return STATUS_CANNOT_DELETE exactly from this place:

```<code>        //  Make sure there is no process mapping this file as an image.

        if (!MmFlushImageSection( &Fcb->NonPaged->SectionObjectPointers,
                                  MmFlushForDelete )) {

            DebugTrace(-1, Dbg, "Cannot delete user mapped image\n", 0);

            return STATUS_CANNOT_DELETE;
}
</code>```

than rm.exe again try open file, already with OpenOptions = FILE_OPEN_FOR_BACKUP_INTENT | FILE_DELETE_ON_CLOSE options. but this call of course fail with the same STATUS_CANNOT_DELETE. now error from this point:

```<code>//  If the user wants to delete on close, we must check at this
//  point though.
//

if (FlagOn(*DesiredAccess, FILE_WRITE_DATA) || DeleteOnClose) {

    Fcb->OpenCount += 1;
    DecrementFcbOpenCount = TRUE;

    if (!MmFlushImageSection( &Fcb->NonPaged->SectionObjectPointers,
                              MmFlushForWrite )) {

        Iosb.Status = DeleteOnClose ? STATUS_CANNOT_DELETE :
                                      STATUS_SHARING_VIOLATION;
        try_return( Iosb );
    }
}
</code>```

after this rm.exe again call ZwSetInformationFile already with FileRenameInformation - where RootDirectory from FILE_RENAME_INFORMATION point to volume (on which file located) root (so like \Device\HarddiskVolume<N>\ and FileName point to some path in recycle bin. as result file actually moved but not deleted. rm.exe deceives you

Body:
I have a file which I want to delete, it's handle is held by system process so everytime I try to delete it it gives Access denied but for some reason cygwin is able to delete it.

I've downloaded the coreutils and investigated the source code of rm executable and found that it uses unlink function to achieve it. I've created a little test program which uses same function but it gives me Access denied anyway.

Then I found this article and guy describes how cygwin is able to delete a file which is the following:

Cygwin opens files always with all sharing flags
  set, so a file opened by a Cygwin process should not result in a sharing
  violation in another open call.  The exception is the first NtOpenFile
  in unlink_nt, which opens the file with FILE_SHARE_DELETE only to find
  out if the file has an open handle somewhere else.  In that case it gets
  a STATUS_SHARING_VIOLATION, the next NtOpenFile will open the file with
  all sharing flags set, and unlink_nt will try to delete the file or to
  rename it, or to move it to the recycle bin, dependent on its path.

Which makes sense, So I started to implement same thing. Here is my code:

HANDLE file;
PIO_STATUS_BLOCK stat;

UNICODE_STRING myUnicodeStr;
RtlInitUnicodeString(&myUnicodeStr, L"C:\\Program Files (x86)\\TSU\\bin\\TSU.sys");

POBJECT_ATTRIBUTES attr;
InitializeObjectAttributes (attr, &myUnicodeStr, OBJ_OPENIF, NULL, NULL);

NtOpenFile(&file, MAXIMUM_ALLOWED, attr, NULL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_DELETE_ON_CLOSE);

NtClose(file);

As you can see I'm trying to open file with sharing flags set and also used FILE_DELETE_ON_CLOSE since I close the handle and I want it to be deleted afterwards.

The problem I have is Segmentation Fault(I'm using cygwin win10) for some reason. Little debugging showed that problem is in InitializeObjectAttributes function for some reason.

P.S
I know it's not the best solution to delete file when it's handle is held by some other process but the main goal is to mimic the rm.exe's behaviour in this way. Hope you can help. Thanks.

Body:
under windows not always possible delete file. for example when some process mapping this file as an image

if try delete running EXE file with rm.exe - it first call ZwOpenFile with DesiredAccess = DELETE, ShareAccess = FILE_SHARE_DELETE and OpenOptions = FILE_OPEN_FOR_BACKUP_INTENT. this is ok. than called ZwSetInformationFile with FileDispositionInformation - the DeleteFile from FILE_DISPOSITION_INFORMATION set to TRUE. this call failed with status STATUS_CANNOT_DELETE.

filesystem return STATUS_CANNOT_DELETE exactly from this place:

        //  Make sure there is no process mapping this file as an image.

        if (!MmFlushImageSection( &Fcb->NonPaged->SectionObjectPointers,
                                  MmFlushForDelete )) {

            DebugTrace(-1, Dbg, "Cannot delete user mapped image\n", 0);

            return STATUS_CANNOT_DELETE;
}

than rm.exe again try open file, already with OpenOptions = FILE_OPEN_FOR_BACKUP_INTENT | FILE_DELETE_ON_CLOSE options. but this call of course fail with the same STATUS_CANNOT_DELETE. now error from this point:

//  If the user wants to delete on close, we must check at this
//  point though.
//

if (FlagOn(*DesiredAccess, FILE_WRITE_DATA) || DeleteOnClose) {

    Fcb->OpenCount += 1;
    DecrementFcbOpenCount = TRUE;

    if (!MmFlushImageSection( &Fcb->NonPaged->SectionObjectPointers,
                              MmFlushForWrite )) {

        Iosb.Status = DeleteOnClose ? STATUS_CANNOT_DELETE :
                                      STATUS_SHARING_VIOLATION;
        try_return( Iosb );
    }
}

after this rm.exe again call ZwSetInformationFile already with FileRenameInformation - where RootDirectory from FILE_RENAME_INFORMATION point to volume (on which file located) root (so like \Device\HarddiskVolume<N>\ and FileName point to some path in recycle bin. as result file actually moved but not deleted. rm.exe deceives you


问:
Python - parse a file & store objects
I'm new to python and I m trying to parse a file.
I have a file with this format :

```<code>Function func1
(
  arg1 arg1
  arg2 arg2
);

Function func2
(
  arg3 arg3
);
</code>```

its pretty repetitive. I'm tryin to parse this file and search for certain functions only and store their args into a list/object (I don't know exactly how) and reuse these infos to write to a file. I started my code like this

```<code>def get_wanted_funcs(path,list_func):
    f = open(path,'r')
    while True:
        text = f.readline()
        if list_func in text:
           ## store name of func + args
templ = myfile_h()
# something like templ.stored_objects = stored_objects
with open(os.path.join(generated_dir, "myfile.h"), "w") as f:
            f.write(str(templ))
</code>```

But I don't what is the best way to proceed to store this objects/items. Any suggets or sample codes are welcome. thank you

答:
You could split by "Function" to get a list consisting of each function. Then use a dictionary to store the name of the function and its arguments. Something like this:

```<code>with open(path, 'r') as file:
    functions = file.read().split('Function')
    functions = functions[1:] # This is to get rid of the blank item at the start due to 'Function' being at the start of the file.

# Right now `functions` looks like this:
# [' func1\n(\n  arg1 arg1\n  arg2 arg2\n);\n\n', ' func2\n(\n  arg3 arg3\n);\n', ' func3\n(\n  arg4 arg4\n  arg5 arg5\n);\n\n', ' func4\n(\n  arg6 arg6\n);']

functions_to_save = ['func1'] # This is a list of functions that we want to save. You can change this to a list of whichever functions you need to save

d = {} # Dictionary

# Next we can split each item in `functions` by whitespace and use slicing to get the arguments

for func in functions:
    func = func.split() # ['func1', '(', 'arg1', 'arg1', 'arg2', 'arg2', ');']
    if func[0] in functions_to_save:
        d[func[0]] = set(func[2:-1]) # set is used to get rid of duplicates
</code>```

Output:

```<code>>>> d
{'func1': {'arg2', 'arg1'}}
</code>```

There are other ways of doing this but this is probably the easiest to understand

Title: Python - parse a file & store objects

Body:
I'm new to python and I m trying to parse a file.
I have a file with this format :

Function func1
(
  arg1 arg1
  arg2 arg2
);

Function func2
(
  arg3 arg3
);

its pretty repetitive. I'm tryin to parse this file and search for certain functions only and store their args into a list/object (I don't know exactly how) and reuse these infos to write to a file. I started my code like this

def get_wanted_funcs(path,list_func):
    f = open(path,'r')
    while True:
        text = f.readline()
        if list_func in text:
           ## store name of func + args
templ = myfile_h()
# something like templ.stored_objects = stored_objects
with open(os.path.join(generated_dir, "myfile.h"), "w") as f:
            f.write(str(templ))

But I don't what is the best way to proceed to store this objects/items. Any suggets or sample codes are welcome. thank you

Body:
You could split by "Function" to get a list consisting of each function. Then use a dictionary to store the name of the function and its arguments. Something like this:

with open(path, 'r') as file:
    functions = file.read().split('Function')
    functions = functions[1:] # This is to get rid of the blank item at the start due to 'Function' being at the start of the file.

# Right now `functions` looks like this:
# [' func1\n(\n  arg1 arg1\n  arg2 arg2\n);\n\n', ' func2\n(\n  arg3 arg3\n);\n', ' func3\n(\n  arg4 arg4\n  arg5 arg5\n);\n\n', ' func4\n(\n  arg6 arg6\n);']

functions_to_save = ['func1'] # This is a list of functions that we want to save. You can change this to a list of whichever functions you need to save

d = {} # Dictionary

# Next we can split each item in `functions` by whitespace and use slicing to get the arguments

for func in functions:
    func = func.split() # ['func1', '(', 'arg1', 'arg1', 'arg2', 'arg2', ');']
    if func[0] in functions_to_save:
        d[func[0]] = set(func[2:-1]) # set is used to get rid of duplicates

Output:

>>> d
{'func1': {'arg2', 'arg1'}}

There are other ways of doing this but this is probably the easiest to understand


问:
Why doesn't NASM have trouble with valid instruction mnemonics as symbol names in operands?
I wrote the following simple program, but nasm refuses to compile it.

```<code>section .text
    global _start

_start:
    mov rax, 0x01
    mov rdi, 0x01
    mov rsi, str
    mov rdx, 0x03
    syscall

    mov rax, 60
    syscall

segment .data
    str db 'Some string'

nasm -f elf64 main.asm
main.asm:15: error: comma, colon, decorator or end of line expected after operand
</code>```

As I read in this answer this is because str is an instruction mnemonic. So I added a colon to str and now it compiles fine. But what about the line

```<code>mov rsi, str
</code>```

str is an instruction mnemonic here, but it still compiles fine. Why?

答:
As the NASM manual explains, other than macro definitions and directives, the format of a NASM source line has some combination of these four fields:

```<code>label:    instruction operands        ; comment
</code>```

After it sees mov as the mnemonic, it's no longer considering the remaining tokens as possible instruction mnemonics.  Assembly language is strictly one instruction per statement.

If you wanted the bytes that encode an str ax instruction as the immediate operand for mov-sign-extended-imm32, you'd have to do that yourself with a numeric constant.  NASM syntax doesn't have a way to do that for you, so its parser doesn't need to recurse into the operands once its found a mnemonic.

Or instead of encoding str manually, use a db to emit the bytes of the mov instruction.

```<code>db 0x48, 0xc7, 0xc6    ; REX.W prefix, opcode for mov r/m64,imm32,  ModR/M = rsi destination
      str  [rax+1]     ; a disp8 makes this 4 bytes long.

;; same machine code as
mov rsi, strict dword 0x0148000f    ; str [rax+1]

;; nasm optimizes it to mov esi, imm32 without strict dword.
;; I guess I should have used that 5-byte instruction for the DB version...
</code>```

Body:
I wrote the following simple program, but nasm refuses to compile it.

section .text
    global _start

_start:
    mov rax, 0x01
    mov rdi, 0x01
    mov rsi, str
    mov rdx, 0x03
    syscall

    mov rax, 60
    syscall

segment .data
    str db 'Some string'

nasm -f elf64 main.asm
main.asm:15: error: comma, colon, decorator or end of line expected after operand

As I read in this answer this is because str is an instruction mnemonic. So I added a colon to str and now it compiles fine. But what about the line

mov rsi, str

str is an instruction mnemonic here, but it still compiles fine. Why?

Body:
As the NASM manual explains, other than macro definitions and directives, the format of a NASM source line has some combination of these four fields:

label:    instruction operands        ; comment

After it sees mov as the mnemonic, it's no longer considering the remaining tokens as possible instruction mnemonics.  Assembly language is strictly one instruction per statement.

If you wanted the bytes that encode an str ax instruction as the immediate operand for mov-sign-extended-imm32, you'd have to do that yourself with a numeric constant.  NASM syntax doesn't have a way to do that for you, so its parser doesn't need to recurse into the operands once its found a mnemonic.

Or instead of encoding str manually, use a db to emit the bytes of the mov instruction.

db 0x48, 0xc7, 0xc6    ; REX.W prefix, opcode for mov r/m64,imm32,  ModR/M = rsi destination
      str  [rax+1]     ; a disp8 makes this 4 bytes long.

;; same machine code as
mov rsi, strict dword 0x0148000f    ; str [rax+1]

;; nasm optimizes it to mov esi, imm32 without strict dword.
;; I guess I should have used that 5-byte instruction for the DB version...


问:
Android Intent ACTION_CALL not making a phone call
In my Android application I would like to make a phone call automatically when user click the button. I have used the below set of code to achieve this functionality

```<code>Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:911"));
                startActivity(intent);
</code>```

and in my AndroidManifest.xml I have added this   <uses-permission android:name="android.permission.CALL_PHONE" /> permission too.

But it is just opening the dialer pad with the given 911 no instead of making a phone call.

答:
I also had the same problem.
Most probably it may be because our device grant the permission to that app then it may work. Just go to settings and grant the permission of "telephone".

Body:
In my Android application I would like to make a phone call automatically when user click the button. I have used the below set of code to achieve this functionality

Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:911"));
                startActivity(intent);

and in my AndroidManifest.xml I have added this   <uses-permission android:name="android.permission.CALL_PHONE" /> permission too.

But it is just opening the dialer pad with the given 911 no instead of making a phone call.