问:
How to convert a `const char *` to simply `char *`?
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

```<code>size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);
</code>```

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

答:
Removing const can be done with const_cast, and is sometimes necessary for using legacy interfaces that were written in C and don't use const.  In such cases, you can do:

```<code>char* ptr = const_cast<char*> (str.c_str());
</code>```

However, from the cplusplus reference page on c_str():

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only granted to remain unchanged until the next call to a non-constant member function of the string object.

This means that it is your responsibility to ensure that ptr is not used to modify the string, and you must handle the lifetime of ptr appropriately.  I.e., you cannot continue to use ptr after str is out of scope, or after you call any non-const methods on str.  If you do that, you go into Undefined Behavior, and will likely crash.

If you are looking for a safe way to interact with a legacy interface that takes char*, you can make your own writable copy:

```<code>char* ptr = new char[ str.size() + 1 ];
strcpy(ptr, str.c_str());
ptr[str.size()] = '\0';
// ... use ptr as much as you want...
delete [] ptr;
</code>```

Body:
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter.

My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparently doesn't work with the function.

Next I put (char *)string.c_str() but this only causes an unhandled exception.

Finally I just tried char *test = string.c_str() but that's not compatible with const either.

What do I do to solve this?

K i just tried const_cast() and i still get an exception thrown and break....
I don't know why PDcurses only takes non-const char pointers.... =(

alright making a char* buffer didn't work when i used this code (time_s is the sting):

size_t length;
    char buffer[12];
    length=time_s.copy(buffer,5,0);
    buffer[length]='\0';
mvinstr(time_loc_y, time_loc_x, buffer);

i even put a stop before mvinstr() and checked the buffer's contents which was "00   /0"
EXACTLY WHAT I WANTED.

but i get an access violation point to "xutility"....

Body:
Removing const can be done with const_cast, and is sometimes necessary for using legacy interfaces that were written in C and don't use const.  In such cases, you can do:

char* ptr = const_cast<char*> (str.c_str());

However, from the cplusplus reference page on c_str():

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only granted to remain unchanged until the next call to a non-constant member function of the string object.

This means that it is your responsibility to ensure that ptr is not used to modify the string, and you must handle the lifetime of ptr appropriately.  I.e., you cannot continue to use ptr after str is out of scope, or after you call any non-const methods on str.  If you do that, you go into Undefined Behavior, and will likely crash.

If you are looking for a safe way to interact with a legacy interface that takes char*, you can make your own writable copy:

char* ptr = new char[ str.size() + 1 ];
strcpy(ptr, str.c_str());
ptr[str.size()] = '\0';
// ... use ptr as much as you want...
delete [] ptr;


来源: stackexchange

问:
Why do I need a 'return' and a new variable?
I am a newbie in Python programming and I would like to understand better the logic of programming. The code below is intended to create a function that assigns its parameters to a dictionary, prompt the user about an artist and a title name, call the function back passing the arguments (given by the user) to the parameters and print the function (the dictionary).

```<code>def make_album(artist, album_name):
    entry = {'name' : artist, 'album' : album_name}
    return entry

while True:
    print("\nPlease, write your fav artist and title: ")
    print("\nType 'q' to quit.")
    band_name = input('Artist name: ')
    if band_name == 'q':
        break
    title_name = input('Title name: ')
    if title_name == 'q':
        break

comp_entry = make_album(band_name, title_name)
print(comp_entry)
</code>```

The code runs perfectly. But there are two points that I can not understand:

Why do I need the 'return entry' line? The function creates a dictionary and it is done. Why a return?

Why do I need to create a variable in the end, assign the result of the function and print it? There is already a variable (entry) addressed as the dictionary! I would like to just write instead:

```<code>make_album(band_name, title_name):
    print(entry)
</code>```

I know, the code will not run, but I would be very happy with some words explaining me the reason of why these 2 points.

答:
entry is defined inside the function, so it cannot be accessed outside of it.

Check this article about closures
http://www.trytoprogram.com/python-programming/python-closures/

ContentLicense: CC BY-SA 4.0

Body:
I am a newbie in Python programming and I would like to understand better the logic of programming. The code below is intended to create a function that assigns its parameters to a dictionary, prompt the user about an artist and a title name, call the function back passing the arguments (given by the user) to the parameters and print the function (the dictionary).

def make_album(artist, album_name):
    entry = {'name' : artist, 'album' : album_name}
    return entry

while True:
    print("\nPlease, write your fav artist and title: ")
    print("\nType 'q' to quit.")
    band_name = input('Artist name: ')
    if band_name == 'q':
        break
    title_name = input('Title name: ')
    if title_name == 'q':
        break

comp_entry = make_album(band_name, title_name)
print(comp_entry)

The code runs perfectly. But there are two points that I can not understand:

Why do I need the 'return entry' line? The function creates a dictionary and it is done. Why a return?

Why do I need to create a variable in the end, assign the result of the function and print it? There is already a variable (entry) addressed as the dictionary! I would like to just write instead:

make_album(band_name, title_name):
    print(entry)

I know, the code will not run, but I would be very happy with some words explaining me the reason of why these 2 points.


问:
How do I run Laravel websockets on Azure?
I've currently got the basic Azure package and am trying to run my laravel application. I used to have my app running on Plesk where websockets worked fine.

I've currently gotten my app to run on azure, but haven't been able to do so on my azure app.

Problem:
When I try to run php artisan websockets:serve in the console it just times out.

I've tried to: increased the time out time but the command just shows a spinner that keeps spinning

What I'm trying to achieve: get laravel websockets running on Azure

This is my first experience with azure.

答:
I solved this by not using the Azure web app service, but he VMS. This allowed me to setup a virtual machine with plesk.

This allowed me to run websockets with my laravel app on my VMS.

Currently Azure web app service doesn't support php sockets, Azure VMS does

Steps I took

Laravel install Azure VMS

Install Ubuntu server 18

