问:
Resources to compare Java to Objective-C (syntax and basics)
I have taught myself a lot of Objective-C over the past year and a half, and have even been able to publish some iOS apps on the App Store.  Concepts that were foreign to me before about object oriented programming are now second nature and I understand MVC, inheritance, polymorphism etc.  I'm now interested in learning to develop for the Android platform, which will entail learning Java.  I want to find resources that can match up Java basics with regards to syntax and structure with the same things from the Objective-C world.

The Wikipedia entry for Objective-C has exactly what I'm looking for with regards to how Objective-C relates to C++.  If there is a document, blog post or book dedicated to something like this for Java in relation to Objective-C I would be all over it like a bear on honey.  It should include things like

Class method declarations and implementations

instance method declarations and implementations

How to compose a method name (ie +/-(returntype)methodName:(type)argument; )

declaring properties

Thank you for all of your suggestions!

答:
"Matching up syntax" is not necessarily a useful thing. The two languages are not merely different syntaxes for the same thing. Lots of people go into a new language with that mindset, and it leads them to write bad code in their new language. For example, class methods in Objective-C are roughly equivalent to static methods in Java, but class methods can be overridden in subclasses while static methods can only be hidden by new static methods — they're more similar to namespaced functions than methods.

Better to just learn Java from a good book or tutorial — without your baggage from Objective-C.


来源: stackexchange

问:
Object to Array of objects conversion in Typescript
I need to convert object to array of object to work with angular2 *ngFor directive. i have got following json object.

```<code>Object {CountryID: 87944818, ISO2: "do", ISO3: "u", Name: "aliqua sit magna tempor"}
</code>```

I need to convert that into array of object like this:

```<code>[Object]
     0: Object
       CountryID: 87944818
       ISO2: "do"
       ISO3: "u"
       Name: "aliqua sit magna tempor"
</code>```

I have done some work around using Object.keys and map but could not acheive the exact output.
Have tried some thing like that:

```<code>let keys:any[] = [];
        for (let key in value) {
            console.log(key);
            keys.push({key: value[key]});
        }
        console.log(keys);
</code>```

value is the object that need to convert.

答:
```<code>keys.push({[key]: value[key]});
</code>```

You dont want to set "key" but rather value of key.

Keys will be:

```<code>[
  {CountryID: 87944818},
  {ISO2: "do"},
  {ISO3: "u"},
  {Name: "aliqua sit magna tempor"},
]
</code>```

I dont know why this should be useful...

ContentLicense: CC BY-SA 3.0

Body:
I need to convert object to array of object to work with angular2 *ngFor directive. i have got following json object.

Object {CountryID: 87944818, ISO2: "do", ISO3: "u", Name: "aliqua sit magna tempor"}

I need to convert that into array of object like this:

[Object]
     0: Object
       CountryID: 87944818
       ISO2: "do"
       ISO3: "u"
       Name: "aliqua sit magna tempor"

I have done some work around using Object.keys and map but could not acheive the exact output.
Have tried some thing like that:

let keys:any[] = [];
        for (let key in value) {
            console.log(key);
            keys.push({key: value[key]});
        }
        console.log(keys);

value is the object that need to convert.

Body:
keys.push({[key]: value[key]});

You dont want to set "key" but rather value of key.

Keys will be:

[
  {CountryID: 87944818},
  {ISO2: "do"},
  {ISO3: "u"},
  {Name: "aliqua sit magna tempor"},
]

I dont know why this should be useful...


问:
Google App Engine: how to find out, which instance is running which instance-class?
I have created and successfully deployed a NodeJS-app on GoogleAppEngine. I know that they offer several "instance-types" with completely different pricings according to CPU-type, CPU-cores, memory and so on...

One can find the instance classes here in this list: https://cloud.google.com/appengine/pricing

But how do i know, which instance-class is running for my app currently? The dashboard doesnt show me that. "gcloud app instances list" hides this information too. "gcloud app describe" also doesnt provide this information....

How can i find out, which instance is running with which instance class?

Update

The solution provided by @eater is not available for me as the final "config"-column he had mentioned is not visible in "my" dashboard:

Update 2

Since this app was configured with "Flexible Environment" the concrete instance type might be not shown here as there is a specific pricing. Apparently this is the answer on my question.

答:
It seems that i can answer by myself:

Since this app was configured with "Flexible Environment" the concrete instance type might be not shown here as there is a specific pricing for "flex"-classes. Apparently this is the answer on my question.


问:
VBA : how to get the rows data while comparing to workbooks and copy the data in third workbook
Hi i am trying to copy the differences  while comparing the two workbooks and past the differences in third workbook. the below code is working upto copying the first differences(row). the code not working for copying all differences (rows) of the two workbooks. please suggest how to copy the all differences</p>

```<code>Sub findingdiff()
Dim FileSys, objFile, myFolder, c As Object
Dim wb1, wb2 As Workbook
Dim wb3 As ThisWorkbook
Set wb3 = ThisWorkbook
FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)
'loop through each file and get date last modified. If largest date then store Filename
        dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".xls") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename = objFile.Name
                End If
            End If
        Next objFile
'opening of latest file in the folder

                Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)
                Set FileSys = Nothing
                Set myFolder = Nothing
With wb2.Sheets("Sheet1")
Sh1LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh1Range = .Range("C1:C" & Sh1LastRow)
End With
 Set wb1 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\do\AR_Report_Excel_Version_06042017.xls")
With wb1.Sheets("Sheet1")
Sh2LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh2Range = .Range("C2:C" & Sh2LastRow)
End With

'compare latest workbook with old workbook
For Each cell In Sh1Range
Set c = Sh2Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 5
cell.Offset(0, 1).Interior.ColorIndex = 5
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

End If
Next cell
'compare  with sheet 1

For Each cell In Sh2Range
Set c = Sh1Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 4
cell.Offset(0, 1).Interior.ColorIndex = 4
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

End If
Next cell

End Sub
</code>```

答:
This should be a comment, but i don't have enough reputation to create one, so this has to do.

When you are declaring

```<code>Dim wb1, wb2 As Workbook
</code>```

only wb2 is declared as Workbook, wb1 is declared as Variant.
To declare wb1 and wb2 as Workbook, write:

```<code>Dim wb1 As Workbook, wb2 As Workbook
</code>```

Same goes with

```<code>Dim FileSys, objFile, myFolder, c As Object
</code>```

Which should be

```<code>Dim FileSys As Object, objFile As Object, myFolder As Object, c As Object
</code>```

Body:
Hi i am trying to copy the differences  while comparing the two workbooks and past the differences in third workbook. the below code is working upto copying the first differences(row). the code not working for copying all differences (rows) of the two workbooks. please suggest how to copy the all differences

Sub findingdiff()
Dim FileSys, objFile, myFolder, c As Object
Dim wb1, wb2 As Workbook
Dim wb3 As ThisWorkbook
Set wb3 = ThisWorkbook
FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)
'loop through each file and get date last modified. If largest date then store Filename
        dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".xls") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename = objFile.Name
                End If
            End If
        Next objFile
'opening of latest file in the folder

                Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)
                Set FileSys = Nothing
                Set myFolder = Nothing
With wb2.Sheets("Sheet1")
Sh1LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh1Range = .Range("C1:C" & Sh1LastRow)
End With
 Set wb1 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\do\AR_Report_Excel_Version_06042017.xls")
With wb1.Sheets("Sheet1")
Sh2LastRow = .Cells(Rows.Count, "C").End(xlUp).Row
Set Sh2Range = .Range("C2:C" & Sh2LastRow)
End With

'compare latest workbook with old workbook
For Each cell In Sh1Range
Set c = Sh2Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 5
cell.Offset(0, 1).Interior.ColorIndex = 5
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

End If
Next cell
'compare  with sheet 1

For Each cell In Sh2Range
Set c = Sh1Range.Find( _
what:=cell, LookIn:=xlValues)
If c Is Nothing Then
cell.Interior.ColorIndex = 4
cell.Offset(0, 1).Interior.ColorIndex = 4
cell.EntireRow.Copy wb3.Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

End If
Next cell

End Sub

Body:
This should be a comment, but i don't have enough reputation to create one, so this has to do.

When you are declaring

Dim wb1, wb2 As Workbook

only wb2 is declared as Workbook, wb1 is declared as Variant.
To declare wb1 and wb2 as Workbook, write:

Dim wb1 As Workbook, wb2 As Workbook

Same goes with

Dim FileSys, objFile, myFolder, c As Object

Which should be

Dim FileSys As Object, objFile As Object, myFolder As Object, c As Object


问:
IfNull with Zero value is Boolean False. How to count?
EDIT : more explicit exemple

I would like to count the number of values of one specific field in a collection.

```<code>chosenSensors = ["CO2_BUR_NE_I_001", "CO2_CEL_SE_I_001"]

match = {'$match':{'$or':list(map(lambda x:{x:{'$exists': True}}, chosenSensors))}}

group = {'$group':{'_id':{'year':{'$year':'$timestamp'}}}}

project = {'$project':{}}

for chosenSensor in chosenSensors:
    group['$group'][chosenSensor+'-Count'] = {'$sum':{'$cond':[{'$ifNull':['$'+chosenSensor, False]}, 1, 0]}}
project['$project'][chosenSensor+'-Count'] = True

sort = {'$sort': {"_id":1}}

pipeline = [match, group, project, sort]

for doc in client["cleanData"]["test"].aggregate(pipeline):
    print(doc)
</code>```

Just below is one sample of my collection. I would like to count the number of values in CO2_BUR_NE_I_001.

I expect to have a count of 4.

```<code>{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226fd"),
    "timestamp" : ISODate("2016-11-17T12:36:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226fe"),
    "timestamp" : ISODate("2016-11-17T12:37:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226ff"),
    "timestamp" : ISODate("2016-11-17T12:38:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 0
}

{
    "_id" : ObjectId("593ab63a1ccb9b0c0fb3d3e5"),
    "timestamp" : ISODate("2016-02-01T19:26:00.000Z"),
    "CO2_CEL_SE_I_001" : 1080
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb22700"),
    "timestamp" : ISODate("2016-11-17T12:39:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6025ccb9b0c0fb226fd"),
    "timestamp" : ISODate("2016-11-17T12:36:00.000Z"),
    "TEM_ETG_001" : 1210
}
</code>```

