问:
strange message from gradle (AndroidStudio).
From one second to the other I got the following error with Gradle in AndroidStudio and I have no clue what to do with it.

Error when trying to start my app:

```<code>Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_map_testApkCopy'.
   > Could not find com.android.support:appcompat-v7:27.0.1.
     Required by:
         project :app
         project :app > com.android.support:design:25.0.0
   > Could not find com.android.support:support-v4:27.0.1.
     Required by:
         project :app > com.android.support:design:25.0.0
         project :app > com.android.support:design:25.0.0 > com.android.support:transition:25.0.0
   > Could not find com.android.support:support-annotations:27.0.1.
     Required by:
         project :app > com.android.support:design:25.0.0 > com.android.support:recyclerview-v7:25.0.0
         project :app > com.android.support:design:25.0.0 > com.android.support:recyclerview-v7:25.0.0 > com.android.support:support-compat:25.0.0
   > Could not find com.android.support:support-annotations:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
   > Could not find com.android.support:support-core-utils:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
   > Could not find com.android.support:appcompat-v7:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:cardview-v7:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:customtabs:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:support-v4:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
</code>```

build.gradle : (Mobile: app) (Did not changed since month. Compared with repo and no change)

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

android {
    signingConfigs {
        sapps {
            keyAlias 'keyalias'
            keyPassword 'xxxxxx'
            storeFile file('C:/eclipse/keystore/mykeystore')
            storePassword 'xxxxxx'
        }
    }
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "appid"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 179
        versionName "2.54"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        resValue "string", "appID", "wgd"
        manifestPlaceholders = [iconpath: "@drawable/icon", versionCode:"161", versionName:"2.37"]

    }
    buildTypes {
        demo {
            buildConfigField "String", "appID", "\"WGD\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            resValue "string", "app_name", "Chronica"
            manifestPlaceholders = [iconpath: "@drawable/icon", facebookid:"@string/facebook_app_id_demo"]
            applicationIdSuffix '.chronicbrowser'
        }
        demo_test {
            buildConfigField "String", "appID", "\"WGD_TEST\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            debuggable true

            resValue "string", "app_name", "Chronica Test"
            manifestPlaceholders = [iconpath: "@drawable/icon", facebookid:"@string/facebook_app_id_demo"]
            applicationIdSuffix '.chronicbrowser_wgd_test'
        }
        timeline {

            buildConfigField "String", "appID", "\"WG\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            resValue "string", "app_name", "WorldHistory"
            applicationIdSuffix '.chronicbrowser_wg_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_timeline", facebookid:"@string/facebook_app_id_timeline"]
        }
        timeline_test {
            buildConfigField "String", "appID", "\"WG_TEST\""
            minifyEnabled false
            debuggable true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Test"
            applicationIdSuffix '.chronicbrowser_wg_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_timeline_test", facebookid:"@string/facebook_app_id_timeline"]
            signingConfig signingConfigs.sapps
        }
        map {
            buildConfigField "String", "appID", "\"WG_MAPS\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Atlas"
            applicationIdSuffix '.chronicbrowser_maps_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_maps", facebookid:"@string/facebook_app_id_maps"]
            signingConfig signingConfigs.sapps
        }
        map_test {
            buildConfigField "String", "appID", "\"WG_MAPS_TEST\""
            //resValue "string", "RES_appID", "wgd"
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Atlas Test"
            applicationIdSuffix '.chronicbrowser_maps_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_maps_test", facebookid:"@string/facebook_app_id_maps"]
            signingConfig signingConfigs.sapps

        }
        worldwarII {
            buildConfigField "String", "appID", "\"WW2\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldWar II"
            applicationIdSuffix '.chronicbrowser_ww2_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_ww2", facebookid:"@string/facebook_app_id_ww2"]
            signingConfig signingConfigs.sapps

        }
        worldwarII_test {
            buildConfigField "String", "appID", "\"WW2_TEST\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldWar II Test"
            applicationIdSuffix '.chronicbrowser_ww2_en_test'
            manifestPlaceholders = [iconpath: "@drawable/icon_ww2", facebookid:"@string/facebook_app_id_ww2"]
            signingConfig signingConfigs.sapps
        }
    }
    compileOptions.encoding = 'ISO-8859-1'
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    testCompile 'junit:junit:4.12'
    compile files('libs/lvl.jar')
    compile files('libs/google-play-services.jar')
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile files('libs/GoogleConversionTrackingSdk-2.2.4.jar')
}