Install Plesk (https://get.plesk.com/)

Connect domain trough name server

Add GitHub repository

Install php version (https://www.vultr.com/docs/how-to-install-and-configure-php-70-or-php-71-on-ubuntu-16-04)

Install laravel dep. “composer global require laravel/installer”

Update dependancies “composer update”

Create Mysql Database

Add .env with settings

Install and configure supervisor for web sockets (https://docs.beyondco.de/laravel-websockets/1.0/basic-usage/starting.html#using-a-different-port)

Additional steps to install web sockets ( https://laracasts.com/discuss/channels/general-discussion/supervisor-configuration-could-not-open-input-file-artisan?page=0 )


问:
Unresolved reference: Parcelize after adding necessary tools in gradle and updating to kotlin latest version
I am trying to annotate a data class with @parcelize and get the following error -

Here is my gradle file -

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

android {

    signingConfigs {
        config {
            keyAlias 'verte_internal_keystore'
            keyPassword ANDROID_STORE_PASSWORD
            storeFile file('verte_internal_keystore.jks')
            storePassword ANDROID_KEY_PASSWORD
        }
    }

    lintOptions {
        abortOnError false
    }

    compileSdkVersion 29
    buildToolsVersion '28.0.3'

    defaultConfig {
        applicationId "com.twoverte"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 16
        versionName ".3.4.0"
        multiDexEnabled true
        buildConfigField "java.util.Date", "BUILD_TIME", "new java.util.Date(" + System.currentTimeMillis() + "L)"
    }

    File signFile = project.file('keyInfos.properties')
    if (signFile.exists()) {
        Properties properties = new Properties()
        properties.load(new FileInputStream(signFile))
        signingConfigs {
            release {
                storeFile file(project.file(properties['keystore.filename']))
                storePassword properties['keystore.password']
                keyAlias properties['keystore.alias']
                keyPassword properties['keystore.password']
            }
        }
    }

    buildTypes {

    ....

    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    productFlavors {

    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.0.0'
    configurations {
        all {
            exclude group: 'org.json', module: 'json'
            exclude group: 'xpp3', module: 'xpp3'
        }
    }

    //Room components
    implementation 'androidx.room:room-runtime:2.2.3'
    annotationProcessor 'androidx.room:room-compiler:2.2.3'

    //Lifecycle components
    implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
    implementation 'androidx.lifecycle:lifecycle-common-java8:2.1.0'

    fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.mockito:mockito-core:1.10.19'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.cocosw:bottomsheet:1.0@aar'
    implementation 'org.igniterealtime.smack:smack-android:4.1.4'
    implementation 'org.igniterealtime.smack:smack-tcp:4.1.4'
    implementation 'org.igniterealtime.smack:smack-im:4.1.4'
    implementation 'org.igniterealtime.smack:smack-extensions:4.1.4'
    implementation 'org.igniterealtime.smack:smack-sasl-provided:4.1.4'
    implementation 'com.github.bumptech.glide:glide:4.8.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
    implementation 'com.amazonaws:aws-android-sdk-s3:2.6.30'
    implementation 'com.squareup.okhttp:okhttp:2.6.0'
    implementation 'io.michaelrocks:libphonenumber-android:8.9.14'

    // Preferred for scheduling background jobs when new push notifications are received.
    // It provides a JobScheduler-compatible API that works on all recent versions of
    // Android (API level 14+) that have Google Play services installed.
    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'

    implementation 'com.facebook.stetho:stetho:1.3.1'
    implementation 'com.facebook.stetho:stetho-okhttp3:1.3.1'
    implementation 'com.github.ksoichiro:android-observablescrollview:1.5.0'
    implementation 'com.google.android.gms:play-services-auth:17.0.0'
    implementation 'com.google.android.gms:play-services-identity:17.0.0'
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation 'com.google.android.gms:play-services-places:17.0.0'
    implementation 'com.google.firebase:firebase-auth:19.2.0'
    implementation 'com.google.firebase:firebase-core:17.2.1'
    implementation 'com.google.firebase:firebase-messaging:20.1.0'
    implementation 'com.google.firebase:firebase-crash:16.2.1'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'de.greenrobot:greendao:2.1.0'
    implementation 'io.github.rockerhieu:emojicon:1.4.2'
    implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
    implementation 'com.github.nkzawa:socket.io-client:0.4.2'
    implementation 'com.github.chrisbanes:PhotoView:2.1.3'
    implementation 'com.github.chrisbanes.photoview:library:1.2.4'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
    implementation 'com.github.nkzawa:socket.io-client:0.4.2'
    implementation 'net.opacapp:multiline-collapsingtoolbar:27.1.1'
    implementation 'org.webrtc:google-webrtc:1.0.23295'
    implementation 'com.github.clans:fab:1.6.4'
    implementation 'io.branch.sdk.android:library:3.0.0'
    implementation 'org.jsoup:jsoup:1.10.3'

    implementation 'com.squareup.retrofit2:retrofit:2.7.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.7.0'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'me.relex:circleindicator:2.1.4'
    implementation 'jp.wasabeef:picasso-transformations:2.2.1'
    implementation 'com.github.ganfra:material-spinner:2.0.0'

    implementation(name: 'appbase', ext: 'aar')
    implementation(name: 'greendao', ext: 'aar')
    implementation(name: 'chat', ext: 'aar')
    implementation(name: 'ffmpeg', ext: 'aar')
    implementation(name: 'imagecropper', ext: 'aar')
    implementation(name: 'imagepicker', ext: 'aar')
    implementation(name: 'webrtc', ext: 'aar')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
repositories {
    mavenCentral()
}

</code>```

What am I missing? I can't seem to get the compiler to know @Parcelize annotation

I have tried to update the kotlin version, checked multiple previous questions about this issue and did not find anything relevant to assist me.

答:
You don't have any dependency to the package kotlinx.android.parcel.

Add this to your dependency in build.gradle

```<code>implementation "org.jetbrains.kotlin:kotlin-android-extensions-runtime:1.3.61"
</code>```

Body:
I am trying to annotate a data class with @parcelize and get the following error -

Here is my gradle file -

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'
apply plugin: 'io.fabric'

android {

    signingConfigs {
        config {
            keyAlias 'verte_internal_keystore'
            keyPassword ANDROID_STORE_PASSWORD
            storeFile file('verte_internal_keystore.jks')
            storePassword ANDROID_KEY_PASSWORD
        }
    }

    lintOptions {
        abortOnError false
    }

    compileSdkVersion 29
    buildToolsVersion '28.0.3'

    defaultConfig {
        applicationId "com.twoverte"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 16
        versionName ".3.4.0"
        multiDexEnabled true
        buildConfigField "java.util.Date", "BUILD_TIME", "new java.util.Date(" + System.currentTimeMillis() + "L)"
    }

    File signFile = project.file('keyInfos.properties')
    if (signFile.exists()) {
        Properties properties = new Properties()
        properties.load(new FileInputStream(signFile))
        signingConfigs {
            release {
                storeFile file(project.file(properties['keystore.filename']))
                storePassword properties['keystore.password']
                keyAlias properties['keystore.alias']
                keyPassword properties['keystore.password']
            }
        }
    }

    buildTypes {

    ....

    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    productFlavors {

    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.0.0'
    configurations {
        all {
            exclude group: 'org.json', module: 'json'
            exclude group: 'xpp3', module: 'xpp3'
        }
    }

    //Room components
    implementation 'androidx.room:room-runtime:2.2.3'
    annotationProcessor 'androidx.room:room-compiler:2.2.3'

    //Lifecycle components
    implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
    implementation 'androidx.lifecycle:lifecycle-common-java8:2.1.0'

    fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.mockito:mockito-core:1.10.19'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.cocosw:bottomsheet:1.0@aar'
    implementation 'org.igniterealtime.smack:smack-android:4.1.4'
    implementation 'org.igniterealtime.smack:smack-tcp:4.1.4'
    implementation 'org.igniterealtime.smack:smack-im:4.1.4'
    implementation 'org.igniterealtime.smack:smack-extensions:4.1.4'
    implementation 'org.igniterealtime.smack:smack-sasl-provided:4.1.4'
    implementation 'com.github.bumptech.glide:glide:4.8.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
    implementation 'com.amazonaws:aws-android-sdk-s3:2.6.30'
    implementation 'com.squareup.okhttp:okhttp:2.6.0'
    implementation 'io.michaelrocks:libphonenumber-android:8.9.14'

    // Preferred for scheduling background jobs when new push notifications are received.
    // It provides a JobScheduler-compatible API that works on all recent versions of
    // Android (API level 14+) that have Google Play services installed.
    implementation 'com.firebase:firebase-jobdispatcher:0.8.5'

    implementation 'com.facebook.stetho:stetho:1.3.1'
    implementation 'com.facebook.stetho:stetho-okhttp3:1.3.1'
    implementation 'com.github.ksoichiro:android-observablescrollview:1.5.0'
    implementation 'com.google.android.gms:play-services-auth:17.0.0'
    implementation 'com.google.android.gms:play-services-identity:17.0.0'
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation 'com.google.android.gms:play-services-places:17.0.0'
    implementation 'com.google.firebase:firebase-auth:19.2.0'
    implementation 'com.google.firebase:firebase-core:17.2.1'
    implementation 'com.google.firebase:firebase-messaging:20.1.0'
    implementation 'com.google.firebase:firebase-crash:16.2.1'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'de.greenrobot:greendao:2.1.0'
    implementation 'io.github.rockerhieu:emojicon:1.4.2'
    implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
    implementation 'com.github.nkzawa:socket.io-client:0.4.2'
    implementation 'com.github.chrisbanes:PhotoView:2.1.3'
    implementation 'com.github.chrisbanes.photoview:library:1.2.4'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
    implementation 'com.github.nkzawa:socket.io-client:0.4.2'
    implementation 'net.opacapp:multiline-collapsingtoolbar:27.1.1'
    implementation 'org.webrtc:google-webrtc:1.0.23295'
    implementation 'com.github.clans:fab:1.6.4'
    implementation 'io.branch.sdk.android:library:3.0.0'
    implementation 'org.jsoup:jsoup:1.10.3'

    implementation 'com.squareup.retrofit2:retrofit:2.7.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.7.0'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'me.relex:circleindicator:2.1.4'
    implementation 'jp.wasabeef:picasso-transformations:2.2.1'
    implementation 'com.github.ganfra:material-spinner:2.0.0'

    implementation(name: 'appbase', ext: 'aar')
    implementation(name: 'greendao', ext: 'aar')
    implementation(name: 'chat', ext: 'aar')
    implementation(name: 'ffmpeg', ext: 'aar')
    implementation(name: 'imagecropper', ext: 'aar')
    implementation(name: 'imagepicker', ext: 'aar')
    implementation(name: 'webrtc', ext: 'aar')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
repositories {
    mavenCentral()
}

What am I missing? I can't seem to get the compiler to know @Parcelize annotation

I have tried to update the kotlin version, checked multiple previous questions about this issue and did not find anything relevant to assist me.

Body:
You don't have any dependency to the package kotlinx.android.parcel.

Add this to your dependency in build.gradle

implementation "org.jetbrains.kotlin:kotlin-android-extensions-runtime:1.3.61"


问:
Scrapy - crawled (200) and referer : none
I'm trying to learn how to use scrapy and python but I'm not an expert at all... very far from here.
I always have an empty file after crawling this page : product of c-discount and I don't understand why...

Here is my code :

```<code>import scrapy

from cdiscount_test.items import CdiscountTestItem

f = open('items.csv', 'w').close()

class CdiscountsellersspiderSpider(scrapy.Spider):
    name = 'CDiscountSellersSpider'
    allowed_domains = ['cdiscount.com']
    start_urls = ['http://www.cdiscount.com/mpv-8732-SATENCO.html']

    def parse(self, response):
        items = CdiscountTestItem()
        name = response.xpath('//div[@class="shtName"]/div[@class="shtOver"]/h1[@itemprop="name"]/text()').extract()
        country = response.xpath('//div[@class="shtName"]/span[@class="shTopCExp"]/text()').extract()

        items['name_seller'] = ''.join(name).strip()
        items['country_seller'] = ''.join(country).strip()
        pass
</code>```

And the result I get in the cmd windows :

```<code>2017-06-20 18:01:50 [scrapy.core.engine] INFO: Spider opened
2017-06-20 18:01:50 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0
pages/min), scraped 0 items (at 0 items/min)
2017-06-20 18:01:50 [scrapy.extensions.telnet] DEBUG: Telnet console
listening on 127.0.0.1:6023
2017-06-20 18:01:51 [scrapy.core.engine] DEBUG: Crawled (200) <GET
http://www.cdiscount.com/robots.txt> (referer: None)
2017-06-20 18:01:51 [scrapy.core.engine] DEBUG: Crawled (200) <GET
http://www.cdiscount.com/mpv-8732-SATENCO.html> (referer: None)
2017-06-20 18:01:51 [scrapy.core.engine] INFO: Closing spider (finished)
</code>```

Is there someone to help me please?

Thanks a lot!!!

答:
One probable scenario for the same issue might be the website content is producing dynamically. You can check that by going to the website and tapping view page source.
In such cases, you might have to use splash along with scrapy.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to learn how to use scrapy and python but I'm not an expert at all... very far from here.
I always have an empty file after crawling this page : product of c-discount and I don't understand why...

Here is my code :

import scrapy

from cdiscount_test.items import CdiscountTestItem

f = open('items.csv', 'w').close()

class CdiscountsellersspiderSpider(scrapy.Spider):
    name = 'CDiscountSellersSpider'
    allowed_domains = ['cdiscount.com']
    start_urls = ['http://www.cdiscount.com/mpv-8732-SATENCO.html']

    def parse(self, response):
        items = CdiscountTestItem()
        name = response.xpath('//div[@class="shtName"]/div[@class="shtOver"]/h1[@itemprop="name"]/text()').extract()
        country = response.xpath('//div[@class="shtName"]/span[@class="shTopCExp"]/text()').extract()

        items['name_seller'] = ''.join(name).strip()
        items['country_seller'] = ''.join(country).strip()
        pass

And the result I get in the cmd windows :

2017-06-20 18:01:50 [scrapy.core.engine] INFO: Spider opened
2017-06-20 18:01:50 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0
pages/min), scraped 0 items (at 0 items/min)
2017-06-20 18:01:50 [scrapy.extensions.telnet] DEBUG: Telnet console
listening on 127.0.0.1:6023
2017-06-20 18:01:51 [scrapy.core.engine] DEBUG: Crawled (200) <GET
http://www.cdiscount.com/robots.txt> (referer: None)
2017-06-20 18:01:51 [scrapy.core.engine] DEBUG: Crawled (200) <GET
http://www.cdiscount.com/mpv-8732-SATENCO.html> (referer: None)
2017-06-20 18:01:51 [scrapy.core.engine] INFO: Closing spider (finished)

Is there someone to help me please?

Thanks a lot!!!


答:
Updated Answer:

kotlin-android-extensions plugin is deprecated.

Now you have to add dependency in app level build.gradle file like below:

```<code>implementation "org.jetbrains.kotlin:kotlin-android-extensions-runtime:1.7.10
</code>```

Old Answer:

Change your build.gradle to add kotlin-android-extensions in below order.

```<code>apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
</code>```

Beside this you have enable experimental feature to use it

```<code>androidExtensions {
    experimental = true
}
</code>```

Title: Unresolved reference: Parcelize after adding necessary tools in gradle and updating to kotlin latest version

Body:
Updated Answer:

kotlin-android-extensions plugin is deprecated.

Now you have to add dependency in app level build.gradle file like below:

implementation "org.jetbrains.kotlin:kotlin-android-extensions-runtime:1.7.10

Old Answer:

Change your build.gradle to add kotlin-android-extensions in below order.

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

Beside this you have enable experimental feature to use it

androidExtensions {
    experimental = true
}


问:
SyntaxError: invalid syntax for listen() in python socket programming
The following is the code to transfer file from Server. I am getting and error saying

Error
    s.listen(2)
    ^
SyntaxError: invalid syntax

Server code

```<code>import socket
import threading
import os

def RetrFile(name,sock):
    filename = sock.recv(1024)
    if os.path.isfile(filename):
        sock.send("EXISTS " + str(os.path.getsize(filename)))
        userResponse = sock.recv(1024)
        if userResponse[:2] == 'OK':
            with open(filename,'rb') as f:
                bytesToSend = f.read(1024)
                sock.send(bytesToSend)
                while bytesToSend != "":
                    bytesToSend = f.read(1024)
                    sock.send(bytesToSend)
    else:
        sock.send("ERR")
    sock.close()

def Main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((socket.gethostname(),1235)
    s.listen(2)
    print("Server started")

    while True:
        c,addr = s.accept()
        print("Client connected ip:<" + str(addr) + ">")
        t = threading.Thread(target = RetrFile, arfs=("retrThread", c))
        t.start()

    s.close()

if __name__ = '__main__':
    Main()
</code>```

Can someone help me out to understand why am I getting this error? I am new to python and socket programming.

答:
This line is missing the closing parenthesis of the tuple:</p>

```<code>s.bind((socket.gethostname(),1235)
</code>```

Body:
The following is the code to transfer file from Server. I am getting and error saying

Error
    s.listen(2)
    ^
SyntaxError: invalid syntax

Server code

import socket
import threading
import os

def RetrFile(name,sock):
    filename = sock.recv(1024)
    if os.path.isfile(filename):
        sock.send("EXISTS " + str(os.path.getsize(filename)))
        userResponse = sock.recv(1024)
        if userResponse[:2] == 'OK':
            with open(filename,'rb') as f:
                bytesToSend = f.read(1024)
                sock.send(bytesToSend)
                while bytesToSend != "":
                    bytesToSend = f.read(1024)
                    sock.send(bytesToSend)
    else:
        sock.send("ERR")
    sock.close()

def Main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((socket.gethostname(),1235)
    s.listen(2)
    print("Server started")

    while True:
        c,addr = s.accept()
        print("Client connected ip:<" + str(addr) + ">")
        t = threading.Thread(target = RetrFile, arfs=("retrThread", c))
        t.start()

    s.close()

if __name__ = '__main__':
    Main()

Can someone help me out to understand why am I getting this error? I am new to python and socket programming.

Body:
This line is missing the closing parenthesis of the tuple:

s.bind((socket.gethostname(),1235)


问:
Putting Custom CSS into Laravel 6
I put my css in the public folder and linked to it in my template, but the css won't work. When I run the file out of Laravel using HTML index, it works fine. But, when I put it in Laravel it won't see the css.

This is my code in the template:

```<code><link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/media.css">
</code>```

Do I need to add anything to make it blade/laravel specific?

答:
use asset like this:

```<code><link rel="stylesheet" href="{{asset('css/style.css')}}">
<link rel="stylesheet" href="{{asset('css/media.css')}}">
</code>```

read this for more info!

Title: Putting Custom CSS into Laravel 6

Body:
I put my css in the public folder and linked to it in my template, but the css won't work. When I run the file out of Laravel using HTML index, it works fine. But, when I put it in Laravel it won't see the css.

This is my code in the template:

<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/media.css">

Do I need to add anything to make it blade/laravel specific?

Body:
use asset like this:

<link rel="stylesheet" href="{{asset('css/style.css')}}">
<link rel="stylesheet" href="{{asset('css/media.css')}}">

read this for more info!


问:
Mpdf issue: Why not work mpdf format,margin,fontsize mPDF\mPDF class value
My mPDF Class

```<code>$mpdf = new \Mpdf\Mpdf(['utf-8', 'A4-L', 1000000, 'cursive', 100000000000000, 100, 100, 0, 0, 0, 'L']);
</code>```

I have use mPDF Update version

答:
try it

```<code>$mpdf = new \Mpdf\Mpdf([
    'tempDir' => __DIR__ . '/pdfdata',
    'mode' => 'utf-8',
    // 'format' => [24, 24],
    'format' => 'A4',
    'margin_left' => 0,
    'margin_right' => 2,
    'margin_bottom' => 2,
    'margin_top' => 2,
    'float' => 'left'

]);
</code>```

Body:
My mPDF Class

$mpdf = new \Mpdf\Mpdf(['utf-8', 'A4-L', 1000000, 'cursive', 100000000000000, 100, 100, 0, 0, 0, 'L']);

I have use mPDF Update version

Body:
try it

$mpdf = new \Mpdf\Mpdf([
    'tempDir' => __DIR__ . '/pdfdata',
    'mode' => 'utf-8',
    // 'format' => [24, 24],
    'format' => 'A4',
    'margin_left' => 0,
    'margin_right' => 2,
    'margin_bottom' => 2,
    'margin_top' => 2,
    'float' => 'left'

]);


问:
Specify the percentColWidth for datagrid column in action script
Tried

```<code>col.setStyle('percentWidth',20) //doesn't work

col.setStyle('percentWidth',0.2)//doesn't work
</code>```

&&

```<code>col.percentWidth //doesnt compile
</code>```

where col is one of the columns in a datagrid

Thanks.

答:
Use the following extended datagrid:

```<code>package {
import mx.controls.DataGrid;
import mx.events.DataGridEvent;

public class ExDataGrid extends DataGrid {

    //--------------------------------------
    //   Constructor
    //--------------------------------------

    public function ExDataGrid() {
        super();
        addEventListener(DataGridEvent.COLUMN_STRETCH, onColumnStretch);
    }

    //------------------------------------------------------------------------------
    //   Properties
    //------------------------------------------------------------------------------

    //--------------------------------------
    //   Private
    //--------------------------------------

    /**
     * @private
     * Keeps track of whether the columns have been manually adjusted or not. If they
     * have, then do not apply the columnWidths that have been specified.
     */
    private var _columnsAdjusted : Boolean = false;

    /**
     * @private
     * Storage for the columnWidths property.
     */
    private var _columnWidths : Array = new Array();

    /**
     * @private
     */
    private var _columnWidthsChanged : Boolean = false;

    /**
     * @private
     * Stores the explicit width portions of the column widths.
     */
    private var _explicitColWidths : Object;

    /**
     * @private
     * Stores the percentage width portions of the column widths.
     */
    private var _percentColWidths : Object;

    //--------------------------------------
    //   Getters / Setters
    //--------------------------------------

    public function get columnWidths() : Array {
        return _columnWidths;
    }

    /**
     * Sets the widths of each of the columns. The widths can either be percentages or
     * explicit widths. For each column in the DataGrid, there should be a column width
     * value. The column widths should be expressed as strings.
     *
     * If there are 4 columns and we want the 1st column to be 40% width, the 2nd column
     * to be 60% width, the 3rd column to be a fixed width of 200, and the 4th column to
     * be a fixed width of 300. Then we would set the columnWidths property to be:
     * ['40%', '60%', 200, 300]
     */
    public function set columnWidths(values : Array) : void {
        if (_columnWidths != values) {
            _columnWidths = values;
            _columnWidthsChanged = true;

            invalidateProperties();
            invalidateDisplayList();
        }
    }

    //------------------------------------------------------------------------------
    //   Functions
    //------------------------------------------------------------------------------

    //--------------------------------------
    //   Protected
    //--------------------------------------

    /**
     * @private
     */
    override protected function commitProperties() : void {
        super.commitProperties();

        if (_columnWidthsChanged) {
            splitPercentWidths(columnWidths);
            _columnWidthsChanged = false;
        }
    }

    /**
     * @private
     * Sizes each of the columns in the DataGrid based on the columnWidths property,
     * unless the user has manually resized the columns, then the column widths will
     * not be adjusted.
     */
    override protected function updateDisplayList(unscaledWidth : Number, unscaledHeight : Number) : void {
        // Determine how much width is left over for percentage calculations after the fixed
        // widths are allocated.
        var leftoverWidth : Number = unscaledWidth;

        for each (var explicitColWidth : Number in _explicitColWidths) {
            leftoverWidth -= explicitColWidth;
        }

        // Manually adjust the column width before doing super.updateDisplayList. This way when
        // super.updateDisplayList is called, it can perform any minor adjustments to the columns,
        // but the column widths will still be pretty consistant with the specified widths.
        if (columns && columnWidths && !_columnsAdjusted && columns.length == columnWidths.length) {
            for (var i : int = 0; i < columnWidths.length; i++) {
                var w : Number = 0;

                if (_explicitColWidths[i]) {
                    w = _explicitColWidths[i];
                }
                else {
                    w = leftoverWidth * (_percentColWidths[i] / 100);
                }

                // Adjust the column's width. After digging through the DataGridColumn, I found
                // 3 different properties that need to be set to override the default column width
                // calculations performed by DataGrid and DataGridColumn. They are _width (changed
                // in the setWidth method), explicitWidth, and preferredWidth.
                columns[i].setWidth(w);
                columns[i].explicitWidth = w;
                columns[i].preferredWidth = w;
            }
        }

        super.updateDisplayList(unscaledWidth, unscaledHeight);
    }

    //--------------------------------------
    //   Private
    //--------------------------------------

    /**
     * @private
     */
    private function onColumnStretch(event : DataGridEvent) : void {
        _columnsAdjusted = true;
    }

    /**
     * Called from the <code>commitProperties()</code> method to break up the columnWidths
     * into percentage based widths and explicit widths.
     *
     * When we calculate the percentage widths in <code>updateDisplayList()</code> we need
     * to know the remaining available width after explicit widths are subtracted.
     */
    private function splitPercentWidths(values : Array) : void {
        if (columns && columnWidths && columnWidths.length > 0) {
            _percentColWidths = new Object();
            _explicitColWidths = new Object();

            for (var i : uint = 0; i < columnWidths.length; i++) {
                var columnWidth : String = columnWidths[i] + "";

                // If columnWidth contains a '%' then it is a percentage width, otherwise
                // it is an explicit width.
                if (columnWidth.indexOf("%") == -1) {
                    _explicitColWidths[i] = Number(columnWidth);
                }
                else {
                    _percentColWidths[i] = Number(columnWidth.substr(0, columnWidth.length - 1));
                }
            }
        }
    }
}
}
</code>```

Declare all column widths as at array assigned to 'columnWidths' with the following syntax:

```<code> columnWidths = ['70%','30%','100'];
</code>```

Widths without a % sign are treated normally.

Body:
Tried

col.setStyle('percentWidth',20) //doesn't work

col.setStyle('percentWidth',0.2)//doesn't work

&&

col.percentWidth //doesnt compile

where col is one of the columns in a datagrid

Thanks.

Body:
Use the following extended datagrid:

package {
import mx.controls.DataGrid;
import mx.events.DataGridEvent;

public class ExDataGrid extends DataGrid {

    //--------------------------------------
    //   Constructor
    //--------------------------------------

    public function ExDataGrid() {
        super();
        addEventListener(DataGridEvent.COLUMN_STRETCH, onColumnStretch);
    }

    //------------------------------------------------------------------------------
    //   Properties
    //------------------------------------------------------------------------------

    //--------------------------------------
    //   Private
    //--------------------------------------

    /**
     * @private
     * Keeps track of whether the columns have been manually adjusted or not. If they
     * have, then do not apply the columnWidths that have been specified.
     */
    private var _columnsAdjusted : Boolean = false;

    /**
     * @private
     * Storage for the columnWidths property.
     */
    private var _columnWidths : Array = new Array();

    /**
     * @private
     */
    private var _columnWidthsChanged : Boolean = false;

    /**
     * @private
     * Stores the explicit width portions of the column widths.
     */
    private var _explicitColWidths : Object;

    /**
     * @private
     * Stores the percentage width portions of the column widths.
     */
    private var _percentColWidths : Object;

    //--------------------------------------
    //   Getters / Setters
    //--------------------------------------

    public function get columnWidths() : Array {
        return _columnWidths;
    }

    /**
     * Sets the widths of each of the columns. The widths can either be percentages or
     * explicit widths. For each column in the DataGrid, there should be a column width
     * value. The column widths should be expressed as strings.
     *
     * If there are 4 columns and we want the 1st column to be 40% width, the 2nd column
     * to be 60% width, the 3rd column to be a fixed width of 200, and the 4th column to
     * be a fixed width of 300. Then we would set the columnWidths property to be:
     * ['40%', '60%', 200, 300]
     */
    public function set columnWidths(values : Array) : void {
        if (_columnWidths != values) {
            _columnWidths = values;
            _columnWidthsChanged = true;

            invalidateProperties();
            invalidateDisplayList();
        }
    }

    //------------------------------------------------------------------------------
    //   Functions
    //------------------------------------------------------------------------------

    //--------------------------------------
    //   Protected
    //--------------------------------------

    /**
     * @private
     */
    override protected function commitProperties() : void {
        super.commitProperties();

        if (_columnWidthsChanged) {
            splitPercentWidths(columnWidths);
            _columnWidthsChanged = false;
        }
    }

    /**
     * @private
     * Sizes each of the columns in the DataGrid based on the columnWidths property,
     * unless the user has manually resized the columns, then the column widths will
     * not be adjusted.
     */
    override protected function updateDisplayList(unscaledWidth : Number, unscaledHeight : Number) : void {
        // Determine how much width is left over for percentage calculations after the fixed
        // widths are allocated.
        var leftoverWidth : Number = unscaledWidth;

        for each (var explicitColWidth : Number in _explicitColWidths) {
            leftoverWidth -= explicitColWidth;
        }

        // Manually adjust the column width before doing super.updateDisplayList. This way when
        // super.updateDisplayList is called, it can perform any minor adjustments to the columns,
        // but the column widths will still be pretty consistant with the specified widths.
        if (columns && columnWidths && !_columnsAdjusted && columns.length == columnWidths.length) {
            for (var i : int = 0; i < columnWidths.length; i++) {
                var w : Number = 0;

                if (_explicitColWidths[i]) {
                    w = _explicitColWidths[i];
                }
                else {
                    w = leftoverWidth * (_percentColWidths[i] / 100);
                }

                // Adjust the column's width. After digging through the DataGridColumn, I found
                // 3 different properties that need to be set to override the default column width
                // calculations performed by DataGrid and DataGridColumn. They are _width (changed
                // in the setWidth method), explicitWidth, and preferredWidth.
                columns[i].setWidth(w);
                columns[i].explicitWidth = w;
                columns[i].preferredWidth = w;
            }
        }

        super.updateDisplayList(unscaledWidth, unscaledHeight);
    }

    //--------------------------------------
    //   Private
    //--------------------------------------

    /**
     * @private
     */
    private function onColumnStretch(event : DataGridEvent) : void {
        _columnsAdjusted = true;
    }

    /**
     * Called from the <code>commitProperties()</code> method to break up the columnWidths
     * into percentage based widths and explicit widths.
     *
     * When we calculate the percentage widths in <code>updateDisplayList()</code> we need
     * to know the remaining available width after explicit widths are subtracted.
     */
    private function splitPercentWidths(values : Array) : void {
        if (columns && columnWidths && columnWidths.length > 0) {
            _percentColWidths = new Object();
            _explicitColWidths = new Object();

            for (var i : uint = 0; i < columnWidths.length; i++) {
                var columnWidth : String = columnWidths[i] + "";

                // If columnWidth contains a '%' then it is a percentage width, otherwise
                // it is an explicit width.
                if (columnWidth.indexOf("%") == -1) {
                    _explicitColWidths[i] = Number(columnWidth);
                }
                else {
                    _percentColWidths[i] = Number(columnWidth.substr(0, columnWidth.length - 1));
                }
            }
        }
    }
}
}

Declare all column widths as at array assigned to 'columnWidths' with the following syntax:

 columnWidths = ['70%','30%','100'];

Widths without a % sign are treated normally.


问:
Connect Angular 4 with LARAVEL 5.4
I want to develope an website with Angular 4 and Laravel 5.4. The question is how to connect in a better way this two framework. It`s a good idea to make a subdomain for laravel 5.4 (api.exameple.com) and running angular 4 on main domain (example.com) and connect it to laravel through API or exist another way to integrate laravel with angular?? And in general is a good idea to use laravel 5.4 and angular 4 for a big project?
Sorry for my bad english.</p>

答:
You should create a containing folder which you can name anything, probably the project name, like my-blog and in that folder (my-blog) you should create your laravel and angular projects.

```<code>ng new frontend(your angular project)
composer create-project laravel/laravel backend
</code>```

These will generate two folders for you in the my-blog folder and you can link them by making api calls from the frontend to the backend.

Title: Connect Angular 4 with LARAVEL 5.4

Body:
You should create a containing folder which you can name anything, probably the project name, like my-blog and in that folder (my-blog) you should create your laravel and angular projects.

ng new frontend(your angular project)
composer create-project laravel/laravel backend

These will generate two folders for you in the my-blog folder and you can link them by making api calls from the frontend to the backend.


问:
Python numpy and pandas for machine learning
just as a disclaimer, this question is in regards to  schoolwork. Literally though, my professor said to use this site for aid.

I am taking machine learning, and while our professor is a brilliant mathematician, he may be a little lacking on the programming side of things.

The name of the game here is to read code portions and find/fix the mistake.

I spend hours on this part, and I reckon my issue is having a dot product between a dataframe and numpy zeroes.

Issues occur like unsupported operand type(s) for +: 'float' and 'str'

I tried reading documentation and this site for a workaround, but I very novice in programming, especially a library like numpy and pandas

This is programming with python pandas

```<code># Initialize the paarmeter set theta with zeros length as equal to column size in X
X = pd.DataFrame(X)
theta = np.zeros(X.shape[1], dtype = int)
print(theta)

def cost_function(X, y, theta):
    """
    cost_function(X, y, theta) computes the cost of using theta as the
    parameter for linear regression to fit the data points in X and y
    """
    ## number of training examples
    m = len(y)

    ## Calculate the cost with the given parameters
    J = 1/(2*m)*np.sum((X.dot(theta)-y)**2)

    return J

#Initial cost
cost_function(X,y,theta)
</code>```

running the last line yields the most issues.

答:
Just use np.dot(X,theta) instead of X.dot(theta). Here is the edited code.

```<code>def cost_function(X, y, theta):
"""
cost_function(X, y, theta) computes the cost of using theta as the
parameter for linear regression to fit the data points in X and y
"""
## number of training examples
    m = len(y)

## Calculate the cost with the given parameters
    J = 1/(2*m)*np.sum((np.dot(X,theta)-y)**2)

    return J

#Initial cost
cost_function(X,y,theta)
</code>```

Hope this will help you.

Body:
just as a disclaimer, this question is in regards to  schoolwork. Literally though, my professor said to use this site for aid.

I am taking machine learning, and while our professor is a brilliant mathematician, he may be a little lacking on the programming side of things.

The name of the game here is to read code portions and find/fix the mistake.

I spend hours on this part, and I reckon my issue is having a dot product between a dataframe and numpy zeroes.

Issues occur like unsupported operand type(s) for +: 'float' and 'str'

I tried reading documentation and this site for a workaround, but I very novice in programming, especially a library like numpy and pandas

This is programming with python pandas

# Initialize the paarmeter set theta with zeros length as equal to column size in X
X = pd.DataFrame(X)
theta = np.zeros(X.shape[1], dtype = int)
print(theta)

def cost_function(X, y, theta):
    """
    cost_function(X, y, theta) computes the cost of using theta as the
    parameter for linear regression to fit the data points in X and y
    """
    ## number of training examples
    m = len(y)

    ## Calculate the cost with the given parameters
    J = 1/(2*m)*np.sum((X.dot(theta)-y)**2)

    return J

#Initial cost
cost_function(X,y,theta)

running the last line yields the most issues.

Body:
Just use np.dot(X,theta) instead of X.dot(theta). Here is the edited code.

def cost_function(X, y, theta):
"""
cost_function(X, y, theta) computes the cost of using theta as the
parameter for linear regression to fit the data points in X and y
"""
## number of training examples
    m = len(y)

## Calculate the cost with the given parameters
    J = 1/(2*m)*np.sum((np.dot(X,theta)-y)**2)

    return J

#Initial cost
cost_function(X,y,theta)

Hope this will help you.


问:
How to extract particular values from a factor store as column value in dataframe
I have a data frame with the following columns :

```<code>df <- A B C
    heart_rate  ['53.0', '1']   94
    heart_rate  ['54.0', '2']   1
    heart_rate  ['54.0', '1']   9
    heart_rate  ['55.0', '0']   1
    heart_rate  ['55.0', '1']   7
</code>```

How to read the df1 which just stores one value for cases where we have y= 1 for B[x,y].Which means :

Output desired dataframe df1

```<code>  df1

    A B C
    heart_rate  53.0    94
    heart_rate  54.0    9
    heart_rate  55.0    7

    structure(list(source = structure(c(1L, 1L, 1L), .Label = "heart_rate", class = "factor"),
        values = structure(3:1, .Label = c("['171.0', '1']", "['172.0', '1']",
        "['173.0', '0']"), class = "factor"), timediff = c(6L, 7L,
        10L)), class = "data.frame", row.names = c(NA, -3L))
</code>```

答:
Using my answer from the previous post, we can get data into separate columns B and D using extract and then use filter to select where D = 1.

```<code>tidyr::extract(df, B, into = c('B', 'D'), "(\\d+\\.\\d+).*(\\d)") %>%
  dplyr::filter(D == 1) %>%
  dplyr::select(-D)

#           A    B  C
#1 heart_rate 53.0 94
#2 heart_rate 54.0  9
#3 heart_rate 55.0  7
</code>```

data

```<code>df <- structure(list(A = structure(c(1L, 1L, 1L, 1L, 1L),
.Label = "heart_rate", class = "factor"),
B = structure(c(1L, 3L, 2L, 4L, 5L), .Label = c("[53.0, 1]",
"[54.0, 1]", "[54.0, 2]", "[55.0, 0]", "[55.0, 1]"), class = "factor"),
C = c(94L, 1L, 9L, 1L, 7L)), class = "data.frame", row.names = c(NA, -5L))
</code>```

Body:
I have a data frame with the following columns :

df <- A B C
    heart_rate  ['53.0', '1']   94
    heart_rate  ['54.0', '2']   1
    heart_rate  ['54.0', '1']   9
    heart_rate  ['55.0', '0']   1
    heart_rate  ['55.0', '1']   7

How to read the df1 which just stores one value for cases where we have y= 1 for B[x,y].Which means :

Output desired dataframe df1

  df1

    A B C
    heart_rate  53.0    94
    heart_rate  54.0    9
    heart_rate  55.0    7

    structure(list(source = structure(c(1L, 1L, 1L), .Label = "heart_rate", class = "factor"),
        values = structure(3:1, .Label = c("['171.0', '1']", "['172.0', '1']",
        "['173.0', '0']"), class = "factor"), timediff = c(6L, 7L,
        10L)), class = "data.frame", row.names = c(NA, -3L))

Body:
Using my answer from the previous post, we can get data into separate columns B and D using extract and then use filter to select where D = 1.

tidyr::extract(df, B, into = c('B', 'D'), "(\\d+\\.\\d+).*(\\d)") %>%
  dplyr::filter(D == 1) %>%
  dplyr::select(-D)

#           A    B  C
#1 heart_rate 53.0 94
#2 heart_rate 54.0  9
#3 heart_rate 55.0  7

data

df <- structure(list(A = structure(c(1L, 1L, 1L, 1L, 1L),
.Label = "heart_rate", class = "factor"),
B = structure(c(1L, 3L, 2L, 4L, 5L), .Label = c("[53.0, 1]",
"[54.0, 1]", "[54.0, 2]", "[55.0, 0]", "[55.0, 1]"), class = "factor"),
C = c(94L, 1L, 9L, 1L, 7L)), class = "data.frame", row.names = c(NA, -5L))


问:
Progress bar button in HTML5
I would like to combine two features of HTML5 into one.  I am trying to essentially make a progress bar button on a page.  The progress bar does not need to be updated on the page, only when the page is refreshed will the bar change position.  Any idea how I could do this?

Thanks

-Jesse

答:
```<code><button onclick="window.alert('Clicked');">
    <progress max="1.0" value="0.7">70%</progress>
</button>
</code>```

Seems to work in Opera & Chrome, it also works OK in Firefox but no support for progress.

Title: Progress bar button in HTML5

Body:
<button onclick="window.alert('Clicked');">
    <progress max="1.0" value="0.7">70%</progress>
</button>

Seems to work in Opera & Chrome, it also works OK in Firefox but no support for progress.


问:
I am not understanding php expression for saving values in a variable, bellow is the line of php
```<code>$copyrights = $config->get( 'template.bottom_bar.copyrights' );
</code>```

I understand $copyrights is a variable that has some value but pleases someone explains me the right side of the expression

```<code>$config->get( 'template.bottom_bar.copyrights' );
</code>```

what does it mean
does 'template.bottom_bar.copyrights' is referring to a file or anything

答:
Some frameworks allow dot notation to access array elements.

In this case,

$config->get( 'template.bottom_bar.copyrights' );
```

<p>This is probably the equivalent of something like (but not quite):</p>

<pre class="lang-php prettyprint-override"><code>$config['template']['bottom_bar']['copyrights'];
</code>```

I say not quite because, depending on your framework, you might have a template.php or a template.ini file in a config directory. This file will have an array of options. The framework will load the various config files and provide a config object/helper like you have there.

The get method usually handles unknown indexes in the array and simply returns null.

Body:
$copyrights = $config->get( 'template.bottom_bar.copyrights' );

I understand $copyrights is a variable that has some value but pleases someone explains me the right side of the expression

$config->get( 'template.bottom_bar.copyrights' );

what does it mean
does 'template.bottom_bar.copyrights' is referring to a file or anything

Body:
Some frameworks allow dot notation to access array elements.

In this case,

$config->get( 'template.bottom_bar.copyrights' );

This is probably the equivalent of something like (but not quite):

$config['template']['bottom_bar']['copyrights'];

I say not quite because, depending on your framework, you might have a template.php or a template.ini file in a config directory. This file will have an array of options. The framework will load the various config files and provide a config object/helper like you have there.

The get method usually handles unknown indexes in the array and simply returns null.


问:
How to get data from my axios request without using a setTimeout?
I am having a problem, I believe many of you have faced it somehow, so I am using axios to get my data :

```<code> let data = axios.get(
    "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
  ).then(response => {
    if (response.status !== 200) {
      console.log("LOADING");
    } else {
      return response.data;
    }
  });
  let tasks = [];

  data.then(response => {
    tasks = response;
  });

  console.log(tasks);

  return tasks;
</code>```

Something like this, response data returns array of 8 items, but tasks is still empty which is normal because the axios request takes some time, I can use setTimeout for 100ms and inside it, I put console.log(tasks); and it will work but is not a proper solution, because what if the server takes 5s to returns the data?

This code is in my reducer, so I have to get my tasks and return them so I can display them, and show a loader when the request is executed.

This is my reducer :

```<code>import update from "immutability-helper";
import Axios from "axios";

export default function getTasksReducer(state = [], action) {
  switch (action.type) {
    case "GET_TASKS":
      let data = Axios.get(
        "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
      ).then(response => {
        if (response.status !== 200) {
          console.log("LOADING");
        } else {
          return response.data;
        }
      });
      let tasks = [];

      data.then(response => {
        tasks = response;
      });

      console.log(tasks);

      return tasks;
    default:
      return state;
  }
}
</code>```

I need some help in this code and also in the conception of it, I mean where should I change my loader state and so forth.

答:
As mentiond as in the other answers, I would setup my reducer only to handle state update and the action creator function to fetch data. Here is the minimal starting point if I were to do it. you can use the loading state to display loading spinners or progress bars.

my action creator function with the individual actions:

```<code>export const GET_TASKS_START = "GET_TASKS";
export const GET_TASKS_SUCCESS = "GET_TASKS_SUCCESS";
export const GET_TASKS_FAILURE = "GET_TASKS_FAILURE";

export const getData = () => dispatch => {
  dispatch(GET_TASKS_START);
  axios
    .get("http://localhost:8080/api/taskExecution?&search=&page=1&size=8")
    .then(response => {
      dispatch({ type: GET_TASKS_SUCESS, payload: response.data });
    })
    .catch(err => {
      dispatch({ type: GET_TASKS_FAILURE, payload: err.response });
    });
};
</code>```

and the reducer would handle the state update as follows:

```<code>import {
  GET_TASKS_SUCCESS,
  GET_TASKS_FAILURE,
  GET_TASKS_START
} from "./Action.js";

const initialState = {
  tasks: [],
  error: null,
  loading: false
};
export default function tasksReducer(state = initialState, action) {
  switch (action.type) {
    case GET_TASKS_START:
      return {
        ...state,
        loading: true
      };
    case GET_TASKS_SUCCESS:
      return {
        ...state,
        loading: false,
        tasks: action.payload,
        error: null
      };
    case GET_TASKS_FAILURE:
      return {
        ...state,
        loading: false,
        error: action.payload
      };
  }
}
</code>```

I would suggest console logging and checking the responses  (data and errors ) and modify the two functions accordingly

Body:
I am having a problem, I believe many of you have faced it somehow, so I am using axios to get my data :

 let data = axios.get(
    "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
  ).then(response => {
    if (response.status !== 200) {
      console.log("LOADING");
    } else {
      return response.data;
    }
  });
  let tasks = [];

  data.then(response => {
    tasks = response;
  });

  console.log(tasks);

  return tasks;

Something like this, response data returns array of 8 items, but tasks is still empty which is normal because the axios request takes some time, I can use setTimeout for 100ms and inside it, I put console.log(tasks); and it will work but is not a proper solution, because what if the server takes 5s to returns the data?

This code is in my reducer, so I have to get my tasks and return them so I can display them, and show a loader when the request is executed.

This is my reducer :

import update from "immutability-helper";
import Axios from "axios";

export default function getTasksReducer(state = [], action) {
  switch (action.type) {
    case "GET_TASKS":
      let data = Axios.get(
        "http://localhost:8080/api/taskExecution?&search=&page=1&size=8"
      ).then(response => {
        if (response.status !== 200) {
          console.log("LOADING");
        } else {
          return response.data;
        }
      });
      let tasks = [];

      data.then(response => {
        tasks = response;
      });

      console.log(tasks);

      return tasks;
    default:
      return state;
  }
}

I need some help in this code and also in the conception of it, I mean where should I change my loader state and so forth.

Body:
As mentiond as in the other answers, I would setup my reducer only to handle state update and the action creator function to fetch data. Here is the minimal starting point if I were to do it. you can use the loading state to display loading spinners or progress bars.

my action creator function with the individual actions:

export const GET_TASKS_START = "GET_TASKS";
export const GET_TASKS_SUCCESS = "GET_TASKS_SUCCESS";
export const GET_TASKS_FAILURE = "GET_TASKS_FAILURE";

export const getData = () => dispatch => {
  dispatch(GET_TASKS_START);
  axios
    .get("http://localhost:8080/api/taskExecution?&search=&page=1&size=8")
    .then(response => {
      dispatch({ type: GET_TASKS_SUCESS, payload: response.data });
    })
    .catch(err => {
      dispatch({ type: GET_TASKS_FAILURE, payload: err.response });
    });
};

and the reducer would handle the state update as follows:

import {
  GET_TASKS_SUCCESS,
  GET_TASKS_FAILURE,
  GET_TASKS_START
} from "./Action.js";

const initialState = {
  tasks: [],
  error: null,
  loading: false
};
export default function tasksReducer(state = initialState, action) {
  switch (action.type) {
    case GET_TASKS_START:
      return {
        ...state,
        loading: true
      };
    case GET_TASKS_SUCCESS:
      return {
        ...state,
        loading: false,
        tasks: action.payload,
        error: null
      };
    case GET_TASKS_FAILURE:
      return {
        ...state,
        loading: false,
        error: action.payload
      };
  }
}

I would suggest console logging and checking the responses  (data and errors ) and modify the two functions accordingly


问:
Why UITableViewCell dynamic view constraint not working properly?
I am trying to create UIButton inside the UITableViewCell using following way

UITableView configuration :

```<code>self.tableView.estimatedRowHeight = 1
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.delegate = self
self.tableView.dataSource = self
</code>```

UITableViewCell:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let uiTableViewCell = UITableViewCell(style: .default, reuseIdentifier: "More");
uiTableViewCell.contentView.backgroundColor = .yellow
let moreBtn = UIButton(type: .system)
moreBtn.setTitle("More", for: .normal)
moreBtn.setTitleColor(.white, for: .normal)
moreBtn.backgroundColor = UIColor.init(hexString: "#2A1771")

moreBtn.translatesAutoresizingMaskIntoConstraints = false
uiTableViewCell.contentView.addSubview(moreBtn)

let leading = NSLayoutConstraint(item: moreBtn, attribute: .leading, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .leading, multiplier: 1, constant: 16)
let trailing = NSLayoutConstraint(item: moreBtn, attribute: .trailing, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .trailing, multiplier: 1, constant: 16)
let top = NSLayoutConstraint(item: moreBtn, attribute: .top, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .top, multiplier: 1, constant: 16)
let bottom = NSLayoutConstraint(item: moreBtn, attribute: .bottom, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .bottom, multiplier: 1, constant: 16)

let height = NSLayoutConstraint(item: moreBtn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 52)

uiTableViewCell.contentView.addConstraints([leading,top,trailing,bottom,height])
NSLayoutConstraint.activate([leading,top,trailing,bottom,height])

return uiTableViewCell

}
</code>```

See this following image.. Why more button going outside from contentView

答:
Your constraints are saying the the button's trailing edge should be 16 more than the content view trailing edge (The constant is +16) and similarly for the bottom edge.

You can either swap the item and toItem properties in those constraints or use -16 as the constant.

You will also have a problem with adding the button in cellForRow as cells are reused when the table view scrolls, resulting in multiple buttons being added to a cell.  You should add the button in the cell itself, either in the initialiser or in awakeFromNib

Body:
I am trying to create UIButton inside the UITableViewCell using following way

UITableView configuration :

self.tableView.estimatedRowHeight = 1
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.delegate = self
self.tableView.dataSource = self

UITableViewCell:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let uiTableViewCell = UITableViewCell(style: .default, reuseIdentifier: "More");
uiTableViewCell.contentView.backgroundColor = .yellow
let moreBtn = UIButton(type: .system)
moreBtn.setTitle("More", for: .normal)
moreBtn.setTitleColor(.white, for: .normal)
moreBtn.backgroundColor = UIColor.init(hexString: "#2A1771")

moreBtn.translatesAutoresizingMaskIntoConstraints = false
uiTableViewCell.contentView.addSubview(moreBtn)

let leading = NSLayoutConstraint(item: moreBtn, attribute: .leading, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .leading, multiplier: 1, constant: 16)
let trailing = NSLayoutConstraint(item: moreBtn, attribute: .trailing, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .trailing, multiplier: 1, constant: 16)
let top = NSLayoutConstraint(item: moreBtn, attribute: .top, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .top, multiplier: 1, constant: 16)
let bottom = NSLayoutConstraint(item: moreBtn, attribute: .bottom, relatedBy: .equal, toItem: uiTableViewCell.contentView, attribute: .bottom, multiplier: 1, constant: 16)

let height = NSLayoutConstraint(item: moreBtn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 52)

uiTableViewCell.contentView.addConstraints([leading,top,trailing,bottom,height])
NSLayoutConstraint.activate([leading,top,trailing,bottom,height])

return uiTableViewCell

}

See this following image.. Why more button going outside from contentView


问:
android- can not make the app multi language
I want to have a multi language app , I've made the recourse file like this :

I've put a string inside each string.xml file "welcome" with the different translates

this is my class :

```<code>public class MyContextWrapper extends ContextWrapper {

public MyContextWrapper(Context base) {
    super(base);
}

@SuppressWarnings("deprecation")
public static ContextWrapper wrap(Context context, String language) {
    Configuration config = context.getResources().getConfiguration();
    Locale sysLocale = null;
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
        sysLocale = getSystemLocale(config);
    } else {
        sysLocale = getSystemLocaleLegacy(config);
    }
    if (!language.equals("") && !sysLocale.getLanguage().equals(language)) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            setSystemLocale(config, locale);
        } else {
            setSystemLocaleLegacy(config, locale);
        }

    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        context = context.createConfigurationContext(config);
    } else {
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
    }
    return new MyContextWrapper(context);
}

@SuppressWarnings("deprecation")
public static Locale getSystemLocaleLegacy(Configuration config){
    return config.locale;
}

@TargetApi(Build.VERSION_CODES.N)
public static Locale getSystemLocale(Configuration config){
    return config.getLocales().get(0);
}

@SuppressWarnings("deprecation")
public static void setSystemLocaleLegacy(Configuration config, Locale locale){
    config.locale = locale;
}

@TargetApi(Build.VERSION_CODES.N)
public static void setSystemLocale(Configuration config, Locale locale){
    config.setLocale(locale);
}
</code>```

this is my first activity and how I call it  :

```<code> @Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(MyContextWrapper.wrap(newBase,"fa"));
}
</code>```

the problem is , it always returns the value from values directory , so it doesn't work .

what is wrong ?

答:
try this code to change language of your app whatever the device language  :</p>

```<code>   Locale locale = new Locale("ar");
   Locale.setDefault(locale);
   Resources res = context.getResources();
   Configuration config = new Configuration();
   DisplayMetrics dm = res.getDisplayMetrics();
   config.locale = locale;
   context.getResources().updateConfiguration(config, dm);
</code>```

Body:
I want to have a multi language app , I've made the recourse file like this :

I've put a string inside each string.xml file "welcome" with the different translates

this is my class :

public class MyContextWrapper extends ContextWrapper {

public MyContextWrapper(Context base) {
    super(base);
}

@SuppressWarnings("deprecation")
public static ContextWrapper wrap(Context context, String language) {
    Configuration config = context.getResources().getConfiguration();
    Locale sysLocale = null;
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
        sysLocale = getSystemLocale(config);
    } else {
        sysLocale = getSystemLocaleLegacy(config);
    }
    if (!language.equals("") && !sysLocale.getLanguage().equals(language)) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            setSystemLocale(config, locale);
        } else {
            setSystemLocaleLegacy(config, locale);
        }

    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        context = context.createConfigurationContext(config);
    } else {
        context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
    }
    return new MyContextWrapper(context);
}

@SuppressWarnings("deprecation")
public static Locale getSystemLocaleLegacy(Configuration config){
    return config.locale;
}

@TargetApi(Build.VERSION_CODES.N)
public static Locale getSystemLocale(Configuration config){
    return config.getLocales().get(0);
}

@SuppressWarnings("deprecation")
public static void setSystemLocaleLegacy(Configuration config, Locale locale){
    config.locale = locale;
}

@TargetApi(Build.VERSION_CODES.N)
public static void setSystemLocale(Configuration config, Locale locale){
    config.setLocale(locale);
}

this is my first activity and how I call it  :

 @Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(MyContextWrapper.wrap(newBase,"fa"));
}

the problem is , it always returns the value from values directory , so it doesn't work .

what is wrong ?

Body:
try this code to change language of your app whatever the device language  :

   Locale locale = new Locale("ar");
   Locale.setDefault(locale);
   Resources res = context.getResources();
   Configuration config = new Configuration();
   DisplayMetrics dm = res.getDisplayMetrics();
   config.locale = locale;
   context.getResources().updateConfiguration(config, dm);


问:
How do you return an array of structs from a function in C?
I'm trying to create an array of structs and fread file data in to the array inside a helper function. I keep getting incompatible pointer type errors when I compile the program. This is my current code:

```<code> struct fentry *read_fentries(FILE *fp){
    fentry *files[MAXFILES];

    // EXTRACT FENTRIES AND FNODES FROM FILE
    if ((fread(files, sizeof(fentry), MAXFILES, fp)) == 0) {
        fprintf(stderr, "Error: could not read file entries\n");
        closefs(fp);
        exit(1);
    }
    return files;
}
</code>```

My main question is how can I create an array of structs of a pre-defined size (MAXFILES) and return it from a function so that I can access the struct array inside my main. Would I have to allocate memory using malloc?

答:
you can also return be the value if you wrap the array. </p>

```<code>#define MAXFILES 50

struct _fentry
{
    FILE *fp;
    int somedata[3];
    double anotherdata[10];
    /* ... */
};

struct fentry
{
    struct _fentry entries[MAXFILES];
};

struct fentry foo()
{
    struct fentry entries;

    /* .... */

    return entries;
}
</code>```

Body:
I'm trying to create an array of structs and fread file data in to the array inside a helper function. I keep getting incompatible pointer type errors when I compile the program. This is my current code:

 struct fentry *read_fentries(FILE *fp){
    fentry *files[MAXFILES];

    // EXTRACT FENTRIES AND FNODES FROM FILE
    if ((fread(files, sizeof(fentry), MAXFILES, fp)) == 0) {
        fprintf(stderr, "Error: could not read file entries\n");
        closefs(fp);
        exit(1);
    }
    return files;
}

My main question is how can I create an array of structs of a pre-defined size (MAXFILES) and return it from a function so that I can access the struct array inside my main. Would I have to allocate memory using malloc?

Body:
you can also return be the value if you wrap the array.

#define MAXFILES 50

struct _fentry
{
    FILE *fp;
    int somedata[3];
    double anotherdata[10];
    /* ... */
};

struct fentry
{
    struct _fentry entries[MAXFILES];
};

struct fentry foo()
{
    struct fentry entries;

    /* .... */

    return entries;
}


问:
Posting to WCF Service sending NULL values
I'm trying to post to my WCF Service from an iPhone app. I have the app posting to the service and trying to send data in the form of a service data contract in XML like below:

```<code>NSData *myPostData = [[NSString stringWithFormat:@"<AddMediaItem xmlns='http://www.example.com'><Item xmlns:a='http://www.example.com/MediaItem'><a:MediaType>iPhone</a:MediaType><a:Description>Description</a:Description><a:Name>Test</a:Name><a:ImageType>JPEG</a:ImageType></Item></AddMediaItem>"] dataUsingEncoding:NSUTF8StringEncoding];

NSMutableData *myMutablePostData = [NSMutableData dataWithData:myPostData];

[request setPostBody:myMutablePostData];
[request setRequestMethod:@"POST"];
[request addRequestHeader:@"Content-Type" value:@"application/xml"];

[request setDidFinishSelector:@selector(uploadFinished:)];
[request setDidFailSelector:@selector(uploadFailed:)];
[request setDelegate:self];
[request startAsynchronous];
</code>```

For testing purposes, I've setup my service to return the data contract that I send to the service. However, when it returns, some of the values seem to be NULLs although from the code above, I am giving them values.

What also seems strange is that the Name data member always has a value, but the other 3 I'm sending return NULL or with the correct values based on the order they appear in the XML I post to the service.

Below is the code for my service contract:

```<code>[ServiceContract(Namespace = "http://www.example.com")]
public interface IImageDiaryService
{

    [OperationContract]
    [WebInvoke(UriTemplate = "AddMediaItem", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
    MediaItem AddMediaItem(MediaItem Item);

}
</code>```

Below is my code for my MediaItem data contract:

```<code>[DataContract(Namespace = "http://www.example.com/MediaItem")]
public class MediaItem
{

    [DataMember]
    public Int32 Id { get; set; }

    [DataMember]
    public String Name { get; set; }

    [DataMember]
    public String Description { get; set; }

    [DataMember]
    public String ImageData { get; set; }

    [DataMember]
    public String ImageType { get; set; }

    [DataMember]
    public String MediaType { get; set; }

}
</code>```

Do let me know if you need any further code.

Any help is much appreciated.

答:
The DataContractSerializer only deserializes in the known order. As carlosfigueira says, default is alphabetical but you can specify an order. Yours aren't alphabetical and so I would expect that you are having server-side serialization issues.

I'd suggest you log what's happening server side. Is the request deserializing correctly inside your service? This will tell you where the data is going missing.

Body:
I'm trying to post to my WCF Service from an iPhone app. I have the app posting to the service and trying to send data in the form of a service data contract in XML like below:

NSData *myPostData = [[NSString stringWithFormat:@"<AddMediaItem xmlns='http://www.example.com'><Item xmlns:a='http://www.example.com/MediaItem'>iPhoneDescriptionTestJPEG</Item></AddMediaItem>"] dataUsingEncoding:NSUTF8StringEncoding];

NSMutableData *myMutablePostData = [NSMutableData dataWithData:myPostData];

[request setPostBody:myMutablePostData];
[request setRequestMethod:@"POST"];
[request addRequestHeader:@"Content-Type" value:@"application/xml"];

[request setDidFinishSelector:@selector(uploadFinished:)];
[request setDidFailSelector:@selector(uploadFailed:)];
[request setDelegate:self];
[request startAsynchronous];

For testing purposes, I've setup my service to return the data contract that I send to the service. However, when it returns, some of the values seem to be NULLs although from the code above, I am giving them values.

What also seems strange is that the Name data member always has a value, but the other 3 I'm sending return NULL or with the correct values based on the order they appear in the XML I post to the service.

Below is the code for my service contract:

[ServiceContract(Namespace = "http://www.example.com")]
public interface IImageDiaryService
{

    [OperationContract]
    [WebInvoke(UriTemplate = "AddMediaItem", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
    MediaItem AddMediaItem(MediaItem Item);

}

Below is my code for my MediaItem data contract:

[DataContract(Namespace = "http://www.example.com/MediaItem")]
public class MediaItem
{

    [DataMember]
    public Int32 Id { get; set; }

    [DataMember]
    public String Name { get; set; }

    [DataMember]
    public String Description { get; set; }

    [DataMember]
    public String ImageData { get; set; }

    [DataMember]
    public String ImageType { get; set; }

    [DataMember]
    public String MediaType { get; set; }

}

Do let me know if you need any further code.

Any help is much appreciated.


问:
Showing error for multiple empty inputs vuejs vuetify
I have three inputs as externalIP as External Host, externalHttpPort as Port and vendor as Vendor, I want to show error message if any of them is missing. but being specific about the name,

```<code>if (!this.externalIP || !this.externalHttpPort || !this.vendor) {
</code>```

when I do if condition, this works but I am not sure how I can tell if which input is empty. only one way which left is to add 3 multiple if

something like this

```<code>  let error;
  error = !this.externalIP
    ? "External IP Address (or URL) is incorrect"
    : "" || !this.externalHttpPort
    ? "Port is missing" : "" || !this.vendor
    ? "Please choose camera vendor or add your camera snapshot URL." : ""
  if (!error == "") {
    this.setNotification({
      text: error,
      color: "warning",
      snackbar: true
    })
    return
  }
</code>```

is there any other way of doing it? Also, Eslint show warning on indentations as well

答:
In this way, you can achieve the same result as by your logic without using multiple if. Also, this way will keep your template & logic clean/easily scalable.

new Vue({
  el: '#app',

  data: {
    fields: [
      {
        key: 'externalIP',
        value: '',
        validationMessage: 'External IP Address (or URL) is incorrect'
      },
      {
        key: 'externalHttpPort',
        value: '',
        validationMessage: 'Port is missing'
      },
      {
        key: 'vendor',
        value: '',
        validationMessage: 'Please choose camera vendor or add your camera snapshot URL.'
      }
    ]
  },

  computed: {
    getError () {
      let e = ''
      for (let i in this.fields) {
        if (!this.fields[i].value) {
          e = this.fields[i].validationMessage
          break
        }
      }
      return e
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">

  <input
    v-for="(field, i) in fields"
    :key="i"
    v-model="fields[i].value"
  />

  <br>{{ getError }}
</div></code>```

Body:
I have three inputs as externalIP as External Host, externalHttpPort as Port and vendor as Vendor, I want to show error message if any of them is missing. but being specific about the name,

if (!this.externalIP || !this.externalHttpPort || !this.vendor) {

when I do if condition, this works but I am not sure how I can tell if which input is empty. only one way which left is to add 3 multiple if

something like this

  let error;
  error = !this.externalIP
    ? "External IP Address (or URL) is incorrect"
    : "" || !this.externalHttpPort
    ? "Port is missing" : "" || !this.vendor
    ? "Please choose camera vendor or add your camera snapshot URL." : ""
  if (!error == "") {
    this.setNotification({
      text: error,
      color: "warning",
      snackbar: true
    })
    return
  }

is there any other way of doing it? Also, Eslint show warning on indentations as well

Body:
In this way, you can achieve the same result as by your logic without using multiple if. Also, this way will keep your template & logic clean/easily scalable.

new Vue({
  el: '#app',

  data: {
    fields: [
      {
        key: 'externalIP',
        value: '',
        validationMessage: 'External IP Address (or URL) is incorrect'
      },
      {
        key: 'externalHttpPort',
        value: '',
        validationMessage: 'Port is missing'
      },
      {
        key: 'vendor',
        value: '',
        validationMessage: 'Please choose camera vendor or add your camera snapshot URL.'
      }
    ]
  },

  computed: {
    getError () {
      let e = ''
      for (let i in this.fields) {
        if (!this.fields[i].value) {
          e = this.fields[i].validationMessage
          break
        }
      }
      return e
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">

  <input
    v-for="(field, i) in fields"
    :key="i"
    v-model="fields[i].value"
  />

  <br>{{ getError }}
</div>


问:
SQL query grammatical exception on converting recursive query to JPQL
This is a JPQl query created from the below mentioned SQL query:

```<code>SELECT * FROM NursingSectionHead head where head.secCode IN (" +
            "WITH NUR_SECTIONS_SEC_CODE (secCode) " +
            "AS (SELECT secCode " +
            "FROM NursingSection " +
            "WHERE secCode = (SELECT loc.nursingSecCode FROM LocationMast loc WHERE loc.id.locCode = :locCode) " +
            "UNION ALL " +
            "SELECT C1.secCode " +
            "FROM NursingSection C1 " +
            "INNER JOIN NUR_SECTIONS_SEC_CODE C2 ON C1.prevSec = C2.secCode)" +
            "SELECT * FROM NUR_SECTIONS_SEC_CODE)
</code>```

This is the SQL query:

```<code>select * from IR_TB_NUR_SEC_HEAD head where HEAD.SEC_CODE IN (
WITH NUR_SECTIONS_SEC_CODE (SEC_CODE)
AS (
     SELECT SEC_CODE
    FROM IR_TB_NUR_SECTIONS
    WHERE SEC_CODE = (select LOC.NURSING_SEC_CODE from mst_tb_location_mast loc where LOC.LOC_CODE = 20023)

    UNION ALL

    SELECT C1.SEC_CODE
    FROM IR_TB_NUR_SECTIONS C1
    INNER JOIN NUR_SECTIONS_SEC_CODE C2 ON C1.PREV_SEC = C2.SEC_CODE
    )
SELECT *
FROM NUR_SECTIONS_SEC_CODE)
</code>```

When executing it returns the below error:

"org.springframework.dao.InvalidDataAccessResourceUsageException:
  could not extract ResultSet; SQL [n/a]; nested exception is
  org.hibernate.exception.SQLGrammarException: could not extract
  ResultSet"

What can I do about the above exception, please?

答:
The "WITH" clause you are using  is known as Common Table Expression (CTE) .I am pretty sure CTE is not supported by JPQL because if it is supported , no one will specially develop a library for supporting CTE query but only for Hibernate.

But you can switch to do use native SQL which should always work provided that your query can really be executed successfully against the database that you are using.

Body:
This is a JPQl query created from the below mentioned SQL query:

SELECT * FROM NursingSectionHead head where head.secCode IN (" +
            "WITH NUR_SECTIONS_SEC_CODE (secCode) " +
            "AS (SELECT secCode " +
            "FROM NursingSection " +
            "WHERE secCode = (SELECT loc.nursingSecCode FROM LocationMast loc WHERE loc.id.locCode = :locCode) " +
            "UNION ALL " +
            "SELECT C1.secCode " +
            "FROM NursingSection C1 " +
            "INNER JOIN NUR_SECTIONS_SEC_CODE C2 ON C1.prevSec = C2.secCode)" +
            "SELECT * FROM NUR_SECTIONS_SEC_CODE)

This is the SQL query:

select * from IR_TB_NUR_SEC_HEAD head where HEAD.SEC_CODE IN (
WITH NUR_SECTIONS_SEC_CODE (SEC_CODE)
AS (
     SELECT SEC_CODE
    FROM IR_TB_NUR_SECTIONS
    WHERE SEC_CODE = (select LOC.NURSING_SEC_CODE from mst_tb_location_mast loc where LOC.LOC_CODE = 20023)

    UNION ALL

    SELECT C1.SEC_CODE
    FROM IR_TB_NUR_SECTIONS C1
    INNER JOIN NUR_SECTIONS_SEC_CODE C2 ON C1.PREV_SEC = C2.SEC_CODE
    )
SELECT *
FROM NUR_SECTIONS_SEC_CODE)

When executing it returns the below error:

"org.springframework.dao.InvalidDataAccessResourceUsageException:
  could not extract ResultSet; SQL [n/a]; nested exception is
  org.hibernate.exception.SQLGrammarException: could not extract
  ResultSet"

What can I do about the above exception, please?


问:
Can anything done with google apps scripts be done with the google API?
I noticed that the Google Apps Script editor uses a Bearer token to make requests for a lot of things, that got me thinking: Is it possible to do all functions that are done with the google apps script with the google API on your own server? What is the essential difference? Just the fact that google apps script runs on google servers, while with the google API you would need to create your own servers?

For example many of the document functions, which I thought could only be done with the API, turns out can be found here https://developers.google.com/docs/api/reference/rest/v1/documents/request#InsertInlineImageRequest

so whats the essential difference?

答:
Just the fact that google apps script runs on google servers, while with the google API you would need to create your own servers?

Yes. There are advantages to both methods:

API:

It's a rest API. You can use your own language(eg: Python) in your servers.

The api is more inclusive. There are  stuff which can be done with the api, which cannot be accomplished  with apps script.

User can set limited scopes for using API.

For example, at Drive API, https://www.googleapis.com/auth/drive.file can be used for Drive API. The same cannot be done with DriveApp of apps script.

Process cost of API is lower than that of the built-in methods for Google Apps Script1 2

Apps script:

No server on your side

Triggers. You can set up functions to run onEdit,onOpen or at a specific time.

Deep integration with Google apps: Sidebars/modal dialogs can only be done with apps script.

All methods of the api can be accessed indirectly through the bearer token.

Authorization/authentication is taken care of by apps script. You don't need to set up oauth.


问:
How do I declare the root element of an XML document in the XSD schema?
I am working on a problem for XML class, and I am new at it. My XSD file validates. The XML file has the following validation error: Cannot find the declaration of element 'catalog'. The XSD filename is catalog.xsd and the XSD code where the element "catalog" is declared is

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

   <xs:element name="description" type="xs:string" />
   <xs:element name="date" type="xs:string" />
   <xs:attribute name="metadata" type="xs:string" />
   <xs:attribute name="cid" type="cidType" />
   <xs:attribute name="src" type="srcType" />
   <xs:attribute name="donatedBy" type="xs:string" />

   <xs:simpleType name="cidType">
      <xs:restriction base="xs:ID">
         <xs:pattern value="c\d{4}" />
      </xs:restriction>
   </xs:simpleType>

   <xs:simpleType name="srcType">
      <xs:restriction base="xs:string">
         <xs:pattern value="[a-zA-Z0-9]+.jpg" />
      </xs:restriction>
   </xs:simpleType>

   <xs:complexType name="catalog">
      <xs:sequence>
         <xs:element name="photo" minOccurs="1" maxOccurs="unbounded" />
      </xs:sequence>
   </xs:complexType>
</code>```

I have been able to resolve all other validation errors, so the two files appear to be referencing each other properly. Is there a step I have missed? Should the "catalog" element be declared in another way?

Thank you!

I am adding the XML code, I did think that perhaps I was missing something there. The file name for the xml is catalog.xml.

```<code>
<catalog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="catalog.xsd">

   <photo cid="c1748" donatedBy="John Borelli">
      <name metadata="tunis cooper property museum">Tunis R. Cooper property</name>
      <description>
      <![CDATA[
         This photo was taken by John Borelli's great-grandfather. It is believed to have been taken around 1830.
         David Demarest originally purchased the site of the chair factory in 1663. This site was under the ownership
         of the Demarest family until 1758.  The property is listed in the National and New Jersey Registers of Historic Places.
      ]]>
      </description>
      <date>circa 1830</date>
      <images>
         <img src="1748a.jpg" />
         <img src="1748b.jpg" />
      </images>
   </photo>

</code>```

答:
The answer to your headline question is, you can't. XSD by design considers every subtree of a valid element to be valid in its own right, and to ensure that this property holds, it doesn't allow the schema to say that element E is a legitimate validation root when its children F, G, and H aren't.

But reading past the headline, that's not your problem. You don't need to declare that catalog is the root element of the document, you just need to declare it.

And from what you have shown, it looks as if you have done so. The two most likely reasons for the error are therefore:

(a) your instance document is actually rooted at a catalog element in a different namespace

(b) you didn't actually succeed in loading this schema document and supplying it to the validator. You say that you have "resolved other validation errors" so this suggests you are picking up the schema, so perhaps (a) is more likely.

To diagnose (a) we would need to see the instance document. To diagnose (b) we would need to see how you are invoking the schema validator.

Body:
I am working on a problem for XML class, and I am new at it. My XSD file validates. The XML file has the following validation error: Cannot find the declaration of element 'catalog'. The XSD filename is catalog.xsd and the XSD code where the element "catalog" is declared is

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

   <xs:element name="description" type="xs:string" />
   <xs:element name="date" type="xs:string" />
   <xs:attribute name="metadata" type="xs:string" />
   <xs:attribute name="cid" type="cidType" />
   <xs:attribute name="src" type="srcType" />
   <xs:attribute name="donatedBy" type="xs:string" />

   <xs:simpleType name="cidType">
      <xs:restriction base="xs:ID">
         <xs:pattern value="c\d{4}" />
      </xs:restriction>
   </xs:simpleType>

   <xs:simpleType name="srcType">
      <xs:restriction base="xs:string">
         <xs:pattern value="[a-zA-Z0-9]+.jpg" />
      </xs:restriction>
   </xs:simpleType>

   <xs:complexType name="catalog">
      <xs:sequence>
         <xs:element name="photo" minOccurs="1" maxOccurs="unbounded" />
      </xs:sequence>
   </xs:complexType>

I have been able to resolve all other validation errors, so the two files appear to be referencing each other properly. Is there a step I have missed? Should the "catalog" element be declared in another way?

Thank you!

I am adding the XML code, I did think that perhaps I was missing something there. The file name for the xml is catalog.xml.

<catalog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="catalog.xsd">

   <photo cid="c1748" donatedBy="John Borelli">
      <name metadata="tunis cooper property museum">Tunis R. Cooper property</name>
      <description>
      <![CDATA[
         This photo was taken by John Borelli's great-grandfather. It is believed to have been taken around 1830.
         David Demarest originally purchased the site of the chair factory in 1663. This site was under the ownership
         of the Demarest family until 1758.  The property is listed in the National and New Jersey Registers of Historic Places.
      ]]>
      </description>
      <date>circa 1830</date>
      <images>

      </images>
   </photo>


问:
Connection to OPENVPN using c#
I'm creating a VPN Client, with Ikve2 and openvpn when comes to IKV2 its straight forward but whereas OPENVPN I had really hard time dealing with OVPN files, as i'm using FREERadius as authentication how can I pass username and password? I already tried connecting through
user-locked profile.</p>

答:
Check the FreeRadius .net Code here</p>

```<code>//args = new string[4];
//args[0] = "192.168.1.1";
//args[1] = "secret";
//args[2] = "username";
//args[3] = "password";
</code>```

```<code>RadiusClient rc = new RadiusClient(args[0], args[1]);
// Use username/password here
RadiusPacket authPacket = rc.Authenticate(args[2], args[3]);
authPacket.SetAttribute(new VendorSpecificAttribute(10135, 1, UTF8Encoding.UTF8.GetBytes("Testing")));
authPacket.SetAttribute(new VendorSpecificAttribute(10135, 2, new[] { (byte)7 }));
RadiusPacket receivedPacket = await rc.SendAndReceivePacket(authPacket);
</code>```

Title: Connection to OPENVPN using c#

Body:
Check the FreeRadius .net Code here

//args = new string[4];
//args[0] = "192.168.1.1";
//args[1] = "secret";
//args[2] = "username";
//args[3] = "password";

RadiusClient rc = new RadiusClient(args[0], args[1]);
// Use username/password here
RadiusPacket authPacket = rc.Authenticate(args[2], args[3]);
authPacket.SetAttribute(new VendorSpecificAttribute(10135, 1, UTF8Encoding.UTF8.GetBytes("Testing")));
authPacket.SetAttribute(new VendorSpecificAttribute(10135, 2, new[] { (byte)7 }));
RadiusPacket receivedPacket = await rc.SendAndReceivePacket(authPacket);