问:
Conflict libraries lodash.js and underscore.js
My project uses the lodash.js library. Off I need to add my project to another project that uses the underscore.js library.
This puts me in conflict errors between these two libraries.

I tried writing this, but it does not change anything:

```<code><script src="/web/externals/underscore/underscore.js"></script>
<script src="/web/externals/lodash/lodash.js"></script>

<script>
    window.lodash = _.noConflict();
    window.underscore = _.noConflict();
</script>

<app-root></app-root>
<script type="text/javascript" src="/etc/inline.bundle.js"></script>
<script type="text/javascript" src="/etc/polyfills.bundle.js"></script>
</code>```

//////////EDIT////////

```<code><script src="/web/externals/underscore/underscore.js"></script>
<script src="/web/externals/lodash/lodash.js"></script>

<script>
    var lodash = _.noConflict()
</script>

<app-root></app-root>
<script type="text/javascript" src="/etc/chat/inline.bundle.js"></script>
<script type="text/javascript" src="/etc/chat/polyfills.bundle.js"></script>
</code>```

答:
To use noConflicts in this case, you need to import one library, use _.noConflicts, then import the other.  For example:

```

FWIW, though, it might be worth looking into bundling your apps with something like webpack.  That would allow each to have its own version of dependencies, without needing to fight over the global scope.

Body:
My project uses the lodash.js library. Off I need to add my project to another project that uses the underscore.js library.
This puts me in conflict errors between these two libraries.

I tried writing this, but it does not change anything:

<app-root></app-root>

//////////EDIT////////

<app-root></app-root>

Body:
To use noConflicts in this case, you need to import one library, use _.noConflicts, then import the other.  For example:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<script>
    window.lodash = _.noConflict();
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script>
    window.underscore = _.noConflict()
</script>

<script>
    console.log("Lodash version is " + lodash.VERSION)
    console.log("Underscore version is " + underscore.VERSION)
</script>

FWIW, though, it might be worth looking into bundling your apps with something like webpack.  That would allow each to have its own version of dependencies, without needing to fight over the global scope.


来源: stackexchange

问:
Writing A Program that clicks a Chrome alert box
I have an alert that comes up in chrome, it slides into the browser on the top right hand side of the window. Every time this specific alert comes up I have to move my mouse over and click the alert box which will then open up a link in a new window. I have to do this multiple times a day. I'd be great if I could write a Javascript or Python program that will automatically "click" the box every time it comes up in the browser. Is there a way to do this? I have a little over a year of programming experience but I don't expect a step by step answer, just set me off in the right direction. I've looked up browser events hoping I could just write an event listener function but I couldn't find one specifically for browser alerts.</p>

答:
If it is the native modal of the browser, then the short answer is no.

You can't do it with javascript as the confirm (alert) pop up is a blocking modal.

No javascript code can run while the confirm modal is open.

If this is a custom modal that built and controlled by javascript then there is a good chance of doing just about anything you want with it.

ContentLicense: CC BY-SA 3.0


问:
Windows 7 Desktop Manager
when we drag a window to the side of the screen we get like a ripple effect, can we change that programaticaly?</p>

答:
i can't be 100% certain, but i'm 99.9999% certain that effect is not under program control.

That is a feature of Windows which, at the very most, would be left as a user preference.

So the answer to your question is, "No, you cannot change that programatically."

ContentLicense: CC BY-SA 2.5

Title: Windows 7 Desktop Manager


问:
How to retrieve each value from string and add them to the list
This is my code so far in C#

```<code>string myString = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";
var tuple = new List<Tuple<int, int>>();
foreach (var value in myString)
{
    int startPos = myString.IndexOf("value:") + "value:".Length;
    int length = myString.LastIndexOf(", data") - startPos;
    string valuesX = myString.Substring(startPos, length);
    int values = int.Parse(valuesX);
    int startPos2 = myString.IndexOf("data:") + "data:".Length;
    int length2 = myString.LastIndexOf(", end") - startPos2;
    string dataX = myString.Substring(startPos2, length2);
    int data = int.Parse(dataX);
    tuple.Add(Tuple.Create(values, data));
}
</code>```

I want to retrieve the value number and data number from string and put them into a list using integer data type

this picture demonstrates what I want to achieve:

The code simply does not work and I would appreciate any help, thank you

答:
Using Linq, you can process the string into substrings and then into values in Lists:

```<code>var tuples = myString.Split(new[] { ", end" }, StringSplitOptions.None) ' split into data strings
                     .Select(s => s.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries) ' split into data string pairs
                     .Select(s2 => Int32.Parse(s2.Split(':')[1])).ToList()) ' extract number and make int32 pairs
                     .Where(s => s.Count > 0) ' exclude empty data strings
                     .Select(s => (s[0], s[1])).ToList(); ' create tuples and put in a List
</code>```

Body:
This is my code so far in C#

string myString = "value:12345, data:34298, end, value2:678910, data2:48957, end, value3:56546, data3:83576, end";
var tuple = new List<Tuple<int, int>>();
foreach (var value in myString)
{
    int startPos = myString.IndexOf("value:") + "value:".Length;
    int length = myString.LastIndexOf(", data") - startPos;
    string valuesX = myString.Substring(startPos, length);
    int values = int.Parse(valuesX);
    int startPos2 = myString.IndexOf("data:") + "data:".Length;
    int length2 = myString.LastIndexOf(", end") - startPos2;
    string dataX = myString.Substring(startPos2, length2);
    int data = int.Parse(dataX);
    tuple.Add(Tuple.Create(values, data));
}

I want to retrieve the value number and data number from string and put them into a list using integer data type

this picture demonstrates what I want to achieve:

The code simply does not work and I would appreciate any help, thank you

Body:
Using Linq, you can process the string into substrings and then into values in Lists:

var tuples = myString.Split(new[] { ", end" }, StringSplitOptions.None) ' split into data strings
                     .Select(s => s.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries) ' split into data string pairs
                     .Select(s2 => Int32.Parse(s2.Split(':')[1])).ToList()) ' extract number and make int32 pairs
                     .Where(s => s.Count > 0) ' exclude empty data strings
                     .Select(s => (s[0], s[1])).ToList(); ' create tuples and put in a List


问:
installing jdk/sbt on new ubuntu machine
I'm trying to install SBT on a fresh Ubuntu 16.04 machine on AWS.  I've never had a problem installing (following instructions) before, but I am now.

I get this error...  "The java installation you have is not up to date
requires at least version 1.6+, you have version 1.8"

Seems confusing, since 1.8 seems to satisfy the 1.6+ requirement.

references

scala - https://www.scala-lang.org/documentation/getting-started-sbt-track/getting-started-with-scala-and-sbt-on-the-command-line.html

sbt - http://www.scala-sbt.org/1.0/docs/Installing-sbt-on-Linux.html

```<code>sudo apt-get update

java -version
# The program 'java' can be found in the following packages:
#  * default-jre
#  * gcj-5-jre-headless
#  * openjdk-8-jre-headless
#  * gcj-4.8-jre-headless
#  * gcj-4.9-jre-headless
#  * openjdk-9-jre-headless
# Try: sudo apt install <selected package>

sudo apt-get install openjdk-8-jdk -y

java -version
# openjdk version "1.8.0_151"
# OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-0ubuntu0.16.04.2-b12)
# OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)

echo "deb https://dl.bintray.com/sbt/debian /" | sudo tee -a /etc/apt/sources.list.d/sbt.list
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2EE0EA64E40A89B84B2DF73499E82A75642AC823
sudo apt-get update
sudo apt-get install sbt

sbt
# /usr/share/sbt/bin/sbt-launch-lib.bash: line 207: bc: command not found

# The java installation you have is not up to date
# requires at least version 1.6+, you have
# version 1.8

