问:
Entity Framework bug? "Context changed" Error, even when not
I have gotten myself into an odd Groundhog Day scenario with an MVC application of mine.

Unless I apply my workaround (Later in this question) each time I debug the application I'm presented with this error:

The model backing the 'UsersContext' context has changed since the
  database was created. Consider using Code First Migrations to update
  the database (http://go.microsoft.com/fwlink/?LinkId=238269).

I have not changed the model.

My workaround workflow is:

Add-Migration WHATEVERNAME (Makes a blank migration)

Delete this migration.

Run: Update-Database

Recompile & Run (Now without error)

Notes:

The __MigrationHistory hashes of the latest migration match in both script and in the database.

I have my MVC application & EF project as separate projects.

I have tried creating an -IgnoreChanges migration, to see if applying this would mitigate the issue.  It did not.

This is quite frustrating, how would I solve this issue permanently?

Note: Automatic migrations are not suitable for my scenario.

答:
This can happen when updating to EF6 which made schema changes to the _MigrationHistory table (https://msdn.microsoft.com/en-us/data/jj591621)

The EF6 version has a new column ContextKey so the migration is probably trying to add that column.

I'm guessing if you scaffold it will just be making those changes - or perhaps there's something you changed a long time ago that wasn't 'picked up' yet for some reason.

OR if you just don't want to deal with it right now you can disable migrations temporarily.

```<code> System.Data.Entity.Database.SetInitializer<UsersContext>(null);
</code>```

Body:
This can happen when updating to EF6 which made schema changes to the _MigrationHistory table (https://msdn.microsoft.com/en-us/data/jj591621)

The EF6 version has a new column ContextKey so the migration is probably trying to add that column.

I'm guessing if you scaffold it will just be making those changes - or perhaps there's something you changed a long time ago that wasn't 'picked up' yet for some reason.

OR if you just don't want to deal with it right now you can disable migrations temporarily.

 System.Data.Entity.Database.SetInitializer<UsersContext>(null);


来源: stackexchange

问:
React - uncaught TypeError: Cannot read property 'setState' of undefined
I am getting the following error

Uncaught TypeError: Cannot read property 'setState' of undefined

even after binding delta in the constructor.

```<code>class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.delta}>+</button>
            </div>
        );
    }
}
</code>```

答:
```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>

    <script src="https://unpkg.com/react@0.14.8/dist/react.min.js"></script>
    <script src="https://unpkg.com/react-dom@0.14.8/dist/react-dom.min.js"></script>
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

  </head>
  <body>
  <div id="root"></div>
    <script type="text/babel">

        class App extends React.Component{

            constructor(props){
                super(props);
                this.state = {
                    counter : 0,
                    isToggle: false
                }
            this.onEventHandler = this.onEventHandler.bind(this);
            }

            increment = ()=>{
                this.setState({counter:this.state.counter + 1});
            }

            decrement= ()=>{
                if(this.state.counter > 0 ){
                this.setState({counter:this.state.counter - 1});
                }else{
                this.setState({counter:0});
                }
            }
            // Either do it as onEventHandler = () => {} with binding with this  // object.
            onEventHandler(){
                this.setState({isToggle:!this.state.isToggle})
                alert('Hello');
            }

            render(){
                return(
                    <div>
                        <button onClick={this.increment}> Increment </button>
                        <button onClick={this.decrement}> Decrement </button>
                        {this.state.counter}
                        <button onClick={this.onEventHandler}> {this.state.isToggle ? 'Hi':'Ajay'} </button>

                    </div>
                    )
            }
        }
        ReactDOM.render(
        <App/>,
        document.getElementById('root'),
      );
    </script>
  </body>
  </html>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am getting the following error

Uncaught TypeError: Cannot read property 'setState' of undefined

even after binding delta in the constructor.

class Counter extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count : 1
        };

        this.delta.bind(this);
    }

    delta() {
        this.setState({
            count : this.state.count++
        });
    }

    render() {
        return (

{this.state.count}

                <button onClick={this.delta}>+</button>

        );
    }
}


问:
Unable to merge dex -Android 3.0.1
I have Android Studio 3.0.1. After added new library, when I tried launching the app it did not launch with the message:

```<code>Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
</code>```

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

But I don't know how to solve this error. I googled this but with no success.

My app gradle:

```<code>apply plugin: 'com.android.application' android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
    applicationId "com.xxxxxxx.app"
    minSdkVersion 15
    targetSdkVersion 26
    multiDexEnabled true
    vectorDrawables.useSupportLibrary = true
    versionCode 3
    versionName "1.0.1"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}}dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:multidex:1.0.2'
compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:26.1.0'
compile 'com.android.volley:volley:1.0.0'
compile files('libs/KGJsonConverter.jar')
compile files('libs/gson-2.2.4.jar')
compile 'com.github.amigold.fundapter:library:1.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile files('libs/PhotoUtil.jar')
compile files('libs/GenAsync.1.2.jar')
compile files('libs/MD5Simply.jar')
compile 'com.soundcloud.android:android-crop:1.0.1@aar'
compile 'com.quickblox:quickblox-android-sdk-core:3.3.0'
compile 'com.quickblox:quickblox-android-sdk-chat:3.3.0'}
</code>```

my project gradle:

```<code>buildscript {
repositories {
    jcenter()
    google()
}  dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'}}allprojects {
repositories {
    jcenter()
    google() maven{ url 'https://github.com/QuickBlox/quickblox-android-sdk-releases/raw/master/'}}}task clean(type: Delete) { delete rootProject.buildDir}
</code>```

答:
Use the dependencies below.</p>

```<code>compile 'com.quickblox:quickblox-android-sdk-videochat-webrtc:3.3.3@aar'
compile 'com.quickblox:quickblox-android-sdk-content:3.3.3@aar'
compile('com.quickblox:quickblox-android-sdk-chat:3.3.3@aar') {
    transitive = true
}
</code>```

Title: Unable to merge dex -Android 3.0.1

Body:
I have Android Studio 3.0.1. After added new library, when I tried launching the app it did not launch with the message:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

But I don't know how to solve this error. I googled this but with no success.

My app gradle:

apply plugin: 'com.android.application' android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
    applicationId "com.xxxxxxx.app"
    minSdkVersion 15
    targetSdkVersion 26
    multiDexEnabled true
    vectorDrawables.useSupportLibrary = true
    versionCode 3
    versionName "1.0.1"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}}dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:multidex:1.0.2'
compile 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:26.1.0'
compile 'com.android.volley:volley:1.0.0'
compile files('libs/KGJsonConverter.jar')
compile files('libs/gson-2.2.4.jar')
compile 'com.github.amigold.fundapter:library:1.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile files('libs/PhotoUtil.jar')
compile files('libs/GenAsync.1.2.jar')
compile files('libs/MD5Simply.jar')
compile 'com.soundcloud.android:android-crop:1.0.1@aar'
compile 'com.quickblox:quickblox-android-sdk-core:3.3.0'
compile 'com.quickblox:quickblox-android-sdk-chat:3.3.0'}

my project gradle:

buildscript {
repositories {
    jcenter()
    google()
}  dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'}}allprojects {
repositories {
    jcenter()
    google() maven{ url 'https://github.com/QuickBlox/quickblox-android-sdk-releases/raw/master/'}}}task clean(type: Delete) { delete rootProject.buildDir}

Body:
Use the dependencies below.

compile 'com.quickblox:quickblox-android-sdk-videochat-webrtc:3.3.3@aar'
compile 'com.quickblox:quickblox-android-sdk-content:3.3.3@aar'
compile('com.quickblox:quickblox-android-sdk-chat:3.3.3@aar') {
    transitive = true
}


问:
could not find compatible versions for gem "rubyzip"
I am using

gem 'axlsx_rails'

gem 'acts_as_xlsx'

for downloading file into excel.
Now I am trying to add the following gem

gem 'caracal'

for downloading file into docx.
Whenever, I am trying to run

bundle install, I got the following error

Bundler could not find compatible versions for gem "rubyzip":   In
  snapshot (Gemfile.lock):
      rubyzip (= 1.0.0)

In Gemfile:
      acts_as_xlsx was resolved to 1.0.6, which depends on
        axlsx (>= 1.0.13) was resolved to 2.0.1, which depends on
          rubyzip (~> 1.0.0)

```<code>caracal was resolved to 0.1.0, which depends on
  rubyzip (~> 1.1)
</code>```

Running bundle update will rebuild your snapshot from scratch, using
  only the gems in your Gemfile, which may resolve the conflict.

My gem file looks like following

source 'https://rubygems.org'

gem 'rails', '4.1.9'

gem 'mysql2', '~> 0.3.19'

gem 'sass-rails', '~> 4.0.3'

gem 'uglifier', '>= 1.3.0'

gem 'coffee-rails', '~> 4.0.0'

gem 'jquery-rails'

gem 'jbuilder', '~> 2.0'

gem 'sdoc', '~> 0.4.0',          group: :doc

gem 'spring',        group: :development

gem 'devise'

group :development do

gem 'better_errors'

gem 'binding_of_caller'

gem 'capistrano', '~> 3.4.1'

gem 'capistrano-rails'

gem 'capistrano-bundler'

gem 'capistrano-rvm'

end

gem 'therubyracer'

gem 'less-rails'

gem 'twitter-bootstrap-rails', '3.2.0'

gem 'cancan'

gem 'carrierwave', github: 'carrierwaveuploader/carrierwave'

gem 'rmagick'

gem 'caracal'

gem 'activerecord-session_store', github:
  'rails/activerecord-session_store'

gem 'carmen-rails', '~> 1.0.0'

gem 'wicked'

gem 'figaro'

gem 'bootstrap-datepicker-rails'

gem 'axlsx_rails'

gem 'acts_as_xlsx'

答:
The axlsx_rails gem hasn't been updated for quite a while and it depends on a version of the axlsx gem that depends on a 1.0.x version of the rubyzip. Whereas caracal depends on a version >= 1.1. That said: Current versions of that gem will not work together.

But an even older version of the axlsx 1.3.6 had a more relaxed dependency to the rubyzip gem - it only requires its version to be >= 0.9.5.

Therefore I suggest - if possible - to downgrade axlsx_rails to 0.1.2 and try again:

```<code># add a version to the axlsx_rails gem in your Gemfile
gem 'axlsx_rails', '0.1.2'
</code>```

And run bundle install again.

Body:
I am using

gem 'axlsx_rails'

gem 'acts_as_xlsx'

for downloading file into excel.
Now I am trying to add the following gem

gem 'caracal'

for downloading file into docx.
Whenever, I am trying to run

bundle install, I got the following error

Bundler could not find compatible versions for gem "rubyzip":   In
  snapshot (Gemfile.lock):
      rubyzip (= 1.0.0)

In Gemfile:
      acts_as_xlsx was resolved to 1.0.6, which depends on
        axlsx (>= 1.0.13) was resolved to 2.0.1, which depends on
          rubyzip (~> 1.0.0)

caracal was resolved to 0.1.0, which depends on
  rubyzip (~> 1.1)

Running bundle update will rebuild your snapshot from scratch, using
  only the gems in your Gemfile, which may resolve the conflict.

My gem file looks like following

source 'https://rubygems.org'

gem 'rails', '4.1.9'

gem 'mysql2', '~> 0.3.19'

gem 'sass-rails', '~> 4.0.3'

gem 'uglifier', '>= 1.3.0'

gem 'coffee-rails', '~> 4.0.0'

gem 'jquery-rails'

gem 'jbuilder', '~> 2.0'

gem 'sdoc', '~> 0.4.0',          group: :doc

gem 'spring',        group: :development

gem 'devise'

group :development do

gem 'better_errors'

gem 'binding_of_caller'

gem 'capistrano', '~> 3.4.1'

gem 'capistrano-rails'

gem 'capistrano-bundler'

gem 'capistrano-rvm'

end

gem 'therubyracer'

gem 'less-rails'

gem 'twitter-bootstrap-rails', '3.2.0'

gem 'cancan'

gem 'carrierwave', github: 'carrierwaveuploader/carrierwave'

gem 'rmagick'

gem 'caracal'

gem 'activerecord-session_store', github:
  'rails/activerecord-session_store'

gem 'carmen-rails', '~> 1.0.0'

gem 'wicked'

gem 'figaro'

gem 'bootstrap-datepicker-rails'

gem 'axlsx_rails'

gem 'acts_as_xlsx'

Body:
The axlsx_rails gem hasn't been updated for quite a while and it depends on a version of the axlsx gem that depends on a 1.0.x version of the rubyzip. Whereas caracal depends on a version >= 1.1. That said: Current versions of that gem will not work together.

But an even older version of the axlsx 1.3.6 had a more relaxed dependency to the rubyzip gem - it only requires its version to be >= 0.9.5.

Therefore I suggest - if possible - to downgrade axlsx_rails to 0.1.2 and try again:

# add a version to the axlsx_rails gem in your Gemfile
gem 'axlsx_rails', '0.1.2'

And run bundle install again.


问:
Device Farm - How to access extra data with appium python
I am trying to run unittests that require external data on device farm with Appium Python. I am uploading the data in the form of a zip file to the 'extra data' argument, and entering "/sdcard/" into the 'android' argument. I am trying to call the files in the python script using "/WordCountTest1MB" here. Note that there is no extension to the files, they are just text. However, all of my tests are failing saying that:

```<code>test_paramec_0__sdcard_WordCountTest1MB failed: IOError: No such file or directory: '/sdcard/WordCountTest1MB'
</code>```

Is there something else I need to be doing to access these files?

Any help is much appreciated!

EDIT:  Here is the code posted below, note that we are trying to find the location of the data within the extra data argument, however the names of these directories changes with each one so we need to initially find the path of at least one of the needed files:

```<code>import unittest2
from appium import webdriver
from parameterized import parameterized
import os

