问:
Reference property in Gradle Properties
My gradle.properties.kts files has the following contents:

```<code>build_version=develop
build_version_code=2
include_vas=false
</code>```

In my build.gradle.kts looks as follows:

```<code>plugins {
    id(Plugins.androidApplication)
    kotlin(Plugins.kotlinAndroid)
    kotlin(Plugins.kotlinExtensions)
    kotlin(Plugins.kapt)
}

android {
    compileSdkVersion(Configs.compileVersion)
    defaultConfig {
        applicationId = Configs.applicationId
        minSdkVersion(Configs.minSdkVersion)
        targetSdkVersion(Configs.targetSdkVersion)
        testInstrumentationRunner = Configs.testInstrumentationRunner
        versionCode =
    }

  buildTypes{

  }
    repositories {
        flatDir {
            dirs("libs")
        }
    }

    dependencies {
        implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar", "*.arr"))))
        implementation(Libs.stdLib)
        implementation(Libs.sunmiui)
        implementation(Libs.slf4j)
        implementation(Libs.appCompact)
        implementation(Libs.otpView)
        implementation(Libs.vectordrawableAnimated)
        implementation(Libs.materialComponents)
        implementation(Libs.recyclerView)
        implementation(Libs.constraintLayout)
        implementation(Libs.junit)
        implementation(Libs.testRunner)
        implementation(Libs.expressoCore)
        implementation(Libs.lifecyleExtensions)
        implementation(Libs.lifecyleCompiler)
        implementation(Libs.roomRuntime)
        implementation(Libs.databindingCompiler)
        implementation(Libs.rxjava)
        implementation(Libs.rxjavaAndroid)
        implementation(Libs.glide)
        implementation(Libs.glideCompiler)
        implementation(Libs.gson)
        implementation(Libs.joda)
        implementation(Libs.countrycodePicker)
        implementation(Libs.timber)
        implementation(Libs.daggerandroidSupport)
        implementation(Libs.daggerandroidProcessor)
    }
</code>```

I am in the process of converting my current gradle scripts to kotlin DSL. The current challenge I am facing is that in the defaultConfig:

```<code>android {
    compileSdkVersion(Configs.compileVersion)
    defaultConfig {
        applicationId = Configs.applicationId
        minSdkVersion(Configs.minSdkVersion)
        targetSdkVersion(Configs.targetSdkVersion)
        testInstrumentationRunner = Configs.testInstrumentationRunner
        versionCode =
    }
</code>```

I refer to the versionCode that is defined in the gradle.properties. The code below was how it was done before the conversion.

```<code>defaultConfig
        {

            multiDexEnabled true
            applicationId "jfjfjrjrjr.comn.jejeu"
            minSdkVersion 24
            targetSdkVersion 28
            versionCode build_version_code as Integer
            versionName build_version
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }
</code>```

How can I do this in Kotlin

答:
What I ended up doing as suggested by @Jeel Vankhede is the following:</p>

```<code>defaultConfig {
    multiDexEnabled = true
    applicationId = Configs.applicationId
    minSdkVersion(Configs.minSdkVersion)
    targetSdkVersion(Configs.targetSdkVersion)
    var value = Integer.parseInt(project.property("build_version_code") as String?)
    versionCode = value
    versionName = project.property("build_version") as String?
    testInstrumentationRunner = Configs.testInstrumentationRunner
}
</code>```

Title: Reference property in Gradle Properties

Body:
My gradle.properties.kts files has the following contents:

build_version=develop
build_version_code=2
include_vas=false

In my build.gradle.kts looks as follows:

plugins {
    id(Plugins.androidApplication)
    kotlin(Plugins.kotlinAndroid)
    kotlin(Plugins.kotlinExtensions)
    kotlin(Plugins.kapt)
}