# Please go to http://www.java.com/getjava/ and download
# a valid Java Runtime and install before running .
</code>```

答:
Looking at the source of the setup, it is using bc to do the arithmetic check on the java version number and is unable to run bc.

https://github.com/sbt/sbt-launcher-package/blob/320d993fa6a9ad857b65d4cafca6ea9e5d1550b3/src/universal/bin/sbt-launch-lib.bash#L207

You can install bc with apt install bc.

Body:
I'm trying to install SBT on a fresh Ubuntu 16.04 machine on AWS.  I've never had a problem installing (following instructions) before, but I am now.

I get this error...  "The java installation you have is not up to date
requires at least version 1.6+, you have version 1.8"

Seems confusing, since 1.8 seems to satisfy the 1.6+ requirement.

references

scala - https://www.scala-lang.org/documentation/getting-started-sbt-track/getting-started-with-scala-and-sbt-on-the-command-line.html

sbt - http://www.scala-sbt.org/1.0/docs/Installing-sbt-on-Linux.html

sudo apt-get update

java -version
# The program 'java' can be found in the following packages:
#  * default-jre
#  * gcj-5-jre-headless
#  * openjdk-8-jre-headless
#  * gcj-4.8-jre-headless
#  * gcj-4.9-jre-headless
#  * openjdk-9-jre-headless
# Try: sudo apt install <selected package>

sudo apt-get install openjdk-8-jdk -y

java -version
# openjdk version "1.8.0_151"
# OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-0ubuntu0.16.04.2-b12)
# OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)

echo "deb https://dl.bintray.com/sbt/debian /" | sudo tee -a /etc/apt/sources.list.d/sbt.list
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2EE0EA64E40A89B84B2DF73499E82A75642AC823
sudo apt-get update
sudo apt-get install sbt

sbt
# /usr/share/sbt/bin/sbt-launch-lib.bash: line 207: bc: command not found

# The java installation you have is not up to date
# requires at least version 1.6+, you have
# version 1.8

# Please go to http://www.java.com/getjava/ and download
# a valid Java Runtime and install before running .

ContentLicense: CC BY-SA 4.0


问:
android - Running app fails with error 'com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex'
I am trying to run my application on my phone but during build time it fails with the following error:

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

java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

What I tried so far, but to no avail:
-> Clean and rebuild (fails on rebuild)
-> Remove ./gradle file and all project build and cache files, then cache invalidation

My project gradle file:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.51'
    repositories {
        jcenter()
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta6'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        jcenter()
        google()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My app Gradle file:

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

def daggerVersion = '2.11'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.connectus.connectus"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/INDEX.LIST'
    }
}

kapt {
    generateStubs = true
}

dependencies {
    /**
     * Kotlin
     */
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile 'org.jetbrains.anko:anko-support-v4:0.10.1'

    /**
     * Unit testing
     */
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:1.10.19'
    testCompile 'org.powermock:powermock-module-junit4:1.6.2'
    testCompile 'org.powermock:powermock-api-mockito:1.6.2'

    /**
     * Android views and widgets
     */
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'

    /**
     * Retrofit
     */
    compile 'com.squareup.retrofit2:retrofit:2.+'
    compile 'com.squareup.retrofit2:converter-gson:2.+'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.+'
    compile 'io.reactivex:rxjava:1.0.4'
    compile 'io.reactivex:rxandroid:0.24.0'

    /**
     * Glide
     */
    compile 'com.github.bumptech.glide:glide:3.7.0'

    /**
     * Dagger 2
     */
    kapt "com.google.dagger:dagger-compiler:$daggerVersion"
    compile "com.google.dagger:dagger:$daggerVersion"
    provided 'org.glassfish:javax.annotation:10.0-b28'

    /**
     * Butterknife for view injection
     */
    compile 'com.jakewharton:butterknife:8.8.1'
    kapt 'com.jakewharton:butterknife-compiler:8.8.1'

    /**
     * GSON
     */
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'org.powermock:powermock-api-mockito:1.6.2'

    /**
     * Facebook SDK
     */
    compile 'com.facebook.android:facebook-login:[4,5)'

    /**
     * UI Testing
     */
    androidTestCompile 'com.android.support:support-annotations:25.3.1'
    androidTestCompile 'junit:junit:4.12'

    testCompile 'com.google.dexmaker:dexmaker:1.2'
    testCompile 'com.google.dexmaker:dexmaker-mockito:1.2'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
        exclude module: 'support-annotations'
    }
    androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.2') {
        exclude module: 'support-annotations'
        exclude module: 'appcompat-v7'
        exclude module: 'support-v4'
        exclude module: 'support-v13'
        exclude module: 'recyclerview-v7'
        exclude module: 'design'
    }
    androidTestCompile('com.android.support.test:runner:0.3') {
        exclude module: 'support-annotations'
    }
    androidTestCompile('com.android.support.test:rules:0.3') {
        exclude module: 'support-annotations'
    }
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
repositories {
    mavenCentral()
}
</code>```

I am using Kotlin and Android Studio 3.0.0 beta 6. What is the problem?

答:
I managed to fix it by just including the base play services and not the full ones:

```<code>-    compile 'com.google.android.gms:play-services:11.6.0'
+    compile 'com.google.android.gms:play-services-base:11.6.0'
</code>```

and removed the appindexing dependencies in my Activity:

```<code>-import com.google.android.gms.appindexing.AppIndex;
-import com.google.android.gms.common.api.GoogleApiClient;
</code>```

(though this might have been a leftover anyway from my upgrade to API 27).

Body:
I am trying to run my application on my phone but during build time it fails with the following error:

Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

What I tried so far, but to no avail:
-> Clean and rebuild (fails on rebuild)
-> Remove ./gradle file and all project build and cache files, then cache invalidation

My project gradle file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.51'
    repositories {
        jcenter()
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta6'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        jcenter()
        google()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My app Gradle file:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

def daggerVersion = '2.11'

android {
    compileSdkVersion 25
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.connectus.connectus"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/INDEX.LIST'
    }
}

kapt {
    generateStubs = true
}

dependencies {
    /**
     * Kotlin
     */
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile 'org.jetbrains.anko:anko-support-v4:0.10.1'

    /**
     * Unit testing
     */
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:1.10.19'
    testCompile 'org.powermock:powermock-module-junit4:1.6.2'
    testCompile 'org.powermock:powermock-api-mockito:1.6.2'

    /**
     * Android views and widgets
     */
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'

    /**
     * Retrofit
     */
    compile 'com.squareup.retrofit2:retrofit:2.+'
    compile 'com.squareup.retrofit2:converter-gson:2.+'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.+'
    compile 'io.reactivex:rxjava:1.0.4'
    compile 'io.reactivex:rxandroid:0.24.0'

    /**
     * Glide
     */
    compile 'com.github.bumptech.glide:glide:3.7.0'

    /**
     * Dagger 2
     */
    kapt "com.google.dagger:dagger-compiler:$daggerVersion"
    compile "com.google.dagger:dagger:$daggerVersion"
    provided 'org.glassfish:javax.annotation:10.0-b28'

    /**
     * Butterknife for view injection
     */
    compile 'com.jakewharton:butterknife:8.8.1'
    kapt 'com.jakewharton:butterknife-compiler:8.8.1'

    /**
     * GSON
     */
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'org.powermock:powermock-api-mockito:1.6.2'

    /**
     * Facebook SDK
     */
    compile 'com.facebook.android:facebook-login:[4,5)'

    /**
     * UI Testing
     */
    androidTestCompile 'com.android.support:support-annotations:25.3.1'
    androidTestCompile 'junit:junit:4.12'

    testCompile 'com.google.dexmaker:dexmaker:1.2'
    testCompile 'com.google.dexmaker:dexmaker-mockito:1.2'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
        exclude module: 'support-annotations'
    }
    androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.2') {
        exclude module: 'support-annotations'
        exclude module: 'appcompat-v7'
        exclude module: 'support-v4'
        exclude module: 'support-v13'
        exclude module: 'recyclerview-v7'
        exclude module: 'design'
    }
    androidTestCompile('com.android.support.test:runner:0.3') {
        exclude module: 'support-annotations'
    }
    androidTestCompile('com.android.support.test:rules:0.3') {
        exclude module: 'support-annotations'
    }
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
repositories {
    mavenCentral()
}

I am using Kotlin and Android Studio 3.0.0 beta 6. What is the problem?

Body:
I managed to fix it by just including the base play services and not the full ones:

-    compile 'com.google.android.gms:play-services:11.6.0'
+    compile 'com.google.android.gms:play-services-base:11.6.0'

and removed the appindexing dependencies in my Activity:

-import com.google.android.gms.appindexing.AppIndex;
-import com.google.android.gms.common.api.GoogleApiClient;

(though this might have been a leftover anyway from my upgrade to API 27).


问:
TypeError : 'manuscript' is an invalid keyword argument for this function
In my health app I am attempting to allow the user to enter patient symptom data and save it.

My app contains Identity, Symptom, and IdentitySymptom models.

A ManyToManyField exists between the Identity and Symptom.

The  IdentitySymptom model contains both ForeignKey fields each referencing the Identity and Symptom model.

In my views document I used class based views to ensure that each Symptom object I created was attached to a patient.

Problem :  Each time I created a Symptom object and click  to save it, it returns this error :

```<code>Traceback:

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/Users/iivri.andre/vision_Map/iivri/script/views.py" in post
  115.             medical_key = IdentitySymptom.objects.create(patient = patient, manuscript = manuscript)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/query.py" in create
  392.         obj = self.model(**kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/base.py" in __init__
  573.                 raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])

Exception Type: TypeError at /script/medical-document/O910231/
Exception Value: 'manuscript' is an invalid keyword argument for this function
</code>```

I have created the patient object from my Identity model.

```<code>class Identity(models.Model):

    NIS =models.CharField(max_length = 200, primary_key = True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    time_patient_creation = models.DateTimeField(auto_now = True)
    first_name = models.CharField(max_length = 80, null = True)
    last_name = models.CharField(max_length = 80, null = True )
    contact = models.CharField(max_length = 15, null = True)
    location  = models.CharField(max_length = 100, blank = True)
    born = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True)

    patient_key = models.ManyToManyField('Symptom')
</code>```

I have also created the Symptom object from the Symptom model

I also created a IdentitySymptom model that contains the ForeignKey field

```<code>class IdentitySymptom(models.Model):

    identity = models.ForeignKey(Identity)
    key_medical = models.ForeignKey(Symptom)
</code>```

This is my views document with the class based views

```<code>from django.shortcuts import render, redirect
from django.views.generic import CreateView, ListView
from script.forms import  IdentityForm, MedicalForm

from script.models import Identity, Symptom, IdentitySymptom

class Identity_view(CreateView):

    model = Identity

    template_name = 'script/script.html'

    def get(self, request):

        form = IdentityForm()

        script = Identity.objects.filter(user = request.user)

        var = {'form':form, 'script':script}

        return render(request, self.template_name, var)

    def post(self, request):

        form = IdentityForm(request.POST)

        being = None

        if form.is_valid():

            NIS = form.save(commit = False)
            #
            NIS.user = request.user

            NIS.save()

            being = form.cleaned_data['NIS']

            form = IdentityForm()

            return redirect('script:script')

        var = {'form': form, 'being':being }

        return render(request, self.template_name, var)

class Identity_list_view(ListView):

    model = Identity

    template_name = 'script/identity_list.html'

    def get(self, request):

        form = IdentityForm()

        script = Identity.objects.filter(user = request.user)

        var = {'form':form, 'script':script}
        return render(request, self.template_name, var)

class Medical_document(CreateView):

    model = Symptom

    template_name = 'script/medical_document.html'

    def get(self, request, pk):

        form = MedicalForm

        script = Symptom.objects.all()
        var = {'form':form, 'script':script, 'pk':pk}

        return render(request, self.template_name, var)

    def post(self, request, pk):

        form = MedicalForm(request.POST)

        state = None

        if form.is_valid():

            manuscript = form.save(commit = False)

            manuscript.user = request.user

            state = form.cleaned_data['description']

            manuscript.save()

            patient = Identity.objects.get(pk=pk)

            medical_key = IdentitySymptom.objects.create(patient = patient, manuscript = manuscript)

            medical_key.patient.patient_key.add(manuscript)

            form = MedicalForm()

            redirect('script:script')

        else:
            print(form.errors)

        var = {'form': form, 'state': state, 'pk':pk}

        return render(request, self.template_name, var)
</code>```

答:
This line

```<code>medical_key = IdentitySymptom.objects.create(patient = patient, manuscript = manuscript)
</code>```

raises the error because IdentitySymptom does not have a manuscript field.

From your definition,

```<code>class IdentitySymptom(models.Model):

    identity = models.ForeignKey(Identity)
    key_medical = models.ForeignKey(Symptom)
</code>```

you can only assign identity and key_medical.

I can see that patient is an Identity instance, and assuming that manuscript is a Symptom, then you actually want to do

```<code>medical_key = IdentitySymptom.objects.create(identity = patient, key_medical = manuscript)
</code>```

Body:
In my health app I am attempting to allow the user to enter patient symptom data and save it.

My app contains Identity, Symptom, and IdentitySymptom models.

A ManyToManyField exists between the Identity and Symptom.

The  IdentitySymptom model contains both ForeignKey fields each referencing the Identity and Symptom model.

In my views document I used class based views to ensure that each Symptom object I created was attached to a patient.

Problem :  Each time I created a Symptom object and click  to save it, it returns this error :

Traceback:

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "/Users/iivri.andre/vision_Map/iivri/script/views.py" in post
  115.             medical_key = IdentitySymptom.objects.create(patient = patient, manuscript = manuscript)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/query.py" in create
  392.         obj = self.model(**kwargs)

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/base.py" in __init__
  573.                 raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])

Exception Type: TypeError at /script/medical-document/O910231/
Exception Value: 'manuscript' is an invalid keyword argument for this function

I have created the patient object from my Identity model.

class Identity(models.Model):

    NIS =models.CharField(max_length = 200, primary_key = True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    time_patient_creation = models.DateTimeField(auto_now = True)
    first_name = models.CharField(max_length = 80, null = True)
    last_name = models.CharField(max_length = 80, null = True )
    contact = models.CharField(max_length = 15, null = True)
    location  = models.CharField(max_length = 100, blank = True)
    born = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True)

    patient_key = models.ManyToManyField('Symptom')

I have also created the Symptom object from the Symptom model

I also created a IdentitySymptom model that contains the ForeignKey field

class IdentitySymptom(models.Model):

    identity = models.ForeignKey(Identity)
    key_medical = models.ForeignKey(Symptom)

This is my views document with the class based views

from django.shortcuts import render, redirect
from django.views.generic import CreateView, ListView
from script.forms import  IdentityForm, MedicalForm

from script.models import Identity, Symptom, IdentitySymptom

class Identity_view(CreateView):

    model = Identity

    template_name = 'script/script.html'

    def get(self, request):

        form = IdentityForm()

        script = Identity.objects.filter(user = request.user)

        var = {'form':form, 'script':script}

        return render(request, self.template_name, var)

    def post(self, request):

        form = IdentityForm(request.POST)

        being = None

        if form.is_valid():

            NIS = form.save(commit = False)
            #
            NIS.user = request.user

            NIS.save()

            being = form.cleaned_data['NIS']

            form = IdentityForm()

            return redirect('script:script')

        var = {'form': form, 'being':being }

        return render(request, self.template_name, var)

class Identity_list_view(ListView):

    model = Identity

    template_name = 'script/identity_list.html'

    def get(self, request):

        form = IdentityForm()

        script = Identity.objects.filter(user = request.user)

        var = {'form':form, 'script':script}
        return render(request, self.template_name, var)

class Medical_document(CreateView):

    model = Symptom

    template_name = 'script/medical_document.html'

    def get(self, request, pk):

        form = MedicalForm

        script = Symptom.objects.all()
        var = {'form':form, 'script':script, 'pk':pk}

        return render(request, self.template_name, var)

    def post(self, request, pk):

        form = MedicalForm(request.POST)

        state = None

        if form.is_valid():

            manuscript = form.save(commit = False)

            manuscript.user = request.user

            state = form.cleaned_data['description']

            manuscript.save()

            patient = Identity.objects.get(pk=pk)

            medical_key = IdentitySymptom.objects.create(patient = patient, manuscript = manuscript)

            medical_key.patient.patient_key.add(manuscript)

            form = MedicalForm()

            redirect('script:script')

        else:
            print(form.errors)

        var = {'form': form, 'state': state, 'pk':pk}

        return render(request, self.template_name, var)

Body:
This line

medical_key = IdentitySymptom.objects.create(patient = patient, manuscript = manuscript)

raises the error because IdentitySymptom does not have a manuscript field.

From your definition,

class IdentitySymptom(models.Model):

    identity = models.ForeignKey(Identity)
    key_medical = models.ForeignKey(Symptom)

you can only assign identity and key_medical.

I can see that patient is an Identity instance, and assuming that manuscript is a Symptom, then you actually want to do

medical_key = IdentitySymptom.objects.create(identity = patient, key_medical = manuscript)


问:
How to convert a fractional Octal to Hex fraction and vice versa in Swift 3?
I am looking for a way to convert a fractional Octal to Hex fraction and vice versa in Swift 3. Self written code without third-party library and Foundation. For example this code converts Octal Integer to Hex:

```<code>for num in OctalVal {
            switch num {
            case "0": result = result * 8
            case "1": result = result * 8 + 1
            case "2": result = result * 8 + 2
            case "3": result = result * 8 + 3
            case "4": result = result * 8 + 4
            case "5": result = result * 8 + 5
            case "6": result = result * 8 + 6
            case "7": result = result * 8 + 7
            default: return "Error"
            }
        }
        n2 = result
        while n2 > 0 {
            c2 = n2 % 16
            n2 = n2 / 16
            k2.append("\(c2)")
        }

        for i in k2.reversed() {
            if(i == "10"){
                fs2 += "A"
            }
            else if(i == "11") {
                fs2 += "B"
            }
            else if(i == "12") {
                fs2 += "C"
            }
            else if(i == "13") {
                fs2 += "D"
            }
            else if(i == "14") {
                fs2 += "E"
            }
            else if(i == "15") {
                fs2 += "F"
            }
            else {
                fs2 += "\(i)"
            }
        }
        return "\(fs2)"
    }
</code>```

And this one Hex to Octal:

```<code>for num in Left {
            switch num {
            case "0": result += "0000"
            break;
            case "1": result += "0001"
            break;
            case "2": result += "0010"
            break;
            case "3": result += "0011"
            break;
            case "4": result += "0100"
            break;
            case "5": result += "0101"
            break;
            case "6": result += "0110"
            break;
            case "7": result += "0111"
            break;
            case "8": result += "1000"
            break;
            case "9": result += "1001"
            break;
            case "A": result += "1010"
            break;
            case "B": result += "1011"
            break;
            case "C": result += "1100"
            break;
            case "D": result += "1101"
            break;
            case "E": result += "1110"
            break;
            case "F": result += "1111"
            break;
            default: return "Error"
            }
        }
</code>```

For example: 12D.3AF9F to 455.1657476 (Octal)

Any ideas regarding fractional part?
Thank you for your attention to my request

答:
Convert hex to binary, pad to make binary string a multiple of 3 in length, then convert binary to octal:

```<code>func hexadecimalFractToOctal(_ hex: String) -> String {
    let hexToBin = ["0": "0000", "1": "0001", "2": "0010", "3": "0011",
                    "4": "0100", "5": "0101", "6": "0110", "7": "0111",
                    "8": "1000", "9": "1001", "A": "1010", "B": "1011",
                    "C": "1100", "D": "1101", "E": "1110", "F": "1111"]

    let binToOct = ["000": "0", "001": "1", "010": "2", "011": "3",
                    "100": "4", "101": "5", "110": "6", "111": "7"]

    // Convert hex string to binary
    var bin = ""
    for char in hex.characters {
        bin += hexToBin[String(char)] ?? ""
    }

    // Pad the string to a multiple of 3 binary digits
    bin += ["", "00", "0"][bin.characters.count % 3]

    var binChars = bin.characters

    var oct = ""

    // Convert binary string to octal 3 digits at a time
    while binChars.count > 0 {
        let b = String(binChars.prefix(3))
        binChars = binChars.dropFirst(3)
        oct += binToOct[b] ?? ""
    }

    return oct
}

print(hexadecimalFractToOctal("3AF9F"))  // "1657476"
</code>```

And the other direction (octal -> hexadecimal):

```<code>func octalFractToHexadecimal(_ oct: String) -> String {
    let octToBin = ["0": "000", "1": "001", "2": "010", "3": "011",
                    "4": "100", "5": "101", "6": "110", "7": "111"]

    let binToHex = ["0000": "0", "0001": "1", "0010": "2", "0011": "3",
                    "0100": "4", "0101": "5", "0110": "6", "0111": "7",
                    "1000": "8", "1001": "9", "1010": "A", "1011": "B",
                    "1100": "C", "1101": "D", "1110": "E", "1111": "F"]

    // Convert octal string to binary
    var bin = ""
    for char in oct.characters {
        bin += octToBin[String(char)] ?? ""
    }

    // Pad the string to a multiple of 4 binary digits
    bin += ["", "000", "00", "0"][bin.characters.count % 4]

    var binChars = bin.characters

    var hex = ""

    // Convert binary string to hexadecimal 4 digits at a time
    while binChars.count > 0 {
        let b = String(binChars.prefix(4))
        binChars = binChars.dropFirst(4)
        hex += binToHex[b] ?? ""
    }

    return hex
}

print(octalFractToHexadecimal("1657476")) // "3AF9F0"
</code>```

Body:
I am looking for a way to convert a fractional Octal to Hex fraction and vice versa in Swift 3. Self written code without third-party library and Foundation. For example this code converts Octal Integer to Hex:

for num in OctalVal {
            switch num {
            case "0": result = result * 8
            case "1": result = result * 8 + 1
            case "2": result = result * 8 + 2
            case "3": result = result * 8 + 3
            case "4": result = result * 8 + 4
            case "5": result = result * 8 + 5
            case "6": result = result * 8 + 6
            case "7": result = result * 8 + 7
            default: return "Error"
            }
        }
        n2 = result
        while n2 > 0 {
            c2 = n2 % 16
            n2 = n2 / 16
            k2.append("\(c2)")
        }

        for i in k2.reversed() {
            if(i == "10"){
                fs2 += "A"
            }
            else if(i == "11") {
                fs2 += "B"
            }
            else if(i == "12") {
                fs2 += "C"
            }
            else if(i == "13") {
                fs2 += "D"
            }
            else if(i == "14") {
                fs2 += "E"
            }
            else if(i == "15") {
                fs2 += "F"
            }
            else {
                fs2 += "\(i)"
            }
        }
        return "\(fs2)"
    }

And this one Hex to Octal:

for num in Left {
            switch num {
            case "0": result += "0000"
            break;
            case "1": result += "0001"
            break;
            case "2": result += "0010"
            break;
            case "3": result += "0011"
            break;
            case "4": result += "0100"
            break;
            case "5": result += "0101"
            break;
            case "6": result += "0110"
            break;
            case "7": result += "0111"
            break;
            case "8": result += "1000"
            break;
            case "9": result += "1001"
            break;
            case "A": result += "1010"
            break;
            case "B": result += "1011"
            break;
            case "C": result += "1100"
            break;
            case "D": result += "1101"
            break;
            case "E": result += "1110"
            break;
            case "F": result += "1111"
            break;
            default: return "Error"
            }
        }

For example: 12D.3AF9F to 455.1657476 (Octal)

Any ideas regarding fractional part?
Thank you for your attention to my request

Body:
Convert hex to binary, pad to make binary string a multiple of 3 in length, then convert binary to octal:

func hexadecimalFractToOctal(_ hex: String) -> String {
    let hexToBin = ["0": "0000", "1": "0001", "2": "0010", "3": "0011",
                    "4": "0100", "5": "0101", "6": "0110", "7": "0111",
                    "8": "1000", "9": "1001", "A": "1010", "B": "1011",
                    "C": "1100", "D": "1101", "E": "1110", "F": "1111"]

    let binToOct = ["000": "0", "001": "1", "010": "2", "011": "3",
                    "100": "4", "101": "5", "110": "6", "111": "7"]

    // Convert hex string to binary
    var bin = ""
    for char in hex.characters {
        bin += hexToBin[String(char)] ?? ""
    }

    // Pad the string to a multiple of 3 binary digits
    bin += ["", "00", "0"][bin.characters.count % 3]

    var binChars = bin.characters

    var oct = ""

    // Convert binary string to octal 3 digits at a time
    while binChars.count > 0 {
        let b = String(binChars.prefix(3))
        binChars = binChars.dropFirst(3)
        oct += binToOct[b] ?? ""
    }

    return oct
}

print(hexadecimalFractToOctal("3AF9F"))  // "1657476"

And the other direction (octal -> hexadecimal):

func octalFractToHexadecimal(_ oct: String) -> String {
    let octToBin = ["0": "000", "1": "001", "2": "010", "3": "011",
                    "4": "100", "5": "101", "6": "110", "7": "111"]

    let binToHex = ["0000": "0", "0001": "1", "0010": "2", "0011": "3",
                    "0100": "4", "0101": "5", "0110": "6", "0111": "7",
                    "1000": "8", "1001": "9", "1010": "A", "1011": "B",
                    "1100": "C", "1101": "D", "1110": "E", "1111": "F"]

    // Convert octal string to binary
    var bin = ""
    for char in oct.characters {
        bin += octToBin[String(char)] ?? ""
    }

    // Pad the string to a multiple of 4 binary digits
    bin += ["", "000", "00", "0"][bin.characters.count % 4]

    var binChars = bin.characters

    var hex = ""

    // Convert binary string to hexadecimal 4 digits at a time
    while binChars.count > 0 {
        let b = String(binChars.prefix(4))
        binChars = binChars.dropFirst(4)
        hex += binToHex[b] ?? ""
    }

    return hex
}

print(octalFractToHexadecimal("1657476")) // "3AF9F0"


问:
How to read a file separated by tabs into a struct
How do you read a file formated like this below seperated by tabs into a struct?
this is the code i have so far i cant get it to work. i can get a whole line in but then how would i seperate the bits of data out??? </p>

```
New England Patriots    6   2       .750    3-2 3-0 1-0 1
Buffalo Bills       5   2       .714    4-0 1-2 1-0 1
```

```<code>ifstream inFile;

string name1;
string conference1;
string division1;
unsigned short wins1;
unsigned short losses1;
float pct1;

int i = 0;
int count = 0;
// this declares the strings we need
string line = "";
int a = 0;
string temp = "";

inFile.open(filename.c_str());

if (!inFile) {
    cerr << "Unable to open file" << filename;
    exit(1);   // call system to stop
}
if (inFile) {

    while (inFile.good())
    {
        //std::getline(inFile, line, '\t'); this is how you get line skipping tabs

        std::getline(inFile, line);
        cout << line;
        cout << endl;
        teams[a].raw = line;
        //cout << teams[a].raw;
        //cout << endl;
        //  teams[a].name = line;

        teams[a].position = a + 1;
        a++;
    }
    cout << teams[20].raw;
    cout << endl;
    cout << a - 1;
    cout << endl;
}
inFile.close();

struct NFL {
    string name;
    string conference;
    string division;
    unsigned short wins;
    string win;
    unsigned short losses;
    string lose;
    float pct;
    string per;
    string home;
    string road;

    string raw;
    int position;
};

struct ExpectedChar { char expected; };

// read a character from a stream and check it has the expected value
std::istream& operator>>(std::istream& in, const ExpectedChar& e)
{
    char c;
    if (in >> c)
        if (c != e.expected)  // failed to read expected character
            in.setstate(std::ios::failbit);
    return in;
}

// read a struct pass from a stream
std::istream& operator>>(std::istream& in, NFL& p)
{
    ExpectedChar tab{ '\t' };
    in >> p.name >> tab >> p.serviceTime >> tab >> p.classType;
    return in;
}
</code>```

答:
Use std::getline() with \n (the default) as the delimiter to read a whole line, and then use std::istringstream to parse values from each line, using std::getline() to read string data that is delimited by something other than spaces.

For example:

```<code>ifstream inFile(filename.c_str());
if (!inFile) {
    cerr << "Unable to open file" << filename;
    exit(1);   // call system to stop
}

string line;
while (getline(inFile, line))
{
    istringstream iss(line);

    getline(iss, teams[a].name, '\t');

    ...

    iss >> teams[a].wins;
    /* or:
    string temp;
    getline(iss, temp, '\t');
    istringstream(temp) >> teams[a].wins;
    */

    ... and so on  ...
}
</code>```

Body:
How do you read a file formated like this below seperated by tabs into a struct?
this is the code i have so far i cant get it to work. i can get a whole line in but then how would i seperate the bits of data out???

New England Patriots    6   2       .750    3-2 3-0 1-0 1
Buffalo Bills       5   2       .714    4-0 1-2 1-0 1

ifstream inFile;

string name1;
string conference1;
string division1;
unsigned short wins1;
unsigned short losses1;
float pct1;

int i = 0;
int count = 0;
// this declares the strings we need
string line = "";
int a = 0;
string temp = "";

inFile.open(filename.c_str());

if (!inFile) {
    cerr << "Unable to open file" << filename;
    exit(1);   // call system to stop
}
if (inFile) {

    while (inFile.good())
    {
        //std::getline(inFile, line, '\t'); this is how you get line skipping tabs

        std::getline(inFile, line);
        cout << line;
        cout << endl;
        teams[a].raw = line;
        //cout << teams[a].raw;
        //cout << endl;
        //  teams[a].name = line;

        teams[a].position = a + 1;
        a++;
    }
    cout << teams[20].raw;
    cout << endl;
    cout << a - 1;
    cout << endl;
}
inFile.close();

struct NFL {
    string name;
    string conference;
    string division;
    unsigned short wins;
    string win;
    unsigned short losses;
    string lose;
    float pct;
    string per;
    string home;
    string road;

    string raw;
    int position;
};

struct ExpectedChar { char expected; };

// read a character from a stream and check it has the expected value
std::istream& operator>>(std::istream& in, const ExpectedChar& e)
{
    char c;
    if (in >> c)
        if (c != e.expected)  // failed to read expected character
            in.setstate(std::ios::failbit);
    return in;
}

// read a struct pass from a stream
std::istream& operator>>(std::istream& in, NFL& p)
{
    ExpectedChar tab{ '\t' };
    in >> p.name >> tab >> p.serviceTime >> tab >> p.classType;
    return in;
}

Body:
Use std::getline() with \n (the default) as the delimiter to read a whole line, and then use std::istringstream to parse values from each line, using std::getline() to read string data that is delimited by something other than spaces.

For example:

ifstream inFile(filename.c_str());
if (!inFile) {
    cerr << "Unable to open file" << filename;
    exit(1);   // call system to stop
}

string line;
while (getline(inFile, line))
{
    istringstream iss(line);

    getline(iss, teams[a].name, '\t');

    ...

    iss >> teams[a].wins;
    /* or:
    string temp;
    getline(iss, temp, '\t');
    istringstream(temp) >> teams[a].wins;
    */

    ... and so on  ...
}


问:
How to add edit and delete buttons in django admin
I want to add 2 buttons in django admin, like on this screenshot, but instead of "Deposit" and "Withdraw" there should be "Edit" and "Delete"

I found lots of answers how to add custom actions, but is there a proper way to add such buttons? All methods for them are written, it seems to me that this two buttons should be added mush more easier.

picture came from here:
https://medium.com/@hakibenita/how-to-add-custom-action-buttons-to-django-admin-8d266f5b0d41

but I'm interested in easier solution, if such exists

答:
list_display from here provides me to add smth for every object. So I added this in my MyModelAdmin:

```<code>def change_button(self, obj):
    return format_html('<a class="btn" href="/admin/my_app/my_model/{}/change/">Change</a>', obj.id)

def delete_button(self, obj):
    return format_html('<a class="btn" href="/admin/my_app/my_model/{}/delete/">Delete</a>', obj.id)

list_display = ('__str__', 'change_button', 'delete_button')
</code>```

And now this two buttons are added. This is still not the best way I guess, but mush easier then adding any other action.

Body:
list_display from here provides me to add smth for every object. So I added this in my MyModelAdmin:

def change_button(self, obj):
    return format_html('<a class="btn" href="/admin/my_app/my_model/{}/change/">Change</a>', obj.id)

def delete_button(self, obj):
    return format_html('<a class="btn" href="/admin/my_app/my_model/{}/delete/">Delete</a>', obj.id)

list_display = ('__str__', 'change_button', 'delete_button')

And now this two buttons are added. This is still not the best way I guess, but mush easier then adding any other action.


问:
How to delete a word from an array in swift?
I have the following variable:

```<code>var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
</code>```

For any of those fruits I have another variable: apple = 1 or 0, appricot = 1 or 0 ...

My question is how to make, for example, the word "Apple" be in the list just if apple == 1? and if apple == 0 my list would be:

```<code>var fruits = [ "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
</code>```

答:
To remove an element from your array you just need to use fruits.remove(at: [index])

So, in your example it would look like this:

```<code>var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
var apple = 0

if apple == 0 {
    fruits.remove(at: 0) //remove 0th index in your array, which is "Apple"
}
</code>```

To approach it a safer way, you can use fruits.filter { $0 != "[fruit name]" }. This keeps the original array, and creates a new array.

It would look something like this:

```<code>var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
var fruits2 = fruits
var apple = 0

if apple == 0 {
    fruits2 = fruits.filter { $0 != "Apple" }
}
</code>```

Body:
I have the following variable:

var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]

For any of those fruits I have another variable: apple = 1 or 0, appricot = 1 or 0 ...

My question is how to make, for example, the word "Apple" be in the list just if apple == 1? and if apple == 0 my list would be:

var fruits = [ "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]

Body:
To remove an element from your array you just need to use fruits.remove(at: [index])

So, in your example it would look like this:

var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
var apple = 0

if apple == 0 {
    fruits.remove(at: 0) //remove 0th index in your array, which is "Apple"
}

To approach it a safer way, you can use fruits.filter { $0 != "[fruit name]" }. This keeps the original array, and creates a new array.

It would look something like this:

var fruits = ["Apple", "Apricot", "Banana", "Blueberry", "Cantaloupe", "Cherry","Clementine", "Coconut"]
var fruits2 = fruits
var apple = 0

if apple == 0 {
    fruits2 = fruits.filter { $0 != "Apple" }
}


问:
Search boolean matrix using pyspark
I have a boolean matrix of M x N, where M = 6000 and N = 1000

```<code>1 | 0 1 0 0 0 1 ----> 1000
2 | 1 0 1 0 1 0 ----> 1000
3 | 0 0 1 1 0 0 ----> 1000
  V
6000
</code>```

Now for each column, I want to find the first occurrence where the value is 1. For the above example, in the first 5 columns, I want 2 1 2 3 2 1.

Now the code I have is

```<code>    sig_matrix = list()
    num_columns = df.columns
    for col_name in num_columns:
        print('Processing column {}'.format(col_name))
        sig_index = df.filter(df[col_name] == 1).\
                    select('perm').limit(1).collect()[0]['perm']
        sig_matrix.append(sig_index)
</code>```

Now the above code is really slow and it takes 5~7 minutes for me to parse 1000 columns is there any faster ways to do this instead of what I am doing? I am also willing to use pandas data frame instead of pyspark dataframe if that is faster.

答:
I ended up solving my problem using numpy. Here is how I did it. </p>

```<code>import numpy as np

sig_matrix = list()
    columns = list(df)
    for col_name in columns:
        sig_index = np.argmax(df[col_name]) + 1
        sig_matrix.append(sig_index)
</code>```

<p>As the values in my columns are 0 and 1, argmax will return the first occurrence of value 1. </p>

Title: Search boolean matrix using pyspark

Body:
I have a boolean matrix of M x N, where M = 6000 and N = 1000

1 | 0 1 0 0 0 1 ----> 1000
2 | 1 0 1 0 1 0 ----> 1000
3 | 0 0 1 1 0 0 ----> 1000
  V
6000

Now for each column, I want to find the first occurrence where the value is 1. For the above example, in the first 5 columns, I want 2 1 2 3 2 1.

Now the code I have is

    sig_matrix = list()
    num_columns = df.columns
    for col_name in num_columns:
        print('Processing column {}'.format(col_name))
        sig_index = df.filter(df[col_name] == 1).\
                    select('perm').limit(1).collect()[0]['perm']
        sig_matrix.append(sig_index)

Now the above code is really slow and it takes 5~7 minutes for me to parse 1000 columns is there any faster ways to do this instead of what I am doing? I am also willing to use pandas data frame instead of pyspark dataframe if that is faster.

Body:
I ended up solving my problem using numpy. Here is how I did it.

import numpy as np

sig_matrix = list()
    columns = list(df)
    for col_name in columns:
        sig_index = np.argmax(df[col_name]) + 1
        sig_matrix.append(sig_index)

As the values in my columns are 0 and 1, argmax will return the first occurrence of value 1.


问:
How can I make a VSCode theme recognize C# interfaces?
I am trying to get a theme for Visual Studio Code working to what I want. Currently, I'm trying to use Obsidian working with C# rules, but I'm not sure which key word to use to override color customizations. VSCode does not seem to recognize interfaces as they're language specific.

```<code>"editor.tokenColorCustomizations": {
        "functions" :{
            "foreground": "#F1F2F3"
        },
        "interface": { //not valid
            "foreground": "#B48C8C"
        }
    }
</code>```

How can I get VSCode color customizations to recognize c# specific syntaxes?

答:
editor.tokenColorCustomizations can use a number of values: comments, functions, keywords, numbers, strings, types and variables.  If none of those work for you textMateRules is available as well.  So you can do something like:

```<code>"editor.tokenColorCustomizations": {
    "textMateRules": [{
        "scope": "yourScopeHere",
        "settings": {
            "fontStyle": "italic",
            "foreground": "#C69650"
        }
    }]
   },
</code>```

So you just have to figure out what scope you need for "interface".

For that, try CTRL-Shift-P and type scope: choose

```<code>Developer: Inspect Editor Tokens and Scopes
</code>```

and for whichever keyword is selected, like interface you will get a listing of its textmate scope.  That should be inserted as the scope value above. [In my experience, it is more accurate to open the "Inspect TM Scopes" panel and then click a couple of items and then the one, like interface, that you want - the scope panel will remain open.]  You can copy from the scopes panel.

You may need only the main scope listed, but if need to narrow its scope you can include the others listed in a comma-separated list in the scopes: ..., ..., ...

Body:
I am trying to get a theme for Visual Studio Code working to what I want. Currently, I'm trying to use Obsidian working with C# rules, but I'm not sure which key word to use to override color customizations. VSCode does not seem to recognize interfaces as they're language specific.

"editor.tokenColorCustomizations": {
        "functions" :{
            "foreground": "#F1F2F3"
        },
        "interface": { //not valid
            "foreground": "#B48C8C"
        }
    }

How can I get VSCode color customizations to recognize c# specific syntaxes?

Body:
editor.tokenColorCustomizations can use a number of values: comments, functions, keywords, numbers, strings, types and variables.  If none of those work for you textMateRules is available as well.  So you can do something like:

"editor.tokenColorCustomizations": {
    "textMateRules": [{
        "scope": "yourScopeHere",
        "settings": {
            "fontStyle": "italic",
            "foreground": "#C69650"
        }
    }]
   },

So you just have to figure out what scope you need for "interface".

For that, try CTRL-Shift-P and type scope: choose

Developer: Inspect Editor Tokens and Scopes

and for whichever keyword is selected, like interface you will get a listing of its textmate scope.  That should be inserted as the scope value above. [In my experience, it is more accurate to open the "Inspect TM Scopes" panel and then click a couple of items and then the one, like interface, that you want - the scope panel will remain open.]  You can copy from the scopes panel.

You may need only the main scope listed, but if need to narrow its scope you can include the others listed in a comma-separated list in the scopes: ..., ..., ...


问:
How to create mp3 from text with Google TTS?
How to create mp3 from any text with Google TTS?

1) I try to find google.translate API, but finded only "audio to text", except "text to audio"!

2) I try to find SpeechSynthesis convert to mp3, but again find nothing!

3) I find only site "beta.soundoftext.com", they generate mp3 audio file without API interface.

So, can anyone help me, please.
I searching for any ways to convert text to SPEECH for my web-site (Dedicated Server). Thank you!

答:
A Python script have been created for it and the script is now available on Github.

All the input there are pretty straightforward, except for the language part where some language code might be less familiar by users, in these cases documentation from Google is available and you can check what's the code for the language you want the engine to speak in.


问:
Python3 - Why calling a operator from a dict is not working
So I have these code:

```<code>def evaluate(expression):
    if any(not (c.isdigit() or c.isspace() or c in '(){}[]+-*/') for c in expression):
        return
    newexp = expression.split()
    stack = Stack()
    for i in newexp:
        if i in ')]}':
            arg2 = stack.pop()
            operator = stack.pop()
            arg1 = stack.pop()
            if stack.pop() not in '([{':
                return
            stack.push({'+': add}[operator](arg1,arg2))
        else:
            stack.push(i)

    #checking
    while not stack.is_empty():
        print(stack.pop())

n = input('Input expression: ')
evaluate(n)
</code>```

if I use

'( 5 + 2 )'

as the input, the output will be

52

I supposed to get

7

as the answer.

Doing this will get 7:

```<code>print({'+': add}['+'](5,2))
</code>```

but isn't it actually the same? Can you guys tell me which part of my code is wrong.

Thanks.

答:
Make this change
stack.push({'+': add}[operator](int(arg1),int(arg2)))

Body:
So I have these code:

def evaluate(expression):
    if any(not (c.isdigit() or c.isspace() or c in '(){}[]+-*/') for c in expression):
        return
    newexp = expression.split()
    stack = Stack()
    for i in newexp:
        if i in ')]}':
            arg2 = stack.pop()
            operator = stack.pop()
            arg1 = stack.pop()
            if stack.pop() not in '([{':
                return
            stack.push({'+': add}[operator](arg1,arg2))
        else:
            stack.push(i)

    #checking
    while not stack.is_empty():
        print(stack.pop())

n = input('Input expression: ')
evaluate(n)

if I use

'( 5 + 2 )'

as the input, the output will be

52

I supposed to get

7

as the answer.

Doing this will get 7:

print({'+': add}['+'](5,2))

but isn't it actually the same? Can you guys tell me which part of my code is wrong.

Thanks.


问:
 within another
 inherits style
I have the following structure in some HTML:

```
<ul class="li_inline">
    <li>
        <ul class="li_block">
            <li>Stuff</li>
            <li>Stuff under stuff</li>
        </ul>
    </li>
    <li>
        <ul class="li_block">
            <li>Stuff</li>
            <li>Stuff under stuff</li>
        </ul>
    </li>
</ul>
```

With the CSS like this:

```
.li_inline li
{
    display: inline;
}

.li_block li
{
    display: block;
}
```

What I would like to happen is to have the two inner
s side by side, but any
s inside them to be below each other. This is so I can get a sidebar and main body side by side, but elements inside them behave normally (ie. one below the other).

Can someone suggest some CSS I can use so that the inner (li_block) lists'
 elements are displayed as block elements, but the
s themselves are displayed side by side?

Thanks,

James

答:
First, thanks for everyone's help! I'm really sorry to look like I'm ignoring your hard efforts away, but I have taken note of all your answers, and they're all very handy.

The solution I have come up with is to simply use display: inline-block for both inner uls, with the outer one left default.

Once again, thanks for your help everyone.

James

Title: <ul> within another <ul> inherits style

Body:
I have the following structure in some HTML:

Stuff

Stuff under stuff

Stuff

Stuff under stuff

With the CSS like this:

.li_inline li
{
    display: inline;
}

.li_block li
{
    display: block;
}

What I would like to happen is to have the two inner
s side by side, but any
s inside them to be below each other. This is so I can get a sidebar and main body side by side, but elements inside them behave normally (ie. one below the other).

Can someone suggest some CSS I can use so that the inner (li_block) lists'
 elements are displayed as block elements, but the
s themselves are displayed side by side?

Thanks,

James


问:
MSCRM Editing Email Templates in Customisation.xml did not update the template
What I am trying to do

I am trying to remove the time section from the email template with a date field.

What have I done

I first tried to edit the template field in the template but could not edit the fields. I read I needed to go into the customisation.xml so I exported the solution, edited the line

```<code>/entity><attribute>piv_estimateddeliverydate/</attribute
</code>```

to

```<code>/entity><attribute>piv_estimateddeliverydate/@date</attribute
</code>```

I have reimported the solution, published the customisations (twice as I needed to double check it had been).

What Is Happening

When I create the email using the template the time part of the data is still visible

What I want to happen

I don't want the time section of the date included in the email.

Other info

The field is DateTime format Date only

答:
The solution was to open each of the templates and hit save. For some reason, this made the changes take place, even though they were imported into the solution and should have already been saved.

If someone can explain why we need to hit save on the email templates after importing the solution containing them, would be great.

Body:
What I am trying to do

I am trying to remove the time section from the email template with a date field.

What have I done

I first tried to edit the template field in the template but could not edit the fields. I read I needed to go into the customisation.xml so I exported the solution, edited the line

/entity><attribute>piv_estimateddeliverydate/</attribute

to

/entity><attribute>piv_estimateddeliverydate/@date</attribute

I have reimported the solution, published the customisations (twice as I needed to double check it had been).

What Is Happening

When I create the email using the template the time part of the data is still visible

What I want to happen

I don't want the time section of the date included in the email.

Other info

The field is DateTime format Date only


问:
Force Wordpress submenus to hide once you move your cursor away from them
I am on a mission to change the default behaviour of Top-Level menus in Wordpress.

For example, I have removed the link functionality from the top-level menus - because I only want people clicking on the sub-menus. (see here if interested)

What is my problem

However, I am having an issue where if you click on one of the top-level items the browser 'focuses' on this and the sub-menu still stays active and out even when you move your cursor away. I want the submenu to disappear when you move your cursor - same as the behaviour when you haven't clicked on the top menu.

What I have tried

I have identified you can force this state by clicking on the link in inspect element and setting the state to focus.

I've tried writing some CSS to stop it happening, but didn't get anywhere with that.

I also added 'stopPropagation' to the jQuery for stopping the link, but it doesn't have the desired effect.

```<code><script>
        jQuery(document).ready(function () {
            // Add the classes to target
            jQuery('a.toplevel_page_bnfo_portal, a.toplevel_page_bnfo_database, a.toplevel_page_bnfo_insights').click(function (event) {
                event.preventDefault(); // cancel the event

                event.stopPropagation(); // Stops event propagating
            });
        });
</script>
</code>```

答:
I have now found a solution using @sarfraz's suggestion on this post which targets 'on mouse down'</p>

```<code>jQuery('a.toplevel_page_bnfo_portal, a.toplevel_page_bnfo_database, a.toplevel_page_bnfo_insights').on('mousedown', function(event) {
            // do your magic
                event.preventDefault();
});
</code>```

Body:
I have now found a solution using @sarfraz's suggestion on this post which targets 'on mouse down'

jQuery('a.toplevel_page_bnfo_portal, a.toplevel_page_bnfo_database, a.toplevel_page_bnfo_insights').on('mousedown', function(event) {
            // do your magic
                event.preventDefault();
});


问:
CSS div 100% height
I'm developing this website and I want the right sidebar to have 100% height.

```<code>body {
    height: 100%;
    min-height: 100%;
    position: relative;
}

mydiv {
    height: 100%;
    min-height: 100%;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    width: 290px;
}
</code>```

I've read a lot of answer, especially this (Prestaul answer):
Setting 100% height on an absolutely positioned element when the content expands past the window size.

But for me this trick does not work, also the fiddle exemple doesn't work!

This is the jsfiddle working example.

This is the same code that doesn't work.

答:
CSS Flexbox was designed to simplify creating these types of layouts.

html {
  height: 100%;
}

body {
  height: 100%;
  display: flex;
}

.Content {
  flex-grow: 1;
}

.Sidebar {
  width: 290px;
  flex-shrink: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="Content" style="background:#bed">Content</div>
<div class="Sidebar" style="background:#8cc">Sidebar</div></code>```

Title: CSS div 100% height

Body:
I'm developing this website and I want the right sidebar to have 100% height.

body {
    height: 100%;
    min-height: 100%;
    position: relative;
}

mydiv {
    height: 100%;
    min-height: 100%;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    width: 290px;
}

I've read a lot of answer, especially this (Prestaul answer):
Setting 100% height on an absolutely positioned element when the content expands past the window size.

But for me this trick does not work, also the fiddle exemple doesn't work!

This is the jsfiddle working example.

This is the same code that doesn't work.

Body:
CSS Flexbox was designed to simplify creating these types of layouts.

html {
  height: 100%;
}

body {
  height: 100%;
  display: flex;
}

.Content {
  flex-grow: 1;
}

.Sidebar {
  width: 290px;
  flex-shrink: 0;
}

<div class="Content" style="background:#bed">Content</div>
<div class="Sidebar" style="background:#8cc">Sidebar</div>


问:
Database file also in bin folder
I am using a server based database in vb.net. Why is a copy of the databasefile (.mdf) also created in the bin folder when I run my application. I think this is the reason why my datagridview does not update my sql table with the following code :

Private Sub SAVE_Click(sender As Object, e As EventArgs) Handles SAVE.Click

    Validate()
    ParsreelsBindingSource.EndEdit()
    TableAdapterManager.UpdateAll(SkeduleringDatabasisDataSet)
    Close()

End Sub
```

答:
You add a data file to your project and that is a source file, just like any other. You don't connect to that file at run time because you don't want to fill it with test data and potentially delete some default data. That data file should remain clean.

When you build, the clean source file is copied to the output folder along with your EXE by default.  It's that copy that you connect to at run time.  You can make as much of a mess of it while testing as you like, safe in the knowledge that your source file is unaffected.  If it's a Release build, you have a clean database to deploy with your app.

By default, the Copy to output directory property of the data file is set to Always copy.  That means that every time your project is built, a new copy of the data file is made in the output folder.  If you run your project twice without making any code changes, there is no build so there is no new copy, so any changes made during the first run will remain. If you make a code change though, the project is built before the second run so your data file is overwritten with a new copy, so your changes will be lost.  It's that behaviour that confuses people who either don't read about how to manage local data files or don't read it properly.  Your changes ARE saved. They are simply overwritten next time you build.

If you set Copy to output directory to Copy never then no database is copied to the output folder.  If your code then tries to connect to a database in that location it will obviously fail.  You would need to copy the data file yourself to that location or, if you change the connection string, to another location.

The most sensible option is to set Copy to output directory to Copy if newer.  In that case, a new copy of the database will not be made unless you've made a change to the schema or default data in the source data file.  That means that changes made while debugging will survive between sessions.  You may find that a new copy is made sometimes when you don't want it to but that's still better than the alternative, which is making a new copy every time.  If you don't touch the source data file, which you have no reason to do if you're not changing the schema or the data, then your test data will survive across sessions.

Title: Database file also in bin folder


问:
What main class should i give in my manifest.mf of a jar file which has an applet without main class?
i am having a applet(not having a main class) and i am having song file (beep.au) and picture file ( a.gif){these 2 files i have used in my applet} and i have created a jar file a.jar which contains the applet class , song file and picture file ... but when i run the jar file i get an error    :- Main-Class manifest-attribute not found .... what should i have to do to do to run the jar file???? (what main class should i give to the manifest.mf as my applet is not having a main method so no main class)</p>

答:
Do you get this error when you try to run the applet in a web browser, or are you trying to run the applet from the command line?  </p>

<p>If you are making an applet, you need to create an html page.  In that page you create an applet tag with the code attribute set to the "main" Applet class.  </p>

Body:
Do you get this error when you try to run the applet in a web browser, or are you trying to run the applet from the command line?

If you are making an applet, you need to create an html page.  In that page you create an applet tag with the code attribute set to the "main" Applet class.


问:
Finding which code segment is faster than the other
Say that we have two C++ code segments, for doing the same task. How can we determine which code will run faster?

As an example lets say there is this global array "some_struct_type numbers[]". Inside a function, I can read a location of this array in two ways(I do not want to alter the content of the array)

some_struct_type val = numbers[i];

some_struct_type* val = &numbers[i]

I assume the second one is faster. but I can't measure the time to make sure because it will be a negligible difference.

So in this type of a situation, how do I figure out which code segment runs faster? Is there a way to compile a single line of code or set of lines and view
how many lines of assembly instructions are there?

I would appreciate your thoughts on this matter.

答:
Eugene Sh. is correct that these two lines aren't doing the same thing - the first one copies the value of numbers[i] into a local variable, whereas the second one stores the address of numbers[i] into a pointer local variable. If you can do what you need using just the address of numbers[i] and referring back to numbers[i], it's likely that will be faster than doing a wholesale copy of the value, although it depends on a lot of factors like the size of the struct, etc.

Regarding the general optimization question, here are some things to consider...

Use a Profiler

The best way to measure the speed of your code is to use a profiling tool. There are a number of different tools available, depending on your target platform - see (for example) How can I profile C++ code running in Linux? and What's the best free C++ profiler for Windows?.

You really want to use a profiler for this because it's notoriously difficult to tell just from looking what the costliest parts of a program will be, for a number of reasons...

# of Instructions != # of Processor Cycles

One reason to use a profiler is that it's often difficult to tell from looking at two pieces of code which one will run faster. Even in assembly code, you can't simply count the number of instructions, because many instructions take multiple processor cycles to complete. This varies considerably by target platform. For example, on some platforms the fastest way to load the value 1 to a CPU register is something straightforward like this:

```<code>MOV r0, #1
</code>```

Whereas on other platforms the fastest approach is actually to clear the register and then increment it, like this:

```<code>CLR r0
INC r0
</code>```

The second case has more instruction lines, but that doesn't necessarily mean that it's slower.

Other Complications

Another reason that it's difficult to tell which pieces of code will most need optimizing is that most modern computers employ fairly sophisticated caches that can dramatically improve performance. Executing a cached loop several times is often less expensive than loading a single piece of data from a location that isn't cached. It can be very difficult to predict exactly what will cause a cache miss, but when using a profiler you don't have to predict - it makes the measurements for you.

Avoid Premature Optimization

For most projects, optimizing your code is best left until relatively late in the process. If you start optimizing too early, you may find that you spend a lot of time optimizing a feature that turns out to be relatively inexpensive compared to your program's other features. That said, there are some notable counterexamples - if you're building a large-scale database tool you might reasonably expect that performance is going to be an important selling point.

Body:
Eugene Sh. is correct that these two lines aren't doing the same thing - the first one copies the value of numbers[i] into a local variable, whereas the second one stores the address of numbers[i] into a pointer local variable. If you can do what you need using just the address of numbers[i] and referring back to numbers[i], it's likely that will be faster than doing a wholesale copy of the value, although it depends on a lot of factors like the size of the struct, etc.

Regarding the general optimization question, here are some things to consider...

Use a Profiler

The best way to measure the speed of your code is to use a profiling tool. There are a number of different tools available, depending on your target platform - see (for example) How can I profile C++ code running in Linux? and What's the best free C++ profiler for Windows?.

You really want to use a profiler for this because it's notoriously difficult to tell just from looking what the costliest parts of a program will be, for a number of reasons...

# of Instructions != # of Processor Cycles

One reason to use a profiler is that it's often difficult to tell from looking at two pieces of code which one will run faster. Even in assembly code, you can't simply count the number of instructions, because many instructions take multiple processor cycles to complete. This varies considerably by target platform. For example, on some platforms the fastest way to load the value 1 to a CPU register is something straightforward like this:

MOV r0, #1

Whereas on other platforms the fastest approach is actually to clear the register and then increment it, like this:

CLR r0
INC r0

The second case has more instruction lines, but that doesn't necessarily mean that it's slower.

Other Complications

Another reason that it's difficult to tell which pieces of code will most need optimizing is that most modern computers employ fairly sophisticated caches that can dramatically improve performance. Executing a cached loop several times is often less expensive than loading a single piece of data from a location that isn't cached. It can be very difficult to predict exactly what will cause a cache miss, but when using a profiler you don't have to predict - it makes the measurements for you.

Avoid Premature Optimization

For most projects, optimizing your code is best left until relatively late in the process. If you start optimizing too early, you may find that you spend a lot of time optimizing a feature that turns out to be relatively inexpensive compared to your program's other features. That said, there are some notable counterexamples - if you're building a large-scale database tool you might reasonably expect that performance is going to be an important selling point.


问:
while loop to find largest number less than
I want my program to get the largest number that is less than 12,000 when cubed but instead it goes to one number higher.     </p>

```<code>count = 0
cubed = 1
while cubed < 12000:
  count += 1
  cubed = count ** 3
print("The largest integer <12000 is", count)
</code>```

答:
The while loop will only stop when cubed >= 12000.

If you want to make it stop before that, you will have to check whether (count+1)**3 < 12000, and only then do count += 1.

```<code>count = 0

while (count+1)**3 < 12000:
  count += 1

print("The largest integer <12000 is", count)
</code>```

PS: simpler method is to take cube-root of 12000 and truncate to integer.

Body:
I want my program to get the largest number that is less than 12,000 when cubed but instead it goes to one number higher.

count = 0
cubed = 1
while cubed < 12000:
  count += 1
  cubed = count ** 3
print("The largest integer <12000 is", count)

Body:
The while loop will only stop when cubed >= 12000.

If you want to make it stop before that, you will have to check whether (count+1)**3 < 12000, and only then do count += 1.

count = 0

while (count+1)**3 < 12000:
  count += 1

print("The largest integer <12000 is", count)

PS: simpler method is to take cube-root of 12000 and truncate to integer.


问:
Chaining DBIOAction with branching, one branch does nothing
Coming from How to get max(id) of table = Rep[Option[Long]] for subsequent insert, without calling db.run in between

I have yet another problem with my code:

```<code>def add(languageCode: String,
  typeId: Long,
  properties: Seq[Property]): Unit = {
    val dbAction = (
        for{
            nodeId <- (nodes.all returning nodes.all.map(_.id)) += Node(typeId)
            language <- (languages.all filter (_.code === languageCode)).result.head
            _ <- DBIO.seq(properties.map
            {
            property =>
                val id = property.id
                val name = property.key
                val value = property.value
                if(id == 0) {
                  val currentPropId: FixedSqlAction[Option[Long], h2Profile.api.NoStream, Effect.Read] = this.properties.all.map(_.id).max.result
                  val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(language.id.get, currentPropId + 1, name)
                  nodeProperties.all += NodeProperty(nodeId, 2, value)
                } else {
                  nodeProperties.all += NodeProperty(nodeId, id, value)
                }
            }: _*)
        } yield()).transactionally

        db.run(dbAction)
}
</code>```

1)
The basic idea is, that if that for each property which has id of 0, there are two inserts to be called. One to actually create that new property in some table, the other to also add the value of that property to another table.

That's in the:

```<code>if(id == 0) {
    val currentPropId: Rep[Option[Long]] = this.properties.all.map(_.id).max
    // FIXME get rid of hardcoded languageId
    val DUMMY_LANGUAGE_ID = 1
    val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(DUMMY_LANGUAGE_ID, currentPropId + 1, name)
    nodeProperties.all += NodeProperty(nodeId, 2, value)
}
</code>```

part.

Now, if that is not the case, only the value of the property needs to be inserted to the correct table, that's what the else part is for.

The problem I face is that for the case where the id == 0 nothing gets inserted.

I also tried it like this:

```<code>if(id == 0) {
    val nextPropId: Rep[Option[Long]] = this.properties.all.map(_.id).max
    // FIXME get rid of hardcoded languageId
    val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(1, 10, name)
    val nodeProperty = nodeProperties.all += NodeProperty(nodeId, 2, value)
    propertyId andThen nodeProperty
}
</code>```

but to no avail.

The else part works just fine. What am I missing here?

edit:

Because I got asked.

```<code>val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(language.id.get, 10, name)
val nodeProperty = nodeProperties.all += NodeProperty(nodeId, 2, value)

log.info(s"Statements: ${propertyId.statements}")
log.info(s"${nodeProperty.statements}")
</code>```

gives me:

Statements: Vector(insert into "properties"
  ("language_id","property_id","name")  values (?,?,?)) Vector(insert
  into "node_property" ("node_id","property_id","value")  values
  (?,?,?))

Which looks just fine.

I would love to log also the content of dbAction itself but as it's a DBIOAction I did not find a way to do so in a meaningful manner.

If I set my logging to trace I get:

```<code>22:18:16:016 - [debug] s.c.QueryCompilerBenchmark - ------------------- Phase: Time ---------
22:18:16:016 - [debug] s.c.QueryCompilerBenchmark -       assignUniqueSymbols:    0.456428 ms
22:18:16:016 - [debug] s.c.QueryCompilerBenchmark -                inferTypes:    0.089135 ms
22:18:16:016 - [debug] s.c.QueryCompilerBenchmark -            insertCompiler:    0.292443 ms
22:18:16:016 - [debug] s.c.QueryCompilerBenchmark -                   codeGen:    0.534494 ms
22:18:16:016 - [debug] s.c.QueryCompilerBenchmark -                     TOTAL:    1.372500 ms
22:18:16:016 - [debug] s.b.B.action - #5: Rollback
</code>```

With no idea why the last line says Rollback as everything before (quite a lot more) seems okay to me.

edit2:

Looks like I finally have it with:

```<code>val dbAction = for {
      nodeId <- (nodes.all returning nodes.all.map(_.id)) += Node(typeId)
      languageId <- (languages.all filter (_.code === languageCode)).map(_.id).result.head
      _ <- DBIO.seq(properties.values.map
      {
        property =>
          val id = property.id
          val name = property.key
          val value = property.value

          if(id == 0) {
            for {
              currentPropId <- this.properties.all.map(_.id).max.result
              propertyId <- (this.properties.all returning this.properties.all.map(_.id)) += Property(languageId, currentPropId.get + 1, name)
              _ <- this.nodeProperties.all += NodeProperty(nodeId, propertyId, value)
            } yield ()
          } else {
            this.nodeProperties.all += NodeProperty(nodeId, id, value)
          }
      }: _*)
    } yield ()
</code>```

答:
It looks like the final answer is to restructure a bit:

```<code> val dbAction = for {
      nodeId <- (nodes.all returning nodes.all.map(_.id)) += Node(typeId)
      languageId <- (languages.all filter (_.code === languageCode)).map(_.id).result.head
      _ <- DBIO.seq(properties.values.map
      {
        property =>
          val id = property.id
          val name = property.key
          val value = property.value

          if(id == 0) {
            for {
              currentPropId <- this.properties.all.map(_.id).max.result
              propertyId <- (this.properties.all returning this.properties.all.map(_.id)) += Property(languageId, currentPropId.get + 1, name)
              _ <- this.nodeProperties.all += NodeProperty(nodeId, propertyId, value)
            } yield ()
          } else {
            this.nodeProperties.all += NodeProperty(nodeId, id, value)
          }
      }: _*)
    } yield ()
</code>```

I would love to see other solutions, but that's the one I found after another long trial and error session. I am still unsure why I couldn't get the andThen approach to work.

And I am wondering what happens to the transactionally if something happens in the inner for comprehension. I guess it wouldn't work according to my interpretation of documentation - http://slick.lightbend.com/doc/3.2.1/dbio.html#transactions-and-pinned-sessions

Nested transactionally actions simply execute inside the existing transaction without additional savepoints.

Body:
Coming from How to get max(id) of table = Rep[Option[Long]] for subsequent insert, without calling db.run in between

I have yet another problem with my code:

def add(languageCode: String,
  typeId: Long,
  properties: Seq[Property]): Unit = {
    val dbAction = (
        for{
            nodeId <- (nodes.all returning nodes.all.map(_.id)) += Node(typeId)
            language <- (languages.all filter (_.code === languageCode)).result.head
            _ <- DBIO.seq(properties.map
            {
            property =>
                val id = property.id
                val name = property.key
                val value = property.value
                if(id == 0) {
                  val currentPropId: FixedSqlAction[Option[Long], h2Profile.api.NoStream, Effect.Read] = this.properties.all.map(_.id).max.result
                  val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(language.id.get, currentPropId + 1, name)
                  nodeProperties.all += NodeProperty(nodeId, 2, value)
                } else {
                  nodeProperties.all += NodeProperty(nodeId, id, value)
                }
            }: _*)
        } yield()).transactionally

        db.run(dbAction)
}

1)
The basic idea is, that if that for each property which has id of 0, there are two inserts to be called. One to actually create that new property in some table, the other to also add the value of that property to another table.

That's in the:

if(id == 0) {
    val currentPropId: Rep[Option[Long]] = this.properties.all.map(_.id).max
    // FIXME get rid of hardcoded languageId
    val DUMMY_LANGUAGE_ID = 1
    val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(DUMMY_LANGUAGE_ID, currentPropId + 1, name)
    nodeProperties.all += NodeProperty(nodeId, 2, value)
}

part.

Now, if that is not the case, only the value of the property needs to be inserted to the correct table, that's what the else part is for.

The problem I face is that for the case where the id == 0 nothing gets inserted.

I also tried it like this:

if(id == 0) {
    val nextPropId: Rep[Option[Long]] = this.properties.all.map(_.id).max
    // FIXME get rid of hardcoded languageId
    val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(1, 10, name)
    val nodeProperty = nodeProperties.all += NodeProperty(nodeId, 2, value)
    propertyId andThen nodeProperty
}

but to no avail.

The else part works just fine. What am I missing here?

edit:

Because I got asked.

val propertyId = (this.properties.all returning this.properties.all.map(_.id)) += Property(language.id.get, 10, name)
val nodeProperty = nodeProperties.all += NodeProperty(nodeId, 2, value)

log.info(s"Statements: ${propertyId.statements}")
log.info(s"${nodeProperty.statements}")

gives me:

Statements: Vector(insert into "properties"
  ("language_id","property_id","name")  values (?,?,?)) Vector(insert
  into "node_property" ("node_id","property_id","value")  values
  (?,?,?))

Which looks just fine.

I would love to log also the content of dbAction itself but as it's a DBIOAction I did not find a way to do so in a meaningful manner.

If I set my logging to trace I get:

22:18:16:016 - [debug] s.c.QueryCompilerBenchmark - ------------------- Phase: Time ---------
22:18:16:016 - [debug] s.c.QueryCompilerBenchmark -       assignUniqueSymbols:    0.456428 ms
22:18:16:016 - [debug] s.c.QueryCompilerBenchmark -                inferTypes:    0.089135 ms
22:18:16:016 - [debug] s.c.QueryCompilerBenchmark -            insertCompiler:    0.292443 ms
22:18:16:016 - [debug] s.c.QueryCompilerBenchmark -                   codeGen:    0.534494 ms
22:18:16:016 - [debug] s.c.QueryCompilerBenchmark -                     TOTAL:    1.372500 ms
22:18:16:016 - [debug] s.b.B.action - #5: Rollback

With no idea why the last line says Rollback as everything before (quite a lot more) seems okay to me.

edit2:

Looks like I finally have it with:

val dbAction = for {
      nodeId <- (nodes.all returning nodes.all.map(_.id)) += Node(typeId)
      languageId <- (languages.all filter (_.code === languageCode)).map(_.id).result.head
      _ <- DBIO.seq(properties.values.map
      {
        property =>
          val id = property.id
          val name = property.key
          val value = property.value

          if(id == 0) {
            for {
              currentPropId <- this.properties.all.map(_.id).max.result
              propertyId <- (this.properties.all returning this.properties.all.map(_.id)) += Property(languageId, currentPropId.get + 1, name)
              _ <- this.nodeProperties.all += NodeProperty(nodeId, propertyId, value)
            } yield ()
          } else {
            this.nodeProperties.all += NodeProperty(nodeId, id, value)
          }
      }: _*)
    } yield ()

Body:
It looks like the final answer is to restructure a bit:

 val dbAction = for {
      nodeId <- (nodes.all returning nodes.all.map(_.id)) += Node(typeId)
      languageId <- (languages.all filter (_.code === languageCode)).map(_.id).result.head
      _ <- DBIO.seq(properties.values.map
      {
        property =>
          val id = property.id
          val name = property.key
          val value = property.value

          if(id == 0) {
            for {
              currentPropId <- this.properties.all.map(_.id).max.result
              propertyId <- (this.properties.all returning this.properties.all.map(_.id)) += Property(languageId, currentPropId.get + 1, name)
              _ <- this.nodeProperties.all += NodeProperty(nodeId, propertyId, value)
            } yield ()
          } else {
            this.nodeProperties.all += NodeProperty(nodeId, id, value)
          }
      }: _*)
    } yield ()

I would love to see other solutions, but that's the one I found after another long trial and error session. I am still unsure why I couldn't get the andThen approach to work.

And I am wondering what happens to the transactionally if something happens in the inner for comprehension. I guess it wouldn't work according to my interpretation of documentation - http://slick.lightbend.com/doc/3.2.1/dbio.html#transactions-and-pinned-sessions

Nested transactionally actions simply execute inside the existing transaction without additional savepoints.


问:
How to read a full UTF-8 hexadecimal values into an int
What I am trying to do is get an int to take in an UTF-8-16-32 character, in doing so it should be able to tell whether it is UTF-8, UTF-16, or UTF-32.

I read binary values from a text file using fopen(fp, "rb"). I run into a problem where a single character is split into two bytes.

For instance, if I try to read a character CENT SIGN

The text file input.txt contains:

```<code>¢
</code>```

I get:

```<code>utf code:       LATIN CAPITAL LETTER A WITH CIRCUMFLEX
binary:         11000010
hexadecimal:    0xC2
decimal:        194
character:      �

utf code:       CENT SIGN
binary:         10100010
hexadecimal:    0xA2
decimal:        162
character:      �

utf code:       LINE FEED (LF)
binary:         00001010
hexadecimal:    0xA
decimal:        10
character:
</code>```

Code:

```<code>int ch;
while ((ch = fgetc(stream)) != EOF) {
    printf(“utf code:\t”);
    findCode(ch); // HERE

    write(1, “binary:         “, 16);
    printBits(ch);

    printf(“\nhexadecimal:\t%X”, ch);

    printf(“\ndecimal:\t%d”, ch);

    printf(“\ncharacter:\t%c\n\n”, ch);
}
</code>```

NOTE: On a UTF-8 database, the binary value for CENT SIGN is 0xC2A2 or 11000010:10100010

答: The problem is that fgetc will only read 1 byte.</p>

Body:
What I am trying to do is get an int to take in an UTF-8-16-32 character, in doing so it should be able to tell whether it is UTF-8, UTF-16, or UTF-32.

I read binary values from a text file using fopen(fp, "rb"). I run into a problem where a single character is split into two bytes.

For instance, if I try to read a character CENT SIGN

The text file input.txt contains:

¢

I get:

utf code:       LATIN CAPITAL LETTER A WITH CIRCUMFLEX
binary:         11000010
hexadecimal:    0xC2
decimal:        194
character:      �

utf code:       CENT SIGN
binary:         10100010
hexadecimal:    0xA2
decimal:        162
character:      �

utf code:       LINE FEED (LF)
binary:         00001010
hexadecimal:    0xA
decimal:        10
character:

Code:

int ch;
while ((ch = fgetc(stream)) != EOF) {
    printf(“utf code:\t”);
    findCode(ch); // HERE

    write(1, “binary:         “, 16);
    printBits(ch);

    printf(“\nhexadecimal:\t%X”, ch);

    printf(“\ndecimal:\t%d”, ch);

    printf(“\ncharacter:\t%c\n\n”, ch);
}

NOTE: On a UTF-8 database, the binary value for CENT SIGN is 0xC2A2 or 11000010:10100010


问:
Making html div take up full screen height
I am building a website based on a template. It uses bootstrap and can be seen here http://www.tombelina.com/fcrusade/

I am trying to get the first image to take up the whole screen on a mobile device screen. Currently it works perfectly for desktops but I can not get it to work with mobile devices.

答:
I think it's because your gametracker image is so wide that it's
  jacking up the layout. It's wider than 100% of the page. Add the
  "img-responsive" class to that image - @aquinas