for dirpath, dirnames, filenames in os.walk("."):
    for filename in [f for f in filenames if f.startswith("WordCountTest10MB.txt")]:
        dir_name =  os.path.join(dirpath, filename)

print os.path.dirname(dir_name)

def Test1(rootDir):
    list_dirs = os.walk(rootDir)
    for root, dirs, files in list_dirs:
        for d in dirs:
            print os.path.join(root, d)
        for f in files:
            print os.path.join(root, f)

# Returns abs path relative to this file and not cwd
PATH = lambda p: os.path.abspath(
    os.path.join(os.path.dirname(__file__), p)
)

def wordcount(filename):
    for j in range(1, 10):
        wordcount = {}
        inFile = filename
        with open(os.path.abspath(inFile)) as file:  # with can auto close the file
            for word in file.read().split():
                if word not in wordcount:
                    wordcount[word] = 1
                else:
                    wordcount[word] += 1
        wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True)
        for k, v in wordcount:
            print(k, v)

class WordCountTest(unittest2.TestCase):

    known_files = {'/WordCountTest1MB.txt',
                   '/WordCountTest5MB.txt',
                   '/WordCountTest10MB.txt'}

    def SetUpClass(self):
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '5.0'
        desired_caps['deviceName'] = 'Android Emulator'
        desired_caps['app'] = PATH('../../../apps/Nothing_v0_apkpure.com.apk')
        self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

    @parameterized.expand(known_files)

    def test_paramec(self, filename):
        os.chdir(dir_name)
        print os.getcwd(), Test1(os.getcwd())
        wordcount(filename)

    def TearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest2.main()
</code>```

答:
two options you can try

1) add .txt in each element of set

```<code> known_files = {'/sdcard/WordCountTest1MB.txt',
 '/sdcard/WordCountTest5MB.txt',
 '/sdcard/WordCountTest10MB.txt'}
</code>```

2) Use combination of glob and fileinput

```<code> import fileinput
 from glob import glob
 #This will store all the file names
 fnames = glob('WordCountTest*')
 for line in fileinput.input(fnames):
     pass # modify your code
</code>```

Body:
I am trying to run unittests that require external data on device farm with Appium Python. I am uploading the data in the form of a zip file to the 'extra data' argument, and entering "/sdcard/" into the 'android' argument. I am trying to call the files in the python script using "/WordCountTest1MB" here. Note that there is no extension to the files, they are just text. However, all of my tests are failing saying that:

test_paramec_0__sdcard_WordCountTest1MB failed: IOError: No such file or directory: '/sdcard/WordCountTest1MB'

Is there something else I need to be doing to access these files?

Any help is much appreciated!

EDIT:  Here is the code posted below, note that we are trying to find the location of the data within the extra data argument, however the names of these directories changes with each one so we need to initially find the path of at least one of the needed files:

import unittest2
from appium import webdriver
from parameterized import parameterized
import os

for dirpath, dirnames, filenames in os.walk("."):
    for filename in [f for f in filenames if f.startswith("WordCountTest10MB.txt")]:
        dir_name =  os.path.join(dirpath, filename)

print os.path.dirname(dir_name)

def Test1(rootDir):
    list_dirs = os.walk(rootDir)
    for root, dirs, files in list_dirs:
        for d in dirs:
            print os.path.join(root, d)
        for f in files:
            print os.path.join(root, f)

# Returns abs path relative to this file and not cwd
PATH = lambda p: os.path.abspath(
    os.path.join(os.path.dirname(__file__), p)
)

def wordcount(filename):
    for j in range(1, 10):
        wordcount = {}
        inFile = filename
        with open(os.path.abspath(inFile)) as file:  # with can auto close the file
            for word in file.read().split():
                if word not in wordcount:
                    wordcount[word] = 1
                else:
                    wordcount[word] += 1
        wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True)
        for k, v in wordcount:
            print(k, v)

class WordCountTest(unittest2.TestCase):

    known_files = {'/WordCountTest1MB.txt',
                   '/WordCountTest5MB.txt',
                   '/WordCountTest10MB.txt'}

    def SetUpClass(self):
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '5.0'
        desired_caps['deviceName'] = 'Android Emulator'
        desired_caps['app'] = PATH('../../../apps/Nothing_v0_apkpure.com.apk')
        self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

    @parameterized.expand(known_files)

    def test_paramec(self, filename):
        os.chdir(dir_name)
        print os.getcwd(), Test1(os.getcwd())
        wordcount(filename)

    def TearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest2.main()

Body:
two options you can try

1) add .txt in each element of set

 known_files = {'/sdcard/WordCountTest1MB.txt',
 '/sdcard/WordCountTest5MB.txt',
 '/sdcard/WordCountTest10MB.txt'}

2) Use combination of glob and fileinput

 import fileinput
 from glob import glob
 #This will store all the file names
 fnames = glob('WordCountTest*')
 for line in fileinput.input(fnames):
     pass # modify your code


问:
Error for partition in KAFKA
Suddenly several topics became an Under Replicated
In the logs such errors
what should I do?</p>

```<code>May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: kafka.common.NotAssignedReplicaException: Leader 1 failed to record follower 2's position -1 since the replica is not recognized to be one of the assigned replicas 1,3,4 for partition [impression,3].
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.cluster.Partition.updateReplicaLogReadResult(Partition.scala:249)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.ReplicaManager$$anonfun$updateFollowerLogReadResults$2.apply(ReplicaManager.scala:905)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.ReplicaManager$$anonfun$updateFollowerLogReadResults$2.apply(ReplicaManager.scala:902)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.ReplicaManager.updateFollowerLogReadResults(ReplicaManager.scala:902)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.ReplicaManager.fetchMessages(ReplicaManager.scala:475)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.KafkaApis.handleFetchRequest(KafkaApis.scala:523)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.KafkaApis.handle(KafkaApis.scala:79)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.KafkaRequestHandler.run(KafkaRequestHandler.scala:60)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at java.lang.Thread.run(Thread.java:745)
</code>```

答:
all KAFKA brokers will choose one as controller broker, which can get by zookeeper znode /controller, try restart this broker. More information see apache kafka wiki.
If can restart the KAFKA cluster (all brokers), is recommended.

Title: Error for partition in KAFKA

Body:
Suddenly several topics became an Under Replicated
In the logs such errors
what should I do?

May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: kafka.common.NotAssignedReplicaException: Leader 1 failed to record follower 2's position -1 since the replica is not recognized to be one of the assigned replicas 1,3,4 for partition [impression,3].
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.cluster.Partition.updateReplicaLogReadResult(Partition.scala:249)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.ReplicaManager$$anonfun$updateFollowerLogReadResults$2.apply(ReplicaManager.scala:905)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.ReplicaManager$$anonfun$updateFollowerLogReadResults$2.apply(ReplicaManager.scala:902)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.ReplicaManager.updateFollowerLogReadResults(ReplicaManager.scala:902)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.ReplicaManager.fetchMessages(ReplicaManager.scala:475)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.KafkaApis.handleFetchRequest(KafkaApis.scala:523)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.KafkaApis.handle(KafkaApis.scala:79)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at kafka.server.KafkaRequestHandler.run(KafkaRequestHandler.scala:60)
May 04 14:17:23 2kafka01.rtty.in kafka-server-start.sh[149443]: at java.lang.Thread.run(Thread.java:745)


问:
Text position got changed after JSON is loaded on canvas in fabricJS
I have observed change in position of text when creating fresh on canvas and when JSON is loaded on canvas. Normally on moving element on canvas values for left and top goes upto 14 decimal places and when JSON is loaded the position comes out to be upto two places.

e.g. In picture1 text left position  is 294.63668348469565 and text top is 202.79140935082407 after saving and loading back JSON, positon slightly got changed but left is 294.63 and top is 202.80 (picture2)
picture1
picture2

I guess upto 14 decimal is for very precision, does less decimal places can govern this change?

答:
By defualt precision value is 2.

If you want to change you can use NUM_FRACTION_DIGITS

```<code>fabric.Object.NUM_FRACTION_DIGITS = value;
</code>```

Where value is in your case 14.

Body:
By defualt precision value is 2.

If you want to change you can use NUM_FRACTION_DIGITS

fabric.Object.NUM_FRACTION_DIGITS = value;

Where value is in your case 14.


问:
Need help about multiclass classifier for Matlab
i need 2 matlab function . These functions will be multiclass classifier . I have 26 different classes . each class has 16 different values . i have 20k rows data at total . each row has class label (integer) and 16 different values as i said . first 16 k rows of the data will be used for training . other remaining 4k rows will be used for estimating classification performance . so i will use this 2 function for classify them and compare their performance .

thanks a lot for every kind of contribution.

答:
Statistics Toolbox provides a variety of different multiclass classifiers including

Bagged Decision Trees
Naive Bayes Classifiers
Linear Discriminant Analysis

You can access the product user guide at
http://www.mathworks.com/help/toolbox/stats/f15360dfi14.html

Alternatively, you might want to consult a recorded webinar titled "Computational Statistics:  Getting Started with Classification using MATLAB"

ContentLicense: CC BY-SA 2.5


问:
Combinations of strings without repetition C
```<code>`#include <stdio.h>
 void convert(int num){
char *word[10];

switch(num){
    case 0: word [0] = "ZERO";
    break;
    case 1: word [1] = "ONE";
    break;
    case 2: word [2] = "TWO";
    break;
    case 3: word [3] = "THREE";
    break;
    case 4: word [4] = "FOUR";
    break;
    case 5: word [5] = "FIVE";
    break;
    case 6: word [6] = "SIX";
    break;
    case 7: word [7] = "SEVEN";
    break;
    case 8: word [8] = "EIGHT";
    break;
    case 9: word [9] = "NINE";
    break;
}
printf("%s", word[num]);

}

int main(){
int a=0;
int b=0;
int c=0;

for(a=0;a<10;a=a+1){
    for(b=0;b<10;b=b+1){
        for(c=0;c<10;c=c+1){
        convert(a);convert(b);convert(c);
        printf("\n");
        }
    }
}´
</code>```