repositories {
    mavenCentral()
}
</code>```

Can someone help me ?

答:
The most recent versions of the Android libraries are available from Google's Maven repository.

To include Google's Maven repository:

in your top-level build.gradle file:

```<code>allprojects {
    repositories {
        google()

        // If you're using a version of Gradle lower than 4.1, you must instead use:
        // maven {
        //     url 'https://maven.google.com'
        // }
        // An alternative URL is 'https://dl.google.com/dl/android/maven2/'
    }
}
</code>```

Details:
https://developer.android.com/studio/build/dependencies.html#google-maven

Body:
From one second to the other I got the following error with Gradle in AndroidStudio and I have no clue what to do with it.

Error when trying to start my app:

Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_map_testApkCopy'.
   > Could not find com.android.support:appcompat-v7:27.0.1.
     Required by:
         project :app
         project :app > com.android.support:design:25.0.0
   > Could not find com.android.support:support-v4:27.0.1.
     Required by:
         project :app > com.android.support:design:25.0.0
         project :app > com.android.support:design:25.0.0 > com.android.support:transition:25.0.0
   > Could not find com.android.support:support-annotations:27.0.1.
     Required by:
         project :app > com.android.support:design:25.0.0 > com.android.support:recyclerview-v7:25.0.0
         project :app > com.android.support:design:25.0.0 > com.android.support:recyclerview-v7:25.0.0 > com.android.support:support-compat:25.0.0
   > Could not find com.android.support:support-annotations:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
   > Could not find com.android.support:support-core-utils:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-core:4.29.0
   > Could not find com.android.support:appcompat-v7:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:cardview-v7:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:customtabs:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0
   > Could not find com.android.support:support-v4:27.0.1.
     Required by:
         project :app > com.facebook.android:facebook-android-sdk:4.29.0 > com.facebook.android:facebook-common:4.29.0

build.gradle : (Mobile: app) (Did not changed since month. Compared with repo and no change)

apply plugin: 'com.android.application'

android {
    signingConfigs {
        sapps {
            keyAlias 'keyalias'
            keyPassword 'xxxxxx'
            storeFile file('C:/eclipse/keystore/mykeystore')
            storePassword 'xxxxxx'
        }
    }
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "appid"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 179
        versionName "2.54"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        resValue "string", "appID", "wgd"
        manifestPlaceholders = [iconpath: "@drawable/icon", versionCode:"161", versionName:"2.37"]

    }
    buildTypes {
        demo {
            buildConfigField "String", "appID", "\"WGD\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            resValue "string", "app_name", "Chronica"
            manifestPlaceholders = [iconpath: "@drawable/icon", facebookid:"@string/facebook_app_id_demo"]
            applicationIdSuffix '.chronicbrowser'
        }
        demo_test {
            buildConfigField "String", "appID", "\"WGD_TEST\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            debuggable true

            resValue "string", "app_name", "Chronica Test"
            manifestPlaceholders = [iconpath: "@drawable/icon", facebookid:"@string/facebook_app_id_demo"]
            applicationIdSuffix '.chronicbrowser_wgd_test'
        }
        timeline {

            buildConfigField "String", "appID", "\"WG\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.sapps
            resValue "string", "app_name", "WorldHistory"
            applicationIdSuffix '.chronicbrowser_wg_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_timeline", facebookid:"@string/facebook_app_id_timeline"]
        }
        timeline_test {
            buildConfigField "String", "appID", "\"WG_TEST\""
            minifyEnabled false
            debuggable true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Test"
            applicationIdSuffix '.chronicbrowser_wg_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_timeline_test", facebookid:"@string/facebook_app_id_timeline"]
            signingConfig signingConfigs.sapps
        }
        map {
            buildConfigField "String", "appID", "\"WG_MAPS\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Atlas"
            applicationIdSuffix '.chronicbrowser_maps_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_maps", facebookid:"@string/facebook_app_id_maps"]
            signingConfig signingConfigs.sapps
        }
        map_test {
            buildConfigField "String", "appID", "\"WG_MAPS_TEST\""
            //resValue "string", "RES_appID", "wgd"
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldHistory Atlas Test"
            applicationIdSuffix '.chronicbrowser_maps_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_maps_test", facebookid:"@string/facebook_app_id_maps"]
            signingConfig signingConfigs.sapps

        }
        worldwarII {
            buildConfigField "String", "appID", "\"WW2\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldWar II"
            applicationIdSuffix '.chronicbrowser_ww2_en'
            manifestPlaceholders = [iconpath: "@drawable/icon_ww2", facebookid:"@string/facebook_app_id_ww2"]
            signingConfig signingConfigs.sapps

        }
        worldwarII_test {
            buildConfigField "String", "appID", "\"WW2_TEST\""
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            resValue "string", "app_name", "WorldWar II Test"
            applicationIdSuffix '.chronicbrowser_ww2_en_test'
            manifestPlaceholders = [iconpath: "@drawable/icon_ww2", facebookid:"@string/facebook_app_id_ww2"]
            signingConfig signingConfigs.sapps
        }
    }
    compileOptions.encoding = 'ISO-8859-1'
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:design:25.0.0'
    testCompile 'junit:junit:4.12'
    compile files('libs/lvl.jar')
    compile files('libs/google-play-services.jar')
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile files('libs/GoogleConversionTrackingSdk-2.2.4.jar')
}

repositories {
    mavenCentral()
}

Can someone help me ?

Body:
The most recent versions of the Android libraries are available from Google's Maven repository.

To include Google's Maven repository:

in your top-level build.gradle file:

allprojects {
    repositories {
        google()

        // If you're using a version of Gradle lower than 4.1, you must instead use:
        // maven {
        //     url 'https://maven.google.com'
        // }
        // An alternative URL is 'https://dl.google.com/dl/android/maven2/'
    }
}

Details:
https://developer.android.com/studio/build/dependencies.html#google-maven


来源: stackexchange

问:
How to avoid external call in JUnit Groovy
Finally I am able to get Groovy class in my Java file and able to perform JUnit on my groovy classes. Now my problem is I want to test my method which triggers RPC calls.but I want to avoid that call in unit test. How should I do that? Below is my sample code for logout how I am proceeding</p>

```<code>@Test
public void logoutTest() {
    GroovyObject loginOject =new Login();
    GroovyObject logoutObject =new Logout();
    XMLRPCServerProxy serverProxy = (XMLRPCServerProxy) loginOject.invokeMethod(
        "getServerProxy",
        "https://urlproxy"
    );
    String sessionId = (String) loginOject.invokeMethod(
        "getSession",
        new Object[]{"username","password",serverProxy}
    );
    logoutObject.invokeMethod("logout",new Object[]{sessionId,serverProxy});
}
</code>```

答:
I'd recommend using Spock for unit-testing Groovy (and Java) code. Latest when it comes to mocking, no Java tool / framework I know is capable of properly mocking Groovy stuff as the language is simply too dynamic to be handled by tools written to hook into Java code.

Spock is written in Groovy and with Groovy in mind when it comes to mocking and stubbing. Spock might look a bit alien if you first look at it, but if you get used to the syntax it is quite amazing what you can do and how easy you can write tests with variying input data and so on.

Spock also is based on JUnit, so every tool that is able to execute and evaluate JUnit tests is also able to cope with Spock tests.

ContentLicense: CC BY-SA 3.0

Body:
Finally I am able to get Groovy class in my Java file and able to perform JUnit on my groovy classes. Now my problem is I want to test my method which triggers RPC calls.but I want to avoid that call in unit test. How should I do that? Below is my sample code for logout how I am proceeding

@Test
public void logoutTest() {
    GroovyObject loginOject =new Login();
    GroovyObject logoutObject =new Logout();
    XMLRPCServerProxy serverProxy = (XMLRPCServerProxy) loginOject.invokeMethod(
        "getServerProxy",
        "https://urlproxy"
    );
    String sessionId = (String) loginOject.invokeMethod(
        "getSession",
        new Object[]{"username","password",serverProxy}
    );
    logoutObject.invokeMethod("logout",new Object[]{sessionId,serverProxy});
}


问:
How ItemRenderer is different from ItemEditor in Flex 4?
I know this type of questions already asked by many person but that post didn't give me more information to understand regarding the actually difference between ItemRenderer and ItenEditor in Flex Framework.

As I know ItemRenderer is used for displaying visual elements mostly and ItemEditor is used for editing purpose mainly.

So I have tried following Example to find the difference among that:

For ItemRenderer I used following codes:

```<code><mx:DataGrid dataProvider="{initDG}">
    <mx:columns>
        <mx:DataGridColumn headerText="Artist" dataField="Artist"/>
        <mx:DataGridColumn headerText="Album" dataField="Album"/>
        <mx:DataGridColumn headerText="Price" dataField="Price">
            <mx:itemRenderer>
                <fx:Component>
                    <mx:TextInput restrict="0-9" maxChars="10" />
                </fx:Component>
            </mx:itemRenderer>
        </mx:DataGridColumn>
        <mx:DataGridColumn headerText="Cover" dataField="Cover"/>
    </mx:columns>
</mx:DataGrid>
</code>```

And I got the result as follows:

Where Price field is showing as editable.

And again I tried the same code with ItemEditor as follows:

```<code><mx:DataGrid dataProvider="{initDG}">
    <mx:columns>
        <mx:DataGridColumn headerText="Artist" dataField="Artist"/>
        <mx:DataGridColumn headerText="Album" dataField="Album"/>
        <mx:DataGridColumn headerText="Price" dataField="Price">
            <mx:itemEditor>
                <fx:Component>
                    <mx:TextInput restrict="0-9" maxChars="10" />
                </fx:Component>
            </mx:itemEditor>
        </mx:DataGridColumn>
        <mx:DataGridColumn headerText="Cover" dataField="Cover"/>
    </mx:columns>
