问:
Django; AWS Elastic Beanstalk ERROR: Your WSGIPath refers to a file that does not exist
I am using this tutorial:
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html

I create the .ebextensions directory inside the root directory, and put this django.config file in it:

```<code>option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: mysite/wsgi.py
</code>```

I've also tried setting the path to mysite/mysite/wsgi.py because I saw that work somewhere but it did not help me.

Everywhere I look shows a different .config file with different arrangements, and I don't know where to go from here. How can I properly set my WSGIPath in Elastic Beanstalk?

答:
I did not use console but GUI.

```<code>ERROR: Your WSGIPath refers to a file that does not exist.
</code>```

where could be problem : Creating .zip file

select all : files of your project (not the project folder)

Note : weworkout is my django project (created by django-admin startproject
 weworkout)

Right way : select all files

Wrong way : selecting project folder

Also this is the only change you have to do to your django project before uploading

weworkout/.ebextensions/django.config file contains

```<code>option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: weworkout/wsgi.py
</code>```

Note : .ebextensions is in same folder as manage.py

Body:
I am using this tutorial:
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html

I create the .ebextensions directory inside the root directory, and put this django.config file in it:

option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: mysite/wsgi.py

I've also tried setting the path to mysite/mysite/wsgi.py because I saw that work somewhere but it did not help me.

Everywhere I look shows a different .config file with different arrangements, and I don't know where to go from here. How can I properly set my WSGIPath in Elastic Beanstalk?

Body:
I did not use console but GUI.

ERROR: Your WSGIPath refers to a file that does not exist.

where could be problem : Creating .zip file

select all : files of your project (not the project folder)

Note : weworkout is my django project (created by django-admin startproject
 weworkout)

Right way : select all files

Wrong way : selecting project folder

Also this is the only change you have to do to your django project before uploading

weworkout/.ebextensions/django.config file contains

option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: weworkout/wsgi.py

Note : .ebextensions is in same folder as manage.py


来源: stackexchange

问:
Android Studio: Error:Execution failed for task ':app:dexDebug'
I'm using Android Studio for the first time and I got the following error after importing the project (previously it was an eclipse project where I had issues too.)

Here is the information given:

```<code>Error:Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    /home/crash-id/Development/SDK/adt-bundle-linux-x86_64-20140702/sdk/build-tools/21.1.2/dx --dex --no-optimize --output /home/crash-id/AndroidstudioProjects/LocalSin/app/build/intermediates/dex/debug --input-list=/home/crash-id/AndroidstudioProjects/LocalSin/app/build/intermediates/tmp/dex/debug/inputList.txt
  Error Code:
    2
  Output:
    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)
        at com.android.dx.command.dexer.Main.run(Main.java:246)
        at com.android.dx.command.dexer.Main.main(Main.java:215)
        at com.android.dx.command.Main.main(Main.java:106)

:app:dexDebug
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode;
    at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
    at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
    at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
    at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
    at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
    at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)
    at com.android.dx.command.dexer.Main.run(Main.java:246)
    at com.android.dx.command.dexer.Main.main(Main.java:215)
    at com.android.dx.command.Main.main(Main.java:106)

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    /home/crash-id/Development/SDK/adt-bundle-linux-x86_64-20140702/sdk/build-tools/21.1.2/dx --dex --no-optimize --output /home/crash-id/AndroidstudioProjects/LocalSin/app/build/intermediates/dex/debug --input-list=/home/crash-id/AndroidstudioProjects/LocalSin/app/build/intermediates/tmp/dex/debug/inputList.txt
  Error Code:
    2
  Output:

    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)
        at com.android.dx.command.dexer.Main.run(Main.java:246)
        at com.android.dx.command.dexer.Main.main(Main.java:215)
        at com.android.dx.command.Main.main(Main.java:106)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED
</code>```

The app build.gradle is this:

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

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.myapp.test"
        minSdkVersion 11
        targetSdkVersion 14
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.google.android.gms:play-services:+'
    compile files('libs/google-play-services.jar')
    compile files('libs/httpcore-4.3.2.jar')
    compile files('libs/httpmime-4.3.4.jar')
}
</code>```

And the project built.gradle is this:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

Do you have any idea what the problem could be and how can it be solved? A good explanation for the problem would be useful too as I am new to Android Studio. Thanks in advance :)

答:
delete all files in c:\users\<username>\.gradle\caches\transforms-2\files-2.1\

Enjoy the command flutter run

ContentLicense: CC BY-SA 3.0

Body:
I'm using Android Studio for the first time and I got the following error after importing the project (previously it was an eclipse project where I had issues too.)

Here is the information given:

Error:Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    /home/crash-id/Development/SDK/adt-bundle-linux-x86_64-20140702/sdk/build-tools/21.1.2/dx --dex --no-optimize --output /home/crash-id/AndroidstudioProjects/LocalSin/app/build/intermediates/dex/debug --input-list=/home/crash-id/AndroidstudioProjects/LocalSin/app/build/intermediates/tmp/dex/debug/inputList.txt
  Error Code:
    2
  Output:
    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)
        at com.android.dx.command.dexer.Main.run(Main.java:246)
        at com.android.dx.command.dexer.Main.main(Main.java:215)
        at com.android.dx.command.Main.main(Main.java:106)

:app:dexDebug
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode;
    at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
    at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
    at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
    at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
    at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
    at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)
    at com.android.dx.command.dexer.Main.run(Main.java:246)
    at com.android.dx.command.dexer.Main.main(Main.java:215)
    at com.android.dx.command.Main.main(Main.java:106)

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    /home/crash-id/Development/SDK/adt-bundle-linux-x86_64-20140702/sdk/build-tools/21.1.2/dx --dex --no-optimize --output /home/crash-id/AndroidstudioProjects/LocalSin/app/build/intermediates/dex/debug --input-list=/home/crash-id/AndroidstudioProjects/LocalSin/app/build/intermediates/tmp/dex/debug/inputList.txt
  Error Code:
    2
  Output:

    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Lcom/google/ads/AdRequest$ErrorCode;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)
        at com.android.dx.command.dexer.Main.run(Main.java:246)
        at com.android.dx.command.dexer.Main.main(Main.java:215)
        at com.android.dx.command.Main.main(Main.java:106)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

The app build.gradle is this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.myapp.test"
        minSdkVersion 11
        targetSdkVersion 14
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:support-v4:18.0.0'
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.google.android.gms:play-services:+'
    compile files('libs/google-play-services.jar')
    compile files('libs/httpcore-4.3.2.jar')
    compile files('libs/httpmime-4.3.4.jar')
}

And the project built.gradle is this:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Do you have any idea what the problem could be and how can it be solved? A good explanation for the problem would be useful too as I am new to Android Studio. Thanks in advance :)

ContentLicense: CC BY-SA 4.0


问:
SOLVED: Looking for a way to automate generation of internal PDF hyperlinks
I have a 300+ page PDF document which needs to have internal page links added to it to reference other pages in the document. The document is created in Visio, which does not support consistent hyperlink generation in PDF export, so the link generation needs to be done on the PDF itself, not up the chain. This is an annual need, and regularly takes over a week due to the amount of manual labor, time, and checking needed.

The text which is hyperlinked has the same format in every case (e.g., "See Section 8.18 - How to Hyperlink"), and I'm certain this can be automated, as there are commercial plugins which can do this, but they cost hundreds of dollars, and are not able to be used in this case due to restrictions imposed by my employer. Example: https://www.evermap.com/ABAddingHyperlinks.asp

I've been looking through the Acrobat Plugin SDK and it seems doable, but I know there is also a higher level scripting language available for Acrobat. Does anyone have experience working with PDFs or with the Acrobat scripting / SDK tools? Are there open source methods for doing this? I've looked everywhere! Willing to learn. I've looked at Ghostscript (Adding internal hyperlink to a pdf) but what I need is way more than just a Table of Contents, and links can appear in many places on the page with line breaks, so consistency is a challenge.

EDIT: I found a solution! Bluebeam software's Revu Extreme works pretty darn well, and can be used as a 30 day free trial of all features. Only limitation is that links which extend across a line break (multiple lines of text) do not properly work in Edge or Chrome's PDF viewer, as they don't properly support hyperlinks with multiple click regions. I've submitted a ticket requesting a feature be added to Revu that fixes this, but for now those links need to be manually fixed following the batch link. The process is described here: https://support.bluebeam.com/online-help/revu2018/Content/RevuHelp/Menus/Batch/Link/Batch-Link--T.htm

答:
You can add hyperlinks to a document with Ghostscript, but you would need to know the location of the text to hyperlink and the destination in advance, you cannot automate it or in fact write any reasonably simple code to automate the task using Ghostscript. You'd need to modify chunks of the PDF interpreter, which is written in PostScript and is not a task for anyone not a PostScript expert.

You could probably do it with MuPDF, and probably using MuJS to script it, but I don't know enough to be certain. It would still require some coding effort, but it would probably be easier to use JavaScript at least.


问:
How to view an animated GIF / PNG frame by frame, or slow it down
Is there a way to view animated GIFs demonstrations step-by-step? Example of an animated image produced with Blender screencast which is way too fast:

Source: What is the fastest way to create a curved plane? on Blender.SE.

My own search was not successful:
- An existing answer on Blender.SE suggests to view animated images in GIMP. Like the OP, I don't think is a convenient method!
- There is an addon for Chrome (GIF Scrubber), but I didn't find one for Firefox.
- There is a service online which take a GIF and add appropriate controls: This same GIF converted.

Question: Is there:

A Firefox addon which add playback controls to an animated image?

Or a stand alone tool?

答:
If you want to view a gif frame by frame -

This website lets you upload an image or paste an image url https://ezgif.com/split

It was helpful for me when trying to build tests for Conway's game of life.


问:
Spack [Scala]: Reduce a nested tuple value by key
Let's say I have a Spark Scala program with a RDD named mention_rdd that goes as follows:

```<code>(name, (filename, sum))
...
(Maria, (file0, 3))
(John, (file0, 1))
(Maria, (file1, 6))
(Maria, (file2, 1))
(John, (file2, 3))
...
</code>```

Where we have the filenames and the number of occurrences for each name.

I want to reduce and find, for each name, the filename with the max occurrences. For example:

```<code>(name, (filename, max(sum))
...
(Maria, (file1, 6))
(John, (file2, 3))
...
</code>```

I tried to access the (filename,sum) tuple of the RDD on its own, so I can reduce from there by name (due to an error that said i can't traverse from the mention_rdd because (String,Int) is not a TraversableOnce type):

```<code>val output = mention_rdd.flatMap(file_counts => file_counts._2.map(file_counts._2._1, file_counts._2._2))
        .reduceByKey((a, b) => if (a > b) a else b)
</code>```

But I got an error saying value map is not a member of (String, Int)

Is this possible to do within Spark? And if so, how? Was my approach flawed from the start?

答:
Why not just:</p>

```<code>val output = mention_rdd.reduceByKey {
  case ((file1, sum1), (file2, sum2)) =>
    if (sum2 >= sum1) (file2, sum2)
    else (file1, sum1)
}
</code>```

Body:
Let's say I have a Spark Scala program with a RDD named mention_rdd that goes as follows:

(name, (filename, sum))
...
(Maria, (file0, 3))
(John, (file0, 1))
(Maria, (file1, 6))
(Maria, (file2, 1))
(John, (file2, 3))
...

Where we have the filenames and the number of occurrences for each name.

I want to reduce and find, for each name, the filename with the max occurrences. For example:

(name, (filename, max(sum))
...
(Maria, (file1, 6))
(John, (file2, 3))
...

I tried to access the (filename,sum) tuple of the RDD on its own, so I can reduce from there by name (due to an error that said i can't traverse from the mention_rdd because (String,Int) is not a TraversableOnce type):

val output = mention_rdd.flatMap(file_counts => file_counts._2.map(file_counts._2._1, file_counts._2._2))
        .reduceByKey((a, b) => if (a > b) a else b)

But I got an error saying value map is not a member of (String, Int)

Is this possible to do within Spark? And if so, how? Was my approach flawed from the start?

Body:
Why not just:

val output = mention_rdd.reduceByKey {
  case ((file1, sum1), (file2, sum2)) =>
    if (sum2 >= sum1) (file2, sum2)
    else (file1, sum1)
}


问:
Mobile Application Development Tools
Subject  - A group of developer looking for Mobile Application Development guidelines(Preferably for Android platform).

We have been searching different sources for information regarding application design phase. Specifically different parts such as Sketching, Prototyping, Navigation flow diagrams...etc. We are more interested to know regarding Navigation flow diagrams. Could anyone please share some good resource where we can reference different types of annotations for our application state. In short...

What will be the best practise to describe my application's different states in form of diagrams? In order to circulate(in team) an idea of how our application will flow in order to accomplish user's goal.

P.S.  Such guidelines should be provided by google? Or these sort of documentation objects should depend on individual design team?

Thank you in advance,

Happy Coding!
Krio

答: I follow the style Google uses on their SDK, see: http://developer.android.com/guide/practices/ui_guidelines/activity_task_design.html. While they do not provide an explicit guide to creating these diagrams, the general principle is easy to understand and follow.</p>

Title: Mobile Application Development Tools


问:
Accelerated framework in Xcode to get a QR factorization of A but zgeqrf cannot been found
I have successfully used sgetrf to obtain a LU factorization of A using accelerated framework in Xcode, when I tried to get a QR factorization of A using the same framework I get the error " Semantic Issue Group No matching function for call to 'zgeqrf_' 1. Candidate function not viable: no known conversion from 'float *' to '__CLPK_doublecomplex *' for 3rd argumen" here is my code:

include

include

int main(int argc, const char * argv[]) {

```<code>float A[4][3] = {{0,-2,1}, {1,3,1}, {0,0,1}, {1,1,5}};

__CLPK_integer m = 4;
__CLPK_integer n = 3;
__CLPK_integer ipiv[3];
__CLPK_doublecomplex tau[n];
__CLPK_doublecomplex work[n];
__CLPK_integer lwork = n;
__CLPK_integer info = 0;

sgetrf_(&m, &n, &A[0][0], &m, ipiv, &info);
zgeqrf_(&m, &n, &A[0][0], &m, tau, work, &lwork, &info);

int row, columns;

for (row=0; row<4; row++)
{
    for(columns=0; columns<3; columns++)
    {
        printf("%f", A[row][columns]);
    }
    printf("\n");
}
</code>```

}

Thanks for your time in advance;

答: From your error message it sounds like zgeqrf_ requires the argument to be of type __CLPK_doublecomplex* instead of float*, but your A is declared as an array of floats. Check the documentation for zgeqrf_ to help understand why.

Body:
I have successfully used sgetrf to obtain a LU factorization of A using accelerated framework in Xcode, when I tried to get a QR factorization of A using the same framework I get the error " Semantic Issue Group No matching function for call to 'zgeqrf_' 1. Candidate function not viable: no known conversion from 'float *' to '__CLPK_doublecomplex *' for 3rd argumen" here is my code:

include

include

int main(int argc, const char * argv[]) {

float A[4][3] = {{0,-2,1}, {1,3,1}, {0,0,1}, {1,1,5}};

__CLPK_integer m = 4;
__CLPK_integer n = 3;
__CLPK_integer ipiv[3];
__CLPK_doublecomplex tau[n];
__CLPK_doublecomplex work[n];
__CLPK_integer lwork = n;
__CLPK_integer info = 0;

sgetrf_(&m, &n, &A[0][0], &m, ipiv, &info);
zgeqrf_(&m, &n, &A[0][0], &m, tau, work, &lwork, &info);

int row, columns;

for (row=0; row<4; row++)
{
    for(columns=0; columns<3; columns++)
    {
        printf("%f", A[row][columns]);
    }
    printf("\n");
}

}

Thanks for your time in advance;


问:
PyQt5: Create transparent window with opaque widgets
Is it possible to make mainWindow completely transparent while other widgets remains visible?

For example:

I want to make app transparent and make everything else visible (like, mainFrame, close button, minimize button)

答:
As @Felipe mentioned you can use
    window.setAttribute(QtCore.Qt.WA_TranslucentBackground)
here is a little example:</p>

```<code>import sys
from PyQt5 import QtWidgets, QtCore

app = QtWidgets.QApplication(sys.argv)

# create invisble widget
window = QtWidgets.QWidget()
window.setAttribute(QtCore.Qt.WA_TranslucentBackground)
window.setWindowFlags(QtCore.Qt.FramelessWindowHint)
window.setFixedSize(800, 600)

# add visible child widget, when this widget is transparent it will also be invisible
visible_child = QtWidgets.QWidget(window)
visible_child.setStyleSheet('QWidget{background-color: white}')
visible_child.setObjectName('vc')
visible_child.setFixedSize(800, 600)
layout = QtWidgets.QGridLayout()

# add a close button
close_button = QtWidgets.QPushButton()
close_button.setText('close window')
close_button.clicked.connect(lambda: app.exit(0))
layout.addWidget(close_button)

# add a button that makes the visible child widget transparent
change_size_button = QtWidgets.QPushButton()
change_size_button.setText('change size')
change_size_button.clicked.connect(lambda: visible_child.setStyleSheet('QWidget#vc{background-color: transparent}'))
layout.addWidget(change_size_button)

visible_child.setLayout(layout)
window.show()
app.exec()
</code>```

Body:
As @Felipe mentioned you can use
    window.setAttribute(QtCore.Qt.WA_TranslucentBackground)
here is a little example:

import sys
from PyQt5 import QtWidgets, QtCore

app = QtWidgets.QApplication(sys.argv)

# create invisble widget
window = QtWidgets.QWidget()
window.setAttribute(QtCore.Qt.WA_TranslucentBackground)
window.setWindowFlags(QtCore.Qt.FramelessWindowHint)
window.setFixedSize(800, 600)

# add visible child widget, when this widget is transparent it will also be invisible
visible_child = QtWidgets.QWidget(window)
visible_child.setStyleSheet('QWidget{background-color: white}')
visible_child.setObjectName('vc')
visible_child.setFixedSize(800, 600)
layout = QtWidgets.QGridLayout()

# add a close button
close_button = QtWidgets.QPushButton()
close_button.setText('close window')
close_button.clicked.connect(lambda: app.exit(0))
layout.addWidget(close_button)

# add a button that makes the visible child widget transparent
change_size_button = QtWidgets.QPushButton()
change_size_button.setText('change size')
change_size_button.clicked.connect(lambda: visible_child.setStyleSheet('QWidget#vc{background-color: transparent}'))
layout.addWidget(change_size_button)

visible_child.setLayout(layout)
window.show()
app.exec()


问:
Pointers and Dynamically Allocating Arrays error in C++
I am getting an introduction to pointers and I don't understand the following code.    </p>

```<code>int main(){
        int *p;
        p=new int[5];
        cout << p <<endl;  // line 4
        *p=3;
        p=p+1;
        cout <<p <<endl;  // line 7
        *p=7;
        cout << p[0] <<endl;
    }
</code>```

<p>line 4 and line 7 prints the memory location as 0xd91730 and 0xd91734 respectively and I understand that. However, why is the last line `( p[0] )  printing 7 on the screen. Isn't p[0] = 3 instead, as assigned in line 5. I am not understanding this concept. Can anyone please help? Thank you.  </p>

答:
It actually does:

p = new int[5] which is fine. You allocated 5 integers worth of memory.
At p[0] you have stored the value 3 (*p = 3)..

You then offset the pointer p by 1 (p = p + 1).. and now you wrote *p = 7.. Of course printing P[0] is going to print 7 because you've offset p from its original position when you did p = p + 1 (P no longer points to the same memory address you had when you did new int[5]).

You never decreased the pointer back to point to 3.

If you did delete[] p after increasing it, it'd be undefined behaviour and possibly crash on you because you are deleting memory location since you increased P.

If you wanted it to print 3, you'd have to do P = P - 1 after writing 7 to P[1].

Body:
I am getting an introduction to pointers and I don't understand the following code.

int main(){
        int *p;
        p=new int[5];
        cout << p <<endl;  // line 4
        *p=3;
        p=p+1;
        cout <<p <<endl;  // line 7
        *p=7;
        cout << p[0] <<endl;
    }

line 4 and line 7 prints the memory location as 0xd91730 and 0xd91734 respectively and I understand that. However, why is the last line `( p[0] )  printing 7 on the screen. Isn't p[0] = 3 instead, as assigned in line 5. I am not understanding this concept. Can anyone please help? Thank you.


问:
Local git repo creation
I have code base checked out from svn. (code_base). I want to create a local git repo from this code base and then use git branches to play with it. So, I am expecting a structure like follows:

currently available code = c:/code_base

git repo on same machine = c:/repo_head  (Based on c:/code_base)

git clients from newly repo = c:/repo_client1 c:/repo_client2

I am trying to create a bare repo (repo_head) and then trying to add code_base but it does not seem to work. I am getting lot of errors.
What is the best way to go about it?

答:
The easiest way is probably to create the folder repo_head then run

```<code>git init repo_head
</code>```

then copy all the contents from code_base into repo_head.  Finally

```<code>git add --all
git commit -a
</code>```

then you will have a new git repo to play with!

You could probably just initialize code_base as a git repo but I'm not sure how that interacts with the svn meta data . . .

Title: Local git repo creation

Body:
The easiest way is probably to create the folder repo_head then run

git init repo_head

then copy all the contents from code_base into repo_head.  Finally

git add --all
git commit -a

then you will have a new git repo to play with!

You could probably just initialize code_base as a git repo but I'm not sure how that interacts with the svn meta data . . .


问:
How to run a subset of a data frame through R function?
I am trying to set up a function that runs a regression analysis on variables of choice (data.var1,data.var2) from a particular subset of my master data frame, but the function is operating over the entire data frame rather than just the subset that I want it to, no matter whether I define the subset within or outside of the function.</p>

```<code>#Function subsetting data by temp and running regression
varReg21C <- function(data.var1,data.var2) {
  data21C <- subset(allPursuit,allPursuit$temp == 21)
  fitData <- lm(data.var1 ~ data.var2, data21C)
  regData <- summary(fitData)
  anovaData <- anova(fitData)
  reg21C <- list(fitData=fitData,regData=regData,anovaData=anovaData)
}

#OR

#Function running regression on data already in subset
data21C <- subset(allPursuit,allPursuit$temp == 21)
data21C
data25C <- subset(allPursuit,allPursuit$temp == 25)
data25C
data29C <- subset(allPursuit,allPursuit$temp == 29)
data29C

varReg21C <- function(data.var1,data.var2) {
  fitData <- lm(data.var1 ~ data.var2, data21C)
  regData <- summary(fitData)
  anovaData <- anova(fitData)
  reg21C <- list(fitData=fitData,regData=regData,anovaData=anovaData)
}
</code>```

答:
Most likely you have data.var1 and data.var2 floating in your environment. You need to define all the inputs and prevent reading directly from the environment, so if we write it like:

```<code>varReg <- function(data.var1,data.var2,DataFrame,TempChoice) {
  data <- subset(DataFrame,temp == TempChoice)
  Form <- paste(data.var1,"~",data.var2)
  fitData <- lm(Form, data)
  regData <- summary(fitData)
  anovaData <- anova(fitData)
  return( list(fitData=fitData,regData=regData,anovaData=anovaData))
}

allPursuit = data.frame(x=runif(100),y=runif(100),z=runif(100),
temp=sample(c(21,25,29),100,replace=TRUE))

varReg("x","y",allPursuit,21)[[1]]

Call:
lm(formula = Form, data = data)

Coefficients:
(Intercept)            y
     0.3126       0.1494

varReg("x","y",allPursuit,25)[[1]]

Call:
lm(formula = Form, data = data)

Coefficients:
(Intercept)            y
    0.55069      0.01734
</code>```

Body:
I am trying to set up a function that runs a regression analysis on variables of choice (data.var1,data.var2) from a particular subset of my master data frame, but the function is operating over the entire data frame rather than just the subset that I want it to, no matter whether I define the subset within or outside of the function.

#Function subsetting data by temp and running regression
varReg21C <- function(data.var1,data.var2) {
  data21C <- subset(allPursuit,allPursuit$temp == 21)
  fitData <- lm(data.var1 ~ data.var2, data21C)
  regData <- summary(fitData)
  anovaData <- anova(fitData)
  reg21C <- list(fitData=fitData,regData=regData,anovaData=anovaData)
}

#OR

#Function running regression on data already in subset
data21C <- subset(allPursuit,allPursuit$temp == 21)
data21C
data25C <- subset(allPursuit,allPursuit$temp == 25)
data25C
data29C <- subset(allPursuit,allPursuit$temp == 29)
data29C

varReg21C <- function(data.var1,data.var2) {
  fitData <- lm(data.var1 ~ data.var2, data21C)
  regData <- summary(fitData)
  anovaData <- anova(fitData)
  reg21C <- list(fitData=fitData,regData=regData,anovaData=anovaData)
}

Body:
Most likely you have data.var1 and data.var2 floating in your environment. You need to define all the inputs and prevent reading directly from the environment, so if we write it like:

varReg <- function(data.var1,data.var2,DataFrame,TempChoice) {
  data <- subset(DataFrame,temp == TempChoice)
  Form <- paste(data.var1,"~",data.var2)
  fitData <- lm(Form, data)
  regData <- summary(fitData)
  anovaData <- anova(fitData)
  return( list(fitData=fitData,regData=regData,anovaData=anovaData))
}

allPursuit = data.frame(x=runif(100),y=runif(100),z=runif(100),
temp=sample(c(21,25,29),100,replace=TRUE))

varReg("x","y",allPursuit,21)[[1]]

Call:
lm(formula = Form, data = data)

Coefficients:
(Intercept)            y
     0.3126       0.1494

varReg("x","y",allPursuit,25)[[1]]

Call:
lm(formula = Form, data = data)

Coefficients:
(Intercept)            y
    0.55069      0.01734


问:
YouTube videos opening unexpectadly and blocking mobile device
This is the html to display 3 videos on the screen. When this is viewed on a mobile device (e.g. Samsung S8), the screen automatically activates.</p>

```<code><div class="row bottom-whitespace">
        <div class="col-sm-4">
        <figure class="img-tbtext video-icon">
        <div class="vid-banner"><img src="../assets/images/video-img1.jpg" class="hover-img">
        <div class="lazyOwl"><img src="../assets/images/play-Icon.png"></div>
        </div>
        <a class="gallery" data-flashy-type="video" href="https://youtu.be/ZfDRNqWfGas" frameborder="0" allowfullscreen=""></a>
        <h5>Change, project and task management</h5>
         </figure>
       </div>
               <div class="col-sm-4">
        <figure class="img-tbtext video-icon " style="background: #ffc107;">
         <div class="vid-banner"><img src="../assets/images/video-img2.jpg" class="hover-img">
        <div class="lazyOwl"><img src="../assets/images/play-Icon.png"></div></div>
        <a class="gallery" data-flashy-type="video" href="https://youtu.be/MY_CFDnNTzU" frameborder="0" allowfullscreen=""></a>
        <h5>Process excellence & waste management</h5>
         </figure>
       </div>
               <div class="col-sm-4">
        <figure class="img-tbtext video-icon" style="background: #8bc34a;">
         <div class="vid-banner"><img src="../assets/images/video-img3.jpg" class="hover-img"><div class="lazyOwl"><img src="../assets/images/play-Icon.png"></div></div>
        <a class="gallery" data-flashy-type="video" href="https://youtu.be/gYfdvWWf1p8" frameborder="0" allowfullscreen=""></a>
        <h5>Quality control, Audit and Quality assurance</h5>
         </figure>
     </div>
</div>
</code>```

答:
Autoplay Videos

In Safari and some other browsers(mobile), autoplay for videos are prevented and an active input from a user is needed. Safari and Chrome decide that on an algorithm which depends on your browser behaviour:

Safari: https://www.cnet.com/news/wwdc-privacy-high-sierra-safari-blocking/

Chrome: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

Can you give us some reproducible code? This way we can check what goes on and maybe find your problem. :)

Body:
This is the html to display 3 videos on the screen. When this is viewed on a mobile device (e.g. Samsung S8), the screen automatically activates.

Change, project and task management

Process excellence & waste management

Quality control, Audit and Quality assurance


问:
Is there a Django equivalent for writing a SQL SELECT statement with a function in the WHERE clause?
I have a series of protein sequence alignments with inserts ('-' character) that need to be removed so I can search for a pattern in the sequence.

I can do this with the following SQL query:

```<code>select sequence
from sequences
where replace(sequences.sequence,"-","") like "%"+pattern+"%"
</code>```

As I understand it, having the replacement and pattern matching in a query should be more efficient than looping through every sequence and doing the replacement and pattern matching in python. Is this correct?

If #1 is correct, is there a Django equivalent of that query?

答:
Yes, you can make use of a Replace expression [Django-doc] with:

```<code>from django.db.models import Value
from django.db.models.functions import <b>Replace</b>

Sequence.objects.annotate(
    replaced=<b>Replace('sequence', Value('-'), Value(''))</b>
).filter(
    <b>replaced__icontains=<i>pattern</i></b>
)</code>```

It will indeed be more efficient than fetching all records and doing the filtering at the Django/Python level, but still this will result in linear search time, which is not very efficient.

It might be better if you can somehow "prepare" the pattern with hypens, and thus remove the Replace part of the database.

Body:
I have a series of protein sequence alignments with inserts ('-' character) that need to be removed so I can search for a pattern in the sequence.

I can do this with the following SQL query:

select sequence
from sequences
where replace(sequences.sequence,"-","") like "%"+pattern+"%"

As I understand it, having the replacement and pattern matching in a query should be more efficient than looping through every sequence and doing the replacement and pattern matching in python. Is this correct?

If #1 is correct, is there a Django equivalent of that query?

Body:
Yes, you can make use of a Replace expression [Django-doc] with:

from django.db.models import Value
from django.db.models.functions import Replace

Sequence.objects.annotate(
    replaced=Replace('sequence', Value('-'), Value(''))
).filter(
    replaced__icontains=pattern
)

It will indeed be more efficient than fetching all records and doing the filtering at the Django/Python level, but still this will result in linear search time, which is not very efficient.

It might be better if you can somehow "prepare" the pattern with hypens, and thus remove the Replace part of the database.


问:
Update the plotly Dash dcc.Textarea value from what user inputs
I am creating a plotly Dash app with a text area from dash core components (dcc.Textarea). The end user wants to save the input from text area so that it can be reused next time the user goes in to update that field. I was able to save the save the text area content, but how do I update the default value for the field with the latest edit? I tried updating the 'value' and 'children' for the text area, but did not work. Here's the code.

```<code>folder=r'C:\Temp'
def text_ar_val(file='TextBox1.txt'):
    with open(folder+fr'\Data\{file}','r') as f:
        return f.read()
app = dash.Dash(__name__)
app.layout = html.Div([dcc.Textarea(
                                id='textarea1', className='textarea1',
                                value=text_ar_val()
                            ),
                            html.Div(daq.StopButton(id='save1',className="button",
                                                    buttonText='Save', n_clicks=0))
                        ])
@app.callback(Output('textarea1', 'children'),
              [Input('save1', 'n_clicks'), Input('textarea1','value')])
def textbox1(n_clicks, value):
    if n_clicks>0:
        global folder
        with open(folder+r'\Data\TextBox1.txt','w') as file:
            file.write(value)
            return value
</code>```

I also tried:

```<code>@app.callback(Output('textarea1', 'value'),
          [Input('save1', 'n_clicks'), Input('textarea1','value')])
</code>```

答:
The dcc.Textarea module takes arguments persistence and persistence_type. Set persistence=True and persistence_type='local'. Setting persistence to True will tell the application to save the last data entered  and setting persistence_type to 'local' will save the last entered data to window.localStorage. So when the user quits the browser and comes back, the filed will have a default value of the data last entered. The code will be:

```<code>app.layout = html.Div([dcc.Textarea(
                                id='textarea1', className='textarea1',
                                value=text_ar_val(),
                                persistence=True, persistence_type='local'
                            ),
                            html.Div(daq.StopButton(id='save1',className="button",
                                                    buttonText='Save', n_clicks=0))
                        ])
</code>```

Everything about and below this code remains the same. Almost all the other dcc compoments will take in argument for persistence and persistence_type (eg. dcc.Dropdown).

For more info, you can go to:

https://dash.plotly.com/dash-core-components/textarea

Body:
I am creating a plotly Dash app with a text area from dash core components (dcc.Textarea). The end user wants to save the input from text area so that it can be reused next time the user goes in to update that field. I was able to save the save the text area content, but how do I update the default value for the field with the latest edit? I tried updating the 'value' and 'children' for the text area, but did not work. Here's the code.

folder=r'C:\Temp'
def text_ar_val(file='TextBox1.txt'):
    with open(folder+fr'\Data\{file}','r') as f:
        return f.read()
app = dash.Dash(__name__)
app.layout = html.Div([dcc.Textarea(
                                id='textarea1', className='textarea1',
                                value=text_ar_val()
                            ),
                            html.Div(daq.StopButton(id='save1',className="button",
                                                    buttonText='Save', n_clicks=0))
                        ])
@app.callback(Output('textarea1', 'children'),
              [Input('save1', 'n_clicks'), Input('textarea1','value')])
def textbox1(n_clicks, value):
    if n_clicks>0:
        global folder
        with open(folder+r'\Data\TextBox1.txt','w') as file:
            file.write(value)
            return value

I also tried:

@app.callback(Output('textarea1', 'value'),
          [Input('save1', 'n_clicks'), Input('textarea1','value')])

Body:
The dcc.Textarea module takes arguments persistence and persistence_type. Set persistence=True and persistence_type='local'. Setting persistence to True will tell the application to save the last data entered  and setting persistence_type to 'local' will save the last entered data to window.localStorage. So when the user quits the browser and comes back, the filed will have a default value of the data last entered. The code will be:

app.layout = html.Div([dcc.Textarea(
                                id='textarea1', className='textarea1',
                                value=text_ar_val(),
                                persistence=True, persistence_type='local'
                            ),
                            html.Div(daq.StopButton(id='save1',className="button",
                                                    buttonText='Save', n_clicks=0))
                        ])

Everything about and below this code remains the same. Almost all the other dcc compoments will take in argument for persistence and persistence_type (eg. dcc.Dropdown).

For more info, you can go to:

https://dash.plotly.com/dash-core-components/textarea


问:
i'm not getting files count using in JQuery?
I'm not getting files to count using in JQuery and I'm using the below html code and jquery function

```<code>        <div class="customerimagebox">
        <input multiple="multiple" type="file" name="Update_Merchandising_to_match_AIMM_images[]" class="Update_Merchandising_to_match_AIMM_images" id="Update_Merchandising_to_match_AIMM_images">
        <i class="fa fa-camera" onclick="fileuploadonclick('Update_Merchandising_to_match_AIMM_images',event)" style="color: black;text-align: center;"></i>
        </div>
        <div class="customerimagebox">
        <input multiple="multiple" type="file" name="Employees_in_Proper_Dress_Code_images[]" class="Employees_in_Proper_Dress_Code_images" id="Employees_in_Proper_Dress_Code_images">
        <i class="fa fa-camera" onclick="fileuploadonclick('Employees_in_Proper_Dress_Code_images',event)" style="color: black;text-align: center;"></i>
        </div>

<script>
function fileuploadonclick(classname,event) {
    event.preventDefault();
    $("."+classname+"").val('').click();
    $(document).on("change","."+classname+"",function (){
        var numFiles = $("input#Update_Merchandising_to_match_AIMM_images",this)[0].files.length;
        alert(numFiles);
    });
</script>
}
</code>```

I'm only getting this error. please check the below image

答:
You have very confusing code. See my short example:

```<code>$("input[type=file]").on("change",function (){
  var numFiles = $(this)[0].files.length;
  alert(numFiles);
 });
</code>```

And in playground with your code: https://jsfiddle.net/denisstukalov/q9xau5yr/6/#&togetherjs=BjIDOeQOoo

Body:
I'm not getting files to count using in JQuery and I'm using the below html code and jquery function

        <input multiple="multiple" type="file" name="Update_Merchandising_to_match_AIMM_images[]" class="Update_Merchandising_to_match_AIMM_images" id="Update_Merchandising_to_match_AIMM_images">

        <input multiple="multiple" type="file" name="Employees_in_Proper_Dress_Code_images[]" class="Employees_in_Proper_Dress_Code_images" id="Employees_in_Proper_Dress_Code_images">

}

I'm only getting this error. please check the below image

Body:
You have very confusing code. See my short example:

$("input[type=file]").on("change",function (){
  var numFiles = $(this)[0].files.length;
  alert(numFiles);
 });

And in playground with your code: https://jsfiddle.net/denisstukalov/q9xau5yr/6/#&togetherjs=BjIDOeQOoo


问:
How to disable automatic white balance from Webcam?
I got a webcam and I'm running some algorithm on the received images to find movements in it.
But, the automatic auto white balance is changing the excepted result of the pixels color variance.
That's why I'm trying to disable it.
Some one knows a way to get the web can image with out this automatic color balance or disable it ?

Tks

答: In my case I found on driver two options that must be disabled, auto white exposure and auto white balance, I disable both of them and the image got as I needed. </p>


问:
how to add image in one fragment and display it in another fragment/pass image through bundle in android
i want to select image in one fragment and display it in another fragment.

how can i do this.

my code is this but not working

```<code>button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            startActivityForResult(gallery, 100);
        }
    });

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    Uri imageUri;
    if (resultCode == RESULT_OK && requestCode == 100){
        imageUri = data.getData();
        file1path = imageUri.getPath();
        TVfrontimg.setText(file1path);
    }
}
</code>```

and i send this using bundle

```<code>Bundle bundle = new Bundle();
bundle.putString("image1", file1path);

registerPartThreeFragment.setArguments(bundle);
transaction.replace(R.id.FLcontainer, registerPartThreeFragment);
transaction.addToBackStack(null);
transaction.commit();
</code>```

in another fragment

```<code>String imgPath = getArguments().getString("image1");
Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(new File(imgPath)));
imageview.setImageBitmap(bitmap);
</code>```

but its not working.please help.

its giving me this error

2020-05-30 00:16:20.808 8995-8995/com.example.deliveryapp E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /raw/storage/emulated/0/DCIM/Camera/IMG_20200319_173033.jpg (No such file or directory)

答:
Please use getDataString() instead of getData()

```<code>if (resultCode == RESULT_OK && requestCode == 100){
        Uri imageUri = Uri.parse(data.getDataString());
        //imageUri = data.getData();
        file1path = imageUri.getPath();
        TVfrontimg.setText(file1path);
}
</code>```

And while setting it to the ImageView use ContentResolver and input stream like so:

```<code>ContentResolver cR = getApplication().getContentResolver();
        try {
            InputStream ip = cR.openInputStream(imageUri);
            Bitmap bmp = BitmapFactory.decodeStream(ip);
            imageView.setImageBitmap(bmp)
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
</code>```

You have to do this because you are getting a contentUri which is different from a file Uri.

Hope this helps.

Body:
i want to select image in one fragment and display it in another fragment.

how can i do this.

my code is this but not working

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
            startActivityForResult(gallery, 100);
        }
    });

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    Uri imageUri;
    if (resultCode == RESULT_OK && requestCode == 100){
        imageUri = data.getData();
        file1path = imageUri.getPath();
        TVfrontimg.setText(file1path);
    }
}

and i send this using bundle

Bundle bundle = new Bundle();
bundle.putString("image1", file1path);

registerPartThreeFragment.setArguments(bundle);
transaction.replace(R.id.FLcontainer, registerPartThreeFragment);
transaction.addToBackStack(null);
transaction.commit();

in another fragment

String imgPath = getArguments().getString("image1");
Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(new File(imgPath)));
imageview.setImageBitmap(bitmap);

but its not working.please help.

its giving me this error

2020-05-30 00:16:20.808 8995-8995/com.example.deliveryapp E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /raw/storage/emulated/0/DCIM/Camera/IMG_20200319_173033.jpg (No such file or directory)

Body:
Please use getDataString() instead of getData()

if (resultCode == RESULT_OK && requestCode == 100){
        Uri imageUri = Uri.parse(data.getDataString());
        //imageUri = data.getData();
        file1path = imageUri.getPath();
        TVfrontimg.setText(file1path);
}

And while setting it to the ImageView use ContentResolver and input stream like so:

ContentResolver cR = getApplication().getContentResolver();
        try {
            InputStream ip = cR.openInputStream(imageUri);
            Bitmap bmp = BitmapFactory.decodeStream(ip);
            imageView.setImageBitmap(bmp)
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

You have to do this because you are getting a contentUri which is different from a file Uri.

Hope this helps.


问:
Cannot find an implicit value for ContextShift
I am trying to create webapp with http4s that is based on Http4sServlet.
The following code does not compile:

```<code>import cats.effect._
import org.http4s.servlet.BlockingServletIo
import org.http4s.servlet.Http4sServlet
import scala.concurrent.ExecutionContext.global
import org.http4s.implicits._

class UserSvcServlet
  extends Http4sServlet[IO](service = UserSvcServer.start
    , servletIo = BlockingServletIo(4096, Blocker.liftExecutionContext(global)))(IOApp)
</code>```

the error message:

```<code>[error] /home/developer/scala/user-svc/src/main/scala/io/databaker/UserSvcServlet.scala:12:54: Cannot find implicit value for ConcurrentEffect[[+A]cats.effect.IO[A]].
[error] Building this implicit value might depend on having an implicit
[error] s.c.ExecutionContext in scope, a Scheduler, a ContextShift[[+A]cats.effect.IO[A]]
[error] or some equivalent type.
[error]   extends Http4sServlet[IO]( service = UserSvcServer.stream
[error]                                                      ^
[error] /home/developer/scala/user-svc/src/main/scala/io/databaker/UserSvcServlet.scala:13:36: Cannot find an implicit value for ContextShift[[+A]cats.effect.IO[A]]:
[error] * import ContextShift[[+A]cats.effect.IO[A]] from your effects library
[error] * if using IO, use cats.effect.IOApp or build one with cats.effect.IO.contextShift
[error]     , servletIo = BlockingServletIo(4096, Blocker.liftExecutionContext(global)))
[error]                                    ^
[error] two errors found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 1 s, completed May 29, 2020, 8:45:00 PM
</code>```

The UserSvcServer is implemented as follows:

```<code>import org.http4s.HttpApp
import cats.effect.{ConcurrentEffect, ContextShift, Timer}
import org.http4s.implicits._
import org.http4s.server.middleware.Logger

object UserSvcServer {

  def start[F[_] : ConcurrentEffect](implicit T: Timer[F], C: ContextShift[F]): HttpApp[F] = {
    val helloWorldAlg = HelloWorld.impl[F]
    val httpApp = UserSvcRoutes.helloWorldRoutes[F](helloWorldAlg).orNotFound
    Logger.httpApp(true, true)(httpApp)
  }
}
</code>```

How can I import ContextShift implicitly?

答:
Context shift is just cats' wrapper over ExecutionContext. You can create one explicitly as stated in docs:

```<code>implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global)
</code>```

You usually create one context shift at the entry point of your app (probably in the main method).

If your app uses IOApp from cats-effect it would have already implicit for contextShift in scope. It will use execution context, which would have number of threads equal to available processors of your computer.

If you want to use created contextShift "deeper" inside your application you can pass it as an implicit parameter:

```<code>def doSomething(implicit cs: ContextShift[IO]): IO[Unit] = ???
</code>```

So in order to make your code work, you need to make sure that method or class calls constructor of UserSvcServlet has implicit for contextShift:
(implicit cs: ContextShift[IO]).

You could also put it in separate object:

```<code>object AppContextShift {

  implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global)
  implicit val t: Timer[IO] = IO.timer(ExecutionContext.global) //you will probably also need timer eventually

}
</code>```

Then you can import it when contextShift is needed:

```<code>import AppContextShift._
</code>```

By the way, using a global execution context for Blocker is not good idea.
Blocked is used for blocking operations and using it with ExecutionContext.global might lead to thread starvation in your app.

The most common approach is to use blocker created from cached thread pool:

```<code>Blocker.liftExecutorService(Executors.newCachedThreadPool())
</code>```

Body:
I am trying to create webapp with http4s that is based on Http4sServlet.
The following code does not compile:

import cats.effect._
import org.http4s.servlet.BlockingServletIo
import org.http4s.servlet.Http4sServlet
import scala.concurrent.ExecutionContext.global
import org.http4s.implicits._

class UserSvcServlet
  extends Http4sServlet[IO](service = UserSvcServer.start
    , servletIo = BlockingServletIo(4096, Blocker.liftExecutionContext(global)))(IOApp)

the error message:

[error] /home/developer/scala/user-svc/src/main/scala/io/databaker/UserSvcServlet.scala:12:54: Cannot find implicit value for ConcurrentEffect[[+A]cats.effect.IO[A]].
[error] Building this implicit value might depend on having an implicit
[error] s.c.ExecutionContext in scope, a Scheduler, a ContextShift[[+A]cats.effect.IO[A]]
[error] or some equivalent type.
[error]   extends Http4sServlet[IO]( service = UserSvcServer.stream
[error]                                                      ^
[error] /home/developer/scala/user-svc/src/main/scala/io/databaker/UserSvcServlet.scala:13:36: Cannot find an implicit value for ContextShift[[+A]cats.effect.IO[A]]:
[error] * import ContextShift[[+A]cats.effect.IO[A]] from your effects library
[error] * if using IO, use cats.effect.IOApp or build one with cats.effect.IO.contextShift
[error]     , servletIo = BlockingServletIo(4096, Blocker.liftExecutionContext(global)))
[error]                                    ^
[error] two errors found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 1 s, completed May 29, 2020, 8:45:00 PM

The UserSvcServer is implemented as follows:

import org.http4s.HttpApp
import cats.effect.{ConcurrentEffect, ContextShift, Timer}
import org.http4s.implicits._
import org.http4s.server.middleware.Logger

object UserSvcServer {

  def start[F[_] : ConcurrentEffect](implicit T: Timer[F], C: ContextShift[F]): HttpApp[F] = {
    val helloWorldAlg = HelloWorld.impl[F]
    val httpApp = UserSvcRoutes.helloWorldRoutes[F](helloWorldAlg).orNotFound
    Logger.httpApp(true, true)(httpApp)
  }
}

How can I import ContextShift implicitly?

Body:
Context shift is just cats' wrapper over ExecutionContext. You can create one explicitly as stated in docs:

implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global)

You usually create one context shift at the entry point of your app (probably in the main method).

If your app uses IOApp from cats-effect it would have already implicit for contextShift in scope. It will use execution context, which would have number of threads equal to available processors of your computer.

If you want to use created contextShift "deeper" inside your application you can pass it as an implicit parameter:

def doSomething(implicit cs: ContextShift[IO]): IO[Unit] = ???

So in order to make your code work, you need to make sure that method or class calls constructor of UserSvcServlet has implicit for contextShift:
(implicit cs: ContextShift[IO]).

You could also put it in separate object:

object AppContextShift {

  implicit val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global)
  implicit val t: Timer[IO] = IO.timer(ExecutionContext.global) //you will probably also need timer eventually

}

Then you can import it when contextShift is needed:

import AppContextShift._

By the way, using a global execution context for Blocker is not good idea.
Blocked is used for blocking operations and using it with ExecutionContext.global might lead to thread starvation in your app.

The most common approach is to use blocker created from cached thread pool:

Blocker.liftExecutorService(Executors.newCachedThreadPool())


问:
Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed
Using Windows 2008 R2. On our server we get this error: "Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again." when trying to map a drive on the command line. However, there are no open Explorer windows to the remote computer, and nothing shows on the remote computer when I do a "net use".

Why does windows think something is connected when "net use" reports that there are no drives or folders open to it??

How can I force Win to stop thinking something is connected without restarting?

It appears that I get the error if I specify a username and password. If I just put in:

```<code> net use n: \\192.168.10.120\test
</code>```

it works, but if I put in

```<code> net use n: \\192.168.10.120\test "<password>" /user:"<domain\username>"
</code>```

it gives the error. Why would that be?

答:
It seems it is enough to restart the windows explorer service:

Open task manager

Find the Windows Explorer proces

Select it. After selection, the "Restart" button will appear in the bottom right corner.

Click the "restart" button. Windows explorer will be reloaded.

It helped in my case.

Body:
Using Windows 2008 R2. On our server we get this error: "Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again." when trying to map a drive on the command line. However, there are no open Explorer windows to the remote computer, and nothing shows on the remote computer when I do a "net use".

Why does windows think something is connected when "net use" reports that there are no drives or folders open to it??

How can I force Win to stop thinking something is connected without restarting?

It appears that I get the error if I specify a username and password. If I just put in:

 net use n: \\192.168.10.120\test

it works, but if I put in

 net use n: \\192.168.10.120\test "<password>" /user:"<domain\username>"

it gives the error. Why would that be?


问:
Gimp switch color channels
I'm capturing a raw framebuffer on an embedded device.  The framebuffer is 32bit BGRA color mode

```<code>cp /dev/fb0 framebuffer.data
</code>```

I can transfer the raw dump to my PC and import it into GIMP, but GIMP only allows me to read the raw data as if it were ARGB, which results in incorrect colors.  Is there a way to just switch the red and blue channels in GIMP?

答:
What you could try in GIMP is to use the channel mixer - it allows to mix new RGB components  out of the image's original RGB  components.

In the screenshot, I've taken a simple image with a red, green and a blue column, and told the channel mixer to turn red into green, green into blue and blue into red. Original colors are shown in the lower half, transformed ones in the upper half of the image.

Title: Gimp switch color channels

Body:
I'm capturing a raw framebuffer on an embedded device.  The framebuffer is 32bit BGRA color mode

cp /dev/fb0 framebuffer.data

I can transfer the raw dump to my PC and import it into GIMP, but GIMP only allows me to read the raw data as if it were ARGB, which results in incorrect colors.  Is there a way to just switch the red and blue channels in GIMP?


问:
How can I get print except statement printed instead of an error below in try/except syntax in Python
I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message i.e., "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.

hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
    hours_float = float(hours_string)
    rate_float = float(rate_string)
except:
    print("Invalid input. Enter a number please.")

result = hours_float * rate_float
print("Pay",result)
```

<p>This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?</p>

```Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
  File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined
```

答:
Since this is a expected situation and it can be treated as a test I would recommend instead of trying to execute the operation with wathever input the user provided you could ask the user for the input and while it is not an integer you ask for the input again.

def get_input(name, var_type):
  userin = None
  while userin is None:
    userin = input(f'Input {name}: ')
    try:
      userin = var_type(userin)
    except ValueError:
      print(f'{name} must be {str(var_type)}, not {str(type(userin))}')
      userin = None
  return userin

hours = get_input('hours', int)
rate = get_input('rate', float)

result = hours * rate
print('Pay', result)
```

The function get_input tries to cast the input input value to the type you want and if it is not as desired it will keep asking until the type matches.

Body:
I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message i.e., "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.

hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
    hours_float = float(hours_string)
    rate_float = float(rate_string)
except:
    print("Invalid input. Enter a number please.")

result = hours_float * rate_float
print("Pay",result)

This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?

Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
  File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined

Body:
Since this is a expected situation and it can be treated as a test I would recommend instead of trying to execute the operation with wathever input the user provided you could ask the user for the input and while it is not an integer you ask for the input again.

def get_input(name, var_type):
  userin = None
  while userin is None:
    userin = input(f'Input {name}: ')
    try:
      userin = var_type(userin)
    except ValueError:
      print(f'{name} must be {str(var_type)}, not {str(type(userin))}')
      userin = None
  return userin

hours = get_input('hours', int)
rate = get_input('rate', float)

result = hours * rate
print('Pay', result)

The function get_input tries to cast the input input value to the type you want and if it is not as desired it will keep asking until the type matches.


问:
Show image on ImageView in Kotlin
I have stored image uri on sqlite database and now i want to upload it to ImageView but my photo doesn't show.
Below my code sheets:

Store image

```<code> override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE){
            local_profile_image.setImageURI(data?.data)
            // Add image to DB
            val usrLogin = intent.getStringExtra("UserLogin")
            val dbHandler = UserDBHelper(this, null)
            var res : Boolean = dbHandler.addUserImage(data?.data.toString(),usrLogin)
            if(res) Toast.makeText(this, "User image add to DB", Toast.LENGTH_LONG).show()
            // ... //
        }
    }
</code>```

Following, you can see how I sav image uri on database

```<code>fun addUserImage(imgPath:String,userLogin:String) : Boolean {
        val db = this.writableDatabase
        val values = ContentValues()
        values.put(COLUMN_LOGIN,userLogin)
        values.put(USR_PROFILE_IMAGE,imgPath)
        db.insert(USR_PROFILE_TAB,null,values)
        if(!imgPath.isEmpty() && !userLogin.isEmpty()) {
            return true
        } else {
            return false
        }
    }
</code>```

Than I fetch image from table using code below:

```<code>fun getUserImage(login: String): String? {
        val db = this.writableDatabase
        val selectQuery = "SELECT  * FROM $USR_PROFILE_TAB WHERE $COLUMN_LOGIN = ?"
        db.rawQuery(selectQuery, arrayOf(login)).use { // .use requires API 16
            if (it.moveToFirst()) {
                val usrImgUri : String = it.getString(it.getColumnIndex(USR_PROFILE_IMAGE))
                return usrImgUri
            }
        }
        return null
    }
</code>```

After fetch image I want to set it on ImageView on different activity in onCreate method, but image doesn't show.

```<code>        val ivUserPhoto = findViewById<ImageView>(R.id.local_profile_image)
        val usrGalleryPhoto = intent.getStringExtra("UsrImage")
        if (usrGalleryPhoto == null) {
            ivUserPhoto.setImageResource(R.drawable.ic_crop_original_black_24dp)
        } else {
            val img_file = File(usrGalleryPhoto)
            val img_bmp = BitmapFactory.decodeFile(img_file.path)
            Toast.makeText(this, img_file.absolutePath, Toast.LENGTH_LONG).show()
            ivUserPhoto.setImageBitmap(img_bmp)
   }
</code>```

What I do wrong ? Help me, please. I am newbie in Kotlin and have started work with in recently.
Thank's a lot.
Denys.

答: Today I have tested my app on different device and I have got surprise.ImageView have show my profile image which I have store before through setImageURI(). I use Android 10 on my smartphone but application work fine on Android 9 device. I will open issue for Kotlin support team.</p>

Title: Show image on ImageView in Kotlin

Body:
I have stored image uri on sqlite database and now i want to upload it to ImageView but my photo doesn't show.
Below my code sheets:

Store image

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE){
            local_profile_image.setImageURI(data?.data)
            // Add image to DB
            val usrLogin = intent.getStringExtra("UserLogin")
            val dbHandler = UserDBHelper(this, null)
            var res : Boolean = dbHandler.addUserImage(data?.data.toString(),usrLogin)
            if(res) Toast.makeText(this, "User image add to DB", Toast.LENGTH_LONG).show()
            // ... //
        }
    }

Following, you can see how I sav image uri on database

fun addUserImage(imgPath:String,userLogin:String) : Boolean {
        val db = this.writableDatabase
        val values = ContentValues()
        values.put(COLUMN_LOGIN,userLogin)
        values.put(USR_PROFILE_IMAGE,imgPath)
        db.insert(USR_PROFILE_TAB,null,values)
        if(!imgPath.isEmpty() && !userLogin.isEmpty()) {
            return true
        } else {
            return false
        }
    }

Than I fetch image from table using code below:

fun getUserImage(login: String): String? {
        val db = this.writableDatabase
        val selectQuery = "SELECT  * FROM $USR_PROFILE_TAB WHERE $COLUMN_LOGIN = ?"
        db.rawQuery(selectQuery, arrayOf(login)).use { // .use requires API 16
            if (it.moveToFirst()) {
                val usrImgUri : String = it.getString(it.getColumnIndex(USR_PROFILE_IMAGE))
                return usrImgUri
            }
        }
        return null
    }

After fetch image I want to set it on ImageView on different activity in onCreate method, but image doesn't show.

        val ivUserPhoto = findViewById<ImageView>(R.id.local_profile_image)
        val usrGalleryPhoto = intent.getStringExtra("UsrImage")
        if (usrGalleryPhoto == null) {
            ivUserPhoto.setImageResource(R.drawable.ic_crop_original_black_24dp)
        } else {
            val img_file = File(usrGalleryPhoto)
            val img_bmp = BitmapFactory.decodeFile(img_file.path)
            Toast.makeText(this, img_file.absolutePath, Toast.LENGTH_LONG).show()
            ivUserPhoto.setImageBitmap(img_bmp)
   }

What I do wrong ? Help me, please. I am newbie in Kotlin and have started work with in recently.
Thank's a lot.
Denys.


问:
"bash: django-admin: command not found" after running django-admin
I had similar problems with pip that was fixed with "python3 -m" but now after install Django I want to make a new project.

When I try to run "django-admin startproject ..." I get "bash: django-admin: command not found".

I don't know if I should mention it but, this is in a virtualenv.

python3 -m pip freeze: Django==3.0.6

echo $PATH: /home/alatimer/Environments/DjangoTutoria_env/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

答:
My problem was i was using python version 2.7 in the venv instead of version 3.6.9.

I assume the older python couldn't recognize the commands (this even includes pip commands).


问:
Can't get Tkinter GUI to show using classes
I am trying to make a Tkinter GUI that takes Excel documents, reads them, and exports them to the window. The issue is when I changed the code to below to incorporate class structure, I cannot make the GUI load properly anymore. </p>

```<code>import tkinter as tk
from tkinter.filedialog import askopenfilename

def NewFile():
    print("New File!")
def OpenFile():
    name = askopenfilename()
    print(name)
def About():
    print("About works")
def deletelist():
    listbox.delete(0, END)

class MainApplication(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.master = master
        self.frame = tk.Frame(self.master)

        self.load = tk.Button(self.frame, text = "Load XLSX File", command = OpenFile)
        self.load.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'w')

        self.ckframe = tk.LabelFrame(self.frame, text="Currency Selections")
        self.ckframe.grid(row = 1, column = 0, padx = 5, pady = 5, stick = 'nesw')
        self.prochk = tk.Checkbutton(self.ckframe, text = '1 Currency').grid(row = 1, column = 0, columnspan = 2, sticky = 'w')
        self.msnchk = tk.Checkbutton(self.ckframe, text = '2 Currency').grid(row = 1, column = 2, columnspan = 2, sticky = 'w')
        self.nightschk = tk.Checkbutton(self.ckframe, text = '3 Currency').grid(row = 1, column = 4, columnspan = 2, sticky = 'w')
        self.semichk = tk.Checkbutton(self.ckframe, text = '4 Currency').grid(row = 2, column = 0, columnspan = 2, sticky = 'w')
        self.instqualCRchk = tk.Checkbutton(self.ckframe, text = '5 Currency').grid(row = 2, column = 2, columnspan = 2, sticky = 'w')
        self.msnCRchk = tk.Checkbutton(self.ckframe, text = '6 Currency').grid(row = 2, column = 4, columnspan = 2, sticky = 'w')

        self.listbox = tk.Listbox(self.frame, width = 83)
        self.listbox.grid(row = 3, column = 0, columnspan = 1, sticky = 'w') # Fix width size function
        self.listbox.insert(1, 'Test1')
        self.listbox.insert(0, 'Test2')
        self.save = tk.Button(self.frame, text = "Save").grid(row = 8, column = 0, padx = 5, pady = 5, stick = 'e')
        self.delete = tk.Button(self.frame, text = "Delete", command = deletelist).grid(row = 8, column = 0, padx = 45, pady = 5, stick = 'e')

if __name__ == '__main__':
    root = tk.Tk()
    MainApplication(root)
    root.mainloop()
</code>```

<p>I searched a lot trying to find a solution to using classes with tkinter GUI and the grid system but I mostly found ways to make GUIs with pack() solution. </p>

答:
The instance of MainApplication is a frame. You never call pack or place or grid on that instance so that frame and all of its children will be invisible.

This frame creates another frame that contains all of the other widgets, self.frame. You never call pack, place, or grid on it either, so it and all of its children will be invisible.

Since the widgets are in a frame that is invisible, and that frame itself is invisible, none of the other widgets will be visible.

The first thing to do is to get rid of self.frame. Remove the line that creates it, and everywhere you reference self.frame, replace it with self.  Since self in this context is already a frame it makes no sense to create another frame inside.

Next, you need to add the instance of MainApplication to the window. Since it's the only widget directly in the root window, pack is the simplest choice.

```<code>root = tk.Tk()
app = = MainApplication(root)
app.pack(fill="both", expand=True)
</code>```

Body:
I am trying to make a Tkinter GUI that takes Excel documents, reads them, and exports them to the window. The issue is when I changed the code to below to incorporate class structure, I cannot make the GUI load properly anymore.

import tkinter as tk
from tkinter.filedialog import askopenfilename

def NewFile():
    print("New File!")
def OpenFile():
    name = askopenfilename()
    print(name)
def About():
    print("About works")
def deletelist():
    listbox.delete(0, END)

class MainApplication(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.master = master
        self.frame = tk.Frame(self.master)

        self.load = tk.Button(self.frame, text = "Load XLSX File", command = OpenFile)
        self.load.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'w')

        self.ckframe = tk.LabelFrame(self.frame, text="Currency Selections")
        self.ckframe.grid(row = 1, column = 0, padx = 5, pady = 5, stick = 'nesw')
        self.prochk = tk.Checkbutton(self.ckframe, text = '1 Currency').grid(row = 1, column = 0, columnspan = 2, sticky = 'w')
        self.msnchk = tk.Checkbutton(self.ckframe, text = '2 Currency').grid(row = 1, column = 2, columnspan = 2, sticky = 'w')
        self.nightschk = tk.Checkbutton(self.ckframe, text = '3 Currency').grid(row = 1, column = 4, columnspan = 2, sticky = 'w')
        self.semichk = tk.Checkbutton(self.ckframe, text = '4 Currency').grid(row = 2, column = 0, columnspan = 2, sticky = 'w')
        self.instqualCRchk = tk.Checkbutton(self.ckframe, text = '5 Currency').grid(row = 2, column = 2, columnspan = 2, sticky = 'w')
        self.msnCRchk = tk.Checkbutton(self.ckframe, text = '6 Currency').grid(row = 2, column = 4, columnspan = 2, sticky = 'w')

        self.listbox = tk.Listbox(self.frame, width = 83)
        self.listbox.grid(row = 3, column = 0, columnspan = 1, sticky = 'w') # Fix width size function
        self.listbox.insert(1, 'Test1')
        self.listbox.insert(0, 'Test2')
        self.save = tk.Button(self.frame, text = "Save").grid(row = 8, column = 0, padx = 5, pady = 5, stick = 'e')
        self.delete = tk.Button(self.frame, text = "Delete", command = deletelist).grid(row = 8, column = 0, padx = 45, pady = 5, stick = 'e')

if __name__ == '__main__':
    root = tk.Tk()
    MainApplication(root)
    root.mainloop()

I searched a lot trying to find a solution to using classes with tkinter GUI and the grid system but I mostly found ways to make GUIs with pack() solution.

Body:
The instance of MainApplication is a frame. You never call pack or place or grid on that instance so that frame and all of its children will be invisible.

This frame creates another frame that contains all of the other widgets, self.frame. You never call pack, place, or grid on it either, so it and all of its children will be invisible.

Since the widgets are in a frame that is invisible, and that frame itself is invisible, none of the other widgets will be visible.

The first thing to do is to get rid of self.frame. Remove the line that creates it, and everywhere you reference self.frame, replace it with self.  Since self in this context is already a frame it makes no sense to create another frame inside.

Next, you need to add the instance of MainApplication to the window. Since it's the only widget directly in the root window, pack is the simplest choice.

root = tk.Tk()
app = = MainApplication(root)
app.pack(fill="both", expand=True)


问:
When using Yad, can a button be made the default?
The title sets the question.
If it can, what is the coding?
Present coding is:-
yad --center --on-top --text-align=center --buttons-layout=center --title ${0##*/} --width=150 --height=60 --text "Do you want tea?" --button=gtk-no:1 --button=gtk-yes:0
I want to make the yes button the default, so even if I just close the box the yes button is selected.
Many thanks
John</p>

答:
This snippet launch a default icon in the systray:</p>

```<code>yad --notification xxx
</code>```

Body:
This snippet launch a default icon in the systray:

yad --notification xxx


问:
Module not found: Error: Can't resolve 'fs' in node_modules\dotenv\lib'
I'm trying to use dotenv with an angle, but when it comes to requiring dotenv

```<code> require('dotenv').config()
 or
 const Dotenv = require('dotenv-webpack');
</code>```

I get the following error:

ERROR in ./node_modules/dotenv/lib/main.js
  Module not found: Error: Can't resolve 'fs' in 'C:\Users\57322\Favorites\Proyecto\core4edu\node_modules\dotenv\lib'

package.json

```<code>"dotenv": "^8.2.0",
"dotenv-webpack": "^1.7.0",
</code>```

答:
I think the problem is related to webpack, I had the same problem on a next.js project and here is how I did to fix the problem.

I created a next.conf.js file in my root folder where there is my .env file, I imported dotenv and I exported the module where there is all my environment and these variables as if below.

Finally in my index file and my components I don’t need to import dotenv, I just need to paste my process.env.API_URL.

I hope this example solves your problem.

Body:
I'm trying to use dotenv with an angle, but when it comes to requiring dotenv

 require('dotenv').config()
 or
 const Dotenv = require('dotenv-webpack');

I get the following error:

ERROR in ./node_modules/dotenv/lib/main.js
  Module not found: Error: Can't resolve 'fs' in 'C:\Users\57322\Favorites\Proyecto\core4edu\node_modules\dotenv\lib'

package.json

"dotenv": "^8.2.0",
"dotenv-webpack": "^1.7.0",


问:
Select subsets from List[Int] by increasing length upto List[Int] length
I have a List of integers as:

```<code>val list= List(5,-2,10,-1,4)
</code>```

And I want the desired result as a List of following subsets from the list

```<code>List(
(5),
(5,-2),
(5,-2,10),
(5,-2,10,-1),
(5,-2,10,-1,4),
(-2,10,-1,4),
(10,-1,4),
(-1,4),
(4)
)
</code>```

How can I write a code using functional programming aspect of Scala?
Or by using any for loop constructs?

答:
The exact result as you want can be achieved by

```<code>val part1 = for (i <- (1 to list.size)) yield list.take(i)
val part2 = for (i <- (1 until list.size)) yield list.drop(i)
(part1 ++ part2).toList
</code>```

If you want one-liner then:

```<code>( (1 to list.size).map(list.take) ++ (1 until list.size).map(list.take) ).toList
</code>```

Body:
I have a List of integers as:

val list= List(5,-2,10,-1,4)

And I want the desired result as a List of following subsets from the list

List(
(5),
(5,-2),
(5,-2,10),
(5,-2,10,-1),
(5,-2,10,-1,4),
(-2,10,-1,4),
(10,-1,4),
(-1,4),
(4)
)

How can I write a code using functional programming aspect of Scala?
Or by using any for loop constructs?

Body:
The exact result as you want can be achieved by

val part1 = for (i <- (1 to list.size)) yield list.take(i)
val part2 = for (i <- (1 until list.size)) yield list.drop(i)
(part1 ++ part2).toList

If you want one-liner then:

( (1 to list.size).map(list.take) ++ (1 until list.size).map(list.take) ).toList


问:
class to class type conversion through constructor method output is 5500 why not 5555
Output is 5500, but why not 5555?

```<code>class product {
public:
    int b;
};

class item {
public:
    int a;
    item(product& obj)
    {
        cout << a;
    }
    item() {}
    void display()
    {
        cout << a;
    }
};

int main()
{
    item obj1;
    product obj2;
    obj1.a = 5;
    cout << obj1.a;
    obj1.display();
    obj1 = obj2;
    //object of product class sent into Constructor of item class*
    cout << obj1.a;
    return 0;
}
</code>```

Here constructor is called of item class and product object is pass through it.

答:
The program has undefined behavior because the used data member a is not initialized.

This conversion constructor

```<code>        item(product &obj)
        {
           cout<<a;
        }
</code>```

that is used in this assignment statement

```<code>obj1=obj2;
</code>```

to convert the object obj2 of the type product to an object of the type item does not initialize the data member a. So the data member has an indeterminate value. And this indeterminate value assigned to the data member a of the object obj1 is outputted in the constructor and in this statement

```<code>cout<<obj1.a;
</code>```

It occurred such a way that the memory occupied by the data member a of the temporary object of the type item contained zeroes. But in general this is not necessary.

Body:
Output is 5500, but why not 5555?

class product {
public:
    int b;
};

class item {
public:
    int a;
    item(product& obj)
    {
        cout << a;
    }
    item() {}
    void display()
    {
        cout << a;
    }
};

int main()
{
    item obj1;
    product obj2;
    obj1.a = 5;
    cout << obj1.a;
    obj1.display();
    obj1 = obj2;
    //object of product class sent into Constructor of item class*
    cout << obj1.a;
    return 0;
}

Here constructor is called of item class and product object is pass through it.

Body:
The program has undefined behavior because the used data member a is not initialized.

This conversion constructor

        item(product &obj)
        {
           cout<<a;
        }

that is used in this assignment statement

obj1=obj2;

to convert the object obj2 of the type product to an object of the type item does not initialize the data member a. So the data member has an indeterminate value. And this indeterminate value assigned to the data member a of the object obj1 is outputted in the constructor and in this statement

cout<<obj1.a;

It occurred such a way that the memory occupied by the data member a of the temporary object of the type item contained zeroes. But in general this is not necessary.


问:
What is Redis change its own configurations
Redis change its own config dir to /etc/cron.d and dbfile to ntp instead of default configuration. Once we restart the redis it will reset to /var/lib/redis and dump.rdb but after awhile, it gives "Failed opening the RDB file" error

Default dire and rdb file has correct permission and redis only allow for internal IPs.

cli output

```<code>127.0.0.1:6381> CONFIG GET dir
1) "dir"
2) "/etc/cron.d"
127.0.0.1:6381> CONFIG GET "dbfilename"
1) "dbfilename"
2) "ntp"
</code>```

/var/log/redis/redis-server.log

```<code>3204:M 21 May 16:07:19.124 * Background saving terminated with success
3204:M 21 May 16:12:18.962 * 10000 changes in 60 seconds. Saving...
3204:M 21 May 16:12:18.967 * Background saving started by pid 25469
25469:C 21 May 16:12:20.931 * DB saved on disk
25469:C 21 May 16:12:20.934 * RDB: 3 MB of memory used by copy-on-write
3204:M 21 May 16:12:20.968 * Background saving terminated with success

3204:M 21 May 16:17:21.082 * 10 changes in 300 seconds. Saving...
3204:M 21 May 16:17:21.088 * Background saving started by pid 25865
25865:C 21 May 16:17:22.800 * DB saved on disk
25865:C 21 May 16:17:22.803 * RDB: 3 MB of memory used by copy-on-write
3204:M 21 May 16:17:22.891 * Background saving terminated with success
3204:M 21 May 16:17:43.669 # Failed opening the RDB file root (in server root dir /var/spool/cron) for saving: Read-only file system
3204:M 21 May 16:17:45.320 # Failed opening the RDB file ntp (in server root dir /etc/cron.d) for saving: Read-only file system
3204:M 21 May 16:22:23.086 * 10 changes in 300 seconds. Saving...
3204:M 21 May 16:22:23.092 * Background saving started by pid 26264
26264:C 21 May 16:22:23.093 # Failed opening the RDB file ntp (in server root dir /etc/cron.d) for saving: Read-only file system
3204:M 21 May 16:22:23.194 # Background saving error
3204:M 21 May 16:22:29.104 * 10 changes in 300 seconds. Saving...
3204:M 21 May 16:22:29.109 * Background saving started by pid 26265
26265:C 21 May 16:22:29.109 # Failed opening the RDB file ntp (in server root dir /etc/cron.d) for saving: Read-only file system
3204:M 21 May 16:22:29.209 # Background saving error
3204:M 21 May 16:22:35.016 * 10 changes in 300 seconds. Saving...
</code>```

答:
Is your server publicly accessibly over the internet?

The most likely explanation is that somebody is connecting to the redis and sending commands to reconfigure it remotely, trying to take control over the server.

There are bots scanning the internet 24/7 looking for exposed software and known vulnerabilities. Quick rule of thumb is that a new service coming up online will be discovered and attacked in less than 5 minutes. (Try running an unpatched Windows XP server and be amazed how short it lasts).

Consider that redis and potentially the whole server was compromised. I hope for you that there was no sensitive information in this redis or that's a data breach.

Block public access, decommission the virtual machine, setup a new one from scratch.

Related redis ticket: https://github.com/antirez/redis/issues/3594

Body:
Redis change its own config dir to /etc/cron.d and dbfile to ntp instead of default configuration. Once we restart the redis it will reset to /var/lib/redis and dump.rdb but after awhile, it gives "Failed opening the RDB file" error

Default dire and rdb file has correct permission and redis only allow for internal IPs.

cli output

127.0.0.1:6381> CONFIG GET dir
1) "dir"
2) "/etc/cron.d"
127.0.0.1:6381> CONFIG GET "dbfilename"
1) "dbfilename"
2) "ntp"

/var/log/redis/redis-server.log

3204:M 21 May 16:07:19.124 * Background saving terminated with success
3204:M 21 May 16:12:18.962 * 10000 changes in 60 seconds. Saving...
3204:M 21 May 16:12:18.967 * Background saving started by pid 25469
25469:C 21 May 16:12:20.931 * DB saved on disk
25469:C 21 May 16:12:20.934 * RDB: 3 MB of memory used by copy-on-write
3204:M 21 May 16:12:20.968 * Background saving terminated with success

3204:M 21 May 16:17:21.082 * 10 changes in 300 seconds. Saving...
3204:M 21 May 16:17:21.088 * Background saving started by pid 25865
25865:C 21 May 16:17:22.800 * DB saved on disk
25865:C 21 May 16:17:22.803 * RDB: 3 MB of memory used by copy-on-write
3204:M 21 May 16:17:22.891 * Background saving terminated with success
3204:M 21 May 16:17:43.669 # Failed opening the RDB file root (in server root dir /var/spool/cron) for saving: Read-only file system
3204:M 21 May 16:17:45.320 # Failed opening the RDB file ntp (in server root dir /etc/cron.d) for saving: Read-only file system
3204:M 21 May 16:22:23.086 * 10 changes in 300 seconds. Saving...
3204:M 21 May 16:22:23.092 * Background saving started by pid 26264
26264:C 21 May 16:22:23.093 # Failed opening the RDB file ntp (in server root dir /etc/cron.d) for saving: Read-only file system
3204:M 21 May 16:22:23.194 # Background saving error
3204:M 21 May 16:22:29.104 * 10 changes in 300 seconds. Saving...
3204:M 21 May 16:22:29.109 * Background saving started by pid 26265
26265:C 21 May 16:22:29.109 # Failed opening the RDB file ntp (in server root dir /etc/cron.d) for saving: Read-only file system
3204:M 21 May 16:22:29.209 # Background saving error
3204:M 21 May 16:22:35.016 * 10 changes in 300 seconds. Saving...


问:
How to fix EOF read error with GZIPInputStream
I am trying to read the contents of a gzip file and create a file from it. I'm running into an issue that I can't see to figure out. Any ideas of suggestion is appreciated. Thank you.</p>

```<code>private static String unzip(String gzipFile, String location){

        try {
            FileInputStream in = new FileInputStream(gzipFile);
            FileOutputStream out = new FileOutputStream(location);
            GZIPInputStream gzip = new GZIPInputStream(in);

            byte[] b = new byte[1024];
            int len;
            while((len = gzip.read(b)) != -1){
                out.write(buffer, 0, len);
            }

            out.close();
            in.close();
            gzip.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:116)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
</code>```

答:
You'll make life much easier on yourself by using Resource Blocks to ensure your files are closed correctly.  For example:

```<code>private static String unzip(String gzipFile, String location){

        try (
            FileInputStream in = new FileInputStream(gzipFile);
            GZIPInputStream gzip = new GZIPInputStream(in);
            FileOutputStream out = new FileOutputStream(location))
        {

            byte[] b = new byte[4096];
            int len;
            while((len = gzip.read(b)) >= 0){
                out.write(b, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
</code>```

You should also ensure you've got a valid .zip file (of course!) and that your input and output filenames are different.

And what's going on with "buffer"?  I assume (as does GPI) you probably meant "b"?

Body:
I am trying to read the contents of a gzip file and create a file from it. I'm running into an issue that I can't see to figure out. Any ideas of suggestion is appreciated. Thank you.

private static String unzip(String gzipFile, String location){

        try {
            FileInputStream in = new FileInputStream(gzipFile);
            FileOutputStream out = new FileOutputStream(location);
            GZIPInputStream gzip = new GZIPInputStream(in);

            byte[] b = new byte[1024];
            int len;
            while((len = gzip.read(b)) != -1){
                out.write(buffer, 0, len);
            }

            out.close();
            in.close();
            gzip.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:116)
at java.io.FilterInputStream.read(FilterInputStream.java:107)

Body:
You'll make life much easier on yourself by using Resource Blocks to ensure your files are closed correctly.  For example:

private static String unzip(String gzipFile, String location){

        try (
            FileInputStream in = new FileInputStream(gzipFile);
            GZIPInputStream gzip = new GZIPInputStream(in);
            FileOutputStream out = new FileOutputStream(location))
        {

            byte[] b = new byte[4096];
            int len;
            while((len = gzip.read(b)) >= 0){
                out.write(b, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

You should also ensure you've got a valid .zip file (of course!) and that your input and output filenames are different.

And what's going on with "buffer"?  I assume (as does GPI) you probably meant "b"?