I want to make all possible combinations with repetition with the strings "zero" "one" "two", etc, 3 by 3, and store each one of them in a array of strings (from "zerozerozero" to "nineninenine").
Right now this is what i have, im only printing each combination, and im having trouble in storing each of them in a array.
I would appreciate any help or advice. :D

答:
We can declare an char array of enough size. For concatenation of three words, we use p to find next pos of insertion of word.

```<code>#include <stdio.h>
#include <string.h>
int convert(int num, char* full_word, int p){
    const char* word;
    switch(num){
        case 0: word = "ZERO";
                break;
        case 1: word = "ONE";
                break;
        case 2: word = "TWO";
                break;
        case 3: word = "THREE";
                break;
        case 4: word = "FOUR";
                break;
        case 5: word = "FIVE";
                break;
        case 6: word = "SIX";
                break;
        case 7: word = "SEVEN";
                break;
        case 8: word = "EIGHT";
                break;
        case 9: word = "NINE";
                break;
    }
    strcpy(full_word + p, word);
    p += strlen(word);
    return p;
}

int main(){
    int a=0;
    int b=0;
    int c=0;
    int ind = 0;

    char arr[1000][20];
    for(a=0;a<10;a=a+1){
        for(b=0;b<10;b=b+1){
            for(c=0;c<10;c=c+1, ++ind){
                char word[100];
                int p = convert(a, word, 0);
                p = convert(b, word, p);
                convert(c, word, p);
                strcpy(arr[ind], word);
            }
        }
    }
    for (int i = 0; i < 1000; ++i) {
        printf("%s\n", arr[i]);
    }
    return 0;
}
</code>```

Body:
`#include <stdio.h>
 void convert(int num){
char *word[10];

switch(num){
    case 0: word [0] = "ZERO";
    break;
    case 1: word [1] = "ONE";
    break;
    case 2: word [2] = "TWO";
    break;
    case 3: word [3] = "THREE";
    break;
    case 4: word [4] = "FOUR";
    break;
    case 5: word [5] = "FIVE";
    break;
    case 6: word [6] = "SIX";
    break;
    case 7: word [7] = "SEVEN";
    break;
    case 8: word [8] = "EIGHT";
    break;
    case 9: word [9] = "NINE";
    break;
}
printf("%s", word[num]);

}

int main(){
int a=0;
int b=0;
int c=0;

for(a=0;a<10;a=a+1){
    for(b=0;b<10;b=b+1){
        for(c=0;c<10;c=c+1){
        convert(a);convert(b);convert(c);
        printf("\n");
        }
    }
}´

I want to make all possible combinations with repetition with the strings "zero" "one" "two", etc, 3 by 3, and store each one of them in a array of strings (from "zerozerozero" to "nineninenine").
Right now this is what i have, im only printing each combination, and im having trouble in storing each of them in a array.
I would appreciate any help or advice. :D

Body:
We can declare an char array of enough size. For concatenation of three words, we use p to find next pos of insertion of word.

#include <stdio.h>
#include <string.h>
int convert(int num, char* full_word, int p){
    const char* word;
    switch(num){
        case 0: word = "ZERO";
                break;
        case 1: word = "ONE";
                break;
        case 2: word = "TWO";
                break;
        case 3: word = "THREE";
                break;
        case 4: word = "FOUR";
                break;
        case 5: word = "FIVE";
                break;
        case 6: word = "SIX";
                break;
        case 7: word = "SEVEN";
                break;
        case 8: word = "EIGHT";
                break;
        case 9: word = "NINE";
                break;
    }
    strcpy(full_word + p, word);
    p += strlen(word);
    return p;
}

int main(){
    int a=0;
    int b=0;
    int c=0;
    int ind = 0;

    char arr[1000][20];
    for(a=0;a<10;a=a+1){
        for(b=0;b<10;b=b+1){
            for(c=0;c<10;c=c+1, ++ind){
                char word[100];
                int p = convert(a, word, 0);
                p = convert(b, word, p);
                convert(c, word, p);
                strcpy(arr[ind], word);
            }
        }
    }
    for (int i = 0; i < 1000; ++i) {
        printf("%s\n", arr[i]);
    }
    return 0;
}


问:
Performance of java if-else with return statement
```<code>private String getString1(int n){

    if (n == 0) {
        return "ZERO";
    }
    if (n == 1) {
        return "ONE";
    }
    if(n == 2) {
        return "TWO";
    }
    return "-NA-";
}

private String getString2(int n){

    if (n == 0) {
        return "ZERO";
    } else if (n == 1) {
        return "ONE";
    } else if(n == 2) {
        return "TWO";
    } else
        return "-NA-";
}
</code>```

I have the above methods getString1(int) and getString2(int). Both will give the same o/p.
But which one is the most efficient way of using? In there any difference in term of performance?

答:
As far as cpu time - NO DIFFERENCE. The compiler will probably optimise them to exactly the same byte-code anyway.

As far as technical debt is concerned - as soon as a real developer looks at this code and replaces it with:

```<code>private static final String[] numbers = {"ZERO", "ONE", "TWO"};

private String getString(int n) {
    return n >= 0 && n < numbers.length? numbers[n]:"-NA-");
}
</code>```

you've just cost your company money.

Body:
private String getString1(int n){

    if (n == 0) {
        return "ZERO";
    }
    if (n == 1) {
        return "ONE";
    }
    if(n == 2) {
        return "TWO";
    }
    return "-NA-";
}

private String getString2(int n){

    if (n == 0) {
        return "ZERO";
    } else if (n == 1) {
        return "ONE";
    } else if(n == 2) {
        return "TWO";
    } else
        return "-NA-";
}

I have the above methods getString1(int) and getString2(int). Both will give the same o/p.
But which one is the most efficient way of using? In there any difference in term of performance?

Body:
As far as cpu time - NO DIFFERENCE. The compiler will probably optimise them to exactly the same byte-code anyway.

As far as technical debt is concerned - as soon as a real developer looks at this code and replaces it with:

private static final String[] numbers = {"ZERO", "ONE", "TWO"};

private String getString(int n) {
    return n >= 0 && n < numbers.length? numbers[n]:"-NA-");
}

you've just cost your company money.


问:
Unable to setup replication in ClickHouse using Zookeeper
I've spent past two days trying to setup replication in ClickHouse, but what ever configuration I try I end up with the same behavior.

I'm able to create a ReplicatedMergeTree table on the first node and insert data to it. Then I create a replica on the second node. The data gets replicated and I can see it querying the second node. But when I insert data to the second node the weird behavior starts. Data is not copied to the first node and it gets the following error:

```<code>2017.11.14 11:16:43.464565 [ 30 ] <Error> DB::StorageReplicatedMergeTree::queueTask()::<lambda(DB::StorageReplicatedMergeTree::LogEntryPtr&)>: Code: 33, e.displayText() = DB::Exception: Cannot read all data, e.what() = DB::Exception,
</code>```

It is very similar to this issue on GitHub.

When I restart the first node it is able to load the new data inserted to the second node and seems to be working. However inserting some more data brings the same error again.

The most recent setup I tried:

Following the tutorial, I have a three node Zookeeper cluster with the following config:

```<code>tickTime=2000
initLimit=10
syncLimit=5
dataDir=/opt/zoo2/data
clientPort=12181
server.1=10.201.1.4:2888:3888
server.2=0.0.0.0:12888:13888
server.3=10.201.1.4:22888:23888
</code>```

The zookeeper config for ClickHouse loooks like this:

```<code><?xml version="1.0"?>
<yandex>
    <zookeeper>
        <node>
            <host>10.201.1.4</host>
            <port>2181</port>
        </node>
        <node>
            <host>10.201.1.4</host>
            <port>12181</port>
        </node>
        <node>
            <host>10.201.1.4</host>
            <port>22181</port>
        </node>
    </zookeeper>
</yandex>
</code>```

I create all tables like this:

```<code>CREATE TABLE t_r (
  id UInt32,
  d Date
) ENGINE = ReplicatedMergeTree('/clickhouse/tables/t_r', '03', d, (d, id), 8192);
</code>```

The only difference accross all replicas is the replica id '03' which is set accordingly.

Thanks for any advice!

答: Actually I figured out the issue by myself. Thanks to @egorlitvinenko I went through all the configs again and I noticed that for all three nodes I had set up the same interserver_http_port. It would not be problem if all the nodes were running on separate machines, but in my test scenario they run side by side hosted on the same OS.

Body:
I've spent past two days trying to setup replication in ClickHouse, but what ever configuration I try I end up with the same behavior.

I'm able to create a ReplicatedMergeTree table on the first node and insert data to it. Then I create a replica on the second node. The data gets replicated and I can see it querying the second node. But when I insert data to the second node the weird behavior starts. Data is not copied to the first node and it gets the following error:

2017.11.14 11:16:43.464565 [ 30 ] <Error> DB::StorageReplicatedMergeTree::queueTask()::<lambda(DB::StorageReplicatedMergeTree::LogEntryPtr&)>: Code: 33, e.displayText() = DB::Exception: Cannot read all data, e.what() = DB::Exception,

It is very similar to this issue on GitHub.

When I restart the first node it is able to load the new data inserted to the second node and seems to be working. However inserting some more data brings the same error again.

The most recent setup I tried:

Following the tutorial, I have a three node Zookeeper cluster with the following config:

tickTime=2000
initLimit=10
syncLimit=5
dataDir=/opt/zoo2/data
clientPort=12181
server.1=10.201.1.4:2888:3888
server.2=0.0.0.0:12888:13888
server.3=10.201.1.4:22888:23888

The zookeeper config for ClickHouse loooks like this:

<?xml version="1.0"?>
<yandex>
    <zookeeper>
        <node>
            <host>10.201.1.4</host>
            <port>2181</port>
        </node>
        <node>
            <host>10.201.1.4</host>
            <port>12181</port>
        </node>
        <node>
            <host>10.201.1.4</host>
            <port>22181</port>
        </node>
    </zookeeper>
</yandex>

I create all tables like this:

CREATE TABLE t_r (
  id UInt32,
  d Date
) ENGINE = ReplicatedMergeTree('/clickhouse/tables/t_r', '03', d, (d, id), 8192);

The only difference accross all replicas is the replica id '03' which is set accordingly.

Thanks for any advice!


问:
Formatting data from an excel sheet (two criteria) in MATLAB
I have a question related to another one recently asked. I download my data as a csv.file. I then format it in MATLAB. I obtan formatted data such as:

I would like to format the data so that I obtain:

In other words, the date should be in the first column, while the two identifier should be in the first two rows, respectively.

I tried the code provided by @gnovice, yet I have problems to adjust for the second identifier. The code is:

```<code>A = accumarray([rowIndex colIndex], data(:, 4), [], @(x) x(1));
A = [NaN colVals; rowVals A];
</code>```

where data is equal to picture (1).

Therefore, I obtain a matrix A like:

```<code> A =
      NaN     1    2     3;
 20160101   100   80    90;
 20170101   150   90   200;