</mx:DataGrid>
</code>```

And I got the result as follows:

But here Price field is non editable .

So As I am new to these controls I am getting confused why it is happening. After using ItemEditor as why that field is non editable.

If anybody have knowledge what is the reason behind that please help me to understand more details regarding these two controls.

答:
Difference between ItemRenderer and ItemEditor:

When you use ItemRenderer you change the aspect of your component. In your case if you have a datagrid column, and apply and itemRenderer with an image you have in your column an image showed.

If you use ItemEditor you act on the aspect of your component when you try to change that column. If you put an ItemEditor on your column as TextInput when you click on your column will show a text input.

Flex has an automatic manage of ItemRenderer and ItemEditor, by default you have renderer is editor so when you want to implement on ly the ItemRenderer the same aspect you can use for edit your column.

If you want to take separate these features you can put rendererIsEditor = false but you must implement two functionalities.

I hope my explanation is clear. Tell me if you have other doubts

Body:
I know this type of questions already asked by many person but that post didn't give me more information to understand regarding the actually difference between ItemRenderer and ItenEditor in Flex Framework.

As I know ItemRenderer is used for displaying visual elements mostly and ItemEditor is used for editing purpose mainly.

So I have tried following Example to find the difference among that:

For ItemRenderer I used following codes:

<mx:DataGrid dataProvider="{initDG}">
    <mx:columns>
        <mx:DataGridColumn headerText="Artist" dataField="Artist"/>
        <mx:DataGridColumn headerText="Album" dataField="Album"/>
        <mx:DataGridColumn headerText="Price" dataField="Price">
            <mx:itemRenderer>
                <fx:Component>
                    <mx:TextInput restrict="0-9" maxChars="10" />
                </fx:Component>
            </mx:itemRenderer>
        </mx:DataGridColumn>
        <mx:DataGridColumn headerText="Cover" dataField="Cover"/>
    </mx:columns>
</mx:DataGrid>

And I got the result as follows:

Where Price field is showing as editable.

And again I tried the same code with ItemEditor as follows:

<mx:DataGrid dataProvider="{initDG}">
    <mx:columns>
        <mx:DataGridColumn headerText="Artist" dataField="Artist"/>
        <mx:DataGridColumn headerText="Album" dataField="Album"/>
        <mx:DataGridColumn headerText="Price" dataField="Price">
            <mx:itemEditor>
                <fx:Component>
                    <mx:TextInput restrict="0-9" maxChars="10" />
                </fx:Component>
            </mx:itemEditor>
        </mx:DataGridColumn>
        <mx:DataGridColumn headerText="Cover" dataField="Cover"/>
    </mx:columns>
</mx:DataGrid>

And I got the result as follows:

But here Price field is non editable .

So As I am new to these controls I am getting confused why it is happening. After using ItemEditor as why that field is non editable.

If anybody have knowledge what is the reason behind that please help me to understand more details regarding these two controls.


问:
Reference type of JVM
In some Java literature, The statement

The reference type of the Java virtual
  machine is cleverly named
  reference

is widely popular. However, authors tend not to explain more why such statement is valid. Another thing that would make me understand this more is

What does the reference type of the JVM means ? Does the JVM represent itself in the heap ?

Would appreciate a lot an explanation on this statement.

Thank you,

Ashmawy

答:
This becomes clearer when the whole paragraph is taken into context:

The reference type of the Java virtual machine is cleverly named reference. Values of type reference come in three flavors: the class type, the interface type, and the array type. All three types have values that are references to dynamically created objects. The class type's values are references to class instances. The array type's values are references to arrays, which are full-fledged objects in the Java virtual machine. The interface type's values are references to class instances that implement an interface. One other reference value is the null value, which indicates the reference variable doesn't refer to any object.

(Taken from http://javadeveloper-jayaprakash-m.blogspot.com/)

I would assume from this that the "cleverly named" bit is referring to the fact that the references come in three different types and the JVM can distinguish between each one.

ContentLicense: CC BY-SA 2.5

Title: Reference type of JVM


问:
Vim: how to dynamically create regex pattern
I would like to concatenate a variable into a regex pattern. For example, considering this pattern for syntax that matches lines from 1 to 3.

syn match Title /\%>0l\%<4l.*/

I would like to be able to dynamically set the second integer in the pattern (the '4' in the above example to whatever the value of b:title_until is). I have tried with string concatenation but it does not work. The intention should be clear in the example below:

```<code>let b:title_until = 10

if exists("b:title_until")
  syn match Title "/\%>0l\%<" + b:title_until + "l.*/"