android {
    compileSdkVersion(Configs.compileVersion)
    defaultConfig {
        applicationId = Configs.applicationId
        minSdkVersion(Configs.minSdkVersion)
        targetSdkVersion(Configs.targetSdkVersion)
        testInstrumentationRunner = Configs.testInstrumentationRunner
        versionCode =
    }

  buildTypes{

  }
    repositories {
        flatDir {
            dirs("libs")
        }
    }

    dependencies {
        implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar", "*.arr"))))
        implementation(Libs.stdLib)
        implementation(Libs.sunmiui)
        implementation(Libs.slf4j)
        implementation(Libs.appCompact)
        implementation(Libs.otpView)
        implementation(Libs.vectordrawableAnimated)
        implementation(Libs.materialComponents)
        implementation(Libs.recyclerView)
        implementation(Libs.constraintLayout)
        implementation(Libs.junit)
        implementation(Libs.testRunner)
        implementation(Libs.expressoCore)
        implementation(Libs.lifecyleExtensions)
        implementation(Libs.lifecyleCompiler)
        implementation(Libs.roomRuntime)
        implementation(Libs.databindingCompiler)
        implementation(Libs.rxjava)
        implementation(Libs.rxjavaAndroid)
        implementation(Libs.glide)
        implementation(Libs.glideCompiler)
        implementation(Libs.gson)
        implementation(Libs.joda)
        implementation(Libs.countrycodePicker)
        implementation(Libs.timber)
        implementation(Libs.daggerandroidSupport)
        implementation(Libs.daggerandroidProcessor)
    }

I am in the process of converting my current gradle scripts to kotlin DSL. The current challenge I am facing is that in the defaultConfig:

android {
    compileSdkVersion(Configs.compileVersion)
    defaultConfig {
        applicationId = Configs.applicationId
        minSdkVersion(Configs.minSdkVersion)
        targetSdkVersion(Configs.targetSdkVersion)
        testInstrumentationRunner = Configs.testInstrumentationRunner
        versionCode =
    }

I refer to the versionCode that is defined in the gradle.properties. The code below was how it was done before the conversion.

defaultConfig
        {

            multiDexEnabled true
            applicationId "jfjfjrjrjr.comn.jejeu"
            minSdkVersion 24
            targetSdkVersion 28
            versionCode build_version_code as Integer
            versionName build_version
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }

How can I do this in Kotlin

Body:
What I ended up doing as suggested by @Jeel Vankhede is the following:

defaultConfig {
    multiDexEnabled = true
    applicationId = Configs.applicationId
    minSdkVersion(Configs.minSdkVersion)
    targetSdkVersion(Configs.targetSdkVersion)
    var value = Integer.parseInt(project.property("build_version_code") as String?)
    versionCode = value
    versionName = project.property("build_version") as String?
    testInstrumentationRunner = Configs.testInstrumentationRunner
}


来源: stackexchange

问:
C libcurl - Is it possible to get request data in raw format
In Libcurl C, using CURLOPT_DEBUGFUNCTION I can set a callback function. Libcurl calls callback and gives data for

CURLINFO_HEADER_IN

CURLINFO_HEADER_OUT

CURLINFO_DATA_IN

CURLINFO_DATA_OUT

CURLINFO_SSL_DATA_IN

CURLINFO_SSL_DATA_OUT

The tx data that is given for CURLINFO_SSL_DATA_OUT is in binary format (encrypted). I need corresponding raw data (unencrypted).

Is it possible?

答:
If you want to see what is actually transmitted, I would recommend using a man-in-the-middle HTTPS proxy.

The proxy is placed between your client and the server.

When a client normally communicates with a server via HTTPS, the client checks the server's certificate chain to see if it is signed by a root certificate trusted by the system.

Thus any proxy between client and server could only forward the data without the possibility to have a look into the encrypted data stream.

So how does it work, then?

Man-in-the-middle proxies intercept traffic and create a server certificate on-the-fly. So it looks to the client as if it is communicating with the server and vice versa.

However, if the client then evaluates the certificate chain, it encounters the root certificate of the proxy that it does not know and therefore does not trust, and terminates server communication immediately (if the client is configured correctly).

So that the proxy can take a look at the HTTPS data, you must include the proxy root certificate in your list of trusted root certificates on your client system.

The proxy can then show all data including the headers.

Some typical representatives of such proxies are (incomplete list):

mitmproxy (https://mitmproxy.org)

Charles (https://www.charlesproxy.com)

Fiddler (https://www.telerik.com/fiddler)

Different methods have different advantages and disadvantages. HTTPS proxies are especially useful when you want to analyze request and response including header quickly and efficiently.

Demo of mitmproxy with a libcurl program

For a quick demo one can use the example program from the libcurl site: https://curl.se/libcurl/c/simple.html:

```<code>gcc -o simple simple.c -lcurl
export https_proxy=localhost:8080
</code>```

In another terminal window one can start the mitmproxy. When the program is started, the request/response appears in mitmproxy and can be analyzed.

It looks like this then:

As mentioned above, you need to configure the appropriate root certificate as described on mitmproxy's website for different operating systems.

ContentLicense: CC BY-SA 4.0

Body:
If you want to see what is actually transmitted, I would recommend using a man-in-the-middle HTTPS proxy.

The proxy is placed between your client and the server.

When a client normally communicates with a server via HTTPS, the client checks the server's certificate chain to see if it is signed by a root certificate trusted by the system.

Thus any proxy between client and server could only forward the data without the possibility to have a look into the encrypted data stream.

So how does it work, then?

Man-in-the-middle proxies intercept traffic and create a server certificate on-the-fly. So it looks to the client as if it is communicating with the server and vice versa.

However, if the client then evaluates the certificate chain, it encounters the root certificate of the proxy that it does not know and therefore does not trust, and terminates server communication immediately (if the client is configured correctly).

So that the proxy can take a look at the HTTPS data, you must include the proxy root certificate in your list of trusted root certificates on your client system.

The proxy can then show all data including the headers.

Some typical representatives of such proxies are (incomplete list):

mitmproxy (https://mitmproxy.org)

Charles (https://www.charlesproxy.com)

Fiddler (https://www.telerik.com/fiddler)

Different methods have different advantages and disadvantages. HTTPS proxies are especially useful when you want to analyze request and response including header quickly and efficiently.

Demo of mitmproxy with a libcurl program

For a quick demo one can use the example program from the libcurl site: https://curl.se/libcurl/c/simple.html:

gcc -o simple simple.c -lcurl
export https_proxy=localhost:8080

In another terminal window one can start the mitmproxy. When the program is started, the request/response appears in mitmproxy and can be analyzed.

It looks like this then:

As mentioned above, you need to configure the appropriate root certificate as described on mitmproxy's website for different operating systems.


问:
R package: use a custom file/directories structure in pkg/R and pkg/src folders
I'm writing a R package which begins to grow in size, and so would really appreciate to use a custom structure in folders pkg/R/ and (especially) in pkg/src/.

For example, let's say I have two families of algorithms of some type A, and some functions of type B, and a main entry point. Ideally R/ or src/ folders would be organized as follow:

typeA/

algorithms1/

algo11.ext

...

algorithms2/

algo21.ext

...

typeB/

function1.ext

...

main.ext

with "ext" in {R,cpp,c,f,...}, and potentially two files having the same name.

Is it possible ? If yes, how can I do that ?

Thanks in advance !

[2012-12-31] EDIT: an idea would be to write a few scripts - maybe inside another R package - to (un)flatten a structured package for tests or diffusion. But there is probably a better solution, so I will wait a bit.

答:
The official package documentation https://cran.r-project.org/doc/manuals/r-devel/R-exts.html, section 1.1.5 contains this quote:

The R and man subdirectories may contain OS-specific subdirectories named unix or windows.

I've tried creating a simple test package with subdirectories in R-3.5.1 and it did not work properly.

Nor devtools::load_all() nor R CMD build successfully exported code from subdirectories in R.

ContentLicense: CC BY-SA 3.0


问:
Flink, how to deserialize protobuf using ProtobufSerializer?
I need to consume kafka via flink, unfortunately, the kafka message is using protobuf in serde, totally no idea how to deal with it, here is the code from internet, but I'm not able to make it work.

```<code>...
import com.google.protobuf.InvalidProtocolBufferException;
import com.twitter.chill.protobuf.ProtobufSerializer;

public class Protobuf2 {

    public static void main(String[] args) throws Exception {
        String inputTopic = "zz";
        String consumerGroup = "foobar";
        String address = "localhost:9092";
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
        environment.getConfig().registerTypeWithKryoSerializer(ExchangeMessage.Order.class, ProtobufSerializer.class);

        FlinkKafkaConsumer<ExchangeMessage.Order> flinkKafkaConsumer = createStringConsumerForTopic(inputTopic, address,
                consumerGroup);
        DataStream<ExchangeMessage.Order> input = environment.addSource(flinkKafkaConsumer);

        input.map(order ->
            {
                System.out.println("foooooooo, " + order.getOid());
                return order;
            });

        environment.execute("kafka02");
    }

    public static FlinkKafkaConsumer<ExchangeMessage.Order> createStringConsumerForTopic(String topic,
            String kafkaAddress, String kafkaGroup) {
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", kafkaAddress);
        props.setProperty("group.id", kafkaGroup);
        FlinkKafkaConsumer<ExchangeMessage.Order> consumer = new FlinkKafkaConsumer<>(topic,
                new OrderSerDeSchema(), props);
        return consumer;
    }

    @SuppressWarnings("serial")
    static class OrderSerDeSchema
            implements DeserializationSchema<ExchangeMessage.Order>, SerializationSchema<ExchangeMessage.Order> {

        @Override
        public ExchangeMessage.Order deserialize(byte[] message) throws IOException {
            ExchangeMessage.Order order = null;
            try {
                order = ExchangeMessage.Order.parseFrom(message);
            } catch (InvalidProtocolBufferException e) {
                e.printStackTrace();
            }
            return order;
        }

        @Override
        public boolean isEndOfStream(ExchangeMessage.Order nextElement) {
            return false;
        }

        @Override
        public TypeInformation<ExchangeMessage.Order> getProducedType() {
            return null;
        }

        @Override
        public byte[] serialize(ExchangeMessage.Order element) {
            return new byte[0];
        }
    }

}
</code>```

This doesn't work, it gives NPE:

```<code>Caused by: java.lang.NullPointerException
    at org.apache.flink.streaming.runtime.tasks.OperatorChain$CopyingChainingOutput.pushToOperator(OperatorChain.java:577)
    at org.apache.flink.streaming.runtime.tasks.OperatorChain$CopyingChainingOutput.collect(OperatorChain.java:554)
    at org.apache.flink.streaming.runtime.tasks.OperatorChain$CopyingChainingOutput.collect(OperatorChain.java:534)
    at org.apache.flink.streaming.api.operators.AbstractStreamOperator$CountingOutput.collect(AbstractStreamOperator.java:718)
    at ......
</code>```

Anyone know what am I doing wrong here? Is it the only way to deser the protobuf -- to use twitter ProtobufSerializer? Or there's another way to go?

答:
add dependency

```<code><dependency>
    <groupId>com.twitter</groupId>
    <artifactId>chill-protobuf</artifactId>
    <version>0.7.6</version>
</dependency>
<dependency>
    <groupId>org.apache.flink</groupId>
    <artifactId>flink-core</artifactId>
    <version>1.8.0</version>
</dependency>
</code>```

and add this in your code

```<code>env.getConfig().registerTypeWithKryoSerializer(MockMessageProto.MockMessage.class, ProtobufSerializer.class);
</code>```

maybe you will meet version conflict, change chill-protobuf version to fix it

Body:
I need to consume kafka via flink, unfortunately, the kafka message is using protobuf in serde, totally no idea how to deal with it, here is the code from internet, but I'm not able to make it work.

...
import com.google.protobuf.InvalidProtocolBufferException;
import com.twitter.chill.protobuf.ProtobufSerializer;

public class Protobuf2 {

    public static void main(String[] args) throws Exception {
        String inputTopic = "zz";
        String consumerGroup = "foobar";
        String address = "localhost:9092";
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
        environment.getConfig().registerTypeWithKryoSerializer(ExchangeMessage.Order.class, ProtobufSerializer.class);

        FlinkKafkaConsumer<ExchangeMessage.Order> flinkKafkaConsumer = createStringConsumerForTopic(inputTopic, address,
                consumerGroup);
        DataStream<ExchangeMessage.Order> input = environment.addSource(flinkKafkaConsumer);

        input.map(order ->
            {
                System.out.println("foooooooo, " + order.getOid());
                return order;
            });

        environment.execute("kafka02");
    }

    public static FlinkKafkaConsumer<ExchangeMessage.Order> createStringConsumerForTopic(String topic,
            String kafkaAddress, String kafkaGroup) {
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", kafkaAddress);
        props.setProperty("group.id", kafkaGroup);
        FlinkKafkaConsumer<ExchangeMessage.Order> consumer = new FlinkKafkaConsumer<>(topic,
                new OrderSerDeSchema(), props);
        return consumer;
    }

    @SuppressWarnings("serial")
    static class OrderSerDeSchema
            implements DeserializationSchema<ExchangeMessage.Order>, SerializationSchema<ExchangeMessage.Order> {

        @Override
        public ExchangeMessage.Order deserialize(byte[] message) throws IOException {
            ExchangeMessage.Order order = null;
            try {
                order = ExchangeMessage.Order.parseFrom(message);
            } catch (InvalidProtocolBufferException e) {
                e.printStackTrace();
            }
            return order;
        }

        @Override
        public boolean isEndOfStream(ExchangeMessage.Order nextElement) {
            return false;
        }

        @Override
        public TypeInformation<ExchangeMessage.Order> getProducedType() {
            return null;
        }

        @Override
        public byte[] serialize(ExchangeMessage.Order element) {
            return new byte[0];
        }
    }

}

This doesn't work, it gives NPE:

Caused by: java.lang.NullPointerException
    at org.apache.flink.streaming.runtime.tasks.OperatorChain$CopyingChainingOutput.pushToOperator(OperatorChain.java:577)
    at org.apache.flink.streaming.runtime.tasks.OperatorChain$CopyingChainingOutput.collect(OperatorChain.java:554)
    at org.apache.flink.streaming.runtime.tasks.OperatorChain$CopyingChainingOutput.collect(OperatorChain.java:534)
    at org.apache.flink.streaming.api.operators.AbstractStreamOperator$CountingOutput.collect(AbstractStreamOperator.java:718)
    at ......

Anyone know what am I doing wrong here? Is it the only way to deser the protobuf -- to use twitter ProtobufSerializer? Or there's another way to go?

Body:
add dependency

<dependency>
    <groupId>com.twitter</groupId>
    <artifactId>chill-protobuf</artifactId>
    <version>0.7.6</version>
</dependency>
<dependency>
    <groupId>org.apache.flink</groupId>
    <artifactId>flink-core</artifactId>
    <version>1.8.0</version>
</dependency>

and add this in your code

env.getConfig().registerTypeWithKryoSerializer(MockMessageProto.MockMessage.class, ProtobufSerializer.class);

maybe you will meet version conflict, change chill-protobuf version to fix it


问:
React Native Navigation Error building Android,:app@debug/compileClasspath': Could not resolve project :react-native-navigation
I'm trying to install react-native-navigation(wix) package, I'm following the steps on android(https://wix.github.io/react-native-navigation/#/installation-android) but in android studio the build fails with the message. Gradle 4.1( I don't know if this is related)

```<code>Could not resolve project :react-native-navigation.
Required by:
project :app

Unable to find a matching configuration of project :react-native-navigation: None of the consumable configurations have attributes.

Error:Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details

Error:Unable to resolve dependency for ':app@debugAndroidTest/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details

Error:Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details

Error:Unable to resolve dependency for ':app@release/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details

Error:Unable to resolve dependency for ':app@releaseUnitTest/compileClasspath': Could not resolve project :react-native-navigation.
</code>```

I leave the details below(my user is called home, is not a typo):

Issue Description
local.properties file

```<code>sdk.dir=/home/home/Android/Sdk
</code>```

settings.gradle

```<code>include ':app'
include ':react-native-navigation'
project(':react-native-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-navigation/android/app/')
App gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    defaultConfig {
        applicationId "com.example.home.myapplication"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "com.android.support:appcompat-v7:25.0.1"
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
   //tried implementation as well here instead of compile but didn't work either
   compile project(':react-native-navigation')

}
</code>```

Environment

React Native Navigation version: "1.1.370"

React Native version: "0.52.0"

Platform(s) (iOS, Android, or both?): Android

Device info (Simulator/Device? OS version? Debug/Release?): Android Studio

Which version of gradle and android api should I use with react native? Is there any way to solve this? I see that my app gradle file is nothing alike the instructions, that compile project statement is not valid in my version of gradle. Any idea? Maybe the local.settings is wrong and is not finding the files?...Any help would be appreciated

答: Do you have the Android SDK 27 installed? Open your Android SDK Manager in Android Studio and make sure you install that version there. Also try creating an emulator that is based on that version. </p>

Body:
I'm trying to install react-native-navigation(wix) package, I'm following the steps on android(https://wix.github.io/react-native-navigation/#/installation-android) but in android studio the build fails with the message. Gradle 4.1( I don't know if this is related)

Could not resolve project :react-native-navigation.
Required by:
project :app

Unable to find a matching configuration of project :react-native-navigation: None of the consumable configurations have attributes.

Error:Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details

Error:Unable to resolve dependency for ':app@debugAndroidTest/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details

Error:Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details

Error:Unable to resolve dependency for ':app@release/compileClasspath': Could not resolve project :react-native-navigation.
Open File
Show Details

Error:Unable to resolve dependency for ':app@releaseUnitTest/compileClasspath': Could not resolve project :react-native-navigation.

I leave the details below(my user is called home, is not a typo):

Issue Description
local.properties file

sdk.dir=/home/home/Android/Sdk

settings.gradle

include ':app'
include ':react-native-navigation'
project(':react-native-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-navigation/android/app/')
App gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    defaultConfig {
        applicationId "com.example.home.myapplication"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "com.android.support:appcompat-v7:25.0.1"
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
   //tried implementation as well here instead of compile but didn't work either
   compile project(':react-native-navigation')

}

Environment

React Native Navigation version: "1.1.370"

React Native version: "0.52.0"

Platform(s) (iOS, Android, or both?): Android

Device info (Simulator/Device? OS version? Debug/Release?): Android Studio

Which version of gradle and android api should I use with react native? Is there any way to solve this? I see that my app gradle file is nothing alike the instructions, that compile project statement is not valid in my version of gradle. Any idea? Maybe the local.settings is wrong and is not finding the files?...Any help would be appreciated


问:
Syntax error or access violation: 1064 You have an error in your SQL syntax in alter table
I am trying to alter the auto_increment by laravel stament function and it is giving the error.

The complete error message displaying is SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1 (SQL: alter table bills AUTO_INCREMENT=9)

```<code>if($quantity[$i]>$qtny)
{
    Bills::where('id','=',$invoice_no)->delete();
    DB::enableQueryLog();
        DB::statement('alter table `bills` AUTO_INCREMENT=?',array('invoice_no'=>$invoice_no));
    dd(DB::getQueryLog());
    //return "<script>alert('Quantity is not available for product ".$item_name[$i]."');location.href='/create';</script>";
}
</code>```

答:
Variable placeholders are not allowed everywhere:

Within the statement, ? characters can be used as parameter markers to indicate where data values are to be bound to the query later when you execute it.

alter table requires a constant here, e.g. you could not use something like alter table bills AUTO_INCREMENT = (select max(id) from bills). Generally, everywhere you could do this, you are allowed to use placeholders (with some exceptions like limit, but those are then mentioned in the documentation).

So in this case you have to use the value directly:

```<code>DB::statement('alter table `bills` AUTO_INCREMENT = '.$invoice_no)
</code>```

Body:
I am trying to alter the auto_increment by laravel stament function and it is giving the error.

The complete error message displaying is SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1 (SQL: alter table bills AUTO_INCREMENT=9)

if($quantity[$i]>$qtny)
{
    Bills::where('id','=',$invoice_no)->delete();
    DB::enableQueryLog();
        DB::statement('alter table `bills` AUTO_INCREMENT=?',array('invoice_no'=>$invoice_no));
    dd(DB::getQueryLog());
    //return "";
}

Body:
Variable placeholders are not allowed everywhere:

Within the statement, ? characters can be used as parameter markers to indicate where data values are to be bound to the query later when you execute it.

alter table requires a constant here, e.g. you could not use something like alter table bills AUTO_INCREMENT = (select max(id) from bills). Generally, everywhere you could do this, you are allowed to use placeholders (with some exceptions like limit, but those are then mentioned in the documentation).

So in this case you have to use the value directly:

DB::statement('alter table `bills` AUTO_INCREMENT = '.$invoice_no)


问:
Deploying a react-native app but not on the app store or play store
I've created a react-native app and I want to be able to show people it without having to start my javascript server and ruby rails server every time.

I don't want to upload it to the app store or play store as I don't think its ready yet. But I want to be able to show it in interviews without having to bring my laptop.

Any advice would be appreciated.

答: You can just build the app with android studio and then save it on google drive or somewhere else, this way anyone can download it and install it, since it is not from play store your phone will only warn you that what you're installing is not from a trusted source but it will still install.</p>


问:
How to implement/show following pop-over above textField?
I m trying to implement following functionality in my iOS project.
Here is the screen,

If user do not enter anything or entered wrong data in email and mobile textFields, I want to show like this.

Case 1: If user didn't entered the email or entered incorrect email then it will show an message/view with "Enter valid Email Address"

Case 2: If user didn't entered the mobile number or entered incorrect mobile number then it will show an message/view with "Enter valid Mobile Number"

How to achieve this using swift?

答: I guess to show an underline and to show a small image at the right end in the UITextField you must have done subclassing of the UITextField. In the same subclass you can add the pop up view as subview and show and hide according your requirements from the delegate methods of UITextField.</p>


问:
Calculate Points from Letters in a Switch Case
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.

```<code>/*
 * To change this license header, choose License Headers in Project      Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package pointsproblem;

/**
 *
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

 public class PointsProblem {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
 public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    //create new object//
    PointsProblem task1 = new PointsProblem();

    File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + input);
        System.exit(0);
    }
    else {
        System.out.println("Successfully opened file: " + input + ".");
    }
    //read all the lines in the file//
   {
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);
            System.out.println("'" + input + "' is worth " + point + " points");

    int point = "";
    switch(point)  {

    case 'a': = "1":
    case 'e': = "1";
    case 'i': = "1";
    case 'l': = "1";
    case 'n': = "1";
    case 'o': = "1";
    case 'r': = "1";
    case 's': = "1";
    case 't': = "1";
    case 'u': = "1";
    case 'g': = "2";
    case 'g': = "2";
    case 'b': = "3";
    case 'm': = "3";
    case 'c': = "3";
    case 'p': = "3";
    case 'f': = "4";
    case 'h': = "4";
    case 'v': = "4";
    case 'w': = "4";
    case 'y': = "4";
    case 'k': = "5";
    case 'j': = "8";
    case 'x': = "8";
    case 'q': = "10";
    case 'z': = "10";

    return score  =  point + "";
        }//end switch

     }//end point calculation loop

    public int getScore() {
        return score;
    }
    //public boolean containsLetter(Character letter) {
        //return points.contains(letter);//

    }
</code>```

I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.

答:
Looks like a Map<Character, Integer> would fit:

```<code>public class PointsProblem {
    final Map<Character, Integer> pointsMap = Map.of(
        'a', 1,
        'e', 1,
        //.......
        'z', 10
    );
</code>```

Then, in your function, simply use the map to find the corresponding point for each character:

```<code>int wordPoints = 0;
for(char c : word.toCharArray())
    wordPoints += pointsMap.get(c);
</code>```

Body:
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.

/*
 * To change this license header, choose License Headers in Project      Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package pointsproblem;

/**
 *
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

 public class PointsProblem {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
 public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    //create new object//
    PointsProblem task1 = new PointsProblem();

    File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + input);
        System.exit(0);
    }
    else {
        System.out.println("Successfully opened file: " + input + ".");
    }
    //read all the lines in the file//
   {
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);
            System.out.println("'" + input + "' is worth " + point + " points");

    int point = "";
    switch(point)  {

    case 'a': = "1":
    case 'e': = "1";
    case 'i': = "1";
    case 'l': = "1";
    case 'n': = "1";
    case 'o': = "1";
    case 'r': = "1";
    case 's': = "1";
    case 't': = "1";
    case 'u': = "1";
    case 'g': = "2";
    case 'g': = "2";
    case 'b': = "3";
    case 'm': = "3";
    case 'c': = "3";
    case 'p': = "3";
    case 'f': = "4";
    case 'h': = "4";
    case 'v': = "4";
    case 'w': = "4";
    case 'y': = "4";
    case 'k': = "5";
    case 'j': = "8";
    case 'x': = "8";
    case 'q': = "10";
    case 'z': = "10";

    return score  =  point + "";
        }//end switch

     }//end point calculation loop

    public int getScore() {
        return score;
    }
    //public boolean containsLetter(Character letter) {
        //return points.contains(letter);//

    }

I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.

Body:
Looks like a Map<Character, Integer> would fit:

public class PointsProblem {
    final Map<Character, Integer> pointsMap = Map.of(
        'a', 1,
        'e', 1,
        //.......
        'z', 10
    );

Then, in your function, simply use the map to find the corresponding point for each character:

int wordPoints = 0;
for(char c : word.toCharArray())
    wordPoints += pointsMap.get(c);


问:
Running plex as a docker container, cannot access web UI
I am trying to set up my Plex server using docker. I have followed the steps on the LinuxServer.io docker page. When I run the docker command, it says that it is running find and I get no errors. However, when I try to access the web UI through localhost:32400/web, all I get is "Problem loading page"

I am using docker for windows with Linux containers.

docker command:

```<code>docker run -d --name=plex --net=host -e PUID=1000 -e PGID=1000 -e TZ=Europe/London -e VERSION=docker -v D:\plex\config:/config -v D:\media\tvseries:/data/tvshows -v D:\media\movies:/data/movies -v D:\media\transcode:/transcode --restart unless-stopped linuxserver/plex
</code>```

when I use docker ps the plex container looks like it is running.

I am new to docker. I have looked around and cannot find why I cannot access the UI.

Please me know if you require additional information.

docker inspect:

```<code>"NetworkMode": "host",
"PortBindings": {
    "32400/tcp": [
        {
            "HostIp": "",
            "HostPort": "32400"
        }
    ]
},
</code>```

please let me know if you require more information

答:
--net=host not work for docker-for-windows.

Reasons:

Linux container need to share a linux host' kernel.

In order to achieve this, when docker for windows run a linux container, it will had to setup a hyper-v machine. If you open the Hyper-V manager, you will see a MobyLinuxVM running.

So, when you use --net=host, the container will just use the network of MobyLinuxVM, not the windows. So, localhost will not work.

Suggestion:

For your scenario, I suggest you to remove --net=host, add port mapping in command line:

```<code>docker run -d --name=plex -p 32400:32400 -e PUID=1000 -e PGID=1000 -e TZ=Europe/London -e VERSION=docker -v D:\plex\config:/config -v D:\media\tvseries:/data/tvshows -v D:\media\movies:/data/movies -v D:\media\transcode:/transcode --restart unless-stopped linuxserver/plex
</code>```

Then, magic will happen here, docker for windows will map the windows's 32400 port to your container using windows route mechanism. And you can visit container's service from windows.

Body:
I am trying to set up my Plex server using docker. I have followed the steps on the LinuxServer.io docker page. When I run the docker command, it says that it is running find and I get no errors. However, when I try to access the web UI through localhost:32400/web, all I get is "Problem loading page"

I am using docker for windows with Linux containers.

docker command:

docker run -d --name=plex --net=host -e PUID=1000 -e PGID=1000 -e TZ=Europe/London -e VERSION=docker -v D:\plex\config:/config -v D:\media\tvseries:/data/tvshows -v D:\media\movies:/data/movies -v D:\media\transcode:/transcode --restart unless-stopped linuxserver/plex

when I use docker ps the plex container looks like it is running.

I am new to docker. I have looked around and cannot find why I cannot access the UI.

Please me know if you require additional information.

docker inspect:

"NetworkMode": "host",
"PortBindings": {
    "32400/tcp": [
        {
            "HostIp": "",
            "HostPort": "32400"
        }
    ]
},

please let me know if you require more information

Body:
--net=host not work for docker-for-windows.

Reasons:

Linux container need to share a linux host' kernel.

In order to achieve this, when docker for windows run a linux container, it will had to setup a hyper-v machine. If you open the Hyper-V manager, you will see a MobyLinuxVM running.

So, when you use --net=host, the container will just use the network of MobyLinuxVM, not the windows. So, localhost will not work.

Suggestion:

For your scenario, I suggest you to remove --net=host, add port mapping in command line:

docker run -d --name=plex -p 32400:32400 -e PUID=1000 -e PGID=1000 -e TZ=Europe/London -e VERSION=docker -v D:\plex\config:/config -v D:\media\tvseries:/data/tvshows -v D:\media\movies:/data/movies -v D:\media\transcode:/transcode --restart unless-stopped linuxserver/plex

Then, magic will happen here, docker for windows will map the windows's 32400 port to your container using windows route mechanism. And you can visit container's service from windows.


问:
Sum column based on another column in Pandas DataFrame
I have a pandas DataFrame like this:

```<code>>>> df = pd.DataFrame({'MONTREGL':[10,10,2222,35,200,56,5555],'SINID':['aaa','aaa','aaa','bbb','bbb','ccc','ccc'],'EXTRA':[400,400,400,500,500,333,333]})
>>> df
   MONTREGL SINID EXTRA
0        10   aaa   400
1        10   aaa   400
2      2222   aaa   400
3        35   bbb   500
4       200   bbb   500
5        56   ccc   333
6      5555   ccc   333
</code>```

I want to sum the column MONTREGL for each groupby SINID...

So I get 2242 for aaa and so on... ALSO I want to keep the value of column EXTRA.

This is the expected result:

```<code>   MONTREGL SINID EXTRA
0      2242   aaa   400
1       235   bbb   500
2      5611   ccc   333
</code>```

Thanks for your help in advance!

答:
I ended up using this script:

```<code>dff = df.groupby(["SINID","EXTRA"]).MONTREGL.sum().reset_index()
</code>```

And it works in this test and production.

Body:
I have a pandas DataFrame like this:

>>> df = pd.DataFrame({'MONTREGL':[10,10,2222,35,200,56,5555],'SINID':['aaa','aaa','aaa','bbb','bbb','ccc','ccc'],'EXTRA':[400,400,400,500,500,333,333]})
>>> df
   MONTREGL SINID EXTRA
0        10   aaa   400
1        10   aaa   400
2      2222   aaa   400
3        35   bbb   500
4       200   bbb   500
5        56   ccc   333
6      5555   ccc   333

I want to sum the column MONTREGL for each groupby SINID...

So I get 2242 for aaa and so on... ALSO I want to keep the value of column EXTRA.

This is the expected result:

   MONTREGL SINID EXTRA
0      2242   aaa   400
1       235   bbb   500
2      5611   ccc   333

Thanks for your help in advance!

Body:
I ended up using this script:

dff = df.groupby(["SINID","EXTRA"]).MONTREGL.sum().reset_index()

And it works in this test and production.


问:
Typescript constrain generic to string literal type for use in computed object property
I'm trying to write a function which will take a string literal and return an object with a single field whose name is that string literal. I can write a function that does what I want, but I don't know how to express the constraint that its argument type be a string literal.

The closest I've got is using a generic type which extends string. This permits string literal types, but also unions of string literal types and the type string, which I don't want to be passed to my function.

This compiles, and does what I want, provided that K is a string literal type. Note that type assertion wasn't necessary in typescript 3.4 but it is required in 3.5.

```<code>function makeObject<K extends string>(key: K): { [P in K]: string } {
  return { [key]: "Hello, World!" } as { [P in K]: string };
}
</code>```

If K is anything other than a string literal, the return type of this function won't be the same as the type of the value it returns.

The 2 avenues I can imagine for making this work are:

constrain K to be only string literals

express that the return type be an object with a single field whose name is a value in K (less satisfying, but at least the type of the function will be honest)

Can typescript's type system express either of these?

If I remove the type assertion in typescript 3.5 I get the error:

```<code>a.ts:2:3 - error TS2322: Type '{ [x: string]: string; }' is not assignable to type '{ [P in K]: string; }'.

2   return { [key]: "Hello, World!" };
</code>```

答:
There is no constraint for something to be a single string literal type. If you specify extends string the compiler will infer string literal types for K but it will also by definition allow unions of string literal types (after all the set of a union of string literal types is included in the set of all strings)

We can create a custom error, that forces as call to be in an error state if it detects a union of string literal types. Such a check can be done using conditional types making sure that K is the same as UnionToIntersection<K>. If this is true K is not a union, since 'a' extends 'a' but  'a' | 'b' does not extends 'a' & 'b'

```<code>type UnionToIntersection<U> =
    (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

type CheckForUnion<T, TErr, TOk> = [T] extends [UnionToIntersection<T>] ? TOk : TErr

function makeObject<K extends string>(key: K & CheckForUnion<K, never, {}>): { [P in K]: string } {
    return { [key]: "Hello, World!" } as { [P in K]: string };
}

makeObject("a")
makeObject("a" as "a" | "b") // Argument of type '"a" | "b"' is not assignable to parameter of type 'never'
</code>```

Body:
I'm trying to write a function which will take a string literal and return an object with a single field whose name is that string literal. I can write a function that does what I want, but I don't know how to express the constraint that its argument type be a string literal.

The closest I've got is using a generic type which extends string. This permits string literal types, but also unions of string literal types and the type string, which I don't want to be passed to my function.

This compiles, and does what I want, provided that K is a string literal type. Note that type assertion wasn't necessary in typescript 3.4 but it is required in 3.5.

function makeObject<K extends string>(key: K): { [P in K]: string } {
  return { [key]: "Hello, World!" } as { [P in K]: string };
}

If K is anything other than a string literal, the return type of this function won't be the same as the type of the value it returns.

The 2 avenues I can imagine for making this work are:

constrain K to be only string literals

express that the return type be an object with a single field whose name is a value in K (less satisfying, but at least the type of the function will be honest)

Can typescript's type system express either of these?

If I remove the type assertion in typescript 3.5 I get the error:

a.ts:2:3 - error TS2322: Type '{ [x: string]: string; }' is not assignable to type '{ [P in K]: string; }'.

2   return { [key]: "Hello, World!" };

Body:
There is no constraint for something to be a single string literal type. If you specify extends string the compiler will infer string literal types for K but it will also by definition allow unions of string literal types (after all the set of a union of string literal types is included in the set of all strings)

We can create a custom error, that forces as call to be in an error state if it detects a union of string literal types. Such a check can be done using conditional types making sure that K is the same as UnionToIntersection<K>. If this is true K is not a union, since 'a' extends 'a' but  'a' | 'b' does not extends 'a' & 'b'

type UnionToIntersection<U> =
    (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

type CheckForUnion<T, TErr, TOk> = [T] extends [UnionToIntersection<T>] ? TOk : TErr

function makeObject<K extends string>(key: K & CheckForUnion<K, never, {}>): { [P in K]: string } {
    return { [key]: "Hello, World!" } as { [P in K]: string };
}

makeObject("a")
makeObject("a" as "a" | "b") // Argument of type '"a" | "b"' is not assignable to parameter of type 'never'


问:
Table borders in HTML email on iPad and iPhone
I have a pixel border showing between table rows when doing email testing. iPhone and iPad only.
I have tried:

```<code>* {
margin:0;
padding:0;

}
</code>```

I have also tried:
this makes the border blue instead of white but I want the border removed completely?

答:
```<code>border: 0;
</code>```

should do it nice and easy

Body:
I have a pixel border showing between table rows when doing email testing. iPhone and iPad only.
I have tried:

* {
margin:0;
padding:0;

}

I have also tried:
this makes the border blue instead of white but I want the border removed completely?

Body:
border: 0;

should do it nice and easy


问:
How to fix "ValueError: not enough values to unpack (expected 2, got 1)"
I am trying to make a music app using tkinter and python, but I am not able to get rid of "ValueError: not enough values to unpack (expected 2, got 1)" bug. Have a look at my code and you'd be much clear with what I am dealing. </p>

<p>The mechanism is pretty simple, I, at first, display the song options via dictionary(list), and after taking the input, corresponding value of "j",(example, if input is 1 then j is one and corresponding value of j is i) to be saved as the name of the song and execute the program by playing the music.  </p>

```<code>list = {
    '1':'Say You Won t Let Go.mp3','2':'In the Jungle the mighty jungle.mp3'
}
lost = ''
print(list)
print("which one?")
this_one = int(input(''))
for j,i in list:
    if j == this_one:
        lost = i
</code>```

答:
You have to use list.items()

```<code>for i, j in list.items():
...
</code>```

Body:
I am trying to make a music app using tkinter and python, but I am not able to get rid of "ValueError: not enough values to unpack (expected 2, got 1)" bug. Have a look at my code and you'd be much clear with what I am dealing.

The mechanism is pretty simple, I, at first, display the song options via dictionary(list), and after taking the input, corresponding value of "j",(example, if input is 1 then j is one and corresponding value of j is i) to be saved as the name of the song and execute the program by playing the music.

list = {
    '1':'Say You Won t Let Go.mp3','2':'In the Jungle the mighty jungle.mp3'
}
lost = ''
print(list)
print("which one?")
this_one = int(input(''))
for j,i in list:
    if j == this_one:
        lost = i

Body:
You have to use list.items()

for i, j in list.items():
...


问:
Download a pdf in android and show in the app
Actually I know how to open a pdf file from assets folder in android app.But now I want to download a pdf from url and store it on sdcard.when the pdf is downloaded it show in the app.Once the pdf is downloaded then "view" will show other wise it shows "download"</p>

答:
If you encounter any issues with the pdf download here is the link:

android download pdf from url then open it with a pdf reader

If you have already done this then you can simply create a SharedPreferences boolean to store weather true if you successfully completed the download process or false if you didin't download it or removed the pdf. Once your app will start check everytime the boolean value and display view or download according to it's value.

Documentation for shared pref: Android Shared preferences example


问:
js doesn't execute 'else' statement
I have an if-else statement in JavaScript which returns false, but doesn't execute the code inside 'else'.

part of the script inside the cshtml file:

```<code>if (@Session["mission"].ToString() != "1") {
    setInterval(function () { myTimer(ctxPoints, ctxLines); }, 1000 / @ViewBag.rate);
} else {
    alert("hi");
}
</code>```

In the debug the '@Session["mission"].ToString() != "1"' statement returns false, but nothing jumps to the screen.

答:
I think you should clear Js code and c# code

```<code>if ("@Session["mission"].ToString()" != "1")
</code>```

Session["mission"].ToString() this print string in c#, but you need to encapsulate it in quote to make this value get type string

Title: js doesn't execute 'else' statement

Body:
I have an if-else statement in JavaScript which returns false, but doesn't execute the code inside 'else'.

part of the script inside the cshtml file:

if (@Session["mission"].ToString() != "1") {
    setInterval(function () { myTimer(ctxPoints, ctxLines); }, 1000 / @ViewBag.rate);
} else {
    alert("hi");
}

In the debug the '@Session["mission"].ToString() != "1"' statement returns false, but nothing jumps to the screen.

Body:
I think you should clear Js code and c# code

if ("@Session["mission"].ToString()" != "1")

Session["mission"].ToString() this print string in c#, but you need to encapsulate it in quote to make this value get type string


答:
try adding:

```<code>border-collapse:collapse;
</code>```

see what happens

Title: Table borders in HTML email on iPad and iPhone

Body:
try adding:

border-collapse:collapse;

see what happens


问:
How to Write two canvas video elements into one new canvas
I have 3 canvas elements which have video running into it, And I want to add these two canvas element to a third canvas element together.
My Code is here. Please anybody help me out for the same

Please have a look on the following code, And help me out.

First Canvas

```<code>var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
</code>```

Second Canvas

```<code>var canvas2 = document.getElementById('canvas2');
var context2 = canvas2.getContext('2d');

var cw = 200;
var ch = 200;
canvas.width = cw;
canvas.height = ch;
canvas2.width = cw;
canvas2.height = ch;
</code>```

Video draw to canvas

```<code>v.addEventListener('play', function(){
    draw(this,context,cw,ch);
},false);
</code>```

Third Canvas

```<code>var can3 = document.getElementById('canvas3');
var ctx3 = can3.getContext('2d');

can3.width = 400;
can3.height = 400;
</code>```

Draw Function

```<code>function draw(v,c,w,h) {
    if(v.paused || v.ended) return false;
    c.drawImage(v,20,0,w,h);
    setTimeout(draw,20,v,c,w,h);
}
</code>```

答:
Actually, What i want is to record the canvas element which has two different video elements which are creating dynamically. So I have change my code to  this code      </p>

```<code>function drawVideosToCanvas() {
    if (isStopDrawingFrames) {
        return;
    }
    var videosLength = videos.length;
    if(videosLength > 2){
        videosLength = 2;
    }

    var fullcanvas = false;
    var remaining = [];

    var length = videos.length;
    videos.forEach(function(video,idx) {
        if (!video.stream) {
            video.stream = {};
        }
        if (video.stream.fullcanvas) {
            fullcanvas = video;
        } else {
            if(idx==0 || idx == (length-1)){
                if(video.stream.active)
                    remaining.push(video);
            }
        }
    });

    if (fullcanvas) {
        canvas.width = fullcanvas.stream.width;
        canvas.height = fullcanvas.stream.height;
    } else if (remaining.length) {
        canvas.width = videosLength > 1 ? remaining[0].width * 2 : remaining[0].width;

        var height = 1;
        if (videosLength === 3 || videosLength === 4) {
            height = 2;
        }
        if (videosLength === 5 || videosLength === 6) {
            height = 3;
        }
        if (videosLength === 7 || videosLength === 8) {
            height = 4;
        }
        if (videosLength === 9 || videosLength === 10) {
            height = 5;
        }

        canvas.height = remaining[0].height * height;
    } else {
        canvas.width = self.width || 360;
        canvas.height = self.height || 240;
    }

    remaining.forEach(function(video, idx) {
        drawImage(video, idx);
    });

    setTimeout(drawVideosToCanvas, self.frameInterval);
}
</code>```

Body:
I have 3 canvas elements which have video running into it, And I want to add these two canvas element to a third canvas element together.
My Code is here. Please anybody help me out for the same

Please have a look on the following code, And help me out.

First Canvas

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

Second Canvas

var canvas2 = document.getElementById('canvas2');
var context2 = canvas2.getContext('2d');

var cw = 200;
var ch = 200;
canvas.width = cw;
canvas.height = ch;
canvas2.width = cw;
canvas2.height = ch;

Video draw to canvas

v.addEventListener('play', function(){
    draw(this,context,cw,ch);
},false);

Third Canvas

var can3 = document.getElementById('canvas3');
var ctx3 = can3.getContext('2d');

can3.width = 400;
can3.height = 400;

Draw Function

function draw(v,c,w,h) {
    if(v.paused || v.ended) return false;
    c.drawImage(v,20,0,w,h);
    setTimeout(draw,20,v,c,w,h);
}

Body:
Actually, What i want is to record the canvas element which has two different video elements which are creating dynamically. So I have change my code to  this code

function drawVideosToCanvas() {
    if (isStopDrawingFrames) {
        return;
    }
    var videosLength = videos.length;
    if(videosLength > 2){
        videosLength = 2;
    }

    var fullcanvas = false;
    var remaining = [];

    var length = videos.length;
    videos.forEach(function(video,idx) {
        if (!video.stream) {
            video.stream = {};
        }
        if (video.stream.fullcanvas) {
            fullcanvas = video;
        } else {
            if(idx==0 || idx == (length-1)){
                if(video.stream.active)
                    remaining.push(video);
            }
        }
    });

    if (fullcanvas) {
        canvas.width = fullcanvas.stream.width;
        canvas.height = fullcanvas.stream.height;
    } else if (remaining.length) {
        canvas.width = videosLength > 1 ? remaining[0].width * 2 : remaining[0].width;

        var height = 1;
        if (videosLength === 3 || videosLength === 4) {
            height = 2;
        }
        if (videosLength === 5 || videosLength === 6) {
            height = 3;
        }
        if (videosLength === 7 || videosLength === 8) {
            height = 4;
        }
        if (videosLength === 9 || videosLength === 10) {
            height = 5;
        }

        canvas.height = remaining[0].height * height;
    } else {
        canvas.width = self.width || 360;
        canvas.height = self.height || 240;
    }

    remaining.forEach(function(video, idx) {
        drawImage(video, idx);
    });

    setTimeout(drawVideosToCanvas, self.frameInterval);
}


问:
Codeigniter rest api route issue
I have create a simple rest api but when I hit the path in url it throw an error i.e. {"status":false,"error":"Unknown method"}. I was thinking that there is some problem in my route.php file. How can I solve this problem? Please help me.

controller: User.php

```<code><?php
    require APPPATH . '/libraries/REST_Controller.php';
    use Restserver\Libraries\REST_Controller;
    class User extends REST_Controller
    {
        function __construct()
        {
            parent::__construct();
            $this->load->database();
        }
        function user_data()
        {
            $this->db->select('*');
            $this->db->from('tbl_books');
            $sql = $this->db->get();
            $result = $sql->result_array();
            $this->response($result, 200);
        }

        function country()
        {
            echo "hello";
        }
    }
</code>```

route.php

```<code>$route['default_controller'] = 'user';
$route['404_override'] = '';
$route['translate_uri_dashes'] = TRUE;
$route['user_data'] = "user/user_data";
$route['country'] = "user/country";
</code>```

答:
As you said, you are calling

http://localhost/rest/user_data

Try calling

http://localhost/rest/user/user_data

In your case : It is trying to call User_data controller, and since it is not present it is giving you an error.

The first part after your base_path is the controller name followed by method of the controller.

http://localhost/rest/user_data

Eg :
http://localhost/rest/controller/controller_method

Refer :https://www.codeigniter.com/user_guide/general/urls.html

Title: Codeigniter rest api route issue

Body:
I have create a simple rest api but when I hit the path in url it throw an error i.e. {"status":false,"error":"Unknown method"}. I was thinking that there is some problem in my route.php file. How can I solve this problem? Please help me.

controller: User.php

<?php
    require APPPATH . '/libraries/REST_Controller.php';
    use Restserver\Libraries\REST_Controller;
    class User extends REST_Controller
    {
        function __construct()
        {
            parent::__construct();
            $this->load->database();
        }
        function user_data()
        {
            $this->db->select('*');
            $this->db->from('tbl_books');
            $sql = $this->db->get();
            $result = $sql->result_array();
            $this->response($result, 200);
        }

        function country()
        {
            echo "hello";
        }
    }

route.php

$route['default_controller'] = 'user';
$route['404_override'] = '';
$route['translate_uri_dashes'] = TRUE;
$route['user_data'] = "user/user_data";
$route['country'] = "user/country";


问:
Create service bus topic request gives exception Operation returned an invalid status code 'Forbidden'
When I try to create a service bus topic programmatically using the sample app (https://github.com/Azure-Samples/service-bus-dotnet-management), Azure gives Operation returned an invalid status code 'Forbidden' exception.

I have verified my TenantId, ClientId, ClientSecret, SubscriptionId and namespace name several times and they seem correct to me. My service bus pricing tier is "Standard".

答:
According to the error, seems you did not add your service principal as a role to your service bus.

You could follow the steps:

Navigate to the azure portal -> your service bus or the subscription whcih your service bus located -> Access control (IAM) -> Add -> Add role assignment -> search your service principal with name and add it as a role(e.g. Owner) -> Save.

For more details, refer to this link.


问:
Creating new instance of Kotlin data class with sorted inner data class
I have a Kotlin data class called ParcelBoxByID.kt and at one point I need to remove some Locker's from the ParcelBoxByID.kt data class.

As an input I get one instance of ParcelBoxByID.kt and I need to get back the same ParcelBoxByID.kt, but with sorted Locker's. I am not sure if removing is even possible in this case so creating a new instace of ParcelBoxByID.kt is also acceptable or creating a copy.

But my question is: How do I sort data class' inner list and return still the parent data class with sorted inner class?

I need to sort them by Locker.status. So if Locker.status is 0, then remove it from the new instance and if it is anything else then it can stay.

ParcelBoxByID.kt

```<code>data class ParcelBoxByID(
        val kioskId: Int,
        val location: Location,
        val stats: Stats,
        val events: List<Event>,
        val lockers: List<Locker>,
        val settings: Settings,
        val modules: String,
        val masterPin: String,
        val visibility: String
) {
    data class Locker(
            val allocationId: Int,
            val kioskId: Int,
            val towerId: Int,
            val lockerId: Int,
            var lockId: String,
            val size: String,
            var lockerCode: String,
            val type: String,
            val status: String,
            val target: String,
            val shipment: Shipment,
            val allocationTime: String,
            val collectionTime: String,
            val lastCollectionDate: String,
            val corporateCustomer: Any,
            val limitedQuantity: Boolean,
            val payment: Any,
            val requestedSize: Any,
            val operatorPin: String,
            val customerPin: String,
            val lastMsgReceived: String,
            var edited: Boolean?
    ) {
        data class Shipment(
                val trackingCode: String,
                val requestedLockerSize: Any,
                val sender: Sender,
                val recipient: Recipient,
                val productId: String,
                val productName: String,
                val height: Any,
                val width: Any,
                val depth: Any,
                val lqWeight: Any,
                val requireIdentification: Boolean,
                val easilyCodeShipment: Any,
                val senderLogisticsContract: Any,
                val payerLogisticsContract: Any,
                val serviceCodes: List<String>,
                val labelProductName: Any,
                val labelProcessNumber: Any,
                val errandCode: Any,
                val international: Boolean,
                val nearbyLocker: Any,
                val ruokakassi: Any,
                val type: String,
                val trackingCode2: Any,
                val toiReturnSender: Any,
                val toiReturnRecipient: Any,
                val additionalInfo: Any,
                val senderName: String,
                val senderPhone: String,
                val recipientName: String,
                val recipientPhone: String,
                val recipientLocation: Any
        ) {
            data class Sender(
                    val phone: String,
                    val name: String,
                    val name2: Any,
                    val street: Any,
                    val postalCode: Any,
                    val city: Any,
                    val country: Any,
                    val locationId: Any,
                    val email: Any,
                    val routingCode: Any
            )

            data class Recipient(
                    val phone: String,
                    val name: String,
                    val name2: Any,
                    val street: Any,
                    val postalCode: Any,
                    val city: Any,
                    val country: Any,
                    val locationId: Any,
                    val email: Any,
                    val routingCode: Any
            )
        }
    }

    data class Settings(
            val LQ_ALLOWED: String,
            val RETURN_ALLOWED: String
    )

    data class Location(
            val id: Any,
            val type: String,
            val pupCode: Any,
            val postalCode: String,
            val routingServiceCode: Any,
            val countryCode: String,
            val postalCodeAreas: List<String>,
            val availability: Any,
            val customerServicePhoneNumber: String,
            val address: Address,
            val labelName: LabelName,
            val publicName: PublicName,
            val locationName: LocationName,
            val additionalInfo: AdditionalInfo,
            val dropOfTimeParcel: Any,
            val openingTimes: List<Any>,
            val coordinates: Any
    ) {
        data class LocationName(
                val fi: String,
                val sv: String,
                val en: String
        )

        data class PublicName(
                val fi: String,
                val sv: String,
                val en: String
        )

        data class Address(
                val fi: Fi,
                val sv: Sv,
                val en: En
        ) {
            data class Sv(
                    val address: Any,
                    val streetName: String,
                    val streetNumber: Any,
                    val postalCode: String,
                    val postalCodeName: String,
                    val municipality: String
            )

            data class En(
                    val address: Any,
                    val streetName: String,
                    val streetNumber: Any,
                    val postalCode: String,
                    val postalCodeName: String,
                    val municipality: String
            )

            data class Fi(
                    val address: Any,
                    val streetName: String,
                    val streetNumber: Any,
                    val postalCode: String,
                    val postalCodeName: String,
                    val municipality: String
            )
        }

        data class LabelName(
                val fi: String,
                val sv: String,
                val en: String
        )

        data class AdditionalInfo(
                val fi: String,
                val sv: String,
                val en: String
        )
    }

    data class Stats(
            val allLockers: Int,
            val emptyLockers: Int,
            val malfunctionLockers: Int,
            val forCustomer: Int,
            val forCourier: Int,
            val bySize: BySize,
            val incoming: Any
    ) {
        data class BySize(
                val XXSMALL: Xxsmall,
                val XSMALL: Xsmall,
                val SMALL: Small,
                val MEDIUM: Medium,
                val LARGE: Large,
                val XLARGE: Xlarge
        ) {
            data class Xxsmall(
                    val empty: Int,
                    val hasContent: Int
            )

            data class Medium(
                    val empty: Int,
                    val hasContent: Int
            )

            data class Xlarge(
                    val empty: Int,
                    val hasContent: Int
            )

            data class Xsmall(
                    val empty: Int,
                    val hasContent: Int
            )

            data class Large(
                    val empty: Int,
                    val hasContent: Int
            )

            data class Small(
                    val empty: Int,
                    val hasContent: Int
            )
        }
    }

    data class Event(
            val id: Int,
            val kioskId: Int,
            val eventType: String,
            val payload: Payload,
            val createdAt: String,
            val modifiedAt: String,
            val status: String,
            val target: String,
            val user: String
    ) {
        data class Payload(
                val exceptionType: String,
                val lockerId: Int,
                val towerId: Int
        )
    }
}
</code>```

答:
You can copy your data-class, assigning sorted list:</p>

```<code>val copyWithSortedLockers = parcelBoxByID.copy(
    lockers = parcelBoxByID.lockers.sortedBy(Locker::status)
)
</code>```

Body:
I have a Kotlin data class called ParcelBoxByID.kt and at one point I need to remove some Locker's from the ParcelBoxByID.kt data class.

As an input I get one instance of ParcelBoxByID.kt and I need to get back the same ParcelBoxByID.kt, but with sorted Locker's. I am not sure if removing is even possible in this case so creating a new instace of ParcelBoxByID.kt is also acceptable or creating a copy.

But my question is: How do I sort data class' inner list and return still the parent data class with sorted inner class?

I need to sort them by Locker.status. So if Locker.status is 0, then remove it from the new instance and if it is anything else then it can stay.

ParcelBoxByID.kt

data class ParcelBoxByID(
        val kioskId: Int,
        val location: Location,
        val stats: Stats,
        val events: List<Event>,
        val lockers: List<Locker>,
        val settings: Settings,
        val modules: String,
        val masterPin: String,
        val visibility: String
) {
    data class Locker(
            val allocationId: Int,
            val kioskId: Int,
            val towerId: Int,
            val lockerId: Int,
            var lockId: String,
            val size: String,
            var lockerCode: String,
            val type: String,
            val status: String,
            val target: String,
            val shipment: Shipment,
            val allocationTime: String,
            val collectionTime: String,
            val lastCollectionDate: String,
            val corporateCustomer: Any,
            val limitedQuantity: Boolean,
            val payment: Any,
            val requestedSize: Any,
            val operatorPin: String,
            val customerPin: String,
            val lastMsgReceived: String,
            var edited: Boolean?
    ) {
        data class Shipment(
                val trackingCode: String,
                val requestedLockerSize: Any,
                val sender: Sender,
                val recipient: Recipient,
                val productId: String,
                val productName: String,
                val height: Any,
                val width: Any,
                val depth: Any,
                val lqWeight: Any,
                val requireIdentification: Boolean,
                val easilyCodeShipment: Any,
                val senderLogisticsContract: Any,
                val payerLogisticsContract: Any,
                val serviceCodes: List<String>,
                val labelProductName: Any,
                val labelProcessNumber: Any,
                val errandCode: Any,
                val international: Boolean,
                val nearbyLocker: Any,
                val ruokakassi: Any,
                val type: String,
                val trackingCode2: Any,
                val toiReturnSender: Any,
                val toiReturnRecipient: Any,
                val additionalInfo: Any,
                val senderName: String,
                val senderPhone: String,
                val recipientName: String,
                val recipientPhone: String,
                val recipientLocation: Any
        ) {
            data class Sender(
                    val phone: String,
                    val name: String,
                    val name2: Any,
                    val street: Any,
                    val postalCode: Any,
                    val city: Any,
                    val country: Any,
                    val locationId: Any,
                    val email: Any,
                    val routingCode: Any
            )

            data class Recipient(
                    val phone: String,
                    val name: String,
                    val name2: Any,
                    val street: Any,
                    val postalCode: Any,
                    val city: Any,
                    val country: Any,
                    val locationId: Any,
                    val email: Any,
                    val routingCode: Any
            )
        }
    }

    data class Settings(
            val LQ_ALLOWED: String,
            val RETURN_ALLOWED: String
    )

    data class Location(
            val id: Any,
            val type: String,
            val pupCode: Any,
            val postalCode: String,
            val routingServiceCode: Any,
            val countryCode: String,
            val postalCodeAreas: List<String>,
            val availability: Any,
            val customerServicePhoneNumber: String,
            val address: Address,
            val labelName: LabelName,
            val publicName: PublicName,
            val locationName: LocationName,
            val additionalInfo: AdditionalInfo,
            val dropOfTimeParcel: Any,
            val openingTimes: List<Any>,
            val coordinates: Any
    ) {
        data class LocationName(
                val fi: String,
                val sv: String,
                val en: String
        )

        data class PublicName(
                val fi: String,
                val sv: String,
                val en: String
        )

        data class Address(
                val fi: Fi,
                val sv: Sv,
                val en: En
        ) {
            data class Sv(
                    val address: Any,
                    val streetName: String,
                    val streetNumber: Any,
                    val postalCode: String,
                    val postalCodeName: String,
                    val municipality: String
            )

            data class En(
                    val address: Any,
                    val streetName: String,
                    val streetNumber: Any,
                    val postalCode: String,
                    val postalCodeName: String,
                    val municipality: String
            )

            data class Fi(
                    val address: Any,
                    val streetName: String,
                    val streetNumber: Any,
                    val postalCode: String,
                    val postalCodeName: String,
                    val municipality: String
            )
        }

        data class LabelName(
                val fi: String,
                val sv: String,
                val en: String
        )

        data class AdditionalInfo(
                val fi: String,
                val sv: String,
                val en: String
        )
    }

    data class Stats(
            val allLockers: Int,
            val emptyLockers: Int,
            val malfunctionLockers: Int,
            val forCustomer: Int,
            val forCourier: Int,
            val bySize: BySize,
            val incoming: Any
    ) {
        data class BySize(
                val XXSMALL: Xxsmall,
                val XSMALL: Xsmall,
                val SMALL: Small,
                val MEDIUM: Medium,
                val LARGE: Large,
                val XLARGE: Xlarge
        ) {
            data class Xxsmall(
                    val empty: Int,
                    val hasContent: Int
            )

            data class Medium(
                    val empty: Int,
                    val hasContent: Int
            )

            data class Xlarge(
                    val empty: Int,
                    val hasContent: Int
            )

            data class Xsmall(
                    val empty: Int,
                    val hasContent: Int
            )

            data class Large(
                    val empty: Int,
                    val hasContent: Int
            )

            data class Small(
                    val empty: Int,
                    val hasContent: Int
            )
        }
    }

    data class Event(
            val id: Int,
            val kioskId: Int,
            val eventType: String,
            val payload: Payload,
            val createdAt: String,
            val modifiedAt: String,
            val status: String,
            val target: String,
            val user: String
    ) {
        data class Payload(
                val exceptionType: String,
                val lockerId: Int,
                val towerId: Int
        )
    }
}

Body:
You can copy your data-class, assigning sorted list:

val copyWithSortedLockers = parcelBoxByID.copy(
    lockers = parcelBoxByID.lockers.sortedBy(Locker::status)
)


问:
Flask/SQLAlchemy/Docker Is there a better way to handle what I think is a circular dependancy? Full github project included
I'm having an issue where I can't get my db object to work in various routes in my app

I've spent a good 6 hours on this today and tried various options including appfactory patterns, extension loading, blueprints and more and no matter what approach I take I am just getting stumped.

I want to keep the blueprint pattern I have, this is key, yet at the base level, I just can't get the .db to load.

This is the full error:

```<code>$ sudo docker-compose up --build
WARNING: The UID variable is not set. Defaulting to a blank string.
Building website
Step 1/10 : FROM python:3.7.2-alpine
 ---> bb1ccaa5880c
Step 2/10 : MAINTAINER (info to live here)
 ---> Using cache
 ---> c86eafc23e13
Step 3/10 : ENV INSTALL_PATH /logrr
 ---> Using cache
 ---> 18de4002edc2
Step 4/10 : RUN mkdir -p $INSTALL_PATH
 ---> Using cache
 ---> 78996ea3714d
Step 5/10 : RUN pip install --upgrade pip
 ---> Using cache
 ---> bf253a9bfe18
Step 6/10 : WORKDIR $INSTALL_PATH
 ---> Using cache
 ---> 04e1a0092af0
Step 7/10 : COPY requirements.txt requirements.txt
 ---> Using cache
 ---> e96a1b830b07
Step 8/10 : RUN pip install -r requirements.txt
 ---> Using cache
 ---> 114d0dcd7eb0
Step 9/10 : COPY . .
 ---> cdc705c36e0d
Step 10/10 : CMD gunicorn -b 0.0.0.0:9000 --access-logfile - "logrr.app:create_app()"
 ---> Running in dbbcb2fa0541
Removing intermediate container dbbcb2fa0541
 ---> 69b7e8cba951
Successfully built 69b7e8cba951
Successfully tagged logrr_website:latest
Recreating logrr_website_1 ... done
Attaching to logrr_website_1
website_1  | Traceback (most recent call last):
website_1  |   File "/usr/local/bin/gunicorn", line 10, in <module>
website_1  |     sys.exit(run())
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 61, in run
website_1  |     WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 223, in run
website_1  |     super(Application, self).run()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 72, in run
website_1  |     Arbiter(self).run()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 60, in __init__
website_1  |     self.setup(app)
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 120, in setup
website_1  |     self.app.wsgi()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
website_1  |     self.callable = self.load()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
website_1  |     return self.load_wsgiapp()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
website_1  |     return util.import_app(self.app_uri)
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
website_1  |     __import__(module)
website_1  |   File "/logrr/logrr/app.py", line 3, in <module>
website_1  |     from logrr.blueprints.register import register
website_1  |   File "/logrr/logrr/blueprints/register/__init__.py", line 1, in <module>
website_1  |     from logrr.blueprints.register.views import register
website_1  |   File "/logrr/logrr/blueprints/register/views.py", line 4, in <module>
website_1  |     from logrr.models import User, Post, Org
website_1  |   File "/logrr/logrr/models.py", line 2, in <module>
website_1  |     from logrr.app import db
website_1  | ImportError: cannot import name 'db' from 'logrr.app' (/logrr/logrr/app.py)
logrr_website_1 exited with code 1
</code>```

I have the full code ready to be run via docker-compose here:
https://github.com/therealrobster/bdIssue

You can run it via the standard sudo docker-compose up --build  I have it set to localhost:9000 at present.

For some reason when I try and access the db models I get errors like ImportError: cannot import name 'db' from 'logrr.app' (/logrr/logrr/app.py)

Can anyone look at the code and tell me what I'm doing wrong please?  6 hours of banging head on desk and I'm at my whits end.

Thank you

答: the problem is in your models.py it is importing db from logrr.app but the db is present in logrr.extensions

Body:
I'm having an issue where I can't get my db object to work in various routes in my app

I've spent a good 6 hours on this today and tried various options including appfactory patterns, extension loading, blueprints and more and no matter what approach I take I am just getting stumped.

I want to keep the blueprint pattern I have, this is key, yet at the base level, I just can't get the .db to load.

This is the full error:

$ sudo docker-compose up --build
WARNING: The UID variable is not set. Defaulting to a blank string.
Building website
Step 1/10 : FROM python:3.7.2-alpine
 ---> bb1ccaa5880c
Step 2/10 : MAINTAINER (info to live here)
 ---> Using cache
 ---> c86eafc23e13
Step 3/10 : ENV INSTALL_PATH /logrr
 ---> Using cache
 ---> 18de4002edc2
Step 4/10 : RUN mkdir -p $INSTALL_PATH
 ---> Using cache
 ---> 78996ea3714d
Step 5/10 : RUN pip install --upgrade pip
 ---> Using cache
 ---> bf253a9bfe18
Step 6/10 : WORKDIR $INSTALL_PATH
 ---> Using cache
 ---> 04e1a0092af0
Step 7/10 : COPY requirements.txt requirements.txt
 ---> Using cache
 ---> e96a1b830b07
Step 8/10 : RUN pip install -r requirements.txt
 ---> Using cache
 ---> 114d0dcd7eb0
Step 9/10 : COPY . .
 ---> cdc705c36e0d
Step 10/10 : CMD gunicorn -b 0.0.0.0:9000 --access-logfile - "logrr.app:create_app()"
 ---> Running in dbbcb2fa0541
Removing intermediate container dbbcb2fa0541
 ---> 69b7e8cba951
Successfully built 69b7e8cba951
Successfully tagged logrr_website:latest
Recreating logrr_website_1 ... done
Attaching to logrr_website_1
website_1  | Traceback (most recent call last):
website_1  |   File "/usr/local/bin/gunicorn", line 10, in <module>
website_1  |     sys.exit(run())
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 61, in run
website_1  |     WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 223, in run
website_1  |     super(Application, self).run()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 72, in run
website_1  |     Arbiter(self).run()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 60, in __init__
website_1  |     self.setup(app)
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 120, in setup
website_1  |     self.app.wsgi()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
website_1  |     self.callable = self.load()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
website_1  |     return self.load_wsgiapp()
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
website_1  |     return util.import_app(self.app_uri)
website_1  |   File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
website_1  |     __import__(module)
website_1  |   File "/logrr/logrr/app.py", line 3, in <module>
website_1  |     from logrr.blueprints.register import register
website_1  |   File "/logrr/logrr/blueprints/register/__init__.py", line 1, in <module>
website_1  |     from logrr.blueprints.register.views import register
website_1  |   File "/logrr/logrr/blueprints/register/views.py", line 4, in <module>
website_1  |     from logrr.models import User, Post, Org
website_1  |   File "/logrr/logrr/models.py", line 2, in <module>
website_1  |     from logrr.app import db
website_1  | ImportError: cannot import name 'db' from 'logrr.app' (/logrr/logrr/app.py)
logrr_website_1 exited with code 1

I have the full code ready to be run via docker-compose here:
https://github.com/therealrobster/bdIssue

You can run it via the standard sudo docker-compose up --build  I have it set to localhost:9000 at present.

For some reason when I try and access the db models I get errors like ImportError: cannot import name 'db' from 'logrr.app' (/logrr/logrr/app.py)

Can anyone look at the code and tell me what I'm doing wrong please?  6 hours of banging head on desk and I'm at my whits end.

Thank you


问:
one-to-one mapping using unique constraint not working as expected
I'm trying this simple uni-directional one-to-one relationship

Person ----> Address

using many-to-one mapping with unique constraint.

This is how my mapping looks like in Person.hbm.xml:

```<code><class name="Person" table="PERSON">
<many-to-one name="address" column="ADDRESS_ID" cascade="all" not-null="true" unique="true"/>
</code>```

I think this should allow only one unique Address per Person - no two Persons can share a common address.

So, the following code should fail. But in this code Hibernate allows both the Johns to stay at same address.

```<code>    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();
    Address address = new Address("Bond Street", "London", 121212);
    Person person1 = new Person("John Doe", address);
    Person person2 = new Person("John McClane", address);
    session.save(person1);
    session.save(person2);
    transaction.commit();
    session.close();
</code>```

Please let me know what am I missing here?

答:
Read http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#d0e7576, and find the many-to-one description in paragraph 5.1.7.1. It says :

unique (optional): enables the DDL
  generation of a unique constraint for
  the foreign-key column. By allowing
  this to be the target of a
  property-ref, you can make the
  association multiplicity one-to-one.

This means that it's used by the database schema generation tool of Hibernate to add a unique constraint. If you don't use it, then you must add this constraint yourself.

Body:
I'm trying this simple uni-directional one-to-one relationship

Person ----> Address

using many-to-one mapping with unique constraint.

This is how my mapping looks like in Person.hbm.xml:

<class name="Person" table="PERSON">
<many-to-one name="address" column="ADDRESS_ID" cascade="all" not-null="true" unique="true"/>

I think this should allow only one unique Address per Person - no two Persons can share a common address.

So, the following code should fail. But in this code Hibernate allows both the Johns to stay at same address.

    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();
    Address address = new Address("Bond Street", "London", 121212);
    Person person1 = new Person("John Doe", address);
    Person person2 = new Person("John McClane", address);
    session.save(person1);
    session.save(person2);
    transaction.commit();
    session.close();

Please let me know what am I missing here?


问:
Comparing value of an object with null
The null literal can only be assigned to reference variables, and usually, we use the .equals() method in comparing with them

Why do we use the operators "equal to" and "not equal to" instead of the .equals() method if dealing with null?

答:
equals is a method, meaning you cannot call it on a null reference (although you could call myVariable.equals(aVariableThatIsNull), and it should return false).

You could use java.util.Objects#equals(Object, Object) to clean up your code, and seemless handle null-safe equality checks.

Title: Comparing value of an object with null