</code>```

How can I adjust my code in a way that the second identifier is taken care of and A becomes:

```<code> A =
      NaN     1    2     3;
      NaN    10   10    15;
 20160101   100   80    90;
 20170101   150   90   200;
</code>```

答:
You can use this code

```<code>C = unique([identifier_1,identifier_2],'rows')
</code>```

And format your data accordingly

Body:
I have a question related to another one recently asked. I download my data as a csv.file. I then format it in MATLAB. I obtan formatted data such as:

I would like to format the data so that I obtain:

In other words, the date should be in the first column, while the two identifier should be in the first two rows, respectively.

I tried the code provided by @gnovice, yet I have problems to adjust for the second identifier. The code is:

A = accumarray([rowIndex colIndex], data(:, 4), [], @(x) x(1));
A = [NaN colVals; rowVals A];

where data is equal to picture (1).

Therefore, I obtain a matrix A like:

 A =
      NaN     1    2     3;
 20160101   100   80    90;
 20170101   150   90   200;

How can I adjust my code in a way that the second identifier is taken care of and A becomes:

 A =
      NaN     1    2     3;
      NaN    10   10    15;
 20160101   100   80    90;
 20170101   150   90   200;

Body:
You can use this code

C = unique([identifier_1,identifier_2],'rows')

And format your data accordingly


问:
dompdf isn't working in laravel
I have make a html view page for generate to a pdf report from this view and i have also installed dompdf library, i have loaded data from database table on this view and create a hyperlink name as Download pdf. but when i click on this link it's show undefined variable dsale error.

here  my controller method.

```<code> //pass data to view
public function dsreport($id,$fromdate,$todate)
{
    $dsale=DB::table('directsales')
            ->join('clients','directsales.client_id','=','clients.id')
            ->join('products','directsales.product_id','=','products.id')
            ->select('clients.client_name','clients.addr','directsales.*','products.name')
            ->where('directsales.client_id','=',$id)
            ->whereBetween('directsales.issue_date',[$fromdate,$todate])
            ->distinct()
            ->paginate(3);
            //->get();
        $sumt=DB::table('directsales')
            ->where('directsales.client_id','=',$id)
            ->sum('directsales.total');

    return view('reports.directsalereport',compact(['dsale','sumt']));
}

//generate pdf
public function dsalepdf()
{
    $pdf=PDF::loadView('reports.directsalereport');
    return $pdf->download('dsread.pdf');
}
</code>```

Here is my view part.

```<code><div class="panel-body">
    <center><h1><strong>M/s. Priti Enterprise</strong></h1></center>
    </center>
    <center><h2><i>Daily Sales Report</i></h2></center>
    <div class="row">
        <div class="col-md-4"><strong>Client Name: {{$dsale[0]->client_name}}</strong></div>
        <div class="col-md-4"></div>
        <div class="col-md-4"><strong>Delivered by: {{$dsale[0]->deliverd_by}}</strong></div>
    </div><br>
    <div class="row">
        <div class="col-md-4"><strong>Client address: {{$dsale[0]->addr}}</strong></div>
        <div class="col-md-4"></div>
        <div class="col-md-4"><strong>Date: {{$dsale[0]->issue_date}}</strong></div>
    </div><br><br>

    <table class="table table-bordered">
        <thead>
            <th class="col-md-1">SL no.</th>
            <th>Product Name</th>
            <th>Invoice no.</th>
            <th>Unit per ctn.</th>
            <th>Unit price</th>
            <th class="col-md-2">Sales</th>
            <th>Value</th>
        </thead>
        <tbody>
            @foreach($dsale as $d)
            <tr>
                <td>#</td>
                <td>{{$d->name}}</td>
                <td>{{$d->transaction_code}}</td>
                <td>{{$d->unitperctn}}</td>
                <td>{{$d->unitprice}}</td>
                <td>{{$d->ctn}} ctn {{$d->pcs}} pcs</td>
                <td>{{$d->total}}</td>
            </tr>
            @endforeach
        </tbody>
    </table>

    <div class="col-md-11"></div>
    <div class="row"><strong>Total:{{$sumt}}</strong></div>
    <div>{{$dsale->links()}}</div>
    <div class="col-md-8"></div>
    <div class="row">
        <a href="{{route('downpdf')}}" class=" btn btn-info"><i class=" glyphicon glyphicon-ok"></i> Download PDF</a>
    </div>
</div>
</code>```

答:
You have an array in compact.

You should use
{{$dsale[0]->links()}}
.

I think you should dont compact an array.

```<code>return view('reports.directsalereport',compact('dsale','sumt'));
</code>```

Edited:
You should pass data to your Pdf view,  too, so your method for downloading pdf should look like this.

```<code>public function dsalepdf()
{

    $dsale=DB::table('directsales')
                ->join('clients','directsales.client_id','=','clients.id')
                ->join('products','directsales.product_id','=','products.id')
                ->select('clients.client_name','clients.addr','directsales.*','products.name')
                ->where('directsales.client_id','=',$id)
                ->whereBetween('directsales.issue_date',[$fromdate,$todate])
                ->distinct()
                ->paginate(3);

            $sumt=DB::table('directsales')
                ->where('directsales.client_id','=',$id)
                ->sum('directsales.total');

    $pdf=PDF::loadView('reports.directsalereport',['dsale' => $dsale,'sumt'=> $sumt]);
    return $pdf->download('dsread.pdf');
}
</code>```

Title: dompdf isn't working in laravel

Body:
I have make a html view page for generate to a pdf report from this view and i have also installed dompdf library, i have loaded data from database table on this view and create a hyperlink name as Download pdf. but when i click on this link it's show undefined variable dsale error.

here  my controller method.

 //pass data to view
public function dsreport($id,$fromdate,$todate)
{
    $dsale=DB::table('directsales')
            ->join('clients','directsales.client_id','=','clients.id')
            ->join('products','directsales.product_id','=','products.id')
            ->select('clients.client_name','clients.addr','directsales.*','products.name')
            ->where('directsales.client_id','=',$id)
            ->whereBetween('directsales.issue_date',[$fromdate,$todate])
            ->distinct()
            ->paginate(3);
            //->get();
        $sumt=DB::table('directsales')
            ->where('directsales.client_id','=',$id)
            ->sum('directsales.total');

    return view('reports.directsalereport',compact(['dsale','sumt']));
}

//generate pdf
public function dsalepdf()
{
    $pdf=PDF::loadView('reports.directsalereport');
    return $pdf->download('dsread.pdf');
}

Here is my view part.

M/s. Priti Enterprise

Daily Sales Report

Client Name: {{$dsale[0]->client_name}}

Delivered by: {{$dsale[0]->deliverd_by}}

Client address: {{$dsale[0]->addr}}

Date: {{$dsale[0]->issue_date}}

            SL no.
            Product Name
            Invoice no.
            Unit per ctn.
            Unit price
            Sales
            Value

            @foreach($dsale as $d)

                #
                {{$d->name}}
                {{$d->transaction_code}}
                {{$d->unitperctn}}
                {{$d->unitprice}}
                {{$d->ctn}} ctn {{$d->pcs}} pcs
                {{$d->total}}

            @endforeach

Total:{{$sumt}}

{{$dsale->links()}}

         Download PDF

Body:
You have an array in compact.

You should use <div>{{$dsale[0]->links()}}</div>.

I think you should dont compact an array.

return view('reports.directsalereport',compact('dsale','sumt'));

Edited:
You should pass data to your Pdf view,  too, so your method for downloading pdf should look like this.

public function dsalepdf()
{

    $dsale=DB::table('directsales')
                ->join('clients','directsales.client_id','=','clients.id')
                ->join('products','directsales.product_id','=','products.id')
                ->select('clients.client_name','clients.addr','directsales.*','products.name')
                ->where('directsales.client_id','=',$id)
                ->whereBetween('directsales.issue_date',[$fromdate,$todate])
                ->distinct()
                ->paginate(3);

            $sumt=DB::table('directsales')
                ->where('directsales.client_id','=',$id)
                ->sum('directsales.total');

    $pdf=PDF::loadView('reports.directsalereport',['dsale' => $dsale,'sumt'=> $sumt]);
    return $pdf->download('dsread.pdf');
}


问:
Do I generate a side effect?
I have the following function and want to know, if it generates a side effect:

```<code>  def build[F[_] : Monad : Foldable, A]
  (consumer: Consumer[String, String])(cb: Vector[KkConsumerRecord] => F[A])
  : KkConsumerThread = {
    val thread = delegate.newThread(() => {
      pool(consumer)(cb)
    })
    thread.setDaemon(true)
    KkConsumerThread(thread)
  }