But I have 3. The value 0 of CO2_CEL_SE_I_001 is not counted as an existing value.

```<code>{'_id': {'year': 2016}, 'CO2_BUR_NE_I_001-Count': 3, 'CO2_CEL_SE_I_001-Count': 5}
</code>```

If I replace 0 by 880 in the involved document...

```<code>{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226ff"),
    "timestamp" : ISODate("2016-11-17T12:38:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}
</code>```

... I find the expected result

```<code>{'_id': {'year': 2016}, 'CO2_BUR_NE_I_001-Count': 4, 'CO2_CEL_SE_I_001-Count': 5}
</code>```

EDIT : Beggining of an answer...

When I use $ifNull on a value which exists, it returns the value. However, when this value is 0, it returns 0. But this return is given to $cond, and when it's 0, the $cond is considered as False and it returns 0 instead of 1 to my $sum. How can i handle that?

答:
The method uses the fact than Null is lower than numbers (int, doubles, long) in the comparison order of BSON types values :
Documentation : comparison/Sort Order

So I just have to compare my value with None.

```<code>{'$sum':{'$cond':[{ '$gt': ['$'+chosenSensor, None]}, 1, 0]}}
</code>```

Body:
EDIT : more explicit exemple

I would like to count the number of values of one specific field in a collection.

chosenSensors = ["CO2_BUR_NE_I_001", "CO2_CEL_SE_I_001"]

match = {'$match':{'$or':list(map(lambda x:{x:{'$exists': True}}, chosenSensors))}}

group = {'$group':{'_id':{'year':{'$year':'$timestamp'}}}}

project = {'$project':{}}

for chosenSensor in chosenSensors:
    group['$group'][chosenSensor+'-Count'] = {'$sum':{'$cond':[{'$ifNull':['$'+chosenSensor, False]}, 1, 0]}}
project['$project'][chosenSensor+'-Count'] = True

sort = {'$sort': {"_id":1}}

pipeline = [match, group, project, sort]

for doc in client["cleanData"]["test"].aggregate(pipeline):
    print(doc)

Just below is one sample of my collection. I would like to count the number of values in CO2_BUR_NE_I_001.

I expect to have a count of 4.

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226fd"),
    "timestamp" : ISODate("2016-11-17T12:36:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226fe"),
    "timestamp" : ISODate("2016-11-17T12:37:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226ff"),
    "timestamp" : ISODate("2016-11-17T12:38:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 0
}

{
    "_id" : ObjectId("593ab63a1ccb9b0c0fb3d3e5"),
    "timestamp" : ISODate("2016-02-01T19:26:00.000Z"),
    "CO2_CEL_SE_I_001" : 1080
}

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb22700"),
    "timestamp" : ISODate("2016-11-17T12:39:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

{
    "_id" : ObjectId("593ab6025ccb9b0c0fb226fd"),
    "timestamp" : ISODate("2016-11-17T12:36:00.000Z"),
    "TEM_ETG_001" : 1210
}

But I have 3. The value 0 of CO2_CEL_SE_I_001 is not counted as an existing value.

{'_id': {'year': 2016}, 'CO2_BUR_NE_I_001-Count': 3, 'CO2_CEL_SE_I_001-Count': 5}

If I replace 0 by 880 in the involved document...

{
    "_id" : ObjectId("593ab6021ccb9b0c0fb226ff"),
    "timestamp" : ISODate("2016-11-17T12:38:00.000Z"),
    "CO2_CEL_SE_I_001" : 1210,
    "CO2_BUR_NE_I_001" : 880
}

... I find the expected result

{'_id': {'year': 2016}, 'CO2_BUR_NE_I_001-Count': 4, 'CO2_CEL_SE_I_001-Count': 5}

EDIT : Beggining of an answer...

When I use $ifNull on a value which exists, it returns the value. However, when this value is 0, it returns 0. But this return is given to $cond, and when it's 0, the $cond is considered as False and it returns 0 instead of 1 to my $sum. How can i handle that?

Body:
The method uses the fact than Null is lower than numbers (int, doubles, long) in the comparison order of BSON types values :
Documentation : comparison/Sort Order

So I just have to compare my value with None.

{'$sum':{'$cond':[{ '$gt': ['$'+chosenSensor, None]}, 1, 0]}}


问:
How to aggregate tests count from different languages modules with Sonarqube?
I am using Sonarqube on a Maven multi-module projects which contains Java and Javascript modules.

All my tests results are (seems to be) read by Sonarqube as the code coverage looks good. When I check files by files, it also looks covered properly.

However, the amount of tests ran on the project homepage is incorrect: I only have the amount of Java tests (617). The Javascript tests count is missing (1646).

Here are my Sonar properties in the root pom.xml:

```<code><sonar.projectVersion>${project.version}</sonar.projectVersion>
<sonar.sourceEncoding>UTF-8</sonar.sourceEncoding>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>

<java-module-1sonar.projectKey>module1</java-module-1sonar.projectKey>
<java-module-1sonar.projectBaseDir>../module1</java-module-1sonar.projectBaseDir>

<java-module-2sonar.projectKey>module2</java-module-2sonar.projectKey>
<java-module-2sonar.projectBaseDir>../module2</java-module-2sonar.projectBaseDir>

<java-module-3sonar.projectKey>module3</java-module-3sonar.projectKey>
<java-module-3sonar.projectBaseDir>../module3</java-module-3sonar.projectBaseDir>

<javascript-modulesonar.projectKey>module4</javascript-modulesonar.projectKey>
<javascript-modulesonar.projectBaseDir>../module4</javascript-modulesonar.projectBaseDir>
</code>```

Am I doing something wrong? Do I have to configure something on the Sonarqube server part?

Thanks for your help.

答:
I finally figured out what I was missing:

First, I was not generating the unit test report within my karma.conf.js

Then, I found a very useful Sonar report for karma: karma-sonarqube-unit-reporter

Finally, I updated my pom.xml to use generic test result (sonar.testExecutionReportPaths property)

Now it works perfectly. I hope my struggle could help other people :)

Body:
I am using Sonarqube on a Maven multi-module projects which contains Java and Javascript modules.

All my tests results are (seems to be) read by Sonarqube as the code coverage looks good. When I check files by files, it also looks covered properly.

However, the amount of tests ran on the project homepage is incorrect: I only have the amount of Java tests (617). The Javascript tests count is missing (1646).

Here are my Sonar properties in the root pom.xml:

<sonar.projectVersion>${project.version}</sonar.projectVersion>
<sonar.sourceEncoding>UTF-8</sonar.sourceEncoding>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>

<java-module-1sonar.projectKey>module1</java-module-1sonar.projectKey>
<java-module-1sonar.projectBaseDir>../module1</java-module-1sonar.projectBaseDir>

<java-module-2sonar.projectKey>module2</java-module-2sonar.projectKey>
<java-module-2sonar.projectBaseDir>../module2</java-module-2sonar.projectBaseDir>

<java-module-3sonar.projectKey>module3</java-module-3sonar.projectKey>
<java-module-3sonar.projectBaseDir>../module3</java-module-3sonar.projectBaseDir>

<javascript-modulesonar.projectKey>module4</javascript-modulesonar.projectKey>
<javascript-modulesonar.projectBaseDir>../module4</javascript-modulesonar.projectBaseDir>

Am I doing something wrong? Do I have to configure something on the Sonarqube server part?

Thanks for your help.


问:
How to change theme background color and text color on selection
Is there any way to change the style of the web page on by user selection using CSS in angular js.

I tried in google but nothing is working for me.

I have a CSS file which will have style. I need to rewrite the style in all divs wherever needed by changing the background colour, text colour, font style.

```<code>    $scope.model.webPageSkin = 'Default';

    // create the list of themes
    $scope.bootstraps = [
        { name: 'Plain', url: 'Plain' },
        { name: 'Blue', url: 'Blue' },
        { name: 'Green', url: 'Green' } ,
        { name: 'Default', url: 'default' } ,
    ];

**Plain.css**

ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #ddd;
}

**default.css**

.ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #3c8dbc;
}

<div class="wrapper>
     <header class="main-header">
          <nav class="navbar navbar-static-top" ng-class="{ChangeColor:
           model.webPageSkin !important;}">
          </nav>
     </header>

<div class="row">
<select  ng-model="model.webPageSkin" ng-options="bootstrap.url as bootstrap.name for bootstrap in bootstraps">
                </select>
</div>
</div>
</code>```

Can anyone suggest me how to do this.

答:
ng-class takes an angularjs expression to evaluate, not the CSS styling you're currently specifying.

ngClass API docs

So your markup needs to change to basically say, I want the css class of 'ChangeColor' whenever angular evalutes model.webPageSkin to be truthy.

```<code>ng-class="{'ChangeColor': model.webPageSkin}">
</code>```

Body:
Is there any way to change the style of the web page on by user selection using CSS in angular js.

I tried in google but nothing is working for me.

I have a CSS file which will have style. I need to rewrite the style in all divs wherever needed by changing the background colour, text colour, font style.

    $scope.model.webPageSkin = 'Default';

    // create the list of themes
    $scope.bootstraps = [
        { name: 'Plain', url: 'Plain' },
        { name: 'Blue', url: 'Blue' },
        { name: 'Green', url: 'Green' } ,
        { name: 'Default', url: 'default' } ,
    ];

**Plain.css**

ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #ddd;
}

**default.css**

.ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #3c8dbc;
}

<select  ng-model="model.webPageSkin" ng-options="bootstrap.url as bootstrap.name for bootstrap in bootstraps">
                </select>

Can anyone suggest me how to do this.

Body:
ng-class takes an angularjs expression to evaluate, not the CSS styling you're currently specifying.

ngClass API docs

So your markup needs to change to basically say, I want the css class of 'ChangeColor' whenever angular evalutes model.webPageSkin to be truthy.