end
----------------------------------------------------------------------
> (NFA) Unknown operator '\%
> Invalid character after \%
> Invalid argument: Title "/\%>0l\%<" + b:title_until + "l.*/"
</code>```

答:
General theory

Vimscript is evaluated exactly like the Ex commands typed in the : command-line. There were no variables in ex, so there's no way to specify them. When typing a command interactively, you'd probably use <C-R>= to insert variable contents:

```<code>:sleep <C-R>=timetowait<CR>m<CR>
</code>```

... but in a script, :execute must be used. All the literal parts of the Ex command must be quoted (single or double quotes), and then concatenated with the variables:

```<code>execute 'sleep' timetowait . 'm'
</code>```

Your problem

For a syntax script, you'd use execute. Additionally, please note that string concatenation in Vim is done with ., not with +. (Also note that I use single quotes to avoid escaping of the backslashes.)

```<code>execute 'syn match Title /\%>0l\%<' . b:title_until . 'l.*/'
</code>```

Alternatively, you can use printf(); this is less cluttered when there are multiple variables. However, here you need to consider that % must be doubled:

```<code>execute printf('syn match Title /\%%>0l\%%<%sl.*/', b:title_until)
</code>```

Final tips

The \%>0l is superfluous and can be omitted, as it will always match: there are no negative lines.

Body:
I would like to concatenate a variable into a regex pattern. For example, considering this pattern for syntax that matches lines from 1 to 3.

syn match Title /\%>0l\%<4l.*/

I would like to be able to dynamically set the second integer in the pattern (the '4' in the above example to whatever the value of b:title_until is). I have tried with string concatenation but it does not work. The intention should be clear in the example below:

let b:title_until = 10

if exists("b:title_until")
  syn match Title "/\%>0l\%<" + b:title_until + "l.*/"
end
----------------------------------------------------------------------
> (NFA) Unknown operator '\%
> Invalid character after \%
> Invalid argument: Title "/\%>0l\%<" + b:title_until + "l.*/"

Body:
General theory

Vimscript is evaluated exactly like the Ex commands typed in the : command-line. There were no variables in ex, so there's no way to specify them. When typing a command interactively, you'd probably use <C-R>= to insert variable contents:

:sleep <C-R>=timetowait<CR>m<CR>

... but in a script, :execute must be used. All the literal parts of the Ex command must be quoted (single or double quotes), and then concatenated with the variables:

execute 'sleep' timetowait . 'm'

Your problem

For a syntax script, you'd use execute. Additionally, please note that string concatenation in Vim is done with ., not with +. (Also note that I use single quotes to avoid escaping of the backslashes.)

execute 'syn match Title /\%>0l\%<' . b:title_until . 'l.*/'

Alternatively, you can use printf(); this is less cluttered when there are multiple variables. However, here you need to consider that % must be doubled:

execute printf('syn match Title /\%%>0l\%%<%sl.*/', b:title_until)

Final tips

The \%>0l is superfluous and can be omitted, as it will always match: there are no negative lines.


问:
Safe use of HttpURLConnection
When using HttpURLConnection does the InputStream need to be closed if we do not 'get' and use it?

i.e. is this safe?

```<code>HttpURLConnection conn = (HttpURLConnection) uri.getURI().toURL().openConnection();
conn.connect();
// check for content type I don't care about
if (conn.getContentType.equals("image/gif") return;
// get stream and read from it
InputStream is = conn.getInputStream();
try {
    // read from is
} finally {
    is.close();
}
</code>```

Secondly, is it safe to close an InputStream before all of it's content has been fully read?

Is there a risk of leaving the underlying socket in ESTABLISHED or even CLOSE_WAIT state?

答:
is it safe to close an InputStream
  before all of it's content has been
  read

You need to read all of the data in the input stream before you close it so that the underlying TCP connection gets cached. I have read that it should not be required in latest Java, but it was always mandated to read the whole response for connection re-use.

Check this post: keep-alive in java6

Title: Safe use of HttpURLConnection

Body:
When using HttpURLConnection does the InputStream need to be closed if we do not 'get' and use it?

i.e. is this safe?

HttpURLConnection conn = (HttpURLConnection) uri.getURI().toURL().openConnection();
conn.connect();
// check for content type I don't care about
if (conn.getContentType.equals("image/gif") return;
// get stream and read from it
InputStream is = conn.getInputStream();
try {
    // read from is
} finally {
    is.close();
}

Secondly, is it safe to close an InputStream before all of it's content has been fully read?

Is there a risk of leaving the underlying socket in ESTABLISHED or even CLOSE_WAIT state?


问:
How to find partitions of a list in Scheme
Say there is any given list in Scheme.  This list is ‘(2 3 4)

I want to find all possible partitions of this list.  This means a partition  where a list is separated into two subsets such that every element of the list must be in one or the other subsets but not both, and no element can be left out of a split.

So, given the list ‘(2 3 4), I want to find all such possible partitions.  These partitions would be the following: {2, 3} and {4}, {2, 4} and {3}, and the final possible partition being {3, 4} and {2}.

I want to be able to recursively find all partitions given a list in Scheme, but I have no ideas on how to do so. Code or psuedocode will help me if anyone can provide it for me!
 I do believe I will have to use lambda for my recursive function.

答:
I discuss several different types of partitions at my blog, though not this specific one. As an example, consider that an integer partition  is the set of all sets of positive integers that sum to the given integer. For instance, the partitions of 4 is the set of sets ((1 1 1 1) (1 1 2) (1 3) (2 2) (4)).

The process is building the partitions is recursive. There is a single partition of 0, the empty set (). There is a single partition of 1, the set (1). There are two partitions of 2, the sets (1 1) and (2). There are three partitions of 3, the sets (1 1 1), (1 2) and (3). There are five partitions of 4, the sets (1 1 1 1), (1 1 2), (1 3), (2 2), and (4). There are seven partitions of 5, the sets (1 1 1 1 1), (1 1 1 2), (1 2 2), (1 1 3), (1 4), (2 3) and (5). And so on. In each case, the next-larger set of partitions is determined by adding each integer x less than or equal to the desired integer n to all the sets formed by the partition of n − x, eliminating any duplicates. Here's how I implement that:

```<code>Petite Chez Scheme Version 8.4
Copyright (c) 1985-2011 Cadence Research Systems

> (define (set-cons x xs)
    (if (member x xs) xs
      (cons x xs)))
> (define (parts n)
    (if (zero? n) (list (list))
      (let x-loop ((x 1) (xs (list)))
        (if (= x n) (cons (list n) xs)
          (let y-loop ((yss (parts (- n x))) (xs xs))
            (if (null? yss) (x-loop (+ x 1) xs)
              (y-loop (cdr yss)
                      (set-cons (sort < (cons x (car yss)))
                                xs))))))))
> (parts 6)
((6) (3 3) (2 2 2) (2 4) (1 1 4) (1 1 2 2) (1 1 1 1 2)
     (1 1 1 1 1 1) (1 1 1 3) (1 2 3) (1 5))
</code>```

I'm not going to solve your homework for you, but your solution will be similar to the one given above. You need to state your algorithm in recursive fashion, then write code to implement that algorithm. Your recursion is going to be something like this: For each item in the set, add the item to each partition of the remaining items of the set, eliminating duplicates.

That will get you started. If you have specific questions, come back here for additional help.

EDIT: Here is my solution. I'll let you figure out how it works.

```<code>(define range (case-lambda ; start, start+step, ..., start+step<stop
  ((stop) (range 0 stop (if (negative? stop) -1 1)))
  ((start stop) (range start stop (if (< start stop) 1 -1)))
  ((start stop step) (let ((le? (if (negative? step) >= <=)))
    (let loop ((x start) (xs (list)))
      (if (le? stop x) (reverse xs) (loop (+ x step) (cons x xs))))))
  (else (error 'range "unrecognized arguments"))))

(define (sum xs) (apply + xs)) ; sum of elements of xs

(define digits (case-lambda ; list of base-b digits of n
  ((n) (digits n 10))
  ((n b) (do ((n n (quotient n b))
              (ds (list) (cons (modulo n b) ds)))
             ((zero? n) ds)))))

(define (part k xs) ; k'th lexicographical left-partition of xs
  (let loop ((ds (reverse (digits k 2))) (xs xs) (ys (list)))
    (if (null? ds) (reverse ys)
      (if (zero? (car ds))
          (loop (cdr ds) (cdr xs) ys)
          (loop (cdr ds) (cdr xs) (cons (car xs) ys))))))

(define (max-lcm xs) ; max lcm of part-sums of 2-partitions of xs
  (let ((len (length xs)) (tot (sum xs)))
    (apply max (map (lambda (s) (lcm s (- tot s)))
                    (map sum (map (lambda (k) (part k xs))
                                  (range (expt 2 (- len 1)))))))))

(display (max-lcm '(2 3 4))) (newline) ; 20
(display (max-lcm '(2 3 4 6))) (newline) ; 56
</code>```

Body:
I discuss several different types of partitions at my blog, though not this specific one. As an example, consider that an integer partition  is the set of all sets of positive integers that sum to the given integer. For instance, the partitions of 4 is the set of sets ((1 1 1 1) (1 1 2) (1 3) (2 2) (4)).

The process is building the partitions is recursive. There is a single partition of 0, the empty set (). There is a single partition of 1, the set (1). There are two partitions of 2, the sets (1 1) and (2). There are three partitions of 3, the sets (1 1 1), (1 2) and (3). There are five partitions of 4, the sets (1 1 1 1), (1 1 2), (1 3), (2 2), and (4). There are seven partitions of 5, the sets (1 1 1 1 1), (1 1 1 2), (1 2 2), (1 1 3), (1 4), (2 3) and (5). And so on. In each case, the next-larger set of partitions is determined by adding each integer x less than or equal to the desired integer n to all the sets formed by the partition of n − x, eliminating any duplicates. Here's how I implement that:

Petite Chez Scheme Version 8.4
Copyright (c) 1985-2011 Cadence Research Systems

> (define (set-cons x xs)
    (if (member x xs) xs
      (cons x xs)))
> (define (parts n)
    (if (zero? n) (list (list))
      (let x-loop ((x 1) (xs (list)))
        (if (= x n) (cons (list n) xs)
          (let y-loop ((yss (parts (- n x))) (xs xs))
            (if (null? yss) (x-loop (+ x 1) xs)
              (y-loop (cdr yss)
                      (set-cons (sort < (cons x (car yss)))
                                xs))))))))
> (parts 6)
((6) (3 3) (2 2 2) (2 4) (1 1 4) (1 1 2 2) (1 1 1 1 2)
     (1 1 1 1 1 1) (1 1 1 3) (1 2 3) (1 5))

I'm not going to solve your homework for you, but your solution will be similar to the one given above. You need to state your algorithm in recursive fashion, then write code to implement that algorithm. Your recursion is going to be something like this: For each item in the set, add the item to each partition of the remaining items of the set, eliminating duplicates.

That will get you started. If you have specific questions, come back here for additional help.

EDIT: Here is my solution. I'll let you figure out how it works.

(define range (case-lambda ; start, start+step, ..., start+step<stop
  ((stop) (range 0 stop (if (negative? stop) -1 1)))
  ((start stop) (range start stop (if (< start stop) 1 -1)))
  ((start stop step) (let ((le? (if (negative? step) >= <=)))
    (let loop ((x start) (xs (list)))
      (if (le? stop x) (reverse xs) (loop (+ x step) (cons x xs))))))
  (else (error 'range "unrecognized arguments"))))

(define (sum xs) (apply + xs)) ; sum of elements of xs

(define digits (case-lambda ; list of base-b digits of n
  ((n) (digits n 10))
  ((n b) (do ((n n (quotient n b))
              (ds (list) (cons (modulo n b) ds)))
             ((zero? n) ds)))))

(define (part k xs) ; k'th lexicographical left-partition of xs
  (let loop ((ds (reverse (digits k 2))) (xs xs) (ys (list)))
    (if (null? ds) (reverse ys)
      (if (zero? (car ds))
          (loop (cdr ds) (cdr xs) ys)
          (loop (cdr ds) (cdr xs) (cons (car xs) ys))))))

(define (max-lcm xs) ; max lcm of part-sums of 2-partitions of xs
  (let ((len (length xs)) (tot (sum xs)))
    (apply max (map (lambda (s) (lcm s (- tot s)))
                    (map sum (map (lambda (k) (part k xs))
                                  (range (expt 2 (- len 1)))))))))

(display (max-lcm '(2 3 4))) (newline) ; 20
(display (max-lcm '(2 3 4 6))) (newline) ; 56


问:
Detect permission of media library ios
In my app, I want to detect that if user give the permission to his media library or not. User may denied media library permission when system popup ask or later from setting. Is there any way to detect the status of media library permission?

Here is my code that access list of songs.

```<code>MPMediaQuery *everything = [MPMediaQuery songsQuery];
NSArray *songArray = [everything items];
</code>```

Please see below screenshot where user can change Media Library permissions.

答:
Swift 4 access check. The simple solution is as follows, and you can alter to include the other alternatives however in my case it was all access or nothing.

```<code>private func checkPermissionForMusic() -> Bool {
    switch MPMediaLibrary.authorizationStatus() {
    case .authorized:
        return true
    default:
        return false
    }
}
</code>```

Caution about using the above solutions - they do perform as a block statement and do not return a value (return true or return "authorised") on the same thread; the result is handled on a background thread. If you decide to use the suggestions above, use a handler (call another function) to handle the result you're expecting. This solution on the other hand tells you immediately if you have access or not. No waiting required.

More info is available in the Apple Docs

Title: Detect permission of media library ios

Body:
In my app, I want to detect that if user give the permission to his media library or not. User may denied media library permission when system popup ask or later from setting. Is there any way to detect the status of media library permission?

Here is my code that access list of songs.

MPMediaQuery *everything = [MPMediaQuery songsQuery];
NSArray *songArray = [everything items];

Please see below screenshot where user can change Media Library permissions.

Body:
Swift 4 access check. The simple solution is as follows, and you can alter to include the other alternatives however in my case it was all access or nothing.

private func checkPermissionForMusic() -> Bool {
    switch MPMediaLibrary.authorizationStatus() {
    case .authorized:
        return true
    default:
        return false
    }
}

Caution about using the above solutions - they do perform as a block statement and do not return a value (return true or return "authorised") on the same thread; the result is handled on a background thread. If you decide to use the suggestions above, use a handler (call another function) to handle the result you're expecting. This solution on the other hand tells you immediately if you have access or not. No waiting required.

More info is available in the Apple Docs


问:
Eclipse Keyboard Shortcut To List All Classes in Project
Eclipse has this awesome thing called a Quick Outline CTRL+O. I want something similar but with classes, as I am entering a new project with tons of classes and no clue which source file they come from.

Example: Press CTRL+Shift+O and all classes are listed, you start typing it modifies the list, you press enter, it opens that source file.

Does this functionality exist in Eclipse? I looked through the Keys menu, couldn't find anything, probably not using the right name for it.

答: Use Ctrl + Shift + H keys to search for classes.


问:
Regex OR pipe not working as expected
I'm attempting to match multiple regular expressions in a single regular expression.

Given two extremely complex regular expressions, how could I keep them separate, yet put them into a single expression which matches both. I thought that was the use of the regex OR pipe, but it seems to not be working as I expected.

As a basic example, I'm working with the following regular expression:

```<code>(?:\s*(\w+)\s*:)|(?:\:\s*(\w+)\s*\,)
</code>```

Testing with the following string:

```<code>{key: value, name: "John", age: 17}
</code>```

And expecting it to capture in the two (\w+) capture groups:

key, value, name and age

But it is only capturing key, name and age without the value.

I can confirm the 2nd part of my expression (after the OR pipe) does indeed match the value when the first part of the expression is omitted (before the OR pipe).

Can someone please explain and provide a solution as to why it is not matching both key and value and only matching key.

答:
Seems that you are capturing : in both groups so the | can't match both

This should work

```<code>(?:\s*(\w+)\s*:)|(?:\s*(\w+)\s*\,)
</code>```

Regex101 live example

Title: Regex OR pipe not working as expected

Body:
I'm attempting to match multiple regular expressions in a single regular expression.

Given two extremely complex regular expressions, how could I keep them separate, yet put them into a single expression which matches both. I thought that was the use of the regex OR pipe, but it seems to not be working as I expected.

As a basic example, I'm working with the following regular expression:

(?:\s*(\w+)\s*:)|(?:\:\s*(\w+)\s*\,)

Testing with the following string:

{key: value, name: "John", age: 17}

And expecting it to capture in the two (\w+) capture groups:

key, value, name and age

But it is only capturing key, name and age without the value.

I can confirm the 2nd part of my expression (after the OR pipe) does indeed match the value when the first part of the expression is omitted (before the OR pipe).

Can someone please explain and provide a solution as to why it is not matching both key and value and only matching key.

Body:
Seems that you are capturing : in both groups so the | can't match both

This should work

(?:\s*(\w+)\s*:)|(?:\s*(\w+)\s*\,)

Regex101 live example

ContentLicense: CC BY-SA 4.0


问:
Visual FOXPRO9 onfocus commandbutton
I have problem with command buttons in visual foxpro, the problem is when I point my focus with keyboard on button it gets some borders, similar to orders you get on windows icons.

How can I turn off those borders, I tried all options but cant figure it out. I'll post pictures with my code and how it looks like.

This is how it looks like

and this is the code.

答:
I Solved this kind of problem by creating a new object with two shape(one for main, other for shadow), one label and one commandbutton(for keypress event).
You can download the class from
https://1drv.ms/f/s!AnBsIoWEbiBXi3OPpfzPENcC3fOf</p>

Title: Visual FOXPRO9 onfocus commandbutton


问:
sql server : create indexes on foreign keys where necessary
I have lots of tables with foreign keys and some have an index while others have not.
All foreign keys are named FK_<name of the foreign key> with indexes named IX_<name of the foreign key>.

Are there some good practices, given the column cardinality of the foreign key, to create (or not) indexes ?
Could this be scripted as T-SQL commands ?

答:
Great work everyone, very helpful.

Adding an enhancement that includes the table schema.  You can also exclude FK names if you prefer (I tend not to add indexes on small tables)

```<code>SELECT
    *
FROM
(
    SELECT TOP 99 PERCENT
            f.name AS ForeignKeyName

        , s.name
                + '.'
                + OBJECT_NAME(f.parent_object_id)
                + '.'
                + COL_NAME(fc.parent_object_id, fc.parent_column_id)
            ParentTable

        , referencedSchema.name
                + '.'
                + OBJECT_NAME (f.referenced_object_id)
                + '.'
                + COL_NAME(fc.referenced_object_id, fc.referenced_column_id)
            ReferencedTable

        , 'CREATE INDEX [IX_' + f.name + ']'
                + ' ON '
                    + '[' + referencedSchema.name + ']'
                    + '.'
                    + '[' + OBJECT_NAME(f.parent_object_id) + ']'
                    + '('
                        + COL_NAME(fc.parent_object_id, fc.parent_column_id)
                    + ')'
            CreateIndexSql

    FROM
        sys.foreign_keys AS f
        INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
        inner join sys.schemas s on f.schema_id = s.schema_id

        inner join sys.tables referencedTable on f.referenced_object_id = referencedTable.object_id
        inner join sys.schemas referencedSchema on referencedTable.schema_id = referencedSchema.schema_id

    ORDER BY
        2, 3, 1
) a
where a.ParentTable not in (
    -- Add any exclusions here so you can forget about them
      ''
)
</code>```

Body:
Great work everyone, very helpful.

Adding an enhancement that includes the table schema.  You can also exclude FK names if you prefer (I tend not to add indexes on small tables)

SELECT
    *
FROM
(
    SELECT TOP 99 PERCENT
            f.name AS ForeignKeyName

        , s.name
                + '.'
                + OBJECT_NAME(f.parent_object_id)
                + '.'
                + COL_NAME(fc.parent_object_id, fc.parent_column_id)
            ParentTable

        , referencedSchema.name
                + '.'
                + OBJECT_NAME (f.referenced_object_id)
                + '.'
                + COL_NAME(fc.referenced_object_id, fc.referenced_column_id)
            ReferencedTable

        , 'CREATE INDEX [IX_' + f.name + ']'
                + ' ON '
                    + '[' + referencedSchema.name + ']'
                    + '.'
                    + '[' + OBJECT_NAME(f.parent_object_id) + ']'
                    + '('
                        + COL_NAME(fc.parent_object_id, fc.parent_column_id)
                    + ')'
            CreateIndexSql

    FROM
        sys.foreign_keys AS f
        INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
        inner join sys.schemas s on f.schema_id = s.schema_id

        inner join sys.tables referencedTable on f.referenced_object_id = referencedTable.object_id
        inner join sys.schemas referencedSchema on referencedTable.schema_id = referencedSchema.schema_id

    ORDER BY
        2, 3, 1
) a
where a.ParentTable not in (
    -- Add any exclusions here so you can forget about them
      ''
)


问:
Tensorflow splitting training data to batches
I have a dataset of images as a Numpy array. (Number of images, length, width, colour range) I would like to split it to batches and feed to tensorflow. What is the good way to do it?</p>

答:
There's a small error in  Thomas Pinetz answer and I can't make comments yet, so here's an extra answer.

int(len(array)/batch_size) will round the division down to the nearest integer, so the last batch wouldn't be processed. To round up the division you can use

```<code>ceil_int = -(-a//b)
</code>```

In addition you might end up with the last batch being very tiny compared to the rest. You can modify your batch size slightly to make this less likely to happen. The complete code is shown below:

```<code>def ceil(a,b):
    return -(-a//b)

n_samples = len(array)
better_batch_size = ceil(n_samples, ceil(n_samples, batch_size))

for i in range(ceil(n_samples, better_batch_size)):
    batch = array[i * better_batch_size: (i+1) * better_batch_size]
</code>```

Body:
There's a small error in  Thomas Pinetz answer and I can't make comments yet, so here's an extra answer.

int(len(array)/batch_size) will round the division down to the nearest integer, so the last batch wouldn't be processed. To round up the division you can use

ceil_int = -(-a//b)

In addition you might end up with the last batch being very tiny compared to the rest. You can modify your batch size slightly to make this less likely to happen. The complete code is shown below:

def ceil(a,b):
    return -(-a//b)

n_samples = len(array)
better_batch_size = ceil(n_samples, ceil(n_samples, batch_size))

for i in range(ceil(n_samples, better_batch_size)):
    batch = array[i * better_batch_size: (i+1) * better_batch_size]


问:
Trigger Specific Jenkins Job on Github Push to specific Directory
I have several Jenkins Job running which Deploy's code to application server. These jobs run automatically whenever there is Commit in Github repository configured through Jenkins Plugin in Github and webhook. Jenkins is running on a Windows system.

We have several applications in the repository, represented by a directory containing the code, each of these applications have a corresponding Jenkins Job which deploy's the code to server when the Job is run.
Since all the applications are in the same repository, so change in any one of the application creates a Push event and thus trigers all the Jobs.

Suppose there are three Applications App1, App2 and App3 and their corresponding Jobs are J1, J2, J3
and  there is a change in App1 and a commit is made in Github repository it causes all the Jobs J1,J2,J3 to trigger and Deploys App1, App2, App3 in server.

It causes unnecessary confusion since App2, App3 do not have any changes in repository but still gets deployed to server.
Is there any way that i can trigger specific Jenkins job build based on Directory level Changes/Commits in the Github repository. Can we use any git hooks somehow to achieve this?

答:
For that to happen, You can sparse checkout to a specific directory in the git so that every jenkins job will be mutual to each other.

jenkins job configure -> Source Code Management -> Git -> Additional Behaviours -> Add -> Sparse Checkout paths

This will simply sparse checkout to a sub directory and checks if there are any commits on that directory only. Hope this helps.


问:
Creating Trigger With pl/Python on Postgres
I am working with postgres-xl  9.5 , it is not supporting triggers. I am trying to write trigger function by using python it should replace

```<code>BEFORE INSERT ON tbl
FOR EACH ROW EXECUTE PROCEDURE fnx()
</code>```

Thanks

答: You cannot create a trigger in Postgres-XL, as the documentation says.</p>

Body:
I am working with postgres-xl  9.5 , it is not supporting triggers. I am trying to write trigger function by using python it should replace

BEFORE INSERT ON tbl
FOR EACH ROW EXECUTE PROCEDURE fnx()

Thanks


问:
Unclear relationship between pointer dereferencing and casting in a specific scenario
I have the following Cpp funtion:

```<code>u_long stringIpV4ToBinary(const char * ipv4)
{
    u_long * buff[1];
    int ret = InetPton(AF_INET, ipv4, &buff);
    if (ret == -1) return 1;
    if (ret == 0) return 1; // more handling needs to be added

// return ntohl(*buff[0]);           // crash, no warning
// return ntohl((*buff)[0]);         // same meaning above (??) crash, no warning
// return ntohl(**buff);             // crash, no warning
// return ntohl(*(buff[0]));         // crash, no warning
// return ntohl(*(u_long*)buff[0]);  // crash, no warning
// return ntohl((u_long)buff[0]);    // works, but produces warnings:: 'type cast': truncation from 'u_long *' to 'u_long'
// return ntohl(*(u_long*)&buff);    // works
// return ntohl(*(u_long*)&buff[0]); // works
// return ntohl(*(u_long*)buff[0]);  // crash, no warning
// return ntohl(*(u_long*)buff);     // works
}
</code>```

I have spent some time trying to extract the value of buff that I need to pass to ntohl() (so you can ignore the first couple of lines). I was playing around with *buff[0] *buff and others, w/o realizing that I need to cast the value of the first element of the array (&buff[0], buff or &buff).

Question: why do I need to cast the retrieved value to (u_long*) and then deference the pointer? Is it ambiguous or unclear to @ runtime that the value held in the buff[0] will be a of type u_long * ?  My expectation was that ntohl(**buff) - (buff is the array name, that decays into a pointer and since the array is of u_long pointers itself) double dereferencing should suffice.

答:
You have buff defined as an array (of size 1) of pointer to u_long.  So InetPton is storing the resulting IP address directly in this pointer variable.  You then get a crash because this IP address is interpreted as a memory address and dereferenced.

buff should be defined as a simple u_long, with it's address passed to InetPton:

```<code>u_long buff;
int ret = InetPton(AF_INET, ipv4, &buff);
</code>```

Then you can do this:

```<code>return ntohl(buff);
</code>```

Improving on this, the MSDN page says the following if the value of the first parameter is AF_INET:

```<code>INT WSAAPI InetPton(
  _In_  INT     Family,
  _In_  PCTSTR pszAddrString,
  _Out_ PVOID  pAddrBuf
);
</code>```

...

When this parameter is specified, the pszAddrString parameter must
  point to a text representation of an IPv4 address and the pAddrBuf
  parameter returns a pointer to an IN_ADDR structure that represents
  the IPv4 address.

So you should instead be passing in the address of an IN_ADDR for the third parameter:

```<code>IN_ADDR addr;
int ret = InetPton(AF_INET, ipv4, &addr);
...
return ntohl(addr.S_addr);
</code>```

EDIT:

Expanding on why the cast makes a difference, it turns out it doesn't.  What makes a difference is the level of indirection and how many times you dereference.

Body:
I have the following Cpp funtion:

u_long stringIpV4ToBinary(const char * ipv4)
{
    u_long * buff[1];
    int ret = InetPton(AF_INET, ipv4, &buff);
    if (ret == -1) return 1;
    if (ret == 0) return 1; // more handling needs to be added

// return ntohl(*buff[0]);           // crash, no warning
// return ntohl((*buff)[0]);         // same meaning above (??) crash, no warning
// return ntohl(**buff);             // crash, no warning
// return ntohl(*(buff[0]));         // crash, no warning
// return ntohl(*(u_long*)buff[0]);  // crash, no warning
// return ntohl((u_long)buff[0]);    // works, but produces warnings:: 'type cast': truncation from 'u_long *' to 'u_long'
// return ntohl(*(u_long*)&buff);    // works
// return ntohl(*(u_long*)&buff[0]); // works
// return ntohl(*(u_long*)buff[0]);  // crash, no warning
// return ntohl(*(u_long*)buff);     // works
}

I have spent some time trying to extract the value of buff that I need to pass to ntohl() (so you can ignore the first couple of lines). I was playing around with *buff[0] *buff and others, w/o realizing that I need to cast the value of the first element of the array (&buff[0], buff or &buff).

Question: why do I need to cast the retrieved value to (u_long*) and then deference the pointer? Is it ambiguous or unclear to @ runtime that the value held in the buff[0] will be a of type u_long * ?  My expectation was that ntohl(**buff) - (buff is the array name, that decays into a pointer and since the array is of u_long pointers itself) double dereferencing should suffice.

Body:
You have buff defined as an array (of size 1) of pointer to u_long.  So InetPton is storing the resulting IP address directly in this pointer variable.  You then get a crash because this IP address is interpreted as a memory address and dereferenced.

buff should be defined as a simple u_long, with it's address passed to InetPton:

u_long buff;
int ret = InetPton(AF_INET, ipv4, &buff);

Then you can do this:

return ntohl(buff);

Improving on this, the MSDN page says the following if the value of the first parameter is AF_INET:

INT WSAAPI InetPton(
  _In_  INT     Family,
  _In_  PCTSTR pszAddrString,
  _Out_ PVOID  pAddrBuf
);

...

When this parameter is specified, the pszAddrString parameter must
  point to a text representation of an IPv4 address and the pAddrBuf
  parameter returns a pointer to an IN_ADDR structure that represents
  the IPv4 address.

So you should instead be passing in the address of an IN_ADDR for the third parameter:

IN_ADDR addr;
int ret = InetPton(AF_INET, ipv4, &addr);
...
return ntohl(addr.S_addr);

EDIT:

Expanding on why the cast makes a difference, it turns out it doesn't.  What makes a difference is the level of indirection and how many times you dereference.


问:
Check for changes in the data of a form without using javascript
I currently have the below javascript to detect changes in my form.

```<code>form.addEventListener("input", function () {
        ChangesMade = true;
        console.log("Change");
    });
</code>```

I now need to include whether or not a change has been made in a call to the controller which means that the value can no long be stored in javascript as this is client side.

答:
Send the form data to the server

On the server side load current data from the DB

Compare and test for changes

Body:
I currently have the below javascript to detect changes in my form.

form.addEventListener("input", function () {
        ChangesMade = true;
        console.log("Change");
    });

I now need to include whether or not a change has been made in a call to the controller which means that the value can no long be stored in javascript as this is client side.


问:
Ruby equivalent operators at "OrElse" and "AndAlso" of Vb.net
There are operators in Ruby similar to "OrElse"and "AndAlso" in VB.NET?

For example in Ruby NoMethodError exception is raised when active_record is nil:

```<code>if active_record.nil? || active_record.errors.count == 0
     ...
end
</code>```

In VB.net i can do:

```<code> If active_record Is Nothing OrElse active_record.errors.count = 0
    ...
 End
</code>```

That does not generate an exception because it is only checked the first expression

答: In this case there will be no exception raised (because only the first term in || will be evaluated). However you might be interested in reading about Object#try from ActiveSupport, which can be helpful when dealing with objects that can be nil.</p>

Body:
There are operators in Ruby similar to "OrElse"and "AndAlso" in VB.NET?

For example in Ruby NoMethodError exception is raised when active_record is nil:

if active_record.nil? || active_record.errors.count == 0
     ...
end

In VB.net i can do:

 If active_record Is Nothing OrElse active_record.errors.count = 0
    ...
 End

That does not generate an exception because it is only checked the first expression


问:
Jenkins pipeline: read values from another jenkinsfile
I use a shared jenkins library and clone another git repo from there. That repo contains a jenkinsfile similar to the follwing:

```<code>#!/usr/bin/env groovy
@Library('mylib')
import jLib.*

someStage{
    myparam = someValue
}
</code>```

I want to read "someValue".
Currently I'm doing this with a regexp but this way I can only retrieve a String and not more complex values like a map.

In the documentation of Shared jenkins libs values are loaded from a jenkinsfile the following way:

```<code>def call(body) {
    // evaluate the body block, and collect configuration into the object
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config
    body()
}
</code>```

How can I extract values from the Jenkinsfile in the workspace in a similar manner? Where does the body come from?

Thank you for your time

答:
I found a solution.

```<code>Map configFromJenkinsfile(jenkinsfile){
    def jenkinsfileConfig = [:]
    def matches = jenkinsfile =~ /(?s)\{(.*?)\}/
    def exec = new GroovyShell(new Binding(jenkinsfileConfig)).evaluate(matches[0][1])
    return jenkinsfileConfig;
}
</code>```

I tested it with passing jenkinsFile as string (after using String projectJenkinsFile = readFile "Jenkinsfile")

I execute the part in the jenkinsfile with all the assignments (between '{' and '}') in a groovyshell with my map as binding. All assignments without type are caught in the binding and can be accessed.

Body:
I use a shared jenkins library and clone another git repo from there. That repo contains a jenkinsfile similar to the follwing:

#!/usr/bin/env groovy
@Library('mylib')
import jLib.*

someStage{
    myparam = someValue
}

I want to read "someValue".
Currently I'm doing this with a regexp but this way I can only retrieve a String and not more complex values like a map.

In the documentation of Shared jenkins libs values are loaded from a jenkinsfile the following way:

def call(body) {
    // evaluate the body block, and collect configuration into the object
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config
    body()
}

How can I extract values from the Jenkinsfile in the workspace in a similar manner? Where does the body come from?

Thank you for your time

Body:
I found a solution.

Map configFromJenkinsfile(jenkinsfile){
    def jenkinsfileConfig = [:]
    def matches = jenkinsfile =~ /(?s)\{(.*?)\}/
    def exec = new GroovyShell(new Binding(jenkinsfileConfig)).evaluate(matches[0][1])
    return jenkinsfileConfig;
}

I tested it with passing jenkinsFile as string (after using String projectJenkinsFile = readFile "Jenkinsfile")

I execute the part in the jenkinsfile with all the assignments (between '{' and '}') in a groovyshell with my map as binding. All assignments without type are caught in the binding and can be accessed.


问:
Ionic 3: deployment typescript error
I finished up the app I was working on and it works on ionic serve with no issues, however when compiling I was met with this, any help is much appreciated.

[15:40:08]  typescript error
            Type ResultPage in C:/Users/Omar/Desktop/InfoKing/src/pages/result/result.ts is part of the declarations of
            2 modules: AppModule in C:/Users/Omar/Desktop/InfoKing/src/app/app.module.ts and ResultPageModule in
            C:/Users/Omar/Desktop/InfoKing/src/pages/result/result.module.ts! Please consider moving ResultPage in
            C:/Users/Omar/Desktop/InfoKing/src/pages/result/result.ts to a higher module that imports AppModule in
            C:/Users/Omar/Desktop/InfoKing/src/app/app.module.ts and ResultPageModule in
            C:/Users/Omar/Desktop/InfoKing/src/pages/result/result.module.ts. You can also create a new NgModule that
            exports and includes ResultPage in C:/Users/Omar/Desktop/InfoKing/src/pages/result/result.ts then import
            that NgModule in AppModule in C:/Users/Omar/Desktop/InfoKing/src/app/app.module.ts and ResultPageModule in
            C:/Users/Omar/Desktop/InfoKing/src/pages/result/result.module.ts.

Error: The Angular AoT build failed. See the issues above
    at C:\Users\Omar\Desktop\InfoKing\node_modules\@ionic\app-scripts\dist\aot\aot-compiler.js:237:55
    at step (C:\Users\Omar\Desktop\InfoKing\node_modules\@ionic\app-scripts\dist\aot\aot-compiler.js:32:23)
    at Object.next (C:\Users\Omar\Desktop\InfoKing\node_modules\@ionic\app-scripts\dist\aot\aot-compiler.js:13:53)
    at fulfilled (C:\Users\Omar\Desktop\InfoKing\node_modules\@ionic\app-scripts\dist\aot\aot-compiler.js:4:58)
    at <anonymous>```

答:
Remove result.module.ts and remove @IonicPage from the result.ts file and run again
hope it works for you

Title: Ionic 3: deployment typescript error


问:
How to rotate file pdf and all image kinds
I have a html page that display PDF and all kinds image.
I'm looking for a way to rotate the file that i display with jQuery.

I tried:

add css class - not working.

Example of the code:

```<code>.rotate90 {
    webkit-transform: rotate(90deg);
    moz-transform: rotate(90deg);
    o-transform: rotate(90deg);
    ms-transform: rotate(90deg);
    transform: rotate(90deg); }

$("buttonId").click(function(){
    $( "objectPdfId" ).addClass( "rotate90" );
});
</code>```

I'm pretty sure it's not the right way

function in JavaScript - not working.

Code:

```<code>    var html = '<object id="objectPdfId" data="' + pathFile + '" type="application/pdf" on click="+rotateMe(this)+"'><embed id="embedPdfId" src="' + pathFile + '" type="application/pdf"></embed></object>';
    $("body").append($(html));

var rotate_factor = 0;

function rotateMe(e) {
    rotate_factor += 1;
    var rotate_angle = (180 * rotate_factor) % 360;
    $(e).rotate({angle:rotate_angle});
}
</code>```

Thanks,

Tal

答:
Why dont u just use PDF.js from Mozilla.
https://mozilla.github.io/pdf.js/

It can rotate the document and even save it like that, if thats what you want.

If you are dead set on your css solution, it should work with transform, so open your favorite browser debugger (F12 - Chrome and Firefox) and see if it is picking up your css document and the element rules.  Take it from there

Note: the last time I used pdf.js it supported image files like jpg and png too so no problem there

Body:
I have a html page that display PDF and all kinds image.
I'm looking for a way to rotate the file that i display with jQuery.

I tried:

add css class - not working.

Example of the code:

.rotate90 {
    webkit-transform: rotate(90deg);
    moz-transform: rotate(90deg);
    o-transform: rotate(90deg);
    ms-transform: rotate(90deg);
    transform: rotate(90deg); }

$("buttonId").click(function(){
    $( "objectPdfId" ).addClass( "rotate90" );
});

I'm pretty sure it's not the right way

function in JavaScript - not working.

Code:

    var html = '<object id="objectPdfId" data="' + pathFile + '" type="application/pdf" on click="+rotateMe(this)+"'><embed id="embedPdfId" src="' + pathFile + '" type="application/pdf"></embed></object>';
    $("body").append($(html));

var rotate_factor = 0;

function rotateMe(e) {
    rotate_factor += 1;
    var rotate_angle = (180 * rotate_factor) % 360;
    $(e).rotate({angle:rotate_angle});
}

Thanks,

Tal