</code>```

Inside the function, I create a thread but do not start it yet. That is mean for me, I do not generate any side effect yet. Am I right?

答: Basically, it seems you are generating a side-effect. Think about it this way - if you call this function repeatedly you'll eventually run out of memory (either by reaching OS thread # limit or java heap size limit).

Title: Do I generate a side effect?

Body:
I have the following function and want to know, if it generates a side effect:

  def build[F[_] : Monad : Foldable, A]
  (consumer: Consumer[String, String])(cb: Vector[KkConsumerRecord] => F[A])
  : KkConsumerThread = {
    val thread = delegate.newThread(() => {
      pool(consumer)(cb)
    })
    thread.setDaemon(true)
    KkConsumerThread(thread)
  }

Inside the function, I create a thread but do not start it yet. That is mean for me, I do not generate any side effect yet. Am I right?


问:
What are the important rules in Object Model Design
We are developing an extension (in C# .NET env.) for a GIS application, which will has predefined types
for modeling the real world objects, start from GenericObject, and goes to more specific types like Pipe and Road with their detailed properties and methods like BottomOfPipe, Diameter and so on.

Surely, there will be an Object Model, Interfaces, Inheritance and lots of other essential parts in the TypeLibrary, and by now we fixed some of them. But as you may know, designing an Object Model is a very ambiguous work, and (I as much as I know), can be done in many different ways and many different results and weaknesses.

Is there any distinct rules in designing O.M.: the Hierarchy, the way of defining Interfaces, abstract and coclasses enums?

Any suggestion, reference or practice?

答:
The Liskov Substitution Principle, often expressed in terms of "is-a".
Many examples of OOP would be better off making use of "has-a" (in c++ private inheritance or explicit composition) rather than public inheritance ("is-a")

Getting Inheritance right is hard. Doing so with interfaces (pure virtual classes) is often easier than for base/sub classes

OwnerDisplayName: A Poostchi


问:
Azure active directory graph api query user
I am working on an app that needs to query Azure AD. The query is working on some fields but on some fields like mobile number it's not working.

Query is working when filtering with name

```<code>var searchResults = await userCollection.Where(user =>
                (user.UserPrincipalName.StartsWith(searchString) ||
                user.DisplayName.StartsWith(searchString) ||
                user.GivenName.StartsWith(searchString) ||
                user.Surname.StartsWith(searchString) ||
                user.Mail.StartsWith(searchString)) && user.AccountEnabled == true).ExecuteAsync();
</code>```

but with mobile number and other fields it throws exception

```<code>var searchResults = await userCollection
                .Where(x => x.Mobile == "+63 922 3965 021").ExecuteAsync();
</code>```

Here is the exception
"Unsupported or invalid query filter clause specified for property 'mobile' of resource 'User'."

答:
There are some properties that you can query that way. The Linq query generates a Filter expression towards the Azure AD Graph API. But others, like the mobile number, you can't.

The properties that are filterable can be seen in the reference for user objects.

The ones that you can filter on are marked as such (e.g. the Surname property: "GET ($filter)").

Body:
I am working on an app that needs to query Azure AD. The query is working on some fields but on some fields like mobile number it's not working.

Query is working when filtering with name

var searchResults = await userCollection.Where(user =>
                (user.UserPrincipalName.StartsWith(searchString) ||
                user.DisplayName.StartsWith(searchString) ||
                user.GivenName.StartsWith(searchString) ||
                user.Surname.StartsWith(searchString) ||
                user.Mail.StartsWith(searchString)) && user.AccountEnabled == true).ExecuteAsync();

but with mobile number and other fields it throws exception

var searchResults = await userCollection
                .Where(x => x.Mobile == "+63 922 3965 021").ExecuteAsync();

Here is the exception
"Unsupported or invalid query filter clause specified for property 'mobile' of resource 'User'."

ContentLicense: CC BY-SA 4.0


问:
ValueError: math domain error in python2
when I run this code:

```<code>max(MIN_LEARNING_RATE, min(0.5, 1.0 - math.log10((t+1)/25)))
</code>```

with t = 0

I've this error:

```<code>ValueError: math domain error
</code>```

but if i run the same code with python 3.6 the error disappeared

答:
Due to rounding in python-2.x, (0+1)/25 evaluates to 1/25, which rounds to 0. Thus, math.log10(0), which is undefined, results in a ValueError.

Either add from __future__ import division to the first line in your program or change the line of code to max(MIN_LEARNING_RATE, min(0.5, 1.0 - math.log10((t+1)/25.0)))

Body:
when I run this code:

max(MIN_LEARNING_RATE, min(0.5, 1.0 - math.log10((t+1)/25)))

with t = 0

I've this error:

ValueError: math domain error

but if i run the same code with python 3.6 the error disappeared


问:
Can I set a maximum value for a number in protobuf?
In protobuf, we only have the choice of using signed or unsigned 32- or 64-bit integer to limit the range of a value.

However, the datastructure I want to define contains a mixture of 8-bit, 16-bit and 32-bit integers to save space on embedded devices. On them, the datastructure is also implemented somewhat differently and requires reserved special values for some fields, so the maximum number for them is not a power of 2.

On these embedded devices, the protobuf definition is only used for transmission to and from them, not for actual storage. So I could just limit the numbers when reading them in.

However, I'd rather define these maximum values in the .proto or .options file to make sure all client applications are aware of these limitations.

Is there a way to do this?

I know there are field options, but the ones listed here does not include an option for this. It is possible to create custom options, but that seems to require writing a compiler extension, which means I have to manually implement this limit checking for every language I want to compile to, and that costs more time than it will ever save.

答:
This is not possible in protobuf by default, and the specification includes no syntax to enforce limits like this.

However, some third party implementations do include such support.

For example, my own nanopb has the int_size option:

int_size: Override the integer type of a field. (To use e.g. uint8_t to save RAM.)

This will return an error at runtime from pb_decode() if the value does not fit in the field.


问:
Which lifecycle event is called when a screen appears?
Suppose I have two screens:

Screen A

Screen B

I am initially landed on Screen A. When I click on a Button I navigate to Screen B. When I press Back Button, I am again navigated to Screen A.

I want to call an action creator when I am navigated to Screen A as mentioned in above scenario.

I just want to know that which lifecycle event will be called every time when a screen is presented.

Isn't there some event like componentWillAppear()?

Note: I am using react-native with react-navigation for navigation.

答: If you use react-native-navigation, you can listen for appearance events: https://wix.github.io/react-native-navigation/#/screen-api?id=listen-to-visibility-events-globally</p>


问:
Blade: Undefined Variable Inside Foreach Loop

I have a controller which gets an array of a User's diaries from my database and passes them to my view:

<?php

public function readDiaries($hash)
{
    $user = User::where('hash', $hash)->first();
    $diaries = Diary::where('user_id', $user->id)->get();

    return view('app.diary.readDiaries', ['diaries' => $diaries]);
}
```

<p>In my view, I am looping through the diaries using a <code>@foreach</code> loop.</p>

<pre class="lang-php prettyprint-override"><code><div id="diaries" class="card-columns">
    @if (count($diaries) > 0)
        @foreach ($diaries as $dairy)
            {{ var_dump($diary) }}
        @endforeach
    @endif
</div>
</code>```

But I am getting the following undefined variable error...

Undefined variable: diary (View: C:\xampp\htdocs\personal_projects\Active\diary_app\resources\views\app\diary\readDiaries.blade.php)

Why is my $diary variable undefined inside the @foreach loop?

答:
It is just a simple spelling mistake,

```<code> @foreach ($diaries as $dairy)
  {{ var_dump($diary) }}
 @endforeach
</code>```

in your foreach you are passing $dairy and dumping var name is $diary
chane it to

```<code>@foreach ($diaries as $dairy)
  {{ var_dump($dairy) }}
@endforeach
</code>```

Habbit of copy paste is sometimes good for us...
:)

Body:
I have a controller which gets an array of a User's diaries from my database and passes them to my view:

<?php

public function readDiaries($hash)
{
    $user = User::where('hash', $hash)->first();
    $diaries = Diary::where('user_id', $user->id)->get();

    return view('app.diary.readDiaries', ['diaries' => $diaries]);
}

In my view, I am looping through the diaries using a @foreach loop.

    @if (count($diaries) > 0)
        @foreach ($diaries as $dairy)
            {{ var_dump($diary) }}
        @endforeach
    @endif

But I am getting the following undefined variable error...

Undefined variable: diary (View: C:\xampp\htdocs\personal_projects\Active\diary_app\resources\views\app\diary\readDiaries.blade.php)

Why is my $diary variable undefined inside the @foreach loop?

Body:
It is just a simple spelling mistake,

 @foreach ($diaries as $dairy)
  {{ var_dump($diary) }}
 @endforeach

in your foreach you are passing $dairy and dumping var name is $diary
chane it to

@foreach ($diaries as $dairy)
  {{ var_dump($dairy) }}
@endforeach

Habbit of copy paste is sometimes good for us...
:)


问:
how to find the skewness of multiple columns and individually print the skew factor of a dataframe
How to find skewness of multiple columns of a dataframe in R withoug individually finding the skewness by writing skewness() multiple no. of times
Instead using a loop or something else i can find the skewness
i tried implementing this using R

```<code>for(i in length(numeric_val)) #numeric_val is a dataframe containing 38 cols and 1460 rows
 {
  if(skewness(as.numeric(unlist(numeric_val[i]))) > 0.75)
  {
    numeric_val[i] = log1p(numeric_val[i])
  }
 }
</code>```

please anyone one help me out.

答:
Maybe something like:</p>

```<code>sapply(df, function(x) ifelse(skewness(x) > 0.75, x <- log1p(x), x))
</code>```

Body:
How to find skewness of multiple columns of a dataframe in R withoug individually finding the skewness by writing skewness() multiple no. of times
Instead using a loop or something else i can find the skewness
i tried implementing this using R

for(i in length(numeric_val)) #numeric_val is a dataframe containing 38 cols and 1460 rows
 {
  if(skewness(as.numeric(unlist(numeric_val[i]))) > 0.75)
  {
    numeric_val[i] = log1p(numeric_val[i])
  }
 }

please anyone one help me out.

Body:
Maybe something like:

sapply(df, function(x) ifelse(skewness(x) > 0.75, x <- log1p(x), x))


问:
HandsOnTable Dropdown Without Editable Text?
Is it possible to use a dropdown column in a HandsOnTable without the editable textbox?

I know you can set the type to dropdown and it will validate/highlight red when you enter an invalid value, but is there a way to completely disable text entry for dropdown columns?  It seems just using the readOnly property on the column blocks the dropdown altogether.

答:
As you said, the readOnly option will disable you dropdown. So I believe the closest solution you can use is the allowIndvalid = false (true by default) :

allowInvalid: true (optional) - allows manual input of value that does not exist in the source. In this case, the field background highlight becomes red and the selection advances to the next cell

allowInvalid: false - does not allow manual input of value that does not exist  in the source. In this case, the ENTER key is ignored and the editor field remains opened.

Documentation Link

You can use this JSFiddle to quickly check this option


问:
Access iframe after it just was appended
My version that does not work:

```<code> $(window).on('load', function() {
      var $iframe = $("<iframe>",
                 {id:"up2europe",
                 marginheight:"5",
                 marginwidth:"5",
                 src:"https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
                 });

       $(".sidebar__right:first").append($iframe).on('load', function()
             alert(document.getElementbyId("#up2europe").documentElement.title);
       });
});
</code>```

So... I'm trying to access the title of the iframe...to check if it was loaded properly.

答:
I believe this is the right method to add an element with jQuery. Check out from this LINK.

Code:

```<code> $(window).on('load', function() {
   var iframe = document.createElement('iframe');
   $(iframe).css({'marginheight':'5px','marginwidth':'5px'});
   $(iframe).attr({'src':'https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d','id':'up2europe','title':'Im iframe'});
   $(".sidebar__right").append(iframe);

    $(iframe).ready(function(){
       alert($(iframe).attr('title'));
    });

 });