ng-class="{'ChangeColor': model.webPageSkin}">


问:
Create shortcut of directory
I want to create shortcut of Autostart directory on my desktop.

I know how to create shortcut of any application for example notepad but how can I create shortcut of directory?

I am trying something like this

```<code>$objShell = New-Object -ComObject ("WScript.Shell")
$objShortCut = $objShell.CreateShortcut($env:USERPROFILE + "\Desktop" + "\Autostart.lnk")
$objShortCut.TargetPath="C:\Users\" + $env:USERPROFILE + "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
$objShortCut.Save()
</code>```

Errors:

```<code>+ $objShortCut.TargetPath="C:\Users\" + $env:USERPROFILE + "\AppData\Ro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException
</code>```

答:
Remove "C:\Users\" +.

```<code>$objShell = New-Object -ComObject ("WScript.Shell")
$objShortCut = $objShell.CreateShortcut($env:USERPROFILE + "\Desktop" + "\Autostart.lnk")
$objShortCut.TargetPath=$env:USERPROFILE + "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
$objShortCut.Save()
</code>```

Title: Create shortcut of directory

Body:
I want to create shortcut of Autostart directory on my desktop.

I know how to create shortcut of any application for example notepad but how can I create shortcut of directory?

I am trying something like this

$objShell = New-Object -ComObject ("WScript.Shell")
$objShortCut = $objShell.CreateShortcut($env:USERPROFILE + "\Desktop" + "\Autostart.lnk")
$objShortCut.TargetPath="C:\Users\" + $env:USERPROFILE + "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
$objShortCut.Save()

Errors:

+ $objShortCut.TargetPath="C:\Users\" + $env:USERPROFILE + "\AppData\Ro ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException

Body:
Remove "C:\Users\" +.

$objShell = New-Object -ComObject ("WScript.Shell")
$objShortCut = $objShell.CreateShortcut($env:USERPROFILE + "\Desktop" + "\Autostart.lnk")
$objShortCut.TargetPath=$env:USERPROFILE + "\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
$objShortCut.Save()


问:
click event on a input text box does not work
here is my input :

```<code><input name="DeviceIP" class="k-input k-textbox" type="text" data-bind="value:DeviceIP">
</code>```

here is my js which is not working

```<code>$('input[name="DeviceIP"]').click(function () {  alert("test") });
</code>```

答:
```<code>$("input[name='DeviceIP']").click(function () {  alert("test")});
</code>```

Body:
here is my input :

<input name="DeviceIP" class="k-input k-textbox" type="text" data-bind="value:DeviceIP">

here is my js which is not working

$('input[name="DeviceIP"]').click(function () {  alert("test") });


问:
Retrieving rows based on another column's aggregate values in MS SQL
I am trying to write a query for MS SQL Server which returns the container_parent_ids that have quantity of 0:

```<code>Container_id | Container_name | container_parent_id | quantity | alive
----------------------------------------------------------------------
1            | ContA          | 12345               | 2        | 1
2            | ContB          | 12345               | 1        | 1
3            | ContC          | 12345               | 0        | 1
4            | ContD          | 12345               | 1        | 1
5            | ContA          | 23456               | 1        | 1
6            | ContB          | 23456               | 0        | 1
7            | ContC          | 23456               | 1        | 1
8            | ContD          | 34567               | 0        | 1
9            | ContE          | 34567               | 0        | 1
</code>```

In the above data, only ContD and ContE should be returned for 34567.

If I group by container_parent_id and use WHERE quanity = 0, the result includes other rows.

This is what I have been trying:

```<code>SELECT count(), container_parent_id from Container where quantity = 0 GROUP BY container_parent_id HAVING count() > 0
</code>```

resulting in:

```<code>3 | ContC | 12345 | 0 | 1
6 | ContB | 23456 | 0 | 1
8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1
</code>```

Problem with running this query or what Renu/Stan suggested is, it returns those containers that have quantity as 0 - as a subset. But, I do not want the first two as they have other containers with quantities 1 or 2 for the same container_parent_id. My final output should just be:

```<code>8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1
</code>```

I.e. every container_parent_id that which has only records with quantity = 0.

答:
Something like this should work:

```<code>SELECT *
FROM Containers
WHERE
    container_parent_id IN (
        SELECT container_parent_id
        FROM Containers
        GROUP BY container_parent_id
        HAVING sum(quantity) = 0
      );
</code>```

First select all the parent IDs that have a total of 0 quantity and then use that as a nested query to get all the container names that have those IDs as parents.

Body:
I am trying to write a query for MS SQL Server which returns the container_parent_ids that have quantity of 0:

Container_id | Container_name | container_parent_id | quantity | alive
----------------------------------------------------------------------
1            | ContA          | 12345               | 2        | 1
2            | ContB          | 12345               | 1        | 1
3            | ContC          | 12345               | 0        | 1
4            | ContD          | 12345               | 1        | 1
5            | ContA          | 23456               | 1        | 1
6            | ContB          | 23456               | 0        | 1
7            | ContC          | 23456               | 1        | 1
8            | ContD          | 34567               | 0        | 1
9            | ContE          | 34567               | 0        | 1

In the above data, only ContD and ContE should be returned for 34567.

If I group by container_parent_id and use WHERE quanity = 0, the result includes other rows.

This is what I have been trying:

SELECT count(), container_parent_id from Container where quantity = 0 GROUP BY container_parent_id HAVING count() > 0

resulting in:

3 | ContC | 12345 | 0 | 1
6 | ContB | 23456 | 0 | 1
8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1

Problem with running this query or what Renu/Stan suggested is, it returns those containers that have quantity as 0 - as a subset. But, I do not want the first two as they have other containers with quantities 1 or 2 for the same container_parent_id. My final output should just be:

8 | ContD | 34567 | 0 | 1
9 | ContE | 34567 | 0 | 1

I.e. every container_parent_id that which has only records with quantity = 0.

Body:
Something like this should work:

SELECT *
FROM Containers
WHERE
    container_parent_id IN (
        SELECT container_parent_id
        FROM Containers
        GROUP BY container_parent_id
        HAVING sum(quantity) = 0
      );

First select all the parent IDs that have a total of 0 quantity and then use that as a nested query to get all the container names that have those IDs as parents.


问:
SQL Insert command throwing errors

```<code> System.Data.SqlClient.SqlException occurred   HResult=0x80131904   Message=Cannot insert explicit value for identity column in table 'DriversDetailsTable' when IDENTITY_INSERT is set to OFF.   Source=.Net SqlClient Data Provider   StackTrace: <Cannot evaluate the exception stack trace>
</code>```

I keep getting the above error when i run my code, not sure why. Here is my code:

```<code>SqlConnection conn = new SqlConnection(@"Data Source = ComputerName\SQLEXPRESS;Initial Catalog = Drivers;Trusted_Connection=True;");
        conn.Open();

        SqlDataAdapter adapter = new SqlDataAdapter();

        SqlCommand command = new SqlCommand($@"INSERT INTO DriversDetailsTable (name, Id, DateJoined) VALUES ('Driver4', 1, '2017-07-06')", conn);
        command.ExecuteNonQuery();

        conn.Close();
</code>```

答:
Yeah, that's cause your Id column is an IDENTITY column and so you should omit it in your INSERT statement like below. Since it's an IDENTITY column you can't explicitly insert values for it unless you set IDENTITY_INSERT to OFF which don't think you wanted to do anyways

```<code>INSERT INTO DriversDetailsTable (name, DateJoined) VALUES ('Driver4', '2017-07-06')
</code>```

SideNote: don't see a reason for C# 6 syntax of string interpolation $@"INSERT when you are using hardcoded/static values

Title: SQL Insert command throwing errors

Body:
 System.Data.SqlClient.SqlException occurred   HResult=0x80131904   Message=Cannot insert explicit value for identity column in table 'DriversDetailsTable' when IDENTITY_INSERT is set to OFF.   Source=.Net SqlClient Data Provider   StackTrace: <Cannot evaluate the exception stack trace>

I keep getting the above error when i run my code, not sure why. Here is my code:

SqlConnection conn = new SqlConnection(@"Data Source = ComputerName\SQLEXPRESS;Initial Catalog = Drivers;Trusted_Connection=True;");
        conn.Open();

        SqlDataAdapter adapter = new SqlDataAdapter();

        SqlCommand command = new SqlCommand($@"INSERT INTO DriversDetailsTable (name, Id, DateJoined) VALUES ('Driver4', 1, '2017-07-06')", conn);
        command.ExecuteNonQuery();

        conn.Close();

Body:
Yeah, that's cause your Id column is an IDENTITY column and so you should omit it in your INSERT statement like below. Since it's an IDENTITY column you can't explicitly insert values for it unless you set IDENTITY_INSERT to OFF which don't think you wanted to do anyways

INSERT INTO DriversDetailsTable (name, DateJoined) VALUES ('Driver4', '2017-07-06')

SideNote: don't see a reason for C# 6 syntax of string interpolation $@"INSERT when you are using hardcoded/static values


问:
Android Custom Tab linked to Activity
How can i get the class below to create tabs that link to activities. its worrking the way it is but the tabs are not linked to any activity. I need the tabs to load different activities?</p>

```<code>import android.app.TabActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.TabHost.TabContentFactory;

public class CustomTabActivity extends TabActivity {
    TabHost mTabHost = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        // mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
        setupTab(new TextView(this), "Tab 1");
        setupTab(new TextView(this), "Tab 2");
        setupTab(new TextView(this), "Tab 3");
    }

    private void setupTab(final View view, final String tag) {
        View tabview = createTabView(mTabHost.getContext(), tag);
        TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview)
                .setContent(new TabContentFactory() {

                    public View createTabContent(String tag) {
                        return view;
                    }
                });
        mTabHost.addTab(setContent);
    }

    private static View createTabView(final Context context, final String text) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.tabs_bg, null);
        TextView tv = (TextView) view.findViewById(R.id.tabsText);
        tv.setText(text);
        return view;
    }
}
</code>```

答:
I need to setConent to Activities and not Views

No, you do not. You gain nothing from having your tabs populated with activities. In fact, doing that causes more harm than good -- you waste heap space, stack space, and CPU time for no added value.

Now, you do not have to define your tab content at runtime if you do not want. For example, here is a sample project that defines the tab content in the same layout as the TabHost itself.

ContentLicense: CC BY-SA 2.5

Title: Android Custom Tab linked to Activity

Body:
How can i get the class below to create tabs that link to activities. its worrking the way it is but the tabs are not linked to any activity. I need the tabs to load different activities?

import android.app.TabActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.TabHost.TabContentFactory;

public class CustomTabActivity extends TabActivity {
    TabHost mTabHost = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        // mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
        setupTab(new TextView(this), "Tab 1");
        setupTab(new TextView(this), "Tab 2");
        setupTab(new TextView(this), "Tab 3");
    }

    private void setupTab(final View view, final String tag) {
        View tabview = createTabView(mTabHost.getContext(), tag);
        TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview)
                .setContent(new TabContentFactory() {

                    public View createTabContent(String tag) {
                        return view;
                    }
                });
        mTabHost.addTab(setContent);
    }

    private static View createTabView(final Context context, final String text) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.tabs_bg, null);
        TextView tv = (TextView) view.findViewById(R.id.tabsText);
        tv.setText(text);
        return view;
    }
}


问:
How to use the changed IndexerName in c# so that WPF elements also gets updated?
I have a class with an indexer defined. As long as I keep the default IndexerName (Item) WPF elements update nicely.
e.g.

```<code>public byte this[int index] {
    get { return ListElements[index].Value; }
    set {
        ListElements[index].Value = value;
        FirePropertyChanged("Item[]");
    }
}
protected void FirePropertyChanged(string propertyName)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
</code>```

In XAML I am binding it as follows

```<code><Label Content="{Binding CurrentDevice[3]}"/>
</code>```

As mentioned, this currently works nicely. However for better readability in the code (e.g. notify event handler method) I tried to change the original code to

```<code>[IndexerName("ElementItem")]
public byte this[int index] {
    get { return ListElements[index].Value; }
    set {
        ListElements[index].Value = value;
        FirePropertyChanged("ElementItem[]");
    }
}
</code>```

The c# event handler method I provided recognized the change when checking for (e.PropertyName == "ElementItem[]") but WPF elements didn't.

Is there a way to get it working in WPF?

I even tried modifying the XAML binding to {Binding CurrentDevice.ElementItem[3]} without success. The initial element read at startup succeeded but afterwards the element did not display the new value.

答:
The indexer binding will look for a property change of Item[], I don't think you can change this.

Reference: https://blogs.msdn.microsoft.com/xtof/2007/09/28/binding-to-indexers/

Body:
I have a class with an indexer defined. As long as I keep the default IndexerName (Item) WPF elements update nicely.
e.g.

public byte this[int index] {
    get { return ListElements[index].Value; }
    set {
        ListElements[index].Value = value;
        FirePropertyChanged("Item[]");
    }
}
protected void FirePropertyChanged(string propertyName)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

In XAML I am binding it as follows

As mentioned, this currently works nicely. However for better readability in the code (e.g. notify event handler method) I tried to change the original code to

[IndexerName("ElementItem")]
public byte this[int index] {
    get { return ListElements[index].Value; }
    set {
        ListElements[index].Value = value;
        FirePropertyChanged("ElementItem[]");
    }
}

The c# event handler method I provided recognized the change when checking for (e.PropertyName == "ElementItem[]") but WPF elements didn't.

Is there a way to get it working in WPF?

I even tried modifying the XAML binding to {Binding CurrentDevice.ElementItem[3]} without success. The initial element read at startup succeeded but afterwards the element did not display the new value.


问:
jQuery UI : How can I set the resizing limit, aspect ratio when I increase/decrease the size of the div
I have a div tag, it is ( div tag ) resizable and inside that I have a h1 tag ( or it would be any tag ).

The Problem :

I am having 2 problems :

The aspect ratio is not working properly as I want means "when I increase/decrease the size of the div its height gets larger" so how can I set it properly and

I want to fix the smallest width on resizing means "if on decreasing the size it reached to 27px it stop decreasing."

Code

```<code>$('.draggable_element').each(function() {
        $(this).resizable({
        autoHide: true,
      handles: 's,e,w',
      aspectRatio: 1/9
    });
})
</code>```

Here is my jsFiddle

UPDATE :

I think I have not properly explained my first problem to know what's the first problem please visit to my fiddle link try to resize (increase/decrease) the div from left side or right side the height of the div will automatically increase that the problem

答:
For your 1st problem, you can use aspectRatio: true, it will use the initial aspect ratio based on your element's width and height.

For your 2nd problem, you can use minWidth option

```<code>$('.draggable_element').each(function() {
    $(this).resizable({
      autoHide: true,
      handles: 's,e,w',
      aspectRatio: true,
      minWidth: 27
  });
})
</code>```

Body:
I have a div tag, it is ( div tag ) resizable and inside that I have a h1 tag ( or it would be any tag ).

The Problem :

I am having 2 problems :

The aspect ratio is not working properly as I want means "when I increase/decrease the size of the div its height gets larger" so how can I set it properly and

I want to fix the smallest width on resizing means "if on decreasing the size it reached to 27px it stop decreasing."

Code

$('.draggable_element').each(function() {
        $(this).resizable({
        autoHide: true,
      handles: 's,e,w',
      aspectRatio: 1/9
    });
})

Here is my jsFiddle

UPDATE :

I think I have not properly explained my first problem to know what's the first problem please visit to my fiddle link try to resize (increase/decrease) the div from left side or right side the height of the div will automatically increase that the problem

Body:
For your 1st problem, you can use aspectRatio: true, it will use the initial aspect ratio based on your element's width and height.

For your 2nd problem, you can use minWidth option

$('.draggable_element').each(function() {
    $(this).resizable({
      autoHide: true,
      handles: 's,e,w',
      aspectRatio: true,
      minWidth: 27
  });
})


答:
Presumably Id is an IDENTITY column. As such, you shouldn't attempt to INSERT into the Id column - omit it from the INSERT statement, and let the database tell you what number it got assigned:

```<code>SqlCommand command = new SqlCommand($@"
INSERT INTO DriversDetailsTable (name, DateJoined) VALUES ('Driver4', '2017-07-06');
SELECT SCOPE_IDENTITY();", conn);
</code>```

and use ExecuteScalar() to get the value back:

```<code>int id = (id)(decimal)command.ExecuteScalar();
</code>```

(see Why does select SCOPE_IDENTITY() return a decimal instead of an integer? for an explanation of the cast)

Other options:

make it not be an IDENTITY column

temporarily disable identity insert during this operation if you need a specific value (not recommended in most cases)

Title: SQL Insert command throwing errors

Body:
Presumably Id is an IDENTITY column. As such, you shouldn't attempt to INSERT into the Id column - omit it from the INSERT statement, and let the database tell you what number it got assigned:

SqlCommand command = new SqlCommand($@"
INSERT INTO DriversDetailsTable (name, DateJoined) VALUES ('Driver4', '2017-07-06');
SELECT SCOPE_IDENTITY();", conn);

and use ExecuteScalar() to get the value back:

int id = (id)(decimal)command.ExecuteScalar();

(see Why does select SCOPE_IDENTITY() return a decimal instead of an integer? for an explanation of the cast)

Other options:

make it not be an IDENTITY column

temporarily disable identity insert during this operation if you need a specific value (not recommended in most cases)


问:
How many users is too much when using session variables?
I'm currently using session variables as a cache to cut down the calls to the database.

I'm wondering at about how many concurrent users does this stop working at? 1,000, 10,000 ....100,000??? Also will iis start flaking out at a certain load? And are there
any alternatives?

I know it depends on how much data I'm storing per user, but I want to hear from other peoples experiences.

I do have it setup so that when the code tries to access a timed out session that it reloads from the database.

I'm currently using iis6 but I could easily use iis7 if it handles sessions better.

Edit: Yes I'm using application variables for non user specific data.

答: If this is of any concern to you, use a State Server or the SQL Storage options for the session. For almost all applications it will not prove to be a problem though.</p>

OwnerDisplayName: Donny V

LastEditorDisplayName: Donny V

OwnerDisplayName: David Thomas Garcia


问:
multiple definition of <function>
```<code>/tmp/ccTQFVCP.o: In function `whiteSpace':
/home/tommo/fly/flyc/config.c:12: multiple definition of `whiteSpace'
/tmp/cc0ccMfz.o:/home/tommo/fly/flyc/config.c:12: first defined here
/tmp/ccTQFVCP.o: In function `lineEnd':
/home/tommo/fly/flyc/config.c:16: multiple definition of `lineEnd'
/tmp/cc0ccMfz.o:/home/tommo/fly/flyc/config.c:16: first defined here
/tmp/ccTQFVCP.o: In function `makeSubStr':
/home/tommo/fly/flyc/config.c:20: multiple definition of `makeSubStr'
/tmp/cc0ccMfz.o:/home/tommo/fly/flyc/config.c:20: first defined here
</code>```

I'm getting this for every function in my file config.c

Every one of my header files has a #ifndef FILE_H header block thing.

Why is it doing this?

```<code>TARGET   = fly
SRC      = main.c gfx.c transform.c entity.c list.c v3.c config.c airplane.c
CPPFLAGS = -Wall
LDFLAGS  = -lglfw -lGL -lGLU
DEBUG    = -g

linux:
    @echo Building for Linux...
    gcc $(CPPFLAGS) $(DEBUG) $(LDFLAGS) $(SRC) -o $(TARGET)
    @echo All done.
clean:
    rm $(TARGET)
help:
    @echo "Available targets for fly"
    @echo " linux: build for linux (default)"
    @echo " clean: clean up directory"

.PHONY: help clean
</code>```

That's my Makefile. git pull from https://github.com/tm1rbrt/fly If you wanna try to build yourself

答: The problem is this: main.c includes config.c. As a consequence, you get everything in config.c twice. It's unconventional that C files include each other, so I recommend to drop the include.</p>

Title: multiple definition of <function>

Body:
/tmp/ccTQFVCP.o: In function `whiteSpace':
/home/tommo/fly/flyc/config.c:12: multiple definition of `whiteSpace'
/tmp/cc0ccMfz.o:/home/tommo/fly/flyc/config.c:12: first defined here
/tmp/ccTQFVCP.o: In function `lineEnd':
/home/tommo/fly/flyc/config.c:16: multiple definition of `lineEnd'
/tmp/cc0ccMfz.o:/home/tommo/fly/flyc/config.c:16: first defined here
/tmp/ccTQFVCP.o: In function `makeSubStr':
/home/tommo/fly/flyc/config.c:20: multiple definition of `makeSubStr'
/tmp/cc0ccMfz.o:/home/tommo/fly/flyc/config.c:20: first defined here

I'm getting this for every function in my file config.c

Every one of my header files has a #ifndef FILE_H header block thing.

Why is it doing this?

TARGET   = fly
SRC      = main.c gfx.c transform.c entity.c list.c v3.c config.c airplane.c
CPPFLAGS = -Wall
LDFLAGS  = -lglfw -lGL -lGLU
DEBUG    = -g

linux:
    @echo Building for Linux...
    gcc $(CPPFLAGS) $(DEBUG) $(LDFLAGS) $(SRC) -o $(TARGET)
    @echo All done.
clean:
    rm $(TARGET)
help:
    @echo "Available targets for fly"
    @echo " linux: build for linux (default)"
    @echo " clean: clean up directory"

.PHONY: help clean

That's my Makefile. git pull from https://github.com/tm1rbrt/fly If you wanna try to build yourself


问:
String mismatch index
I have two strings and I want to get the index where the mismatch happens:

```<code>str = "abcdef"
str2 = "abddef"

Output: 2
</code>```

So can anyone tell me is there an inbuilt function in java to get the index? If not can someone give me a hint to do so? Thank You!

答:
```<code>public static int myCompare(String s1, String s2){
    int counter = 0;
    while (s1.length() > counter && s2.length() > counter){
      if (s1.charAt(counter) == s2.charAt(counter))
        counter++;
      else
        return counter;
    }

    if (counter < s1.length() || counter < s2.length() )
      return counter;
    else
      return -1;
  }
</code>```

If they are equal return -1, otherwise the 0-index where it has been found a mismatch.

Title: String mismatch index

Body:
I have two strings and I want to get the index where the mismatch happens:

str = "abcdef"
str2 = "abddef"

Output: 2

So can anyone tell me is there an inbuilt function in java to get the index? If not can someone give me a hint to do so? Thank You!

Body:
public static int myCompare(String s1, String s2){
    int counter = 0;
    while (s1.length() > counter && s2.length() > counter){
      if (s1.charAt(counter) == s2.charAt(counter))
        counter++;
      else
        return counter;
    }

    if (counter < s1.length() || counter < s2.length() )
      return counter;
    else
      return -1;
  }

If they are equal return -1, otherwise the 0-index where it has been found a mismatch.


问:
Can someone look into a web servers folders?
More a web server security question.

Is it possible for someone to "probe" into a folder on a web server, even if an index file is in place?

I assume they can't, but if I wanted to store .pdf applications as random names (93fe3509edif094.pdf) I want to make sure there's no way to list all the pdfs in the folder.

Thank you.

答:
Generally speaking, no.  Especially if you explicitly turn off the directory listing for that specific directory.

```<code><Directory /path/to/directory>
   Options -Indexes
</Directory>
</code>```

Source: http://httpd.apache.org/docs/1.3/misc/FAQ.html

However, you should be securing files through some sort of authentication process rather than just file names.  What you propose can be found by simply brute forcing the file name.  Also, people can share URLs, folks can sniff and find the URL, etc.  Use a better method.

Body:
Generally speaking, no.  Especially if you explicitly turn off the directory listing for that specific directory.

<Directory /path/to/directory>
   Options -Indexes
</Directory>

Source: http://httpd.apache.org/docs/1.3/misc/FAQ.html

However, you should be securing files through some sort of authentication process rather than just file names.  What you propose can be found by simply brute forcing the file name.  Also, people can share URLs, folks can sniff and find the URL, etc.  Use a better method.


问:
How to add ripple effect and have custom background on button in android?
Please tell me how to achieve both these together, I have gone through many already questions, but they dont specifically deal with my issue.

I want to have ripple effect on my button as well as it should be rounded and have background color. Also I should be able to control ripple effect color.

I tried few things which are listed below.

First Method: I tried setting style="@style/AppTheme"in the <Button> tag. This gives me ripple effect and background color (using <item name="colorButtonNormal">#500347</item>in the style) but the button is not rounded.

So to achieve rounded shape I gave android:background="@drawable/button_bg" in the <Button> tag. This makes button rounded and also background color is achieved, But Ripple effect is gone.

Second Method: I tried the using selector.
 1. Created button_background.xml

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

    <item
        android:state_focused="true"
        android:drawable="@drawable/button_bg"/>

    <item
        android:state_pressed="true"
        android:drawable="@drawable/ripple_effect"/>

    <item
        android:drawable="@drawable/ripple_effect"/>

</selector>
</code>```

rounded background for button in button_bg.xml:

```<code>  <shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
    android:color="#500347" />

<corners
    android:radius="10dip" />

<padding
    android:bottom="0dip"
    android:left="0dip"
    android:right="0dip"
    android:top="0dip" />
</code>```

ripple_effet.xml:

```<code>    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
  android:color="@android:color/holo_green_dark"
   tools:targetApi="lollipop">

    <item android:id="@android:id/mask">

<shape android:shape="rectangle">

    <solid android:color="@android:color/holo_green_dark" />

    <corners android:radius="10dip" />

</shape>
</code>```

In <Button> tag
android:background="@drawable/button_bg"

With this method button just goes white when pressed returns to background color.

Please tell me how to do it.

答:
I did it this way :-

android:background="@drawable/ad_action_view_bg" to my view. // Background is a Ripple drawable

Then I set android - foreground to required color.

Body:
Please tell me how to achieve both these together, I have gone through many already questions, but they dont specifically deal with my issue.

I want to have ripple effect on my button as well as it should be rounded and have background color. Also I should be able to control ripple effect color.

I tried few things which are listed below.

First Method: I tried setting style="@style/AppTheme"in the <Button> tag. This gives me ripple effect and background color (using <item name="colorButtonNormal">#500347</item>in the style) but the button is not rounded.

So to achieve rounded shape I gave android:background="@drawable/button_bg" in the <Button> tag. This makes button rounded and also background color is achieved, But Ripple effect is gone.

Second Method: I tried the using selector.
 1. Created button_background.xml

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

    <item
        android:state_focused="true"
        android:drawable="@drawable/button_bg"/>

    <item
        android:state_pressed="true"
        android:drawable="@drawable/ripple_effect"/>

    <item
        android:drawable="@drawable/ripple_effect"/>

</selector>

rounded background for button in button_bg.xml:

  <shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
    android:color="#500347" />

<corners
    android:radius="10dip" />

<padding
    android:bottom="0dip"
    android:left="0dip"
    android:right="0dip"
    android:top="0dip" />

ripple_effet.xml:

    <ripple xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
  android:color="@android:color/holo_green_dark"
   tools:targetApi="lollipop">

    <item android:id="@android:id/mask">

<shape android:shape="rectangle">

    <solid android:color="@android:color/holo_green_dark" />

    <corners android:radius="10dip" />

</shape>

In <Button> tag
android:background="@drawable/button_bg"

With this method button just goes white when pressed returns to background color.

Please tell me how to do it.


问:
Google Form Script to Add Pre-Filled Text
I have a Form that my staff uses to send me data through out the day.

One of the sections is a " long answer text" box for any comments.

Usually there are no comments so it is left blank.

My question is -

is there a way to automatically pre fill text in a google form and how?

I have used the pre filled link but if the user decides to submit another form (which they always do), it will take them back to the original form link and not the pre fill link.

This data is sent to a spreadsheet with a custom dashboard with the most recent data.

If there is a blank in the comment column, it will grab the last non blank cell in the column section and give off the wrong comment for that data.

I havent found a way to fill all the blank cells with "no comment" in google sheets without filling all the cells that have not been used for google form submissions. Figured it might be easier to start with any script magic from google form instead of google sheets.

Thank you in advance

答:
A couple of ideas.

First, you wrote:

I have used the pre filled link but if the user decides to submit
  another form (which they always do), it will take them back to the
  original form link and not the pre fill link.

To deal with this, remove this option in the forms settings, within the presentation tab.  Then your users will only be able to use the pre-fill link you have provided them with.

Secondly to handle the situation where a user removes your prefilled text (or they find the form link that isn't prefilled and use that instead) you could write a script that gets triggered on a form submission to check this value and replace any blanks with "no comment".

The script should be attached to the spreadsheet that collects the form response.

Here is some rough code that might work for you...

```<code>function onFormSubmit_noComments(e) {
  var col = 5 //replace this with your column number for the comments field (1st column is 1)
  var row = e.range.getRow(); //The row in the spreadsheet that was just inserted
  var commentsCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(row, col);
  var answers = e.range.getValues();

  if (!answers[0][col - 1]) {//this will fire if the field was left blank
     commentsCell.setValue("No Comment");
  }
}
</code>```

Body:
A couple of ideas.

First, you wrote:

I have used the pre filled link but if the user decides to submit
  another form (which they always do), it will take them back to the
  original form link and not the pre fill link.

To deal with this, remove this option in the forms settings, within the presentation tab.  Then your users will only be able to use the pre-fill link you have provided them with.

Secondly to handle the situation where a user removes your prefilled text (or they find the form link that isn't prefilled and use that instead) you could write a script that gets triggered on a form submission to check this value and replace any blanks with "no comment".

The script should be attached to the spreadsheet that collects the form response.

Here is some rough code that might work for you...

function onFormSubmit_noComments(e) {
  var col = 5 //replace this with your column number for the comments field (1st column is 1)
  var row = e.range.getRow(); //The row in the spreadsheet that was just inserted
  var commentsCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(row, col);
  var answers = e.range.getValues();

  if (!answers[0][col - 1]) {//this will fire if the field was left blank
     commentsCell.setValue("No Comment");
  }
}


答:
This code works as expected. Here is a minimal example of working code (same as yours, only jQuery is included)</p>

```<code><html>
<head>
  <script
      src="https://code.jquery.com/jquery-3.2.1.js"
      integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
      crossorigin="anonymous"></script>
</head>
<body>
<input name="DeviceIP" class="k-input k-textbox" type="text" data-bind="value:DeviceIP">
</body>
</html>
<script>
  $('input[name="DeviceIP"]').click(function() {
    alert("test")
  });
</script>
</code>```

Title: click event on a input text box does not work

Body:
This code works as expected. Here is a minimal example of working code (same as yours, only jQuery is included)

<html>
<head>
  <script
      src="https://code.jquery.com/jquery-3.2.1.js"
      integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
      crossorigin="anonymous"></script>
</head>
<body>
<input name="DeviceIP" class="k-input k-textbox" type="text" data-bind="value:DeviceIP">
</body>
</html>
<script>
  $('input[name="DeviceIP"]').click(function() {
    alert("test")
  });
</script>


问:
CSS trouble to place buttom border under logos top right of the page
I'm trying to put a border under my  logos at the top of the page right.

Before I'm adding position:absolute; to the div, my 2 logos are placed where I want them to be under the contact me top right. But the border on the left side of the page, when I put position:absolute; it moves but the logos jump down the page.

css #para {
  margin-right: 1.66%;
  float: right;
  font-family: indie flower;
  position: absolute;
  top: 0px;
  right: 0px;
}

.fb {
  width: 27px;
  float: right;
  right: 5px;
  position: absolute;
  margin-top: 3px;
  top: 35px;
}

#in {
  margin-top: 4px;
  width: 25px;
  float: right;
  position: absolute;
  right: 40px;
  top: 35px;
}

div {
  border-bottom: 1.5px solid red;
  width: 60px;
  right: 5px;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="para">Contact me </p>
<div>
  <img class="fb" width="10" src="https://cdn3.iconfinder.com/data/icons/picons-social/57/46-facebook-512.png">
  <img id="in" width="25" src="https://image.flaticon.com/icons/png/512/69/69366.png">
</div></code>```

答:
From the snippet you have posted, it looks like it may be because you are positioning the icons absolute while not moving the container (which has the border).

I would recommend the below. I have removed the absolute positioning from the icons, along with the floats, and instead have positioned the icon container.

css #para {
  margin-right: 1.66%;
  float: right;
  font-family: indie flower;
  position: absolute;
  top: 0px;
  right: 0px;
}

.fb {
  width: 27px;
  margin-top: 3px;
}

#in {
  margin-top: 4px;
  width: 25px;
}

.icon-container {
  border-bottom: 1.5px solid red;
  width: 60px;
  right: 5px;
  top: 0px;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="para">Contact me </p>
<div class="icon-container">
  <img class="fb" width="10" src="https://cdn3.iconfinder.com/data/icons/picons-social/57/46-facebook-512.png">
  <img id="in" width="25" src="https://image.flaticon.com/icons/png/512/69/69366.png">
</div></code>```

Body:
I'm trying to put a border under my  logos at the top of the page right.

Before I'm adding position:absolute; to the div, my 2 logos are placed where I want them to be under the contact me top right. But the border on the left side of the page, when I put position:absolute; it moves but the logos jump down the page.

css #para {
  margin-right: 1.66%;
  float: right;
  font-family: indie flower;
  position: absolute;
  top: 0px;
  right: 0px;
}

.fb {
  width: 27px;
  float: right;
  right: 5px;
  position: absolute;
  margin-top: 3px;
  top: 35px;
}

#in {
  margin-top: 4px;
  width: 25px;
  float: right;
  position: absolute;
  right: 40px;
  top: 35px;
}

div {
  border-bottom: 1.5px solid red;
  width: 60px;
  right: 5px;
  position: absolute;
}

Contact me

Body:
From the snippet you have posted, it looks like it may be because you are positioning the icons absolute while not moving the container (which has the border).

I would recommend the below. I have removed the absolute positioning from the icons, along with the floats, and instead have positioned the icon container.

css #para {
  margin-right: 1.66%;
  float: right;
  font-family: indie flower;
  position: absolute;
  top: 0px;
  right: 0px;
}

.fb {
  width: 27px;
  margin-top: 3px;
}

#in {
  margin-top: 4px;
  width: 25px;
}

.icon-container {
  border-bottom: 1.5px solid red;
  width: 60px;
  right: 5px;
  top: 0px;
  position: absolute;
}

<p id="para">Contact me </p>
<div class="icon-container">
  <img class="fb" width="10" src="https://cdn3.iconfinder.com/data/icons/picons-social/57/46-facebook-512.png">
  <img id="in" width="25" src="https://image.flaticon.com/icons/png/512/69/69366.png">
</div>


问:
Combine values in one array by condition in php
I have an arrays like this
array

```<code>$array1 = array('key1'=>5,'key2'=>1,'key3'=>1);
</code>```

output expected

```<code> $array1 = array('key1'=>5);
</code>```

another exambles
array

```<code>$array2 = array('key1'=>1,'key2'=>1,'key3'=>1);
</code>```

output expected

```<code>$array2 = array('key1'=>1);
</code>```

another example array

```<code>$array3 = array('key1'=>1,'key2'=>1,'key3'=>2,'key4'=>1);
</code>```

output expected

```<code>$array3 = array('key3'=>2);
</code>```

my condition is
 if the values in the array are 1, any one of the key value is the result for that array
if the value of the array are 1 except one key value, result is that particular key value

Is this possible?

答:
if you are specific to only 1 duplicate value try below logic or
if you are looking max value and key as mentioned @Phylogenesis use this logic</p>

```<code>$array1 = array('key1'=>5,'key2'=>1,'key3'=>1);
$array2 = array('key1'=>1,'key2'=>1,'key3'=>1);
$array3 = array('key1'=>1,'key2'=>1,'key3'=>2,'key4'=>1);

$array1 = filterArray($array1);
$array2 = filterArray($array2);
$array3 = filterArray($array3);

print_r($array1);
print_r($array2);
print_r($array3);

function filterArray($array)
{
    $newArray = [];
    if (in_array(1, array_values($array))) {

        foreach ($array as $key => $val) {
            if ($val != 1) {
                $newArray[$key] = $val;
                break;
            }

        }
        if (empty($newArray)) {
            $newArray['key1'] = 1;
        }
    }

    return $newArray;
}
</code>```

Body:
I have an arrays like this
array

$array1 = array('key1'=>5,'key2'=>1,'key3'=>1);

output expected

 $array1 = array('key1'=>5);

another exambles
array

$array2 = array('key1'=>1,'key2'=>1,'key3'=>1);

output expected

$array2 = array('key1'=>1);

another example array

$array3 = array('key1'=>1,'key2'=>1,'key3'=>2,'key4'=>1);

output expected

$array3 = array('key3'=>2);

my condition is
 if the values in the array are 1, any one of the key value is the result for that array
if the value of the array are 1 except one key value, result is that particular key value

Is this possible?

Body:
if you are specific to only 1 duplicate value try below logic or
if you are looking max value and key as mentioned @Phylogenesis use this logic

$array1 = array('key1'=>5,'key2'=>1,'key3'=>1);
$array2 = array('key1'=>1,'key2'=>1,'key3'=>1);
$array3 = array('key1'=>1,'key2'=>1,'key3'=>2,'key4'=>1);

$array1 = filterArray($array1);
$array2 = filterArray($array2);
$array3 = filterArray($array3);

print_r($array1);
print_r($array2);
print_r($array3);

function filterArray($array)
{
    $newArray = [];
    if (in_array(1, array_values($array))) {

        foreach ($array as $key => $val) {
            if ($val != 1) {
                $newArray[$key] = $val;
                break;
            }

        }
        if (empty($newArray)) {
            $newArray['key1'] = 1;
        }
    }

    return $newArray;
}


问:
Issue with Jenkins and Git submodules
I am trying to get Jenkins working on a Windows PC and have found a weird issue with submodules.

I have a git repo with three submodules. After a while it seems I got Git itself working on Jenkins so a normal clone works. However the clone does not clone the submodules inside the main repo, so I checked the box to recursively update submodules.

However, when I run my job:

```<code>Started by user <User>
Building in workspace X:\Jenkins\<JobName>
- C:/Program Files/Git/bin/git.exe rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
- C:/Program Files/Git/bin/git.exe config remote.origin.url ssh://git@<server>/<repo>.git # timeout=10
Fetching upstream changes from  ssh://git@<server>/<repo>.git
- C:/Program Files/Git/bin/git.exe --version # timeout=10
using GIT_SSH to set credentials
- C:/Program Files/Git/bin/git.exe fetch --tags --progress  ssh://git@<server>/<repo>.git +refs/heads/*:refs/remotes/origin/*
- C:/Program Files/Git/bin/git.exe rev-parse "refs/remotes/origin/master^{commit}" # timeout=10
- C:/Program Files/Git/bin/git.exe rev-parse "refs/remotes/origin/origin/master^{commit}" # timeout=10
Checking out Revision b13204ee1c6717a82d1c7a17922f2a477efd119d (refs/remotes/origin/master)
Commit message: "testinggg.."
- C:/Program Files/Git/bin/git.exe config core.sparsecheckout # timeout=10
- C:/Program Files/Git/bin/git.exe checkout -f b13204ee1c6717a82d1c7a17922f2a477efd119d
- C:/Program Files/Git/bin/git.exe rev-list b13204ee1c6717a82d1c7a17922f2a477efd119d # timeout=10
- C:/Program Files/Git/bin/git.exe remote # timeout=10
- C:/Program Files/Git/bin/git.exe submodule init # timeout=10
- C:/Program Files/Git/bin/git.exe submodule sync # timeout=10
- C:/Program Files/Git/bin/git.exe config --get remote.origin.url # timeout=10
- C:/Program Files/Git/bin/git.exe submodule init # timeout=10
- C:/Program Files/Git/bin/git.exe config -f .gitmodules --get-regexp ^submodule\.(.*)\.url # timeout=10
- C:/Program Files/Git/bin/git.exe config --get submodule.top.url # timeout=10
- C:/Program Files/Git/bin/git.exe remote # timeout=10
- C:/Program Files/Git/bin/git.exe config --get remote.origin.url # timeout=10
- C:/Program Files/Git/bin/git.exe config -f .gitmodules --get submodule.top.path # timeout=10
using GIT_SSH to set credentials
- C:/Program Files/Git/bin/git.exe submodule update --init --recursive top
FATAL: Command "C:/Program Files/Git/bin/git.exe submodule update --init --recursive top" returned status code 1:
stdout:
stderr: fatal: Needed a single revision
Unable to find current revision in submodule path 'top'

hudson.plugins.git.GitException: Command "C:/Program Files/Git/bin/git.exe submodule update --init --recursive top" returned status code 1:
stdout:
stderr: fatal: Needed a single revision
Unable to find current revision in submodule path 'top'

    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1903)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1622)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:71)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$7.execute(CliGitAPIImpl.java:1076)
    at hudson.plugins.git.extensions.impl.SubmoduleOption.onCheckoutCompleted(SubmoduleOption.java:102)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1182)
    at hudson.scm.SCM.checkout(SCM.java:495)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1276)
    at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:560)
    at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:485)
    at hudson.model.Run.execute(Run.java:1735)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:405)
Finished: FAILURE
</code>```

What does Git mean when it says:

Needed a single revision Unable to find current revision in submodule path 'top'

I have looked around and found nothing :(

I have replicated this sequence of command on a normal shell and no error appeared.

Any help will be appreciated. Thanks!

答: To anybody getting similar issues, check the box for Jenkins to wipe out the local workspace and force repository clone once. That worked for me ;)</p>

Title: Issue with Jenkins and Git submodules

Body:
I am trying to get Jenkins working on a Windows PC and have found a weird issue with submodules.

I have a git repo with three submodules. After a while it seems I got Git itself working on Jenkins so a normal clone works. However the clone does not clone the submodules inside the main repo, so I checked the box to recursively update submodules.

However, when I run my job:

Started by user <User>
Building in workspace X:\Jenkins\<JobName>
- C:/Program Files/Git/bin/git.exe rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
- C:/Program Files/Git/bin/git.exe config remote.origin.url ssh://git@<server>/<repo>.git # timeout=10
Fetching upstream changes from  ssh://git@<server>/<repo>.git
- C:/Program Files/Git/bin/git.exe --version # timeout=10
using GIT_SSH to set credentials
- C:/Program Files/Git/bin/git.exe fetch --tags --progress  ssh://git@<server>/<repo>.git +refs/heads/*:refs/remotes/origin/*
- C:/Program Files/Git/bin/git.exe rev-parse "refs/remotes/origin/master^{commit}" # timeout=10
- C:/Program Files/Git/bin/git.exe rev-parse "refs/remotes/origin/origin/master^{commit}" # timeout=10
Checking out Revision b13204ee1c6717a82d1c7a17922f2a477efd119d (refs/remotes/origin/master)
Commit message: "testinggg.."
- C:/Program Files/Git/bin/git.exe config core.sparsecheckout # timeout=10
- C:/Program Files/Git/bin/git.exe checkout -f b13204ee1c6717a82d1c7a17922f2a477efd119d
- C:/Program Files/Git/bin/git.exe rev-list b13204ee1c6717a82d1c7a17922f2a477efd119d # timeout=10
- C:/Program Files/Git/bin/git.exe remote # timeout=10
- C:/Program Files/Git/bin/git.exe submodule init # timeout=10
- C:/Program Files/Git/bin/git.exe submodule sync # timeout=10
- C:/Program Files/Git/bin/git.exe config --get remote.origin.url # timeout=10
- C:/Program Files/Git/bin/git.exe submodule init # timeout=10
- C:/Program Files/Git/bin/git.exe config -f .gitmodules --get-regexp ^submodule\.(.*)\.url # timeout=10
- C:/Program Files/Git/bin/git.exe config --get submodule.top.url # timeout=10
- C:/Program Files/Git/bin/git.exe remote # timeout=10
- C:/Program Files/Git/bin/git.exe config --get remote.origin.url # timeout=10
- C:/Program Files/Git/bin/git.exe config -f .gitmodules --get submodule.top.path # timeout=10
using GIT_SSH to set credentials
- C:/Program Files/Git/bin/git.exe submodule update --init --recursive top
FATAL: Command "C:/Program Files/Git/bin/git.exe submodule update --init --recursive top" returned status code 1:
stdout:
stderr: fatal: Needed a single revision
Unable to find current revision in submodule path 'top'

hudson.plugins.git.GitException: Command "C:/Program Files/Git/bin/git.exe submodule update --init --recursive top" returned status code 1:
stdout:
stderr: fatal: Needed a single revision
Unable to find current revision in submodule path 'top'

    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1903)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:1622)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$300(CliGitAPIImpl.java:71)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$7.execute(CliGitAPIImpl.java:1076)
    at hudson.plugins.git.extensions.impl.SubmoduleOption.onCheckoutCompleted(SubmoduleOption.java:102)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1182)
    at hudson.scm.SCM.checkout(SCM.java:495)
    at hudson.model.AbstractProject.checkout(AbstractProject.java:1276)
    at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:560)
    at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:485)
    at hudson.model.Run.execute(Run.java:1735)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:405)
Finished: FAILURE

What does Git mean when it says:

Needed a single revision Unable to find current revision in submodule path 'top'

I have looked around and found nothing :(

I have replicated this sequence of command on a normal shell and no error appeared.

Any help will be appreciated. Thanks!


问:
Can't Fix ASP.NET MVC Validation
I've been trying to fix the validation on my form for a while now, but can't get it to work properly. The validation works fine, unless I enter a valid email address. If I do, then it just skips all other validation for some reason.

Also, would appreciate advice about if I'm doing it right with the split of everything in the controller. Should there be 2 actions (1 for GET to just load the empty form and 1 for POST when the user submits it)? Am I doing something wrong there?

EDIT: Correction: If I enter a valid email address, the form submits fine and ignores the other validation. If I don't have a valid email address, the validation checks everything.

Here's my model class:

```<code>public class User
{
    public int ID { get; set; }

    [DisplayName("Name")]
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [DisplayName("Email")]
    [DataType(DataType.EmailAddress)]
    [Required(ErrorMessage = "Email is required")]
    [RegularExpression(
        @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
            @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
        ErrorMessage = "Invalid email")]
    public string Email { get; set; }

    [DisplayName("Password")]
    [DataType(DataType.Password)]
    [Required(ErrorMessage = "Password required")]
    [MinLength(6, ErrorMessage = "Min 6 characters")]
    public string Password { get; set; }
}
</code>```

Here is my controller:

```<code>    public ActionResult Register()
    {
        ViewBag.LoggedIn = false;

        return View();
    }

    [HttpPost]
    public ActionResult Register(User user)
    {
        ViewBag.LoggedIn = false;

        user.Password = PasswordHash.CreateHash(user.Password);

        using (var context = new FoundationContext())
        {
            // if user exists
            if (context.Users.FirstOrDefault(n => n.Email == user.Email) != null) return Login(true);

            context.Users.Add(user);
            context.SaveChanges();
        }

        return View("~/Views/Home.Index.cshtml");
    }
</code>```

And here is my form:

```<code>    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-10 text-center">
                    <input type="submit" value="Register" class="btn btn-primary" />
                </div>
            </div>
        </div>
    }
</code>```

And of course bottom of the body includes:

```<code>@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</code>```

答:
Use  Modelstate.IsValid. It tells you if any model errors have been added to ModelState.

```<code>public ActionResult Register(User user)
{
    if (!ModelState.IsValid)
    {
       return View();
    }

    //your code
}
</code>```

Title: Can't Fix ASP.NET MVC Validation

Body:
I've been trying to fix the validation on my form for a while now, but can't get it to work properly. The validation works fine, unless I enter a valid email address. If I do, then it just skips all other validation for some reason.

Also, would appreciate advice about if I'm doing it right with the split of everything in the controller. Should there be 2 actions (1 for GET to just load the empty form and 1 for POST when the user submits it)? Am I doing something wrong there?

EDIT: Correction: If I enter a valid email address, the form submits fine and ignores the other validation. If I don't have a valid email address, the validation checks everything.

Here's my model class:

public class User
{
    public int ID { get; set; }

    [DisplayName("Name")]
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [DisplayName("Email")]
    [DataType(DataType.EmailAddress)]
    [Required(ErrorMessage = "Email is required")]
    [RegularExpression(
        @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
            @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
        ErrorMessage = "Invalid email")]
    public string Email { get; set; }

    [DisplayName("Password")]
    [DataType(DataType.Password)]
    [Required(ErrorMessage = "Password required")]
    [MinLength(6, ErrorMessage = "Min 6 characters")]
    public string Password { get; set; }
}

Here is my controller:

    public ActionResult Register()
    {
        ViewBag.LoggedIn = false;

        return View();
    }

    [HttpPost]
    public ActionResult Register(User user)
    {
        ViewBag.LoggedIn = false;

        user.Password = PasswordHash.CreateHash(user.Password);

        using (var context = new FoundationContext())
        {
            // if user exists
            if (context.Users.FirstOrDefault(n => n.Email == user.Email) != null) return Login(true);

            context.Users.Add(user);
            context.SaveChanges();
        }

        return View("~/Views/Home.Index.cshtml");
    }

And here is my form:

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })

                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

                    <input type="submit" value="Register" class="btn btn-primary" />

    }

And of course bottom of the body includes:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)

Body:
Use  Modelstate.IsValid. It tells you if any model errors have been added to ModelState.

public ActionResult Register(User user)
{
    if (!ModelState.IsValid)
    {
       return View();
    }

    //your code
}


问:
Setting xticklabels, x axis formatting in matplotlib
I would like to format my x axis with the legend values at the mid point of each bar whilst retaining the gender group identification. I'd like lower the gender groups to sit below the other xticklabels for clarity.

To this point, I've added xticks but actually labeling them correctly and neatly is proving trickier.

```<code>from itertools import chain, cycle
import logging
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
matplotlib.style.use("ggplot")

m = {"Males" :  {"Yes": 2, "No": 8}}
w = {"Females": {"Yes": 3, "No": 7}}
data = {**m, **w}
df = DataFrame(data)
# relative freq table
df_ft = (df / df.sum() * 100).T

ax = plt.subplot(111)
df_ft.plot(ax=ax, kind="bar", ylim=(0, 90),
           title="Would you prefer to work at home? (10 males, 10 females)",
           rot=0)
plt.ylabel("Relative Frequency (%)")

midp = 0.125  # standard bar width/2
t_l = ax.get_xticks().tolist()
ticks = list(chain.from_iterable((t - midp, t + midp) for t in t_l))
ax.set_xticks(t_l + ticks)

plt.show()
</code>```

答:
Altair would do a great job here.

```<code>from altair import *
from pandas import DataFrame

df = DataFrame({'Males': {'Yes': 2, 'No': 8}, 'Females': {'Yes': 3, 'No': 7}})
df = df.stack().reset_index()
df.columns=['response','gender','count']
</code>```

Vis #1

```<code>Chart(df).mark_bar().encode(x='gender',y='count',color='response').configure_cell(width=200, height=200)
</code>```

Vis 2

```<code>Chart(df).mark_bar().encode(x=X('response', axis=False),
                            y=Y('count', axis=Axis(grid=False)),
                            color='response',
                            column=Column('gender', axis=Axis(axisWidth=1.0, offset=-8.0, orient='bottom'),scale=Scale(padding=30.0))).configure_cell(width=200, height=200).configure_facet_cell(strokeWidth=0)
</code>```

Body:
I would like to format my x axis with the legend values at the mid point of each bar whilst retaining the gender group identification. I'd like lower the gender groups to sit below the other xticklabels for clarity.

To this point, I've added xticks but actually labeling them correctly and neatly is proving trickier.

from itertools import chain, cycle
import logging
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
matplotlib.style.use("ggplot")

m = {"Males" :  {"Yes": 2, "No": 8}}
w = {"Females": {"Yes": 3, "No": 7}}
data = {**m, **w}
df = DataFrame(data)
# relative freq table
df_ft = (df / df.sum() * 100).T

ax = plt.subplot(111)
df_ft.plot(ax=ax, kind="bar", ylim=(0, 90),
           title="Would you prefer to work at home? (10 males, 10 females)",
           rot=0)
plt.ylabel("Relative Frequency (%)")

midp = 0.125  # standard bar width/2
t_l = ax.get_xticks().tolist()
ticks = list(chain.from_iterable((t - midp, t + midp) for t in t_l))
ax.set_xticks(t_l + ticks)

plt.show()

Body:
Altair would do a great job here.

from altair import *
from pandas import DataFrame

df = DataFrame({'Males': {'Yes': 2, 'No': 8}, 'Females': {'Yes': 3, 'No': 7}})
df = df.stack().reset_index()
df.columns=['response','gender','count']

Vis #1

Chart(df).mark_bar().encode(x='gender',y='count',color='response').configure_cell(width=200, height=200)

Vis 2

Chart(df).mark_bar().encode(x=X('response', axis=False),
                            y=Y('count', axis=Axis(grid=False)),
                            color='response',
                            column=Column('gender', axis=Axis(axisWidth=1.0, offset=-8.0, orient='bottom'),scale=Scale(padding=30.0))).configure_cell(width=200, height=200).configure_facet_cell(strokeWidth=0)


问:
can't start SAP application server
I can't find any information that is relevant to my specific situation. Around a month ago I had created my own application server which has become my local development machine. The tutorial I followed was available here: https://blogs.sap.com/2016/11/03/sap-nw-as-abap-7.50-sp2-developer-edition-to-download-consise-installation-guide/

This has been working fine until this morning. Last night I shut SAP system down using stopsap and shutdown the VM via shutdown -h 0. When I used startsap this morning it hung infinitely when trying to start the database.

```<code>linux-nsts:npladm 92> startsap
Checking syb Database
Database is not avaliable via R3Trans
------------------------------------------
starting database NPL ...
Log file: /sybase/NPL/startdb.log
</code>```

Checking that log file I find the following messages:

```<code>------------------------------ Thu Jul 6 09:35:22 CEST 2017
/usr/sap/NPL/SYS/exe/run/startdb was killed or interrupted. Terminating.
</code>```

In the trace file in the home directory

```<code>Running /usr/sap/SYS/exe/run/startdb
DB startup failed
</code>```

I can't find any other articles that are relevant to my situation. My host file is perfectly fine and the IP can be pinged. I only have one linux user, npladm for starting SAP. The only other command I could find was R3trans but I'm not sure if this would be the right program in this instance.

```<code>linux-nsts:npladm 7> R3trans -d
This is R3trans version 6.25 (release 745 - 30.10.15 - 12:47:42 ).
unicode enabled version
2EETW169 no connect possible: "DBMS - SYBASE --- "
R3trans finished (0012)
</code>```

As for the operating system itself I'm not aware to any changes I could have made that could have caused this. The only command I run on the server is startsap and stopsap.

I'm out of ideas where to look, can anybody offer advice?

EDIT: The license for SYBASE expired and it needed to be updated in my case. There is a link in the tutorial explaining how to switch it and where to download a new one.

答:
I stumbled upon by accident the folder /sybase and found a number of log files in there. My server isn't starting because my database no longer has a license. It expired today, actually.

https://mdocs.sap.com/mcm/public/v1/open?shr=dRhHsVYVLc5c1UDveogwtXBdL9m82JccRlvvBXO6K5Q

```<code>00:0000:00000:00000:2017/07/06 10:08:09.37 kernel  SySAM: Using licenses from: /sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_DE.lic:/sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_TestDrive.lic:/sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_XE.lic
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: Failed to obtain license(s) for ASE_CORE feature from license file(s) or server(s).
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: Licenses exist for ASE, but a license containing the configured (PE=EE;LT=AC) attributes could not be obtained. Verify that ASE is configured to use the correct type of license, and either reconfigure; or generate and deploy the desired license from the Sybase Product Download Center.
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: Feature has expired.
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: License feature name:  ASE_CORE
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: Expire date:   30-jun-2017
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: License search path:   /sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_DE.lic:/sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_TestDrive.lic:/sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_XE.lic:
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: FlexNet Licensing error:-10,32
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: For further information, refer to the Sybase Software Asset Management website at http://www.sybase.com/sysam
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  There is no valid license for ASE server product. Installation date is not found or installation grace period has expired. Server will not boot.
</code>```

ContentLicense: CC BY-SA 4.0

Title: can't start SAP application server

Body:
I can't find any information that is relevant to my specific situation. Around a month ago I had created my own application server which has become my local development machine. The tutorial I followed was available here: https://blogs.sap.com/2016/11/03/sap-nw-as-abap-7.50-sp2-developer-edition-to-download-consise-installation-guide/

This has been working fine until this morning. Last night I shut SAP system down using stopsap and shutdown the VM via shutdown -h 0. When I used startsap this morning it hung infinitely when trying to start the database.

linux-nsts:npladm 92> startsap
Checking syb Database
Database is not avaliable via R3Trans
------------------------------------------
starting database NPL ...
Log file: /sybase/NPL/startdb.log

Checking that log file I find the following messages:

------------------------------ Thu Jul 6 09:35:22 CEST 2017
/usr/sap/NPL/SYS/exe/run/startdb was killed or interrupted. Terminating.

In the trace file in the home directory

Running /usr/sap/SYS/exe/run/startdb
DB startup failed

I can't find any other articles that are relevant to my situation. My host file is perfectly fine and the IP can be pinged. I only have one linux user, npladm for starting SAP. The only other command I could find was R3trans but I'm not sure if this would be the right program in this instance.

linux-nsts:npladm 7> R3trans -d
This is R3trans version 6.25 (release 745 - 30.10.15 - 12:47:42 ).
unicode enabled version
2EETW169 no connect possible: "DBMS - SYBASE --- "
R3trans finished (0012)

As for the operating system itself I'm not aware to any changes I could have made that could have caused this. The only command I run on the server is startsap and stopsap.

I'm out of ideas where to look, can anybody offer advice?

EDIT: The license for SYBASE expired and it needed to be updated in my case. There is a link in the tutorial explaining how to switch it and where to download a new one.

Body:
I stumbled upon by accident the folder /sybase and found a number of log files in there. My server isn't starting because my database no longer has a license. It expired today, actually.

https://mdocs.sap.com/mcm/public/v1/open?shr=dRhHsVYVLc5c1UDveogwtXBdL9m82JccRlvvBXO6K5Q

00:0000:00000:00000:2017/07/06 10:08:09.37 kernel  SySAM: Using licenses from: /sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_DE.lic:/sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_TestDrive.lic:/sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_XE.lic
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: Failed to obtain license(s) for ASE_CORE feature from license file(s) or server(s).
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: Licenses exist for ASE, but a license containing the configured (PE=EE;LT=AC) attributes could not be obtained. Verify that ASE is configured to use the correct type of license, and either reconfigure; or generate and deploy the desired license from the Sybase Product Download Center.
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: Feature has expired.
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: License feature name:  ASE_CORE
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: Expire date:   30-jun-2017
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: License search path:   /sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_DE.lic:/sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_TestDrive.lic:/sybase/NPL/SYSAM-2_0/licenses/SYBASE_ASE_XE.lic:
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: FlexNet Licensing error:-10,32
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  SySAM: For further information, refer to the Sybase Software Asset Management website at http://www.sybase.com/sysam
00:0000:00000:00000:2017/07/06 10:08:09.42 kernel  There is no valid license for ASE server product. Installation date is not found or installation grace period has expired. Server will not boot.