问:
running a mapper and reducer program in hadoop-3.1.3
I am trying to run a hadoop container. What I did is I downloaded hadoop from
https://hadoop.apache.org/releases.html
I downloaded 3.1.3 file https://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-3.1.3/hadoop-3.1.3-src.tar.gz the installation was successful. I see following

```<code>debian@osboxes:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
python              latest              eeadc22d21a9        2 weeks ago         933MB
hadoop-build-1001   latest              1d1a162a72a6        3 months ago        2.02GB
hadoop-build        latest              5c1480006f78        3 months ago        1.96GB
ubuntu              xenial              5f2bf26e3524        3 months ago        123MB
</code>```

Now when I try to run an image

```<code> docker run -it --user debian 1d1a162a72a6
</code>```

I get error

```<code>docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "chdir to cwd (\"/root\") set in config.json failed: permission denied": unknown.
debian@osboxes:~$
</code>```

I was not able to understand any thing as why these errors are coming and how to get rid of above error.
I somehow could login to container as root user and then inside that I did a su debian so I was able to login as debian,
Now I have programs mapper and reducer which I wanted to run in them.
I did then

```<code>RUN apt-get update
RUN apt-get install default-jdk wget -y
RUN apt-get install python3 -y
RUN wget
http://mirrors.estointernet.in/apache/hadoop/common/hadoop-2.10.0/hadoop-2.10.0.tar.gz
RUN tar -xzvf hadoop-2.10.0.tar.gz
ENV JAVA_HOME $(readlink -f /usr/bin/java | sed "s:bin/java::")
RUN mv hadoop-2.10.0 /usr/local/hadoop
ENV PATH /usr/local/hadoop/bin:$PATH
RUN rm -rf hadoop-2*
</code>```

now I have installed hadoop-2.10.0 in hadoop 3 and then I executed my programmes.
I had to edit .bashrc of debian inside container.
I am wondering how could I run the mapper and reducer program in the hadoop-3.1.3 which I had build and compiled from sources or did I do any mistake here?

Is there a better way to use the hadoop-3.1.3 environment which took me hours to compile and install.

update 1

in the build script of hadoop sources file I downloaded there are following lines

```<code>docker build -t "hadoop-build-${USER_ID}" - <<UserSpecificDocker
FROM hadoop-build
RUN groupadd --non-unique -g ${GROUP_ID} ${USER_NAME}
RUN useradd -g ${GROUP_ID} -u ${USER_ID} -k /root -m ${USER_NAME}
RUN echo "${USER_NAME} ALL=NOPASSWD: ALL" > "/etc/sudoers.d/hadoop-build-${USER_ID}"
ENV HOME /home/${USER_NAME}

UserSpecificDocker

# By mapping the .m2 directory you can do an mvn install from
# within the container and use the result on your normal
# system.  And this also is a significant speedup in subsequent
# builds because the dependencies are downloaded only once.
docker run --rm=true -t -i \
  -v "${PWD}:/home/${USER_NAME}/hadoop${V_OPTS:-}" \
  -w "/home/${USER_NAME}/hadoop" \
  -v "${HOME}/.m2:/home/${USER_NAME}/.m2${V_OPTS:-}" \
  -u "${USER_NAME}" \
  "hadoop-build-${USER_ID}"
"start-build-env.sh"
</code>```

so I think I am having development environment of hadoop.
However my problem lies in containers.
When I do docker ps -a
I see

```<code>19a4eff3b5e5        1d1a162a72a6        "/bin/bash"              3 hours ago         Exited (0) 3 hours ago                          assignment4
30933891f08c        eeadc22d21a9        "python3"                3 hours ago         Exited (0) 3 hours ago                          python
ccdab94fd32f        1d1a162a72a6        "/bin/bash"              9 hours ago         Exited (0) 5 hours ago                          confident_wu
ce462ecfc5f2        1d1a162a72a6        "/bin/bash -v /home/…"   9 hours ago         Exited (127) 9 hours ago                        stupefied_grothendieck
6123f134934c        1d1a162a72a6        "/bin/bash"              9 hours ago         Exited (1) 9 hours ago                          stupefied_taussig
0ed23a8112a4        1d1a162a72a6        "/bin/bash"              10 hours ago        Exited (0) 10 hours ago                         vigilant_bartik
c343731b7cde        1d1a162a72a6        "/bin/bash"              11 hours ago        Exited (0) 10 hours ago                         gallant_ardinghelli
2f95d3b4c1b8        1d1a162a72a6        "/bin/bash"              11 hours ago        Created                                         nice_hermann
5ebe9f18c744        1d1a162a72a6        "/bin/bash"              27 hours ago        Created                                         pensive_easley
c1b43edfafb9        1d1a162a72a6        "/bin/bash"              27 hours ago        Exited (1) 3 hours ago                          adoring_williams
42dea69d1d4e        1d1a162a72a6        "/bin/bash"              27 hours ago        Created                                         funny_austin
6f736902e650        1d1a162a72a6        "/bin/bash"              27 hours ago        Exited (1) 27 hours ago                         strange_ride
09306e5ec5d1        1d1a162a72a6        "--name=kaushik"         32 hours ago        Created                                         pensive_shtern
699fb2a23e1c        1d1a162a72a6        "--name=kaushik"         32 hours ago        Created                                         sharp_feistel
9f7b29ab512e        1d1a162a72a6        "--name=kaushik"         32 hours ago        Created                                         elastic_payne2
25bfc74fab3b        1d1a162a72a6        "/bin/bash"              33 hours ago        Exited (1) 31 hours ago                         festive_einstein
e658dd320297        1d1a162a72a6        "/bin/bash"              33 hours ago        Up 3 hours                                      objectiv:
</code>```

I do not know how many containers were created and I made changes to enviornments inside containers. After a reboot I could not find any changes made to these containers. How can my containers survive a reboot?

答:
I am not able to understand how to use existing image to run mapper and reducer code.

Run docker exec to enter into the container

Run yarn jar commands...

No different than any other way to submit jobs

Body:
I am trying to run a hadoop container. What I did is I downloaded hadoop from
https://hadoop.apache.org/releases.html
I downloaded 3.1.3 file https://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-3.1.3/hadoop-3.1.3-src.tar.gz the installation was successful. I see following

debian@osboxes:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
python              latest              eeadc22d21a9        2 weeks ago         933MB
hadoop-build-1001   latest              1d1a162a72a6        3 months ago        2.02GB
hadoop-build        latest              5c1480006f78        3 months ago        1.96GB
ubuntu              xenial              5f2bf26e3524        3 months ago        123MB

Now when I try to run an image

 docker run -it --user debian 1d1a162a72a6

I get error

docker: Error response from daemon: OCI runtime create failed: container_linux.go:346: starting container process caused "chdir to cwd (\"/root\") set in config.json failed: permission denied": unknown.
debian@osboxes:~$

I was not able to understand any thing as why these errors are coming and how to get rid of above error.
I somehow could login to container as root user and then inside that I did a su debian so I was able to login as debian,
Now I have programs mapper and reducer which I wanted to run in them.
I did then

RUN apt-get update
RUN apt-get install default-jdk wget -y
RUN apt-get install python3 -y
RUN wget
http://mirrors.estointernet.in/apache/hadoop/common/hadoop-2.10.0/hadoop-2.10.0.tar.gz
RUN tar -xzvf hadoop-2.10.0.tar.gz
ENV JAVA_HOME $(readlink -f /usr/bin/java | sed "s:bin/java::")
RUN mv hadoop-2.10.0 /usr/local/hadoop
ENV PATH /usr/local/hadoop/bin:$PATH
RUN rm -rf hadoop-2*

now I have installed hadoop-2.10.0 in hadoop 3 and then I executed my programmes.
I had to edit .bashrc of debian inside container.
I am wondering how could I run the mapper and reducer program in the hadoop-3.1.3 which I had build and compiled from sources or did I do any mistake here?

Is there a better way to use the hadoop-3.1.3 environment which took me hours to compile and install.

update 1

in the build script of hadoop sources file I downloaded there are following lines

docker build -t "hadoop-build-${USER_ID}" - <<UserSpecificDocker
FROM hadoop-build
RUN groupadd --non-unique -g ${GROUP_ID} ${USER_NAME}
RUN useradd -g ${GROUP_ID} -u ${USER_ID} -k /root -m ${USER_NAME}
RUN echo "${USER_NAME} ALL=NOPASSWD: ALL" > "/etc/sudoers.d/hadoop-build-${USER_ID}"
ENV HOME /home/${USER_NAME}

UserSpecificDocker

# By mapping the .m2 directory you can do an mvn install from
# within the container and use the result on your normal
# system.  And this also is a significant speedup in subsequent
# builds because the dependencies are downloaded only once.
docker run --rm=true -t -i \
  -v "${PWD}:/home/${USER_NAME}/hadoop${V_OPTS:-}" \
  -w "/home/${USER_NAME}/hadoop" \
  -v "${HOME}/.m2:/home/${USER_NAME}/.m2${V_OPTS:-}" \
  -u "${USER_NAME}" \
  "hadoop-build-${USER_ID}"
"start-build-env.sh"

so I think I am having development environment of hadoop.
However my problem lies in containers.
When I do docker ps -a
I see

19a4eff3b5e5        1d1a162a72a6        "/bin/bash"              3 hours ago         Exited (0) 3 hours ago                          assignment4
30933891f08c        eeadc22d21a9        "python3"                3 hours ago         Exited (0) 3 hours ago                          python
ccdab94fd32f        1d1a162a72a6        "/bin/bash"              9 hours ago         Exited (0) 5 hours ago                          confident_wu
ce462ecfc5f2        1d1a162a72a6        "/bin/bash -v /home/…"   9 hours ago         Exited (127) 9 hours ago                        stupefied_grothendieck
6123f134934c        1d1a162a72a6        "/bin/bash"              9 hours ago         Exited (1) 9 hours ago                          stupefied_taussig
0ed23a8112a4        1d1a162a72a6        "/bin/bash"              10 hours ago        Exited (0) 10 hours ago                         vigilant_bartik
c343731b7cde        1d1a162a72a6        "/bin/bash"              11 hours ago        Exited (0) 10 hours ago                         gallant_ardinghelli
2f95d3b4c1b8        1d1a162a72a6        "/bin/bash"              11 hours ago        Created                                         nice_hermann
5ebe9f18c744        1d1a162a72a6        "/bin/bash"              27 hours ago        Created                                         pensive_easley
c1b43edfafb9        1d1a162a72a6        "/bin/bash"              27 hours ago        Exited (1) 3 hours ago                          adoring_williams
42dea69d1d4e        1d1a162a72a6        "/bin/bash"              27 hours ago        Created                                         funny_austin
6f736902e650        1d1a162a72a6        "/bin/bash"              27 hours ago        Exited (1) 27 hours ago                         strange_ride
09306e5ec5d1        1d1a162a72a6        "--name=kaushik"         32 hours ago        Created                                         pensive_shtern
699fb2a23e1c        1d1a162a72a6        "--name=kaushik"         32 hours ago        Created                                         sharp_feistel
9f7b29ab512e        1d1a162a72a6        "--name=kaushik"         32 hours ago        Created                                         elastic_payne2
25bfc74fab3b        1d1a162a72a6        "/bin/bash"              33 hours ago        Exited (1) 31 hours ago                         festive_einstein
e658dd320297        1d1a162a72a6        "/bin/bash"              33 hours ago        Up 3 hours                                      objectiv:

I do not know how many containers were created and I made changes to enviornments inside containers. After a reboot I could not find any changes made to these containers. How can my containers survive a reboot?


来源: stackexchange

问:
How to focus Textbox with Alt + letter
I need to quick focus the text box using Alt+Letter combination. In my form for each textbox is a label. For this label I can specify name as '&My Label' and M letter will be underlined when I press the Alt button. But how I can focus the textbox (in winforms)?

P.S. As I remember WPF has possibility to bind label with textbox. And if label get focus textbox will get focus automatically.

答: This works automatically. Just make sure the TextBox you want to focus is the next one in the tab order, i.e. if the Label has TabIndex = 0, the TextBox needs TabIndex = 1.

ContentLicense: CC BY-SA 3.0

Title: How to focus Textbox with Alt + letter


问:
Searching For Existing Values in Array
I have been trying to search for an existing value in an array like below

```<code>var values = []
values.push(localStorage.getItem('items'));

console.log(values);

if (values.includes(2)) {
  alert('Already Exists.');
}
</code>```

When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.

My challenge is how to find the value 2 in the array values ?

答:
First of all, this isn't jQuery, it's vanilla JS.

Second, after doing localStorage.setItem("items", [1,2,3,4,5,6]);, items in local storage will equal to "1,2,3,4,5,6", which is no longer the appropriate format.

Rather, save your array with localStorage.setItem("items", JSON.stringify([1,2,3,4,5,6]));. When you want to retrieve those items, write let vals = JSON.parse(localStorage.getItem("items"));, and search in vals with

vals.includes(2) for a true/false answer,

vals.find(val => val === 2) for 2 or undefined,

val.indexOf(2) to get the index of the
first element equal to 2.

Hope this helps.

ContentLicense: CC BY-SA 4.0

Title: Searching For Existing Values in Array

Body:
I have been trying to search for an existing value in an array like below

var values = []
values.push(localStorage.getItem('items'));

console.log(values);

if (values.includes(2)) {
  alert('Already Exists.');
}

When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.

My challenge is how to find the value 2 in the array values ?


问:
Why website is not accessible by clicking on login button while recording it with proxy server using Jmeter?
I have set up a proxy server and trying to record a script by adding "http script recorder", but the problem is I am able to access a website but not able to login.

my website has been loaded but once I enter credentials and click on the login button then a website is not behaving, login button also not responding.

答:
In case of any problems with JMeter first of all you should look at jmeter.log file, if anything goes wrong JMeter normally writes an error message to this log file which in majority of cases is enough to get to the bottom of the issue.

With regards to your problem, my expectation is that login normally uses HTTPS protocol and you need to perform some extra configuration so JMeter would be able to intercept and decrypt HTTPS traffic.

You need to install JMeter's self-signed certificate to your browser, the file is called ApacheJMeterTemporaryRootCA.crt and it's being generated in "bin" folder of your JMeter installation when you start JMeter proxy.

You just need to import it into your browser and it should resolve you issue. Follow your browser documentation to learn more about certificates installation processes, some hints are also given in the HTTPS recording and certificates chapter of the HTTP(S) Test Script Recorder JMeter User Manual entry.

Alternative way is using JMeter Chrome Extension, in this case you won't have to worry about proxies and certificates so the recording process will be faster and easier.


问:
Can't Add Icon To Electron App With Electron Builder
I have made an app with Electron and am trying to package it with Electron Builder.

Link to repository

Does not contain node_modules folder: Repo here

I have a folder named build with my icon.ico in it and my package.json is as follows:

```<code>{
    "name": "attendant",
    "productName": "Attendant",
    "version": "0.1.0",
    "description": "A simple app to streamline web development by allowing you index.html to open on a live server in the default browser",
    "main": "main.js",
    "scripts": {
        "start": "electron .",
        "pack": "electron-builder --dir",
        "dist": "electron-builder"
    },
    "devDependencies": {
        "electron": "^8.0.1",
        "electron-builder": "^22.3.2"
    },
    "build": {
        "appId": "com.attendant",
        "win": {
            "icon": "./build/icon.png",
            "title": "Attendant",
            "msi": true
        }
    }
}
</code>```

However, I receive the following error:

```<code>error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

Any ideas why this happening and how to fix it?

With the following package.json:

```<code>{
    "name": "attendant",
    "productName": "Attendant",
    "version": "0.1.0",
    "description": "A simple app to streamline web development by allowing you index.html to open on a live server in the default browser",
    "main": "main.js",
    "scripts": {
        "start": "electron .",
        "pack": "electron-builder --dir",
        "dist": "electron-builder build"
    },
    "devDependencies": {
        "electron": "^8.0.1",
        "electron-builder": "^22.3.2"
    },
    "build": {
        "appId": "com.attendant",
        "directories": {
            "buildResources": "build"
        },
        "win": {
            "icon": "build/icon.png",
            "title": "Attendant",
            "msi": true
        }
    }
}
</code>```

I receive the error:

```<code>yarn dist
yarn run v1.22.0
warning package.json: No license field
$ electron-builder build
  • electron-builder  version=22.3.2 os=10.0.18363
  • loaded configuration  file=package.json ("build" field)
  • author is missed in the package.json  appPackageFile=C:\Users\alexr\Documents\GitHub\attendant-app\app\package.json
  ⨯ Invalid configuration object. electron-builder 22.3.2 has been initialised using a configuration object that
does not match the API schema.
 - configuration.win should be one of these:
   object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? } | null
   -> Options related to how build Windows targets.
   Details:
    * configuration.win has an unknown property 'title'. These properties are valid:
      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?,
generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }
    * configuration.win has an unknown property 'msi'. These properties are valid:
      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?,
generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }
     How to fix:
     1. Open https://www.electron.build/configuration/win
     2. Search the option name on the page (or type in into Search to find across the docs).
       * Not found? The option was deprecated or not exists (check spelling).
       * Found? Check that the option in the appropriate place. e.g. "title" only in the "dmg", not in the root.
  stackTrace=

                                                                   ValidationError: Invalid configuration object. electron-builder 22.3.2 has been initialised using a configuration object that does not match the API schema.

                                                                    - configuration.win should be one of these:

                                                                      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? } | null

                                                                      -> Options related to how build Windows targets.

                                                                      Details:

                                                                       * configuration.win has an unknown property 'title'. These properties are valid:

                                                                         object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }

                                                                       * configuration.win has an unknown property 'msi'. These properties are valid:

                                                                         object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }

                                                                        How to fix:

                                                                        1. Open https://www.electron.build/configuration/win

                                                                        2. Search the option name on the page (or type in into Search to find across the docs).

                                                                          * Not found? The option was deprecated
or not exists (check spelling).

                                                                          * Found? Check that the option in the appropriate place. e.g. "title" only in the "dmg", not in the root.

                                                                       at validate (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\@develar\schema-utils\dist\validate.js:50:11)

                                                                       at validateConfig (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\util\config.ts:229:3)

                                                                       at Packager._build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:342:5)

                                                                       at Packager.build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:337:12)

                                                                       at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

Edit number 2

I am now receiving the following error:

```<code>yarn run v1.22.0
warning package.json: No license field
$ electron-builder build
  • electron-builder  version=22.3.2 os=10.0.18363
  • loaded configuration  file=package.json ("build" field)
  • author is missed in the package.json  appPackageFile=C:\Users\alexr\Documents\GitHub\attendant-app\app\package.json
  • writing effective config  file=dist\builder-effective-config.yaml
  • packaging       platform=win32 arch=x64 electron=8.0.1 appOutDir=dist\win-unpacked
  • asar usage is disabled — this is strongly not recommended  solution=enable asar and use asarUnpack to unpack
files that must be externally available
  ⨯ cannot execute  cause=exit status 1
                    errorOut=Fatal error: Unable to commit changes

                    command='C:\Users\alexr\AppData\Local\electron-builder\Cache\winCodeSign\winCodeSign-2.5.0\rcedit-x64.exe' 'C:\Users\alexr\Documents\GitHub\attendant-app\app\dist\win-unpacked\Attendant.exe' --set-version-string FileDescription Attendant --set-version-string ProductName Attendant --set-version-string LegalCopyright 'Copyright © 2020 Attendant' --set-file-version 1.1.0 --set-product-version 1.1.0.0 --set-version-string InternalName Attendant --set-version-string OriginalFilename '' --set-icon 'C:\Users\alexr\Documents\GitHub\attendant-app\app\dist\.icon-ico\icon.ico'
                    workingDir=
  ⨯ C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-bin\win\x64\app-builder.exe exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE  stackTrace=

                                                  Error: C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-bin\win\x64\app-builder.exe exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE

                                                      at ChildProcess.<anonymous> (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\util.ts:239:14)

                                                      at Object.onceWrapper (events.js:313:26)

                                                      at ChildProcess.emit (events.js:223:5)

                                                      at maybeClose (internal/child_process.js:1021:16)

                                                      at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)

                                                  From previous event:

                                                      at processImmediate (internal/timers.js:439:21)

                                                  From previous event:

                                                      at WinPackager.signApp (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\winPackager.ts:357:27)

                                                      at WinPackager.doPack (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\platformPackager.ts:243:16)

                                                      at WinPackager.pack (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\platformPackager.ts:114:5)

                                                      at Packager.doBuild (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:444:9)

                                                      at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)

                                                      at Packager._build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:373:31)

                                                      at Packager.build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:337:12)

                                                      at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

</code>```

thanks for the support so far

答:
I Just went through your logs, I found the below error,

configuration.win has an unknown property 'title'. These properties are valid:

The title of the app should be given in productName property. The title keyword is invalid according to the document.

Also, I figured out there is buildResources that is missing in the build configurations. I recommend using .ico file for icons instead of png images.

```<code>"scripts": {
    "start": "electron .",
    "pack": "electron-builder --dir",
    "dist": "electron-builder build"
},
"build": {
    "productName": "Attendant",
    "appId": "com.experiment.attendant",
    "directories": {
        "buildResources": "build"
    },
    "files": [
      "build/**/*",
    ],
    "win": {
        "asar": false,
        "target": "nsis",
        "icon": "build/icon.ico"
    },
    "nsis": {
      "installerIcon": "build/icon.ico",
      "installerHeaderIcon": "build/icon.ico",
      "deleteAppDataOnUninstall": true
    },
}
</code>```

For more configurations,

Common Configurations

Windows Configurations

See the working example for windows and Linux configurations.
GITHUB

Body:
I have made an app with Electron and am trying to package it with Electron Builder.

Link to repository

Does not contain node_modules folder: Repo here

I have a folder named build with my icon.ico in it and my package.json is as follows:

{
    "name": "attendant",
    "productName": "Attendant",
    "version": "0.1.0",
    "description": "A simple app to streamline web development by allowing you index.html to open on a live server in the default browser",
    "main": "main.js",
    "scripts": {
        "start": "electron .",
        "pack": "electron-builder --dir",
        "dist": "electron-builder"
    },
    "devDependencies": {
        "electron": "^8.0.1",
        "electron-builder": "^22.3.2"
    },
    "build": {
        "appId": "com.attendant",
        "win": {
            "icon": "./build/icon.png",
            "title": "Attendant",
            "msi": true
        }
    }
}

However, I receive the following error:

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Any ideas why this happening and how to fix it?

With the following package.json:

{
    "name": "attendant",
    "productName": "Attendant",
    "version": "0.1.0",
    "description": "A simple app to streamline web development by allowing you index.html to open on a live server in the default browser",
    "main": "main.js",
    "scripts": {
        "start": "electron .",
        "pack": "electron-builder --dir",
        "dist": "electron-builder build"
    },
    "devDependencies": {
        "electron": "^8.0.1",
        "electron-builder": "^22.3.2"
    },
    "build": {
        "appId": "com.attendant",
        "directories": {
            "buildResources": "build"
        },
        "win": {
            "icon": "build/icon.png",
            "title": "Attendant",
            "msi": true
        }
    }
}

I receive the error:

yarn dist
yarn run v1.22.0
warning package.json: No license field
$ electron-builder build
  • electron-builder  version=22.3.2 os=10.0.18363
  • loaded configuration  file=package.json ("build" field)
  • author is missed in the package.json  appPackageFile=C:\Users\alexr\Documents\GitHub\attendant-app\app\package.json
  ⨯ Invalid configuration object. electron-builder 22.3.2 has been initialised using a configuration object that
does not match the API schema.
 - configuration.win should be one of these:
   object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? } | null
   -> Options related to how build Windows targets.
   Details:
    * configuration.win has an unknown property 'title'. These properties are valid:
      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?,
generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }
    * configuration.win has an unknown property 'msi'. These properties are valid:
      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?,
generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }
     How to fix:
     1. Open https://www.electron.build/configuration/win
     2. Search the option name on the page (or type in into Search to find across the docs).
       * Not found? The option was deprecated or not exists (check spelling).
       * Found? Check that the option in the appropriate place. e.g. "title" only in the "dmg", not in the root.
  stackTrace=

                                                                   ValidationError: Invalid configuration object. electron-builder 22.3.2 has been initialised using a configuration object that does not match the API schema.

                                                                    - configuration.win should be one of these:

                                                                      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? } | null

                                                                      -> Options related to how build Windows targets.

                                                                      Details:

                                                                       * configuration.win has an unknown property 'title'. These properties are valid:

                                                                         object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }

                                                                       * configuration.win has an unknown property 'msi'. These properties are valid:

                                                                         object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }

                                                                        How to fix:

                                                                        1. Open https://www.electron.build/configuration/win

                                                                        2. Search the option name on the page (or type in into Search to find across the docs).

                                                                          * Not found? The option was deprecated
or not exists (check spelling).

                                                                          * Found? Check that the option in the appropriate place. e.g. "title" only in the "dmg", not in the root.

                                                                       at validate (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\@develar\schema-utils\dist\validate.js:50:11)

                                                                       at validateConfig (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\util\config.ts:229:3)

                                                                       at Packager._build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:342:5)

                                                                       at Packager.build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:337:12)

                                                                       at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Edit number 2

I am now receiving the following error:

yarn run v1.22.0
warning package.json: No license field
$ electron-builder build
  • electron-builder  version=22.3.2 os=10.0.18363
  • loaded configuration  file=package.json ("build" field)
  • author is missed in the package.json  appPackageFile=C:\Users\alexr\Documents\GitHub\attendant-app\app\package.json
  • writing effective config  file=dist\builder-effective-config.yaml
  • packaging       platform=win32 arch=x64 electron=8.0.1 appOutDir=dist\win-unpacked
  • asar usage is disabled — this is strongly not recommended  solution=enable asar and use asarUnpack to unpack
files that must be externally available
  ⨯ cannot execute  cause=exit status 1
                    errorOut=Fatal error: Unable to commit changes

                    command='C:\Users\alexr\AppData\Local\electron-builder\Cache\winCodeSign\winCodeSign-2.5.0\rcedit-x64.exe' 'C:\Users\alexr\Documents\GitHub\attendant-app\app\dist\win-unpacked\Attendant.exe' --set-version-string FileDescription Attendant --set-version-string ProductName Attendant --set-version-string LegalCopyright 'Copyright © 2020 Attendant' --set-file-version 1.1.0 --set-product-version 1.1.0.0 --set-version-string InternalName Attendant --set-version-string OriginalFilename '' --set-icon 'C:\Users\alexr\Documents\GitHub\attendant-app\app\dist\.icon-ico\icon.ico'
                    workingDir=
  ⨯ C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-bin\win\x64\app-builder.exe exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE  stackTrace=

                                                  Error: C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-bin\win\x64\app-builder.exe exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE

                                                      at ChildProcess.<anonymous> (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\util.ts:239:14)

                                                      at Object.onceWrapper (events.js:313:26)

                                                      at ChildProcess.emit (events.js:223:5)

                                                      at maybeClose (internal/child_process.js:1021:16)

                                                      at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)

                                                  From previous event:

                                                      at processImmediate (internal/timers.js:439:21)

                                                  From previous event:

                                                      at WinPackager.signApp (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\winPackager.ts:357:27)

                                                      at WinPackager.doPack (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\platformPackager.ts:243:16)

                                                      at WinPackager.pack (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\platformPackager.ts:114:5)

                                                      at Packager.doBuild (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:444:9)

                                                      at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)

                                                      at Packager._build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:373:31)

                                                      at Packager.build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:337:12)

                                                      at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

thanks for the support so far

Body:
I Just went through your logs, I found the below error,

configuration.win has an unknown property 'title'. These properties are valid:

The title of the app should be given in productName property. The title keyword is invalid according to the document.

Also, I figured out there is buildResources that is missing in the build configurations. I recommend using .ico file for icons instead of png images.

"scripts": {
    "start": "electron .",
    "pack": "electron-builder --dir",
    "dist": "electron-builder build"
},
"build": {
    "productName": "Attendant",
    "appId": "com.experiment.attendant",
    "directories": {
        "buildResources": "build"
    },
    "files": [
      "build/**/*",
    ],
    "win": {
        "asar": false,
        "target": "nsis",
        "icon": "build/icon.ico"
    },
    "nsis": {
      "installerIcon": "build/icon.ico",
      "installerHeaderIcon": "build/icon.ico",
      "deleteAppDataOnUninstall": true
    },
}

For more configurations,

Common Configurations

Windows Configurations

See the working example for windows and Linux configurations.
GITHUB


问:
python dataframe merge columns according to other column values
What I want to do is merge columns according to values in another column
It is better illustrated with a simple example:
I have a dataframe with 5 columns:

```<code>| player_num    | team_1.x  | team_1.y  | team_2.x  | team_2.y  |
|------------   |---------- |---------- |---------- |---------- |
| 1             | x_1       | y_1       | x_2       | y_2       |
| 4             | x_3       | y_3       | x_4       | y_4       |
| 8             | x_5       | y_5       | x_6       | y_6       |
</code>```

I want to get the following table:

```<code>| x     | y     |
|-----  |-----  |
| x_1   | y_1   |
| x_3   | y_3   |
| x_6   | y_6   |
</code>```

where the columns are filled with values from team_1.x and team_1.y for rows of players with number less than 5 and values from team_2.x and team_2.y for rows of players with number bigger than 5

答:
This is not at all an elegant solution, but it should work...</p>

```<code>for i in df.loc[:, 'player_num']:
    index = df.loc[df.loc[:, 'player_num'] == i].index[0]

    if i >= 5:
        df.loc[index, 'x'] = df.loc[index, 'team_2.x']
        df.loc[index, 'y'] = df.loc[index, 'team_2.y']

    else:
        df.loc[index, 'x'] = df.loc[index, 'team_1.x']
        df.loc[index, 'y'] = df.loc[index, 'team_1.x']
</code>```

Body:
What I want to do is merge columns according to values in another column
It is better illustrated with a simple example:
I have a dataframe with 5 columns:

| player_num    | team_1.x  | team_1.y  | team_2.x  | team_2.y  |
|------------   |---------- |---------- |---------- |---------- |
| 1             | x_1       | y_1       | x_2       | y_2       |
| 4             | x_3       | y_3       | x_4       | y_4       |
| 8             | x_5       | y_5       | x_6       | y_6       |

I want to get the following table:

| x     | y     |
|-----  |-----  |
| x_1   | y_1   |
| x_3   | y_3   |
| x_6   | y_6   |

where the columns are filled with values from team_1.x and team_1.y for rows of players with number less than 5 and values from team_2.x and team_2.y for rows of players with number bigger than 5

Body:
This is not at all an elegant solution, but it should work...

for i in df.loc[:, 'player_num']:
    index = df.loc[df.loc[:, 'player_num'] == i].index[0]

    if i >= 5:
        df.loc[index, 'x'] = df.loc[index, 'team_2.x']
        df.loc[index, 'y'] = df.loc[index, 'team_2.y']

    else:
        df.loc[index, 'x'] = df.loc[index, 'team_1.x']
        df.loc[index, 'y'] = df.loc[index, 'team_1.x']


问:
How to stop XAMPP's MySQL Service after updating MariaDB
I've updated my MariaDB to version 10.3.14 using this steps (link)

It has been successfully installed, but when I tried to stop the MySQL Service from XAMPP Control Panel, it won't stop.

The status always shows like this:

[mysql] Attempting to stop MySQL app...

Like the picture below:

How can I stop that?

答:
I also had this issue so for anyone looking for an answer to fix the panel rather than using taskkill from cmd here is why this is happening:

The XAMPP Control panel you have installed is 32bit, while upgrading your MariaDB by following this method you downloaded the 64bit MariaDb version. That is why the XAMPP panel will not stop the MySQL process.

Download the 32bit version of MariaDB and re-do the installation process and it should be all sorted.


问:
Difference between Casting and Parsing
I have been working on some code for a while. for now i have just used the keywords as-is without actually understanding them. So here is my question

What is the difference between Casting and Parsing?

UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"] as String--> is this Casting or parsing?

(String) UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"]
-->is this Casting or parsing?

UserAdapter.GetIdAndUserTypeByEmailAndPassword(Email, Password).Rows[0]["UserType"].ToString()

What is the difference bewtween x.ToString() and (String) x?

答:
for the batter idea please check the below link.

http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/57518616-a142-4e89-99c9-e2fa6b01ef6f

Title: Difference between Casting and Parsing


问:
Azure ASP Web API error 405 method not allowed
I have a web api application that I have written and tested locally using VS2017 and IIS Express 10.  I am able to POST and GET when running locally using either HTTP or HTTPS.  When I publish to Azure I am getting method not allowed on both the post and get over HTTP.

How do I configure the Azure server to allow all the HTTP verbs?

How to configure HTTPS on Azure is another story...

Thanks :-)

答: Please check if you are passing the params correctly. Wasted a lot of time figuring that out.


问:
List files recursively with folder and file size
I want to share a summary of a directory with file names and sizes in plain text.

This thread shows a file list with human-readable file sizes, e.g. on macOS:

```
$ du -h -d 10
 14G    ./190803 Aaah
 13G    ./190804 (no sound)
```

This post lists a file structure with a nice tree:

```
$ find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
.
|____.DS_Store
|____190803 Aaah
| |____190803 Aaah.mp4
| |____DSC_0011.MOV
| |____DSC_0012.MOV
| |____DSC_0013.MOV
| |____DSC_0014.MOV
| |____DSC_0015.MOV
| |____DSC_0016.MOV
|____190804 (no sound)
| |_____DSC0018.MOV
| |_____DSC0019.MOV
| |_____DSC0020.MOV
| |_____DSC0021.MOV
| |_____DSC0022.MOV
| |_____DSC0023.MOV
| |____DSC_0017.MOV
```

How can I combine both and show the human-readable file size next to each item, file or folder, in the latter tree display?

答:
You can try this:</p>

```<code>for f in $(ls -R); do wc -c $f;done
</code>```

Body:
I want to share a summary of a directory with file names and sizes in plain text.

This thread shows a file list with human-readable file sizes, e.g. on macOS:

$ du -h -d 10
 14G    ./190803 Aaah
 13G    ./190804 (no sound)

This post lists a file structure with a nice tree:

$ find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
.
|____.DS_Store
|____190803 Aaah
| |____190803 Aaah.mp4
| |____DSC_0011.MOV
| |____DSC_0012.MOV
| |____DSC_0013.MOV
| |____DSC_0014.MOV
| |____DSC_0015.MOV
| |____DSC_0016.MOV
|____190804 (no sound)
| |_____DSC0018.MOV
| |_____DSC0019.MOV
| |_____DSC0020.MOV
| |_____DSC0021.MOV
| |_____DSC0022.MOV
| |_____DSC0023.MOV
| |____DSC_0017.MOV

How can I combine both and show the human-readable file size next to each item, file or folder, in the latter tree display?

Body:
You can try this:

for f in $(ls -R); do wc -c $f;done


问:
How to use
 tag as variable
Anyone knows how to make br tag as variable?
I want to output a txt file that has textbox value.
I want to set a specific counts of break lines. Like 100 times.

Example.
Hello
Earth

Output
Hello
(line break 100times)
Earth

答:
You can use string.repeat() to repeat a string N times :

const a_lot_of_new_lines = "
".repeat(100);
document.getElementById("foo").innerHTML = "Hello" + a_lot_of_new_lines + "Earth";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="foo">
<div></code>```

Title: How to use <br> tag as variable

Body:
You can use string.repeat() to repeat a string N times :

const a_lot_of_new_lines = "<br>".repeat(100);
document.getElementById("foo").innerHTML = "Hello" + a_lot_of_new_lines + "Earth";

<div id="foo">
<div>


问:
Android NullPointerException in Retrofit response
In my activity I have more than one Retrofit services operations and these services relay on same Retrofit Callback methods. And these causes null pointer when one service try to get a callback at the same time callback is used by other service, how to fix this problem?

I have been using retrofit for my webservice calls. It is working fine in emulator but when I use a real device it crashes and got the error log as:

```<code>  java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
    at com.itmam.info.jadara.Notiﬁcations.Notifications_Items_Adapter$4.onResponse(Notifications_Items_Adapter.java:309)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:888)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:213)
    at android.app.ActivityThread.main(ActivityThread.java:8147)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
</code>```

This is my Retrofit client class:

```<code>public class RetrofitGeneral {

private static Retrofit retrofit;
private static final String BASE_URL = "My_URL";

public static Retrofit getRetrofitInstance() {
    if (retrofit == null) {
        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
 }
}
</code>```

This is my Retrofit Service interface:

```<code>public interface getClientDetails {
@FormUrlEncoded
@POST("WebService.asmx/SelectClientById")
Call<List<ClientDetails>> getClientdetails(
        @Field("ClientID") int ClientID,
        @Field("Token") String Token,
        @Field("CurrentEmployeeID") int CurrentEmployeeID
 );
}
</code>```

And this way i am making a call to Retrofit service from my adapter onBindViewHolder that call the retrofit more than one time:

```<code>@Override
public void onBindViewHolder(Notifications_Items_Adapter.Notifications_Holder holder, int position) {
    myHolder = holder;
    holderList.add(holder);
    getTaskId(position);
    getTaskDetails(taskID);

}
</code>```

This is my retrofit callBack method:

```<code>private void getTaskDetails(int taskID){
    getTaskDetails getTaskDetails=RetrofitGeneral.getRetrofitInstance().create(getTaskDetails.class);
    Call<List<Task>> listCall=getTaskDetails.getDetails(taskID,Log_in.getToken(),Log_in.CurrentEmployeeID);
    listCall.enqueue(new Callback<List<Task>>(){
        @Override
        public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
            task = response.body().get(0); // Error here after the second call.
            tasksList.add(task);
        }

        @Override
        public void onFailure(Call<List<Task>> call, Throwable t) {

        }
    });
}
</code>```

Please help :)

答:
The problem was fixed by using Retrofit Synchronous like that :

```<code>UserService service = ServiceGenerator.createService(UserService.class);

// 1. Calling '/api/users/2' - synchronously

Call<UserApiResponse> callSync = service.getUser(2);

try
{
  Response<UserApiResponse> response = callSync.execute();
  UserApiResponse apiResponse = response.body();

  //API response
  System.out.println(apiResponse);
}
catch (Exception ex)
{
  ex.printStackTrace();
}
</code>```

from Retrofit 2 – Synchronous and asynchronous call example.

Body:
In my activity I have more than one Retrofit services operations and these services relay on same Retrofit Callback methods. And these causes null pointer when one service try to get a callback at the same time callback is used by other service, how to fix this problem?

I have been using retrofit for my webservice calls. It is working fine in emulator but when I use a real device it crashes and got the error log as:

  java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
    at com.itmam.info.jadara.Notiﬁcations.Notifications_Items_Adapter$4.onResponse(Notifications_Items_Adapter.java:309)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:888)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:213)
    at android.app.ActivityThread.main(ActivityThread.java:8147)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)

This is my Retrofit client class:

public class RetrofitGeneral {

private static Retrofit retrofit;
private static final String BASE_URL = "My_URL";

public static Retrofit getRetrofitInstance() {
    if (retrofit == null) {
        retrofit = new retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
 }
}

This is my Retrofit Service interface:

public interface getClientDetails {
@FormUrlEncoded
@POST("WebService.asmx/SelectClientById")
Call<List<ClientDetails>> getClientdetails(
        @Field("ClientID") int ClientID,
        @Field("Token") String Token,
        @Field("CurrentEmployeeID") int CurrentEmployeeID
 );
}

And this way i am making a call to Retrofit service from my adapter onBindViewHolder that call the retrofit more than one time:

@Override
public void onBindViewHolder(Notifications_Items_Adapter.Notifications_Holder holder, int position) {
    myHolder = holder;
    holderList.add(holder);
    getTaskId(position);
    getTaskDetails(taskID);

}

This is my retrofit callBack method:

private void getTaskDetails(int taskID){
    getTaskDetails getTaskDetails=RetrofitGeneral.getRetrofitInstance().create(getTaskDetails.class);
    Call<List<Task>> listCall=getTaskDetails.getDetails(taskID,Log_in.getToken(),Log_in.CurrentEmployeeID);
    listCall.enqueue(new Callback<List<Task>>(){
        @Override
        public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
            task = response.body().get(0); // Error here after the second call.
            tasksList.add(task);
        }

        @Override
        public void onFailure(Call<List<Task>> call, Throwable t) {

        }
    });
}

Please help :)

Body:
The problem was fixed by using Retrofit Synchronous like that :

UserService service = ServiceGenerator.createService(UserService.class);

// 1. Calling '/api/users/2' - synchronously

Call<UserApiResponse> callSync = service.getUser(2);

try
{
  Response<UserApiResponse> response = callSync.execute();
  UserApiResponse apiResponse = response.body();

  //API response
  System.out.println(apiResponse);
}
catch (Exception ex)
{
  ex.printStackTrace();
}

from Retrofit 2 – Synchronous and asynchronous call example.


问:
Attempt to invoke virtual method 'int java.lang.String.hashCode()'
I'm trying to load images from URL into girdview using Volley Library. For this I'm following this tutorial. When I run my project, it collects all URLs from server database and then store in arraylist. But doesn't displays images. And I am getting java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference error. It doesn't even point to any line number of code where I'm getting this error. See below Logcat Output :

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
        at com.android.volley.Request.<init>(Request.java:136)
        at com.android.volley.toolbox.ImageRequest.<init>(ImageRequest.java:71)
        at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:219)
        at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:171)
        at com.android.volley.toolbox.NetworkImageView.loadImageIfNecessary(NetworkImageView.java:141)
        at com.android.volley.toolbox.NetworkImageView.onLayout(NetworkImageView.java:190)
        at android.view.View.layout(View.java:15596)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.GridView.setupChild(GridView.java:1542)
        at android.widget.GridView.makeAndAddView(GridView.java:1436)
        at android.widget.GridView.makeRow(GridView.java:361)
        at android.widget.GridView.fillDown(GridView.java:302)
        at android.widget.GridView.fillFromTop(GridView.java:437)
        at android.widget.GridView.layoutChildren(GridView.java:1276)
        at android.widget.AbsListView.onLayout(AbsListView.java:2148)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.widget.ScrollView.onLayout(ScrollView.java:1502)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:494)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
        at android.view.Choreographer.doCallbacks(Choreographer.java:580)
        at android.view.Choreographer.doFrame(Choreographer.java:550)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
</code>```

Can anybody help me what is the exact problem and how do I solve this ?

答: My server is https and so was getting a different error. I removed the https and remained with the domain name only and it failed to work so I ended up putting up the https: and contacting my host to ease the security rules on the domain or create special provision for the specific domain. Check where you implement your site url and add http or https depending on how your site looks on browser.</p>

Body:
I'm trying to load images from URL into girdview using Volley Library. For this I'm following this tutorial. When I run my project, it collects all URLs from server database and then store in arraylist. But doesn't displays images. And I am getting java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference error. It doesn't even point to any line number of code where I'm getting this error. See below Logcat Output :

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
        at com.android.volley.Request.<init>(Request.java:136)
        at com.android.volley.toolbox.ImageRequest.<init>(ImageRequest.java:71)
        at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:219)
        at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:171)
        at com.android.volley.toolbox.NetworkImageView.loadImageIfNecessary(NetworkImageView.java:141)
        at com.android.volley.toolbox.NetworkImageView.onLayout(NetworkImageView.java:190)
        at android.view.View.layout(View.java:15596)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.GridView.setupChild(GridView.java:1542)
        at android.widget.GridView.makeAndAddView(GridView.java:1436)
        at android.widget.GridView.makeRow(GridView.java:361)
        at android.widget.GridView.fillDown(GridView.java:302)
        at android.widget.GridView.fillFromTop(GridView.java:437)
        at android.widget.GridView.layoutChildren(GridView.java:1276)
        at android.widget.AbsListView.onLayout(AbsListView.java:2148)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.widget.ScrollView.onLayout(ScrollView.java:1502)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:494)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
        at android.view.View.layout(View.java:15596)
        at android.view.ViewGroup.layout(ViewGroup.java:4966)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
        at android.view.Choreographer.doCallbacks(Choreographer.java:580)
        at android.view.Choreographer.doFrame(Choreographer.java:550)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Can anybody help me what is the exact problem and how do I solve this ?


问:
Simple clone of gradle test task not recognized as test in IntelliJ
I want to have a very simple clone of a gradle task like this:

```<code>project.tasks.register("runTests") {
    it.group = "otherGroup"
    it.dependsOn("jvmTest")
}
</code>```

The problem is, that the source task (jvmTest) is a test task. And when I do the simple dependsOn like in my example, intellij does not recognize it as a test task (e.g. it only displays the output in the build terminal but does not show the fancy green, yellow and red test symbols)

I tried to add it as follows

```<code>project.tasks.register("runTests", Test::class.java){
    it.group = "otherGroup"
    it.dependsOn("jvmTest")
}
</code>```

but this will result in a NullPointerException when running it

答:
dependsOn only creates an execution dependency on the task graph in Gradle, it will not create a different test task nor will it clone the one depended upon.

Have a look at the sample on how to create additional tests.

Body:
I want to have a very simple clone of a gradle task like this:

project.tasks.register("runTests") {
    it.group = "otherGroup"
    it.dependsOn("jvmTest")
}

The problem is, that the source task (jvmTest) is a test task. And when I do the simple dependsOn like in my example, intellij does not recognize it as a test task (e.g. it only displays the output in the build terminal but does not show the fancy green, yellow and red test symbols)

I tried to add it as follows

project.tasks.register("runTests", Test::class.java){
    it.group = "otherGroup"
    it.dependsOn("jvmTest")
}

but this will result in a NullPointerException when running it


问:
MySQL JOIN: Only return rows where all values from right table are NULL
I have two MySQL tables like this:

```<code>orders:
+----------+------+
| order_id | name |
+----------+------+
| 1        | Mary |
| 2        | John |
| 3        | Anne |
+----------+------+

order_details:
+----------+----------------+
| order_id | shipped        |
+----------+----------------+
| 1        | null           |
| 1        | null           |
| 1        | SHIPPED-123ABC |
| 2        | null           |
| 2        | null           |
| 3        | SHIPPED-XYZ    |
| 3        | SHIPPED-XYZ    |
| 3        | null           |
+----------+----------------+
</code>```

Now I want to join the order_details-table to the orders-table but only show the entries that only  have NULL shipped values in the order_details table. So in this example only order_id #2 would get returned.

So the result would be:

```<code>+----------+------+---------+
| order_id | name | shipped |
+----------+------+---------+
| 2        | John | null    |
+----------+------+---------+
</code>```

Thank you!

答:
You can use not exists :

```<code>select o.order_id, o.name, null as shipped
from orders o
where not exists (select 1
                  from order_details od
                   where od.order_id = o.order_id and od.shipped is not null
                 );
</code>```

Simple aggregation with JOIN would also work :

```<code>select o.order_id, o.name, null as shipped
from orders o inner join
     order_details od
     on od.order_id = o.order_id
group by o.order_id, o.name
having min(od.shipped) = max(od.shipped) and min(od.shipped) is null;
</code>```

Body:
I have two MySQL tables like this:

orders:
+----------+------+
| order_id | name |
+----------+------+
| 1        | Mary |
| 2        | John |
| 3        | Anne |
+----------+------+

order_details:
+----------+----------------+
| order_id | shipped        |
+----------+----------------+
| 1        | null           |
| 1        | null           |
| 1        | SHIPPED-123ABC |
| 2        | null           |
| 2        | null           |
| 3        | SHIPPED-XYZ    |
| 3        | SHIPPED-XYZ    |
| 3        | null           |
+----------+----------------+

Now I want to join the order_details-table to the orders-table but only show the entries that only  have NULL shipped values in the order_details table. So in this example only order_id #2 would get returned.

So the result would be:

+----------+------+---------+
| order_id | name | shipped |
+----------+------+---------+
| 2        | John | null    |
+----------+------+---------+

Thank you!

Body:
You can use not exists :

select o.order_id, o.name, null as shipped
from orders o
where not exists (select 1
                  from order_details od
                   where od.order_id = o.order_id and od.shipped is not null
                 );

Simple aggregation with JOIN would also work :

select o.order_id, o.name, null as shipped
from orders o inner join
     order_details od
     on od.order_id = o.order_id
group by o.order_id, o.name
having min(od.shipped) = max(od.shipped) and min(od.shipped) is null;


问:
SubClass of FrameLayout Class doesn't redraw canvas screens?
When I am using FrameLayout Class(GameView) to use addView(object)  so that I can use ontouchlistener() but it only draws Rocket and shooter (classes used to draw , all are called in GameView ) but it didn't  reDraws it (refer summary at bottom)

GameView.java

//Package and Imports
public class GameView extends FrameLayout implements View.OnTouchListener {

    public GameView(Context context, AttributeSet attrs) {
        super(context,attrs);
        mContext = context;
        startTime = (int)(SystemClock.elapsedRealtime());
        cannon = new shooter(Color.BLUE,mContext); bullets = new ArrayList<> ();            explosions =new ArrayList<>(); item = new Rocket( Color.RED,mContext);
addView(item);
        addView(cannon);
        cannon.setOnTouchListener(this);
        for (int i = 0; i < bullets.size(); i++) {
            addView(bullets.get(i));
            bullets.get(i).setOnTouchListener(this);
        }
    }
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            for (int i = bullets.size() - 1; i >= 0; i--) {
                if (//if bullet is touched) {
                    if (bullets.size() > 0) {
                        bullets.subList(i, bullets.size()).clear();
                    } } }
            if (//if cannon is touched)) {
                cannon.move();
            }
        }
        return true;
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int time = (int)(SystemClock.elapsedRealtime() - startTime);
        drawGameBoard(canvas);
        if((time/6000)%2==0) // Code to alter cannon color at every 6000 sec which also didn't work
{
  if(cannon.paint.getColor()!=Color.BLUE) {
                cannon.paint.setColor(Color.BLUE);
                cannon.invalidate();
            }
        }
        else {
            if(cannon.paint.getColor()!=Color.RED) {
                cannon.paint.setColor(Color.RED);
                cannon.invalidate();
            }
        }
        invalidate();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        width = w;
        height = h;

        cannon.setBounds(0,0,width,height);
        item.setBounds(0,0,width,height);
        for (int i = 0; i < bullets.size(); i++ ) {
            bullets.get(i).setBounds(0,0,width,height);
        }

    }

    public void drawGameBoard(Canvas canvas) {

        cannon.draw(canvas);
        for (int i = bullets.size() - 1; i >= 0; i--) {
            if (bullets.get(i) != null) {
                bullets.get(i).draw(canvas);

                if (!bullets.get(i).move()) {
                    bullets.remove(i);
                }
            }
        }

        for (int i = explosions.size() - 1; i >= 0; i--) {
            if (explosions.get(i) != null) {
                if (!explosions.get(i).draw(canvas)) {
                    explosions.remove(i);
                }
            }
        }

        if (item!= null) {
            item.draw(canvas);
            RectF guyRect = item.getRect();
            for (int i = bullets.size() - 1; i >= 0; i--) {
                if (RectF.intersects(guyRect, bullets.get(i).getRect())) {
                    explosions.add(new Blast(Color.RED,mContext, item.getX(), item.getY()));
                    item.reset();
                    bullets.remove(i);
                    break;
                }
            }

            if (!item.move()) {
                item = null;
            }
        }
    }
    // Whenever the user shoots a bullet, create a new bullet moving upwards
    public void shootCannon() {

        bullets.add(new Goliyaan(cannon.paint.getColor() ,mContext, cannon.getPosition(), (float) (height-100)));

    }
}
```

<p>Shooter(cannon) Class use to draw a cannon at bottom<-- only this is drawn (works)</p>

<pre class="lang-java prettyprint-override"><code>//package and imports
public class shooter extends View  {
   //declared variables as used
    public shooter(int color, Context c) {
        super(c);
       //initialized paint objects
    }
    public void setBounds(int lx, int ly, int ux, int uy) {
        lowerX = lx;
        lowerY = ly;
        upperX = ux;
        upperY = uy;

    }
    public void move() {
       //moves cannon
        invalidate();
    }
    public float getPosition()
    {
        return shootPoint;
    }
    public int shooterY(){ return (int)top;}
    public void draw(Canvas canvas)
    {
        super.draw(canvas);
    //draws a cannon(drawRect and circle)
    }
}

</code>```

SameWay Goliyaan(Bullets) class extends view

/* Actually in hindi spoken language goliyaan means bullet*/

package and import
public class Goliyaan extends View {
//DECLARED VARIABLES AS USED
    // Constructor
    public Goliyaan(int color, Context c, float startx, float starty) {
        super(c);
        //INITIALIZed
    }

 //Here is some less important functions like setbounds,getters and rect(use for collision detection)
    public boolean move() {
        // Get new (x,y) position
        y -= stepY;
        if (y - radius < 0) {
            return false;
        }
        else
            return true;
    }

    // draw the bullet on the canvas
    public void draw(Canvas canvas) {
        super.draw(canvas);

        canvas.drawCircle(x, y, radius, paint);
    }
}

```

<p>Might You Need Rocket(item) class </p>

<pre class="lang-java prettyprint-override"><code>//Package and Imports
public class Rocket extends View

// INITIALIZED VARIABLES HERE AS USED
        // Constructor
        public Rocket(int color, Context c) {
            super(c);
            mContext = c;
            // create a bitmap from the supplied image
            aliens = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(c.getResources(),
                    R.drawable.rocket),dst,dst, false);

        }

        public void setBounds(int lx, int ly, int ux, int uy) {
            lowerX = lx;
            lowerY = ly;
            upperX = ux;
            upperY = uy;

            x = (float) ((upperX-50)*Math.random());
            y = 0;
        }

        public boolean move() {
            // Get new (x,y) position. Movement is always in vertical direction downwards
            y += stepY;

            if (y + 50 > upperY) {
               reset();
                return true;
            }
            else
                return true;
        }

        public void reset() {
            x = (float) ((upperX-50)*Math.random());
            y = 0;
        }

        // Returns the rectangle enclosing the Rocket. Used for collision detection
        public RectF getRect() {
            return new RectF(x,y,x+50,y+50);
        }

        // HERE IS getX() and getY() Function

        public void draw(Canvas canvas) {
super.draw(canvas);
            canvas.drawBitmap(aliens, x, y, null);
        }
    }

</code>```

Summary

I have GameView Class(Custom View) that draws a cannon , bullets , item and explosions(Blast class)

But after extending FrameLayout class (earlier view class) to use addView and ontouchlistener
only it draws but doesn't move means didn't invalidate()  it

Before that all was drawn and moves,  when I extended View class and didn't used addView(..)

Also, i didn't need addView(items) but when I remove it , it didn't draw Rocket

Feel free to Ignore but If you can please help me

答: you need to call setWillNotDraw(false) in the constructor of your FrameLayout otherwise its onDraw won't be called.

Body:
When I am using FrameLayout Class(GameView) to use addView(object)  so that I can use ontouchlistener() but it only draws Rocket and shooter (classes used to draw , all are called in GameView ) but it didn't  reDraws it (refer summary at bottom)

GameView.java

//Package and Imports
public class GameView extends FrameLayout implements View.OnTouchListener {

    public GameView(Context context, AttributeSet attrs) {
        super(context,attrs);
        mContext = context;
        startTime = (int)(SystemClock.elapsedRealtime());
        cannon = new shooter(Color.BLUE,mContext); bullets = new ArrayList<> ();            explosions =new ArrayList<>(); item = new Rocket( Color.RED,mContext);
addView(item);
        addView(cannon);
        cannon.setOnTouchListener(this);
        for (int i = 0; i < bullets.size(); i++) {
            addView(bullets.get(i));
            bullets.get(i).setOnTouchListener(this);
        }
    }
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            for (int i = bullets.size() - 1; i >= 0; i--) {
                if (//if bullet is touched) {
                    if (bullets.size() > 0) {
                        bullets.subList(i, bullets.size()).clear();
                    } } }
            if (//if cannon is touched)) {
                cannon.move();
            }
        }
        return true;
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int time = (int)(SystemClock.elapsedRealtime() - startTime);
        drawGameBoard(canvas);
        if((time/6000)%2==0) // Code to alter cannon color at every 6000 sec which also didn't work
{
  if(cannon.paint.getColor()!=Color.BLUE) {
                cannon.paint.setColor(Color.BLUE);
                cannon.invalidate();
            }
        }
        else {
            if(cannon.paint.getColor()!=Color.RED) {
                cannon.paint.setColor(Color.RED);
                cannon.invalidate();
            }
        }
        invalidate();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        width = w;
        height = h;

        cannon.setBounds(0,0,width,height);
        item.setBounds(0,0,width,height);
        for (int i = 0; i < bullets.size(); i++ ) {
            bullets.get(i).setBounds(0,0,width,height);
        }

    }

    public void drawGameBoard(Canvas canvas) {

        cannon.draw(canvas);
        for (int i = bullets.size() - 1; i >= 0; i--) {
            if (bullets.get(i) != null) {
                bullets.get(i).draw(canvas);

                if (!bullets.get(i).move()) {
                    bullets.remove(i);
                }
            }
        }

        for (int i = explosions.size() - 1; i >= 0; i--) {
            if (explosions.get(i) != null) {
                if (!explosions.get(i).draw(canvas)) {
                    explosions.remove(i);
                }
            }
        }

        if (item!= null) {
            item.draw(canvas);
            RectF guyRect = item.getRect();
            for (int i = bullets.size() - 1; i >= 0; i--) {
                if (RectF.intersects(guyRect, bullets.get(i).getRect())) {
                    explosions.add(new Blast(Color.RED,mContext, item.getX(), item.getY()));
                    item.reset();
                    bullets.remove(i);
                    break;
                }
            }

            if (!item.move()) {
                item = null;
            }
        }
    }
    // Whenever the user shoots a bullet, create a new bullet moving upwards
    public void shootCannon() {

        bullets.add(new Goliyaan(cannon.paint.getColor() ,mContext, cannon.getPosition(), (float) (height-100)));

    }
}

Shooter(cannon) Class use to draw a cannon at bottom<-- only this is drawn (works)

//package and imports
public class shooter extends View  {
   //declared variables as used
    public shooter(int color, Context c) {
        super(c);
       //initialized paint objects
    }
    public void setBounds(int lx, int ly, int ux, int uy) {
        lowerX = lx;
        lowerY = ly;
        upperX = ux;
        upperY = uy;

    }
    public void move() {
       //moves cannon
        invalidate();
    }
    public float getPosition()
    {
        return shootPoint;
    }
    public int shooterY(){ return (int)top;}
    public void draw(Canvas canvas)
    {
        super.draw(canvas);
    //draws a cannon(drawRect and circle)
    }
}

SameWay Goliyaan(Bullets) class extends view

/* Actually in hindi spoken language goliyaan means bullet*/

package and import
public class Goliyaan extends View {
//DECLARED VARIABLES AS USED
    // Constructor
    public Goliyaan(int color, Context c, float startx, float starty) {
        super(c);
        //INITIALIZed
    }

 //Here is some less important functions like setbounds,getters and rect(use for collision detection)
    public boolean move() {
        // Get new (x,y) position
        y -= stepY;
        if (y - radius < 0) {
            return false;
        }
        else
            return true;
    }

    // draw the bullet on the canvas
    public void draw(Canvas canvas) {
        super.draw(canvas);

        canvas.drawCircle(x, y, radius, paint);
    }
}

Might You Need Rocket(item) class

//Package and Imports
public class Rocket extends View

// INITIALIZED VARIABLES HERE AS USED
        // Constructor
        public Rocket(int color, Context c) {
            super(c);
            mContext = c;
            // create a bitmap from the supplied image
            aliens = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(c.getResources(),
                    R.drawable.rocket),dst,dst, false);

        }

        public void setBounds(int lx, int ly, int ux, int uy) {
            lowerX = lx;
            lowerY = ly;
            upperX = ux;
            upperY = uy;

            x = (float) ((upperX-50)*Math.random());
            y = 0;
        }

        public boolean move() {
            // Get new (x,y) position. Movement is always in vertical direction downwards
            y += stepY;

            if (y + 50 > upperY) {
               reset();
                return true;
            }
            else
                return true;
        }

        public void reset() {
            x = (float) ((upperX-50)*Math.random());
            y = 0;
        }

        // Returns the rectangle enclosing the Rocket. Used for collision detection
        public RectF getRect() {
            return new RectF(x,y,x+50,y+50);
        }

        // HERE IS getX() and getY() Function

        public void draw(Canvas canvas) {
super.draw(canvas);
            canvas.drawBitmap(aliens, x, y, null);
        }
    }

Summary

I have GameView Class(Custom View) that draws a cannon , bullets , item and explosions(Blast class)

But after extending FrameLayout class (earlier view class) to use addView and ontouchlistener
only it draws but doesn't move means didn't invalidate()  it

Before that all was drawn and moves,  when I extended View class and didn't used addView(..)

Also, i didn't need addView(items) but when I remove it , it didn't draw Rocket

Feel free to Ignore but If you can please help me


问:
Drag/Drop Issue on iPad Safari
I am trying to create a drag/drop effect on iPad (using a library based on jQTouch/jQuery UI)

There is a fixed width/height div and I use overflow:auto for the div..So it is something like;

```<code>div #draggable{
height: 350px;
margin: 0;
overflow: auto;
width: 235px;
}
</code>```

Now while I am able to drag this div, it only drags within the scrollable fixed width/height region...

I actually want it to be dragged outside, as the drop area is outside of this region...

Could you please help me. Thank you.

Also in case you have any other references for iPad Drag/Drop Javascript (apart from Sencha Touch)

Thank you...

答: Assuming this is a jQuery UI draggable, you need to make sure the containment option is set appropriately, and you need to check the appendTo property is set appropriately. In general, setting the latter to $(document.body) will work. See: http://jqueryui.com/demos/draggable/#option-appendTo

Title: Drag/Drop Issue on iPad Safari

Body:
I am trying to create a drag/drop effect on iPad (using a library based on jQTouch/jQuery UI)

There is a fixed width/height div and I use overflow:auto for the div..So it is something like;

div #draggable{
height: 350px;
margin: 0;
overflow: auto;
width: 235px;
}

Now while I am able to drag this div, it only drags within the scrollable fixed width/height region...

I actually want it to be dragged outside, as the drop area is outside of this region...

Could you please help me. Thank you.

Also in case you have any other references for iPad Drag/Drop Javascript (apart from Sencha Touch)

Thank you...


问:
How to build query string with Javascript
Just wondering if there is anything built-in to Javascript that can take a Form and return the query parameters, eg: "var1=value&var2=value2&arr[]=foo&arr[]=bar..."

I've been wondering this for years.

答:
I know this is very late answer but works very well...

```<code>var obj = {
a:"a",
b:"b"
}

Object.entries(obj).map(([key, val])=>`${key}=${val}`).join("&");
</code>```

note: object.entries will return key,values pairs

output from above line will be a=a&b=b

Hope its helps someone.

Happy Coding...

OwnerDisplayName: John II

Body:
I know this is very late answer but works very well...

var obj = {
a:"a",
b:"b"
}

Object.entries(obj).map(([key, val])=>`${key}=${val}`).join("&");

note: object.entries will return key,values pairs

output from above line will be a=a&b=b

Hope its helps someone.

Happy Coding...


问:
Flutter application crashes when providing custom application class in Android's Manifest file
I am working on a Flutter application. I have to initialize an object in Application class in Android, and I have created a custom application class that is extending FlutterApplication class. I have provided the class name in Manifest file too but when I run the application it crashes.

Please suggest, how can I do that. Below is the code of application class and manifest file.

Thank You.

Manifest file

```<code> <application
    android:name="com.example.app.MyApplication"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name">
 ...
 </application>
</code>```

MyApplication class

```<code>package com.example.app;
import android.app.Application;
import io.flutter.view.FlutterMain
import io.flutter.app.FlutterApplication;

class MyApplication extends FlutterApplication {

    @override
    public void onCreate() {
        FlutterMain.startInitialization(this)

    }
}
</code>```

答:
The application class handles the context, environment setup etc during app start up process so along with manifest registration, you must call super.onCreate() as stated:

If you override this method, be sure to call {@code
  super.onCreate()}.

so do

```<code>class MyApplication extends FlutterApplication {

    @override
    public void onCreate() {
        super.onCreate() // add this
    }
}
</code>```

Note: With super.onCreate(), there's no need to call FlutterMain.startInitialization(this), as will be done by FlutterApplication

```<code>public class Application extends FlutterApplication implements PluginRegistrantCallback {
  @Override
  public void onCreate() {
    super.onCreate();
    AlarmService.setPluginRegistrant(this);
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  }

  @Override
  public void registerWith(PluginRegistry registry) {
    GeneratedPluginRegistrant.registerWith(registry);
  }
}
</code>```

Body:
I am working on a Flutter application. I have to initialize an object in Application class in Android, and I have created a custom application class that is extending FlutterApplication class. I have provided the class name in Manifest file too but when I run the application it crashes.

Please suggest, how can I do that. Below is the code of application class and manifest file.

Thank You.

Manifest file

 <application
    android:name="com.example.app.MyApplication"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name">
 ...
 </application>

MyApplication class

package com.example.app;
import android.app.Application;
import io.flutter.view.FlutterMain
import io.flutter.app.FlutterApplication;

class MyApplication extends FlutterApplication {

    @override
    public void onCreate() {
        FlutterMain.startInitialization(this)

    }
}

Body:
The application class handles the context, environment setup etc during app start up process so along with manifest registration, you must call super.onCreate() as stated:

If you override this method, be sure to call {@code
  super.onCreate()}.

so do

class MyApplication extends FlutterApplication {

    @override
    public void onCreate() {
        super.onCreate() // add this
    }
}

Note: With super.onCreate(), there's no need to call FlutterMain.startInitialization(this), as will be done by FlutterApplication

public class Application extends FlutterApplication implements PluginRegistrantCallback {
  @Override
  public void onCreate() {
    super.onCreate();
    AlarmService.setPluginRegistrant(this);
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  }

  @Override
  public void registerWith(PluginRegistry registry) {
    GeneratedPluginRegistrant.registerWith(registry);
  }
}


问:
How to change label on input focus when input comes after label?
```<code><div id="my-field">
    <label class="my-label">Label</label>
    <input class="my-input" value="input" />
</div>
</code>```

```<code>#my-field{
}
.my-label {
}
.my-input{
}
</code>```

Is there any way I can customize the CSS of .my-label when input is in focus without touching the HTML? There are multiple ways to select successor sibling elements. But any way to select predecessor(s)?

Note: There is a restriction in the project that HTML cannot be modified here. Everything has to be done in CSS only. No jQuery/JS either.

答:
No. there is unfortunately no predecessor selector in css

```<code>input:focus -+ label { ... }
</code>```

would be lovely.

having the label after the input would be dooable:

```<code>input:focus + label { ... }
</code>```

you could use some positioning to display before...

Body:
    Label
    <input class="my-input" value="input" />

#my-field{
}
.my-label {
}
.my-input{
}

Is there any way I can customize the CSS of .my-label when input is in focus without touching the HTML? There are multiple ways to select successor sibling elements. But any way to select predecessor(s)?

Note: There is a restriction in the project that HTML cannot be modified here. Everything has to be done in CSS only. No jQuery/JS either.

Body:
No. there is unfortunately no predecessor selector in css

input:focus -+ label { ... }

would be lovely.

having the label after the input would be dooable:

input:focus + label { ... }

you could use some positioning to display before...