</code>```

Body:
My version that does not work:

 $(window).on('load', function() {
      var $iframe = $("",
                 {id:"up2europe",
                 marginheight:"5",
                 marginwidth:"5",
                 src:"https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
                 });

       $(".sidebar__right:first").append($iframe).on('load', function()
             alert(document.getElementbyId("#up2europe").documentElement.title);
       });
});

So... I'm trying to access the title of the iframe...to check if it was loaded properly.

Body:
I believe this is the right method to add an element with jQuery. Check out from this LINK.

Code:

 $(window).on('load', function() {
   var iframe = document.createElement('iframe');
   $(iframe).css({'marginheight':'5px','marginwidth':'5px'});
   $(iframe).attr({'src':'https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d','id':'up2europe','title':'Im iframe'});
   $(".sidebar__right").append(iframe);

    $(iframe).ready(function(){
       alert($(iframe).attr('title'));
    });

 });


问:
sklearn always predicts 1 when trying to predict digits
I'm trying to write code that predicts digits from curves in blender.
so I converted the curves to matrices like the ones sklearn use and tried to predict the number, unfortunately, no matter what I do the prediction is always 1.

the 2d matrix (it looks like the circle that I have in blender):

```<code>[[  0.   0.   0.   0.   0.   0.   0.   0.]
 [  0.   0.   0.  25.  25.   0.   0.   0.]
 [  0.  25.  25.  25.   0.  25.  25.   0.]
 [  0.  25.   0.   0.   0.   0.  25.   0.]
 [  0.  25.   0.   0.   0.   0.  25.   0.]
 [  0.  25.   0.   0.   0.   0.  25.   0.]
 [  0.   0.  25.  25.  25.  25.   0.   0.]
 [  0.   0.   0.   0.   0.   0.   0.   0.]]
</code>```

the code:

```<code>import bpy
import numpy as np
from sklearn import datasets
from sklearn import svm
import scipy.misc

ob = bpy.context.object
assert ob.type == 'CURVE' # throw error if it's not a curve
curve = ob.data
spline = curve.splines.active # let's assume there's only one
assert spline.type == 'BEZIER' # throw error if it's not a bezier

shortest = None
shortestDist = 10000
shortest_x = None
shortestDist_x = 10000
result = []
for point in spline.bezier_points:
    dist = point.co.y
    dist_x = point.co.x
    if dist < shortestDist : #test if better so far
        shortest = point
        shortestDist = dist
    if dist_x < shortestDist_x : #test if better so far
        shortest_x = point
        shortestDist_x = dist

print(1 / abs(shortest.co.y))
result.append([shortest, shortestDist, dist, dist_x])
mult_y = 1 / abs(shortest.co.y)
mult_x = 1 / abs(shortest_x.co.x)
point_pos = []
for point in spline.bezier_points:
    loc = point.co.y
    loc_x = point.co.x
    max_y = loc * mult_y
    max_x = loc_x * mult_x
    point_pos.append([loc, loc_x])

matrix = np.zeros((8, 8))
pixel = []

for index in enumerate(matrix):
    matrix_to_co_y = 1 / len(matrix) * index[0]
    for index_y in enumerate(matrix[index[0]]):
        matrix_to_co_x = 1 / len(matrix) * index_y[0]
        #print(matrix_to_co_y)
        for point in point_pos:
            if matrix_to_co_y > point[0] > matrix_to_co_y - 1 / len(matrix):
                if matrix_to_co_x > point[1] > matrix_to_co_x - 1 / len(matrix):
                    pixel.append([index[0], index_y[0]])

for p in enumerate(pixel):
    matrix[p[1][0]][p[1][1]] = 25

flat = np.ravel(matrix)

digits = datasets.load_digits()

clf = svm.SVC(gamma=0.001, C=100)

x,y = digits.data[:-1], digits.target[:-1]
clf.fit(x,y)
print('Prediction:',clf.predict([flat]))

print(matrix)
</code>```

I don't know what I'm doing wrong.
Any help would be appreciated

答:
This could either be a problem with your input image or with the classifier.
To test where the problem is you could

1) Try using more than one input image. Try making one image for each digit, 0-9. If your classifier predicts "1" for all of them, the problem is probably in the classifier. But if it can predict some of them, then it was likely just your single input image that caused trouble.

2) Try using a different classifier. Almost anything can give you decent performance on the digits dataset. I tried with RandomForestClassifier, and it correctly predicts your image as "0".

Proof of concept:

```<code>import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
my_input = np.array(
 [[  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
 [  0.,   0.,   0.,  25.,  25.,   0.,   0.,   0.],
 [  0.,  25.,  25.,  25.,   0.,  25.,  25.,   0.],
 [  0.,  25.,   0.,   0.,   0.,   0.,  25.,   0.],
 [  0.,  25.,   0.,   0.,   0.,   0.,  25.,   0.],
 [  0.,  25.,   0.,   0.,   0.,   0.,  25.,   0.],
 [  0.,   0.,  25.,  25.,  25.,  25.,   0.,   0.],
 [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.]])
iris = datasets.load_iris()
digits = datasets.load_digits()
clf = RandomForestClassifier()
clf.fit(digits.data, digits.target)
clf.predict(my_input.reshape(1, -1))
# Outputs array([0])
</code>```

Body:
I'm trying to write code that predicts digits from curves in blender.
so I converted the curves to matrices like the ones sklearn use and tried to predict the number, unfortunately, no matter what I do the prediction is always 1.

the 2d matrix (it looks like the circle that I have in blender):

[[  0.   0.   0.   0.   0.   0.   0.   0.]
 [  0.   0.   0.  25.  25.   0.   0.   0.]
 [  0.  25.  25.  25.   0.  25.  25.   0.]
 [  0.  25.   0.   0.   0.   0.  25.   0.]
 [  0.  25.   0.   0.   0.   0.  25.   0.]
 [  0.  25.   0.   0.   0.   0.  25.   0.]
 [  0.   0.  25.  25.  25.  25.   0.   0.]
 [  0.   0.   0.   0.   0.   0.   0.   0.]]

the code:

import bpy
import numpy as np
from sklearn import datasets
from sklearn import svm
import scipy.misc

ob = bpy.context.object
assert ob.type == 'CURVE' # throw error if it's not a curve
curve = ob.data
spline = curve.splines.active # let's assume there's only one
assert spline.type == 'BEZIER' # throw error if it's not a bezier

shortest = None
shortestDist = 10000
shortest_x = None
shortestDist_x = 10000
result = []
for point in spline.bezier_points:
    dist = point.co.y
    dist_x = point.co.x
    if dist < shortestDist : #test if better so far
        shortest = point
        shortestDist = dist
    if dist_x < shortestDist_x : #test if better so far
        shortest_x = point
        shortestDist_x = dist

print(1 / abs(shortest.co.y))
result.append([shortest, shortestDist, dist, dist_x])
mult_y = 1 / abs(shortest.co.y)
mult_x = 1 / abs(shortest_x.co.x)
point_pos = []
for point in spline.bezier_points:
    loc = point.co.y
    loc_x = point.co.x
    max_y = loc * mult_y
    max_x = loc_x * mult_x
    point_pos.append([loc, loc_x])

matrix = np.zeros((8, 8))
pixel = []

for index in enumerate(matrix):
    matrix_to_co_y = 1 / len(matrix) * index[0]
    for index_y in enumerate(matrix[index[0]]):
        matrix_to_co_x = 1 / len(matrix) * index_y[0]
        #print(matrix_to_co_y)
        for point in point_pos:
            if matrix_to_co_y > point[0] > matrix_to_co_y - 1 / len(matrix):
                if matrix_to_co_x > point[1] > matrix_to_co_x - 1 / len(matrix):
                    pixel.append([index[0], index_y[0]])

for p in enumerate(pixel):
    matrix[p[1][0]][p[1][1]] = 25

flat = np.ravel(matrix)

digits = datasets.load_digits()

clf = svm.SVC(gamma=0.001, C=100)

x,y = digits.data[:-1], digits.target[:-1]
clf.fit(x,y)
print('Prediction:',clf.predict([flat]))

print(matrix)

I don't know what I'm doing wrong.
Any help would be appreciated

Body:
This could either be a problem with your input image or with the classifier.
To test where the problem is you could

1) Try using more than one input image. Try making one image for each digit, 0-9. If your classifier predicts "1" for all of them, the problem is probably in the classifier. But if it can predict some of them, then it was likely just your single input image that caused trouble.

2) Try using a different classifier. Almost anything can give you decent performance on the digits dataset. I tried with RandomForestClassifier, and it correctly predicts your image as "0".

Proof of concept:

import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
my_input = np.array(
 [[  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
 [  0.,   0.,   0.,  25.,  25.,   0.,   0.,   0.],
 [  0.,  25.,  25.,  25.,   0.,  25.,  25.,   0.],
 [  0.,  25.,   0.,   0.,   0.,   0.,  25.,   0.],
 [  0.,  25.,   0.,   0.,   0.,   0.,  25.,   0.],
 [  0.,  25.,   0.,   0.,   0.,   0.,  25.,   0.],
 [  0.,   0.,  25.,  25.,  25.,  25.,   0.,   0.],
 [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.]])
iris = datasets.load_iris()
digits = datasets.load_digits()
clf = RandomForestClassifier()
clf.fit(digits.data, digits.target)
clf.predict(my_input.reshape(1, -1))
# Outputs array([0])


问:
How to call the usb tethering intent in android 4.0 and 3.0?
I am developing an application for Android 3.0 and above. I want to communicate to a PC by tethering.

How do I call the "Wireless and networks-Tethering and portable hotspot Intent" by code to enable the tethering manually?

答:
this code just starts the tethering settings and clicks on the USB tethering checkbox (setting it on if it's off and vice versa).</p>

```<code>adb shell am start -n com.android.settings/.TetherSettings && adb shell input keyevent 20 && adb shell input keyevent 20 && adb shell input keyevent KEYCODE_ENTER && sleep 2 && adb shell input keyevent 4
</code>```

Body:
this code just starts the tethering settings and clicks on the USB tethering checkbox (setting it on if it's off and vice versa).

adb shell am start -n com.android.settings/.TetherSettings && adb shell input keyevent 20 && adb shell input keyevent 20 && adb shell input keyevent KEYCODE_ENTER && sleep 2 && adb shell input keyevent 4


问:
Windows update apparently deleted Android SDK files from Visual Studio
I just restarted my Windows 10 machine to install some updates, and afterward I started getting this error in Visual Studio:

```<code>Error       Xamarin.Android for Visual Studio requires Android SDK.
Please install it or set Android SDK path on Tools->Options->Xamarin->Android Settings menu.            0
</code>```

Which I thought was weird, since I'd never run into any issues with my Android SDK before. So I went to Tools->Android to open the SDK manager, but all the options were grayed out and not selectable. Here's a screenshot:

So I did a little research, and this post told me to manually start my SDK manager with the .exe file. So I searched my files for the SDK manager, but when I clicked to open it, I got this error message:

```<code>The item that this shortcut refers to has been changed or moved.
Would you like to remove this shortcut?
</code>```

And I got the same error for the Uninstall Android SDK Tools and AVD Manager shortcuts. So it seems that all my Android SDK files were for some reason deleted during my Windows updates.

Then I noticed that under Visual Studio Tools->Options->Xamarin->Android, the "Android SDK Location" was empty. Screenshot:

So then I downloaded Android Studio from the official site, found the location to the .exe file, and then copy-and-pasted the path into the "Android SDK Location" field, and clicked "OK". But the field wasn't saved. No matter what I do, when I open Options, the "Android SDK Location" field is always empty.

I have no idea how to proceed. Anyone have any ideas?

UPDATE

I ran Visual Studio Installer, clicked Modify, and under "Individual Components", it tells me that I already have the latest Android SDK setup (API level 25) installed. Do I need to install something other than that? Screenshot:

答:
First, Android SDK Location path is Android SDK path not .exe file path.
Second, check the path C:\Program Files (x86)\Android\android-sdk which is default path to store Android SDK by Visual Studio to see whether it exists. In my computer like this:

If it doesn't exists, it maybe have been deleted by your computer update process.
Why the "Android SDK Location" field is always empty is because the path is wrong.

You can also get Android SDK path with the Android Studio which you have downloaded:

Android Stuido -> File -> Settings -> Appearance & Behavior -> System Settings -> Android SDK, then copy-and-pasted the Android SDK Location path to Visual Studio. Find it like this in Android Studio:

Body:
I just restarted my Windows 10 machine to install some updates, and afterward I started getting this error in Visual Studio:

Error       Xamarin.Android for Visual Studio requires Android SDK.
Please install it or set Android SDK path on Tools->Options->Xamarin->Android Settings menu.            0

Which I thought was weird, since I'd never run into any issues with my Android SDK before. So I went to Tools->Android to open the SDK manager, but all the options were grayed out and not selectable. Here's a screenshot:

So I did a little research, and this post told me to manually start my SDK manager with the .exe file. So I searched my files for the SDK manager, but when I clicked to open it, I got this error message:

The item that this shortcut refers to has been changed or moved.
Would you like to remove this shortcut?

And I got the same error for the Uninstall Android SDK Tools and AVD Manager shortcuts. So it seems that all my Android SDK files were for some reason deleted during my Windows updates.

Then I noticed that under Visual Studio Tools->Options->Xamarin->Android, the "Android SDK Location" was empty. Screenshot:

So then I downloaded Android Studio from the official site, found the location to the .exe file, and then copy-and-pasted the path into the "Android SDK Location" field, and clicked "OK". But the field wasn't saved. No matter what I do, when I open Options, the "Android SDK Location" field is always empty.

I have no idea how to proceed. Anyone have any ideas?

UPDATE

I ran Visual Studio Installer, clicked Modify, and under "Individual Components", it tells me that I already have the latest Android SDK setup (API level 25) installed. Do I need to install something other than that? Screenshot:


问:
change from mySQL to SQL and now cant get record creation
I am running WAMP 2.5 on Win7 and created a webpage to insert records into a mySQL database. This worked perfectly.
Then I needed to use SQL Server 2014 (remote server on LAN) instead of mySQL (local in WAMP), and while everything seems ok, i am not getting the records created in the table, yet no error either.
Account used to log in with is db owner.
Any help would be great.
Thanks
Len

Code is as follow (I call sqlconnect.php for db connection) and get confirmation that connection was successful.
File is called insert-data.php so it calls itself if form is empty and Submit is selected.

```<code><?php

if(!empty($_POST['mcpbarcode'])) {
    header("Location insert-data.php");
    include('sqlconnect.php');

    $mcpbarcode = $_POST['mcpbarcode'];
    $sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
                    VALUES ('$mcpbarcode')";
sqlsrv_query($conn,$sqlinsert);
    if (!$sqlinsert)    {
        die('error inserting new record');
    }
    $newrecord = "New record added";
}
?>
<html>
<head>
<title> Insert Barcode into Database</title>
</head>
<h3><font color = red>This window must be open and active</font></h3>
<img src="header.jpg" alt="anyname" style="width:800px;height:165px;">
<body>
<h1> Insert barcode into Database</h1>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<label>Barcode:<input type="text" name="mcpbarcode" autofocus /></label>
<br /><br />
<input type="submit" value="Add new record" />
</form>
<?php
$newrecord="";
echo $newrecord
?>
</body>
</html>
</code>```

答:
See if it's working like that:

If mcpbarcode column is a string type (varchar, char etc):

```<code> $sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
                    VALUES ('".$mcpbarcode."')"
</code>```

OR if mcpbarcode column is int, float, etc:

```<code> $sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
                    VALUES (".$mcpbarcode.")"
</code>```

but you should have an error on mysql also ...

Body:
I am running WAMP 2.5 on Win7 and created a webpage to insert records into a mySQL database. This worked perfectly.
Then I needed to use SQL Server 2014 (remote server on LAN) instead of mySQL (local in WAMP), and while everything seems ok, i am not getting the records created in the table, yet no error either.
Account used to log in with is db owner.
Any help would be great.
Thanks
Len

Code is as follow (I call sqlconnect.php for db connection) and get confirmation that connection was successful.
File is called insert-data.php so it calls itself if form is empty and Submit is selected.

<?php

if(!empty($_POST['mcpbarcode'])) {
    header("Location insert-data.php");
    include('sqlconnect.php');

    $mcpbarcode = $_POST['mcpbarcode'];
    $sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
                    VALUES ('$mcpbarcode')";
sqlsrv_query($conn,$sqlinsert);
    if (!$sqlinsert)    {
        die('error inserting new record');
    }
    $newrecord = "New record added";
}
?>

<title> Insert Barcode into Database</title>

This window must be open and active

 Insert barcode into Database

<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
Barcode:<input type="text" name="mcpbarcode" autofocus />

<input type="submit" value="Add new record" />
</form>
<?php
$newrecord="";
echo $newrecord
?>

Body:
See if it's working like that:

If mcpbarcode column is a string type (varchar, char etc):

 $sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
                    VALUES ('".$mcpbarcode."')"

OR if mcpbarcode column is int, float, etc:

 $sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
                    VALUES (".$mcpbarcode.")"

but you should have an error on mysql also ...


问:
How to rotate a large background image once the next image loads, but without having to preload all at once?
I need a large rotating background image on a homepage. This is how I want it to work:

During the first round, the next image is displayed only after it is preloaded. While it's waiting on the current image, there should be a small spinner overlaid in the corner. Once it cycles through each and consequently they all have been loaded, it will default to a regular interval.

I don't want to have to preload all the images and then cycle through, but I also don't want to just cycle through and have one disappear and a gap until the next loads.

I've been looking around for jQuery plugins that cycle background images and preload only the next image at a time. So far I've just found plugins that only rotate or only preload. Does what I want exist? If so, where can I find it? Otherwise, do I have to find a way to merge the two myself? Any tips for doing that?

Thanks for any help!

答:
I have an example here:

http://jsfiddle.net/jtbowden/27UHX/

It preloads each image, calling the next preload after it is done.  After the last one, it begins rotating through each image normally.

It's mostly plain JavaScript.


问:
How to separate a list into two different lists ?(Python2.7)
My current data is in the format of :

```<code>[  1982,      1, 108108,   5568],
[  1982,      2,  64488,   2433],
...,
[  2007,    498,   4341,    395],
[  2007,    499,   4328,    274],
[  2007,    500,   4323,   -118]]
</code>```

I want to put all of the data that is from 1982 into one list, and all of the data that is from 2007 into another list.

How would I do this?

答:
Try the following:</p>

```<code>def accessYear(year, data):
    return filter(lambda i: i[0] == year, data)
</code>```

Body:
My current data is in the format of :

[  1982,      1, 108108,   5568],
[  1982,      2,  64488,   2433],
...,
[  2007,    498,   4341,    395],
[  2007,    499,   4328,    274],
[  2007,    500,   4323,   -118]]

I want to put all of the data that is from 1982 into one list, and all of the data that is from 2007 into another list.

How would I do this?

Body:
Try the following:

def accessYear(year, data):
    return filter(lambda i: i[0] == year, data)


问:
subgroup identification with regression tree
I am very interested in a recent paper on "Tutorial in biostatistics: data-driven subgroup identification and analysis in clinical trials " (DOI: 10.1002/sim.7064), and I want to reproduce results in the section "Performance of the tree-based regression approach". However, the partitioning tree seems not get the result as I want.

```<code>set.seed(123)
n <- 1000
x1 <- rnorm(n)
x2 <- runif(n)
t <- rbinom(n,1,0.5)
x3 <- rbinom(n,1,0.3)
x4 <- rnorm(n)
z <-1+ 2*x1-1.8*x2+(x1>=-0.3)*(x2>=0.4)*t-(x1< -0.3)*(x2<0.4)*t
pr = 1/(1+exp(-z))
y = rbinom(n,1,pr)
dt <- data.frame(x1,x2,x3,x4,t,y)

library(party)
mb <- mob(y~t-1|x1+x2+x3+x4,
  data=dt,
  model = glinearModel,
  family = binomial(),
  control=mob_control(minsplit=100))
plot(mb)
</code>```

The figure is shown above. It is supposed to split on x1 and x2 at cutoff values of -0.3 and 0.4 defined in the simulation. However, it doesn't appear to do so.x1 dominated the node partition and x2 seems not an important determinant of the partitioning process. What's wrong with the code?

答:
```<code>set.seed(123)
n <- 1000
x1 <- rnorm(n)
x2 <- runif(n)
t <- rbinom(n,1,0.5)
x3 <- rbinom(n,1,0.3)
x4 <- rnorm(n)
z <-1+ 2*x1-1.8*x2+
  (x1>=-0.3)*(x2>=0.4)*t-
  (x1< -0.3)*(x2<0.4)*t
pr = 1/(1+exp(-z))
y = as.factor(rbinom(n,1,pr))
dt <- data.frame(x1,x2,x3=as.factor(x3),
  x4,t=as.factor(t),y)
</code>```

The treatment effect should be statistically significant at two covariate space:

```<code>dt1 <- dt[x1>=-0.3&x2>=0.4,]
dt2 <- dt[x1< -0.3&x2<0.4,]
chisq.test(table(dt1$t,dt1$y))
Pearson's Chi-squared test with Yates' continuity correction

data:  table(dt1$t, dt1$y)
X-squared = 11.684, df = 1, p-value = 0.0006305

prop.table(table(dt1$t,dt1$y),1)
chisq.test(table(dt2$t,dt2$y))
prop.table(table(dt2$t,dt2$y),1)
chisq.test(table(dt$t,dt$y))
</code>```

I use the glmtree() fucntion and the result is different from your output that interaction with x2 is correctly identified on the left, but the right side fails to capture the partition on x2.

```<code>library(partykit)
tr1 <- glmtree(y~t+x1+x2 | x1+x2+x3+x4,
  data=dt,
  family = binomial())
plot(tr1,tp_args = list(which = 1))
</code>```

Body:
I am very interested in a recent paper on "Tutorial in biostatistics: data-driven subgroup identification and analysis in clinical trials " (DOI: 10.1002/sim.7064), and I want to reproduce results in the section "Performance of the tree-based regression approach". However, the partitioning tree seems not get the result as I want.

set.seed(123)
n <- 1000
x1 <- rnorm(n)
x2 <- runif(n)
t <- rbinom(n,1,0.5)
x3 <- rbinom(n,1,0.3)
x4 <- rnorm(n)
z <-1+ 2*x1-1.8*x2+(x1>=-0.3)*(x2>=0.4)*t-(x1< -0.3)*(x2<0.4)*t
pr = 1/(1+exp(-z))
y = rbinom(n,1,pr)
dt <- data.frame(x1,x2,x3,x4,t,y)

library(party)
mb <- mob(y~t-1|x1+x2+x3+x4,
  data=dt,
  model = glinearModel,
  family = binomial(),
  control=mob_control(minsplit=100))
plot(mb)

The figure is shown above. It is supposed to split on x1 and x2 at cutoff values of -0.3 and 0.4 defined in the simulation. However, it doesn't appear to do so.x1 dominated the node partition and x2 seems not an important determinant of the partitioning process. What's wrong with the code?

Body:
set.seed(123)
n <- 1000
x1 <- rnorm(n)
x2 <- runif(n)
t <- rbinom(n,1,0.5)
x3 <- rbinom(n,1,0.3)
x4 <- rnorm(n)
z <-1+ 2*x1-1.8*x2+
  (x1>=-0.3)*(x2>=0.4)*t-
  (x1< -0.3)*(x2<0.4)*t
pr = 1/(1+exp(-z))
y = as.factor(rbinom(n,1,pr))
dt <- data.frame(x1,x2,x3=as.factor(x3),
  x4,t=as.factor(t),y)

The treatment effect should be statistically significant at two covariate space:

dt1 <- dt[x1>=-0.3&x2>=0.4,]
dt2 <- dt[x1< -0.3&x2<0.4,]
chisq.test(table(dt1$t,dt1$y))
Pearson's Chi-squared test with Yates' continuity correction

data:  table(dt1$t, dt1$y)
X-squared = 11.684, df = 1, p-value = 0.0006305

prop.table(table(dt1$t,dt1$y),1)
chisq.test(table(dt2$t,dt2$y))
prop.table(table(dt2$t,dt2$y),1)
chisq.test(table(dt$t,dt$y))

I use the glmtree() fucntion and the result is different from your output that interaction with x2 is correctly identified on the left, but the right side fails to capture the partition on x2.

library(partykit)
tr1 <- glmtree(y~t+x1+x2 | x1+x2+x3+x4,
  data=dt,
  family = binomial())
plot(tr1,tp_args = list(which = 1))


问:
How to remove the rows while using add more functionality
Here I want to make add more functionality, if I am clicking add more button means I want to make a copy of one row it is working fine, but again I want to remove this row means I don't how to do? if I am clicking remove button I want to remove the selected row, not for all rows, I am a new person of development anyone means please update my snippet

var i=0;
$(document).on("click",".addSharingType",function() {
  i++;

  var htmlText = '';
  htmlText += '

 Sharing Type<select class="form-control seelectcss1 border" name="sharingType[]" required=""><option value="">Select</option><option value="Single Sharing">Single Sharing</option><option value="Two Sharing">Two Sharing</option><option value="Three Sharing">Three Sharing</option><option value="Four Sharing">Four Sharing</option></select>

Rent With Food :
<input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">

Please Enter Amount

Rent Without Food
<input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">

Advance Amount
<input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">

';

  htmlText +='

<button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> Add</button>  <button type="button" class="btn btn-danger addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> remove</button>

';

  htmlText +='

';
  htmlText +='

';
  $('.sharingType').append(htmlText);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

<div class="controls">
  <div class="row">
    <div class="col-md-6 col-sm-4 col-xs-12">
      <label>Sharing Type</label>
      <select class="form-control seelectcss1 border" name="sharingType[]" required="">
        <option value="">Select</option>
        <option value="Single Sharing">Single Sharing</option>
        <option value="Two Sharing">Two Sharing</option>
        <option value="Three Sharing">Three Sharing</option>
        <option value="Four Sharing">Four Sharing</option>
      </select>
    </div>
  </div>

  <div class="row entry">
    <div class="col-md-3 col-sm-4 col-xs-12" style="padding-right:5px;">
      <div class="form-group" id="imm">
        <label class="control-label">Rent With Food :</label>
        <br>
        <input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">
        <img src="image/rup.png" id="try"> <div id="word"></div>
        <p class="custom-error amountError" style="display:none">Please Enter Amount</p>
     </div>
    </div>

    <div class="col-md-3 col-sm-4 col-xs-12" style="padding-right:5px;">
      <div class="form-group" id="imm">
        <label class="control-label">Rent Without Food </label>
        <br>
        <input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">
        <img src="image/rup.png" id="try"><div id="word1"></div>
      </div>
    </div>
    <div class="col-md-3 col-sm-4 col-xs-12">
      <div class="form-group" id="imm">
        <label class="control-label">Advance Amount</label>
        <br>
        <input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">
        <img src="image/rup.png" id="try"><div id="word2"></div>
      </div>
    </div>

    <div class="col-md-3 col-sm-4 col-xs-12">
      <div class="form-group" id="imm">
        <button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"><span class="glyphicon glyphicon-plus"></span> Add Sharing</button>
      </div>
    </div>
  </div>
</div>
<div class="sharingType"></div></code>```

答:
@Mithun I am glad you got the answer that you wanted. I did give an attempt to fix you code; But I found it a bit uncomfortable given that you were appending html via javascript (which is never a good practise)

So, I accomplished your requirement (delete rows, clone rows) in pure javascript.

Since you are new to development, may I request that you avoid using libraries right away and try coding in vanilla js. Believe me, this will make you a great developer.

Have a look at my snippet; I hope it gives you an idea of solving the same issue in vanilla js.   Cheers

window.onload = addEventListeners();

function addEventListeners() {
  let cloneButtons = document.getElementsByClassName("clone");
  let deleteButtons = document.getElementsByClassName("delete");

  for(let button of cloneButtons) {
     button.onclick = cloneDiv;
  }
  for(let button of deleteButtons) {
     button.onclick = deleteDiv;
  }
}

function cloneDiv() {
   let wrapper = document.getElementById("wrapper");
   let clonedDiv = wrapper.firstElementChild.cloneNode(true);
   wrapper.appendChild(clonedDiv);
   addEventListeners();
}

function deleteDiv() {
   let targetDiv = this.closest('.divToClone');
   targetDiv.remove();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
<div class="divToClone">
<p>
this line
</p>
<p>
will be
</p>
<p>
cloned or removed
</p>
<p>
based on your choice
</p>
<button class="clone"> Clone row </button>
<button class="delete"> Delete row </button>
</div>
</div></code>```

Body:
Here I want to make add more functionality, if I am clicking add more button means I want to make a copy of one row it is working fine, but again I want to remove this row means I don't how to do? if I am clicking remove button I want to remove the selected row, not for all rows, I am a new person of development anyone means please update my snippet

var i=0;
$(document).on("click",".addSharingType",function() {
  i++;

  var htmlText = '';
  htmlText += '

 Sharing Type<select class="form-control seelectcss1 border" name="sharingType[]" required=""><option value="">Select</option><option value="Single Sharing">Single Sharing</option><option value="Two Sharing">Two Sharing</option><option value="Three Sharing">Three Sharing</option><option value="Four Sharing">Four Sharing</option></select>

Rent With Food :
<input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">

Please Enter Amount

Rent Without Food
<input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">

Advance Amount
<input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">

';

  htmlText +='

<button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> Add</button>  <button type="button" class="btn btn-danger addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> remove</button>

';

  htmlText +='

';
  htmlText +='

';
  $('.sharingType').append(htmlText);
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

      Sharing Type
      <select class="form-control seelectcss1 border" name="sharingType[]" required="">
        <option value="">Select</option>
        <option value="Single Sharing">Single Sharing</option>
        <option value="Two Sharing">Two Sharing</option>
        <option value="Three Sharing">Three Sharing</option>
        <option value="Four Sharing">Four Sharing</option>
      </select>

        Rent With Food :

        <input type="number" class="form-control nput border" name="withFood[]" id="withfood" onkeyup="word.innerHTML=convertNumberToWords(this.value)">

Please Enter Amount

        Rent Without Food

        <input type="number" class="form-control nput border" name="withoutFood[]" id="withoutfood" onkeyup="word1.innerHTML=convertNumberToWords1(this.value)">

        Advance Amount

        <input type="number" class="form-control  nput border" name="advance[]" id="advance" onkeyup="word2.innerHTML=convertNumberToWords1(this.value)">

        <button type="button" class="btn btn-success addSharingType" style="margin-top: 26px;height: 38px;" id="admore"> Add Sharing</button>

Body:
@Mithun I am glad you got the answer that you wanted. I did give an attempt to fix you code; But I found it a bit uncomfortable given that you were appending html via javascript (which is never a good practise)

So, I accomplished your requirement (delete rows, clone rows) in pure javascript.

Since you are new to development, may I request that you avoid using libraries right away and try coding in vanilla js. Believe me, this will make you a great developer.

Have a look at my snippet; I hope it gives you an idea of solving the same issue in vanilla js.   Cheers

window.onload = addEventListeners();

function addEventListeners() {
  let cloneButtons = document.getElementsByClassName("clone");
  let deleteButtons = document.getElementsByClassName("delete");

  for(let button of cloneButtons) {
     button.onclick = cloneDiv;
  }
  for(let button of deleteButtons) {
     button.onclick = deleteDiv;
  }
}

function cloneDiv() {
   let wrapper = document.getElementById("wrapper");
   let clonedDiv = wrapper.firstElementChild.cloneNode(true);
   wrapper.appendChild(clonedDiv);
   addEventListeners();
}

function deleteDiv() {
   let targetDiv = this.closest('.divToClone');
   targetDiv.remove();
}

<div id="wrapper">
<div class="divToClone">
<p>
this line
</p>
<p>
will be
</p>
<p>
cloned or removed
</p>
<p>
based on your choice
</p>
<button class="clone"> Clone row </button>
<button class="delete"> Delete row </button>
</div>
</div>


问:
Random BigFloats Julia
Is it possible to generate random numbers of BigFloat type uniformly distributed in the interval [0,1)?

I mean, since rand(BigFloat) is not available it seems we have to use BigFloat(rand()) for that ending. However this is not satisfactory for me as  we are generating random Float64 numbers that are converted to BigFloats basically by "adding" a string of zeros, but in essence they are Float64 random numbers. Is this correct? If yes, is there any special library to generate random numbers with arbitrary precision?

Title: Random BigFloats Julia

Body:
Is this method good:

randbigfloat(n) =
  ( e = rand(0:n) ;
    parse(BigFloat, join([rand('0':'9', e)...,'.',rand('0':'9', n-e)...])) )

With usage:

julia> randbigfloat(10)
3.09424947699999999999999999999999999999999999999999999999999999999999999999999e+05

julia> randbigfloat(10)
7.146482599999999999999999999999999999999999999999999999999999999999999999999975

It might not be the most efficient method though.