问:
Execution failed for task ':app:mergeDebugResources' when building project on Jenkins
I'm trying to build an Android application with jenkins but I'm getting "Execution failed for task ':app:mergeDebugResources'" error each time I try it.

I saw that the problem could be that the path is too large and AAPT2 is displaying an error because of that. I tried moving the directory of my project and adding "multiDexEnabled true" on my build gradle but it seems that nothing of this works

Gradle version:

```<code>dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
    }
</code>```

This is my build gradle

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

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

And this is the error I get each time I try to build my project with Jenkins

```<code>Execution failed for task ':app:mergeDebugResources'.
> 8 exceptions were raised by workers:
  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\drawable-xxhdpi-v4\abc_text_select_handle_middle_mtrl_light.png: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\layout\abc_action_bar_up_container.xml: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\drawable-xhdpi-v4\abc_ab_share_pack_mtrl_alpha.9.png: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\anim\abc_tooltip_exit.xml: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\layout\abc_search_dropdown_item_icons_2line.xml: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\drawable-hdpi-v4\abc_ic_menu_share_mtrl_alpha.png: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\drawable\abc_btn_colored_material.xml: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\drawable-hdpi-v4\abc_textfield_search_default_mtrl_alpha.9.png: error: file not found.
</code>```

答:
Run following commands from your jenkins terminal.

```<code>    gradlew clean
    gradle assembleDebug
</code>```

If above command does not work, then delete gradle folder.

```<code>    rm -rf C:\Windows\System32\config\systemprofile\.gradle
</code>```

and then build using command

```<code>    gradle assembleDebug
</code>```

Body:
I'm trying to build an Android application with jenkins but I'm getting "Execution failed for task ':app:mergeDebugResources'" error each time I try it.

I saw that the problem could be that the path is too large and AAPT2 is displaying an error because of that. I tried moving the directory of my project and adding "multiDexEnabled true" on my build gradle but it seems that nothing of this works

Gradle version:

dependencies {
        classpath 'com.android.tools.build:gradle:3.4.1'
    }

This is my build gradle

apply plugin: 'com.android.application'

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

And this is the error I get each time I try to build my project with Jenkins

Execution failed for task ':app:mergeDebugResources'.
> 8 exceptions were raised by workers:
  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\drawable-xxhdpi-v4\abc_text_select_handle_middle_mtrl_light.png: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\layout\abc_action_bar_up_container.xml: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\drawable-xhdpi-v4\abc_ab_share_pack_mtrl_alpha.9.png: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\anim\abc_tooltip_exit.xml: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\layout\abc_search_dropdown_item_icons_2line.xml: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\drawable-hdpi-v4\abc_ic_menu_share_mtrl_alpha.png: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\drawable\abc_btn_colored_material.xml: error: file not found.

  com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource compilation failed
  C:\Windows\System32\config\systemprofile\.gradle\caches\transforms-2\files-2.1\2e8dd75caf52c41c02aeae6cef700c6a\res\drawable-hdpi-v4\abc_textfield_search_default_mtrl_alpha.9.png: error: file not found.

Body:
Run following commands from your jenkins terminal.

    gradlew clean
    gradle assembleDebug

If above command does not work, then delete gradle folder.

    rm -rf C:\Windows\System32\config\systemprofile\.gradle

and then build using command

    gradle assembleDebug


来源: stackexchange

问:
Multiple Ace Editor content returns only one line
I have implemented two ACE editors on my single page. The first editor:

```<code>$('#custom_css').val(custom_css_editor.getSession().getValue());
</code>```

returns all the codes I've typed, but unfortunately the other editor:

```<code>$('#custom_script').val(custom_js_editor.getSession().getValue());
</code>```

returns only one line. What do you think is the cause of such glitch?

Here's what I want to show up:

Here are the codes I have:

var custom_css_editor = ace.edit("custom_css_editor", {
  theme: "ace/theme/twilight",
  mode: "ace/mode/css",
  maxLines: 10
});
var custom_js_editor = ace.edit("custom_js_editor", {
  theme: "ace/theme/twilight",
  mode: "ace/mode/javascript",
  maxLines: 10
});

document.querySelector('#custom_css_editor .ace_text-input')
  .setAttribute('name', 'custom_css');
document.querySelector('#custom_css_editor .ace_text-input')
  .setAttribute('id', 'custom_css');
document.querySelector('#custom_js_editor .ace_text-input')
  .setAttribute('name', 'custom_script');
document.querySelector('#custom_js_editor .ace_text-input')
  .setAttribute('id', 'custom_script');

custom_css_editor.session.on('change', function() {
  $('#custom_css').val(custom_css_editor.getValue());
});
$('#custom_css').val(custom_css_editor.session.getValue());
custom_js_editor.getSession().on('change', function() {
  $('#custom_script').val(custom_js_editor.getValue());
});
$('#custom_script').val(custom_js_editor.session.getValue());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
  <label class="lbl-input" for="custom_css">Custom CSS</label>
  <div id="custom_css_editor"></div>
</div>
<div class="form-group">
  <label class="lbl-input" for="custom_script">Custom Scripts</label>
  <div id="custom_js_editor"></div>
</div>

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.4/ace.js"></script></code>```

答: Okay, i have to add <input type="hidden" id="custom_css" value="" /> and custom_script" value="" /> to render the full content of css and js editors, magic it worked!

ContentLicense: CC BY-SA 4.0

Body:
I have implemented two ACE editors on my single page. The first editor:

$('#custom_css').val(custom_css_editor.getSession().getValue());

returns all the codes I've typed, but unfortunately the other editor:

$('#custom_script').val(custom_js_editor.getSession().getValue());

returns only one line. What do you think is the cause of such glitch?

Here's what I want to show up:

Here are the codes I have:

var custom_css_editor = ace.edit("custom_css_editor", {
  theme: "ace/theme/twilight",
  mode: "ace/mode/css",
  maxLines: 10
});
var custom_js_editor = ace.edit("custom_js_editor", {
  theme: "ace/theme/twilight",
  mode: "ace/mode/javascript",
  maxLines: 10
});

document.querySelector('#custom_css_editor .ace_text-input')
  .setAttribute('name', 'custom_css');
document.querySelector('#custom_css_editor .ace_text-input')
  .setAttribute('id', 'custom_css');
document.querySelector('#custom_js_editor .ace_text-input')
  .setAttribute('name', 'custom_script');
document.querySelector('#custom_js_editor .ace_text-input')
  .setAttribute('id', 'custom_script');

custom_css_editor.session.on('change', function() {
  $('#custom_css').val(custom_css_editor.getValue());
});
$('#custom_css').val(custom_css_editor.session.getValue());
custom_js_editor.getSession().on('change', function() {
  $('#custom_script').val(custom_js_editor.getValue());
});
$('#custom_script').val(custom_js_editor.session.getValue());

  Custom CSS

  Custom Scripts


问:
Comment lines in orgmode
Consult org document with the comments lines:

The Org Manual: Comment lines

12.6 Comment lines

Lines starting with zero or more whitespace characters followed by one ‘#’ and a whitespace are treated as comments and, as such, are not exported.

Likewise, regions surrounded by #+BEGIN_COMMENT ... #+END_COMMENT are not exported.

Finally, a ‘COMMENT’ keyword at the beginning of an entry, but after any other keyword or priority cookie, comments out the entire subtree. In this case, the subtree is not exported and no code block within it is executed either129. The command below helps changing the comment status of a headline.

C-c ;

Toggle the ‘COMMENT’ keyword at the beginning of an entry.

#+BEGIN_COMMENT  …  #+END_COMMENT works correctly.

However,

Lines starting with zero or more whitespace characters followed by one ‘#’ and a whitespace are treated as comments and, as such, are not exported.

Do I misunderstand that statement?

答:
You read it well: working comment syntax are

```<code>#+BEGIN_COMMENT
this is a comment
#+END_COMMENT
</code>```

or

```<code># this is a comment (needs at least one first whitespace after #)
</code>```

However

```<code>#this is not a comment (it is exported as "#this is not a comment")
</code>```

Title: Comment lines in orgmode

Body:
You read it well: working comment syntax are

#+BEGIN_COMMENT
this is a comment
#+END_COMMENT

or

# this is a comment (needs at least one first whitespace after #)

However

#this is not a comment (it is exported as "#this is not a comment")


问:
Return value is not the same as predicted from a defined function
```<code>james=open('C:/Users/skora da_bura/Documents/data.txt')
jake=james.read()
james.close()

numblist=[]
charlist=[]

def Read(numblist,charlist):
   for i in range(0,len(jake),4):

      numblist.append(int(jake[i]))

   for i in range(2,len(jake),4):
      charlist.append(jake[i])
      Bring = numblist,charlist

   james = open('C:/Users/skora da_bura/Documents/data.txt')
   jake22 = james.readlines()
   james.close()
   back='Number of lines read',len(jake22)

   return back

    print(Read([],[]))
    print(charlist)
</code>```

the charlist returns [] even though I had appended values to it to make a list when I was defining the function Read.
I don't seem to see what the problem is with the code

答: The charlist you define in the signature of Read shadows the global charlist. They're different variables that happen to have the same name. If you intend to modify the global variable, you shouldn't try to pass it as a parameter.

Body:
james=open('C:/Users/skora da_bura/Documents/data.txt')
jake=james.read()
james.close()

numblist=[]
charlist=[]

def Read(numblist,charlist):
   for i in range(0,len(jake),4):

      numblist.append(int(jake[i]))

   for i in range(2,len(jake),4):
      charlist.append(jake[i])
      Bring = numblist,charlist

   james = open('C:/Users/skora da_bura/Documents/data.txt')
   jake22 = james.readlines()
   james.close()
   back='Number of lines read',len(jake22)

   return back

    print(Read([],[]))
    print(charlist)

the charlist returns [] even though I had appended values to it to make a list when I was defining the function Read.
I don't seem to see what the problem is with the code


问:
if else for ant script
hi current i have this ant script:

```<code>        <target name="Cleanup Snapshots" description="Cleanup TrueCM snapshots">
        <echo>Executing: ${TrueCM_App}\ssremove.exe  -h${TrueCM_Host} "${TrueCM_New_SS}"</echo>
        <exec executable="${TrueCM_App}\ssremove.exe"   failonerror="${TrueCM_Failon_Exec}">
            <arg line="-h ${TrueCM_Host}"/>
            <arg line='-f "${TrueSASE}/${Product_version}/${name}"'/>
        </exec>

    </target>
</code>```

what this script does is that it will execute ssremove.exe with some parameters as shown.

however, this script above is only valid when the parameter ${Product_version} contains the word "Extensions" for example 6.00_Extensions

Else if they dont contain "Extensions" the script should look like this:

```<code>    <target name="Cleanup Snapshots" description="Cleanup TrueCM snapshots">
        <echo>Executing: ${TrueCM_App}\ssremove.exe  -h${TrueCM_Host} "${TrueCM_New_SS}"</echo>
        <exec executable="${TrueCM_App}\ssremove.exe"   failonerror="${TrueCM_Failon_Exec}">
            <arg line="-h ${TrueCM_Host}"/>
            <arg line='-f "${TrueSASE}/${name}"'/>
        </exec>

    </target>
</code>```

so my question is how should i add the if else statements that contain exactly the line "Extensions"? or how do i check if "Extensions" word is present?

答:
Just to outline a solution if you can't add a custom library to your Ant build. Note that you need a pretty recent version of Ant (>= 1.7, I think).

First, you need to put the result of the test in a property (use a condition with contains; see the Ant Manual). Then you can use that property in exec to skip it when the property is true.

```<code><condition property="hasExtensions">
    <contains string="${Product_version}" substring="Extensions">
</condition>

<exec ... unless="hasExtensions">
    ...
</exec>
</code>```

ContentLicense: CC BY-SA 3.0

Title: if else for ant script

Body:
hi current i have this ant script:

        <target name="Cleanup Snapshots" description="Cleanup TrueCM snapshots">
        <echo>Executing: ${TrueCM_App}\ssremove.exe  -h${TrueCM_Host} "${TrueCM_New_SS}"</echo>
        <exec executable="${TrueCM_App}\ssremove.exe"   failonerror="${TrueCM_Failon_Exec}">
            <arg line="-h ${TrueCM_Host}"/>
            <arg line='-f "${TrueSASE}/${Product_version}/${name}"'/>
        </exec>

    </target>

what this script does is that it will execute ssremove.exe with some parameters as shown.

however, this script above is only valid when the parameter ${Product_version} contains the word "Extensions" for example 6.00_Extensions

Else if they dont contain "Extensions" the script should look like this:

    <target name="Cleanup Snapshots" description="Cleanup TrueCM snapshots">
        <echo>Executing: ${TrueCM_App}\ssremove.exe  -h${TrueCM_Host} "${TrueCM_New_SS}"</echo>
        <exec executable="${TrueCM_App}\ssremove.exe"   failonerror="${TrueCM_Failon_Exec}">
            <arg line="-h ${TrueCM_Host}"/>
            <arg line='-f "${TrueSASE}/${name}"'/>
        </exec>

    </target>

so my question is how should i add the if else statements that contain exactly the line "Extensions"? or how do i check if "Extensions" word is present?

Body:
Just to outline a solution if you can't add a custom library to your Ant build. Note that you need a pretty recent version of Ant (>= 1.7, I think).

First, you need to put the result of the test in a property (use a condition with contains; see the Ant Manual). Then you can use that property in exec to skip it when the property is true.

<condition property="hasExtensions">
    <contains string="${Product_version}" substring="Extensions">
</condition>

<exec ... unless="hasExtensions">
    ...
</exec>


问:
Android ViewPager when swiping on last screen
Im having trouble figuring out how to capture a swipe event on the last page of a view pager.

Basically the requirement is that when the user is on the last page, and they try to swipe to get to the next page, the activity should close.

I've tried doing this onPageScrolled but I cant seem to differentiate a left or right swipe when in there. When on the last page, the user should still maintain the functionality to move to the previous page.

So basically the case is

```<code>When on last page
    if swipe prev (do normal behaviour)
    if swipe next (finish activity)
</code>```

Can anyone provide any suggestions?
Thanks

答:
```<code>int lastPosition;
int currentPosition;

//View pager assign
ViewPager viewPager = findViewById(R.id.viewPager);
//PageIndicatorView external https://github.com/romandanylyk
PageIndicatorView pageIndicatorView = findViewById(R.id.pageIndicatorView);

//customise pageIndicatorView design
pageIndicatorView.setAnimationType(AnimationType.THIN_WORM);
pageIndicatorView.setViewPager(viewPager);

//BannerAdapter is an custom adapter for viewpage i made.
//assign data here
BannerAdapter pagerAdapter = new BannerAdapter(this, banner, new OnClickListener() {
            @Override
            public void onClick() {

            }
        });
viewPager.setAdapter(pagerAdapter);

//listener for View Pager
//this is where process of making the infinite loop
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            //assign position so that can be manipulated
            currentPosition = position;
        }
        @Override
        public void onPageSelected(int position) {
            //set pager indicator position here
            pageIndicatorView.setSelection(position);
        }
        @Override
        public void onPageScrollStateChanged(int state) {
            //check state 0 mean no ongoing process
            if(state == 0){
                //check currentPosition == lastPosition to detect that scroll cant scroll anymore
                if(currentPosition == lastPosition){
                    int lastitem = banner.size() - 1;
                    //check position if either last item/first item
                    //and set viewpager current page as follow
                    if(currentPosition == lastitem){
                        viewPager.setCurrentItem(0);
                    }else if(currentPosition == 0){
                        viewPager.setCurrentItem(lastitem);
                    }
                }else{
                    lastPosition = currentPosition;
                }
                Log.d("ScrollState", "currentPosition: " + currentPosition);
            }
            /*empty*/
        }
    });
</code>```

Body:
Im having trouble figuring out how to capture a swipe event on the last page of a view pager.

Basically the requirement is that when the user is on the last page, and they try to swipe to get to the next page, the activity should close.

I've tried doing this onPageScrolled but I cant seem to differentiate a left or right swipe when in there. When on the last page, the user should still maintain the functionality to move to the previous page.

So basically the case is

When on last page
    if swipe prev (do normal behaviour)
    if swipe next (finish activity)

Can anyone provide any suggestions?
Thanks


问:
Untracking directories with Git-SVN
Let's imagine that I have a very big (> 1Gb) SVN repository, I check it out in full with git svn but then decides that I want to stop tracking some directories / files on the "git side", that is, not tracking locally and not pushing when I push the branch to a remote.

I imagine that deleting those with git rm would work, however, my question is: does this break things for git-svn or will git-svn still be able to update from SVN?

答:
You might want to try a sparse clone in a separate local Git repository, as in this question, with git svn clone --include-path.

Anything else would change the checksum of the existing revision (if you used git filter-branch) or would dcommit a deletion (if you use git rm)

Or you could mark the directory as ignored, adding the .gitignore to the Subversion repository, for others to also ignore the same folder.

Title: Untracking directories with Git-SVN


问:
How to fix "Cannot read property 'trim' of undefined" error in node
I'm implementing a simple WebAPI in Firebase cloud functions with express by TypeScript.
My code is following.

```<code>import * as functions from 'firebase-functions';
import * as express from 'express';

const app = express()

app.post('/', (req, res) => {
    var resText: string = "NotEmpty"
    const text: string = req.body.text

    if (isEmpty(text)) {
        resText = "Empty"
    }
    console.log("text: ", text)
    console.log("resText: ", resText)
    res.send("Echo " + resText)
})

exports.api = functions.https.onRequest(app)

const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    const trimedStr = str.trim()
    const result = (trimedStr === null || trimedStr === "")
    console.log("result: ", result)
    return result
}

</code>```

Build to transform typescript to javascript worked fine.
However, when I did POST method, following error occurred.

```<code>>  TypeError: Cannot read property 'trim' of undefined
>      at isEmpty (/Users/kenny/Test/firebase_functions/functions/lib/index.js:22:27)
>      at app.post (/Users/kenny/Test/firebase_functions/functions/lib/index.js:9:9)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/route.js:137:
13)
>      at Route.dispatch (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/rou
te.js:112:3)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at /Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:281:22
>      at Function.process_params (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/r
outer/index.js:335:12)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:275:
10)
>      at expressInit (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/middleware/in
it.js:40:5)

</code>```

How can I fix this error ?

答:
In JavaScript, a truthy value is a value that is considered  true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

so why can't you use like below ?

```<code> if (!text) {
        resText = "Empty"
    }
</code>```

Body:
I'm implementing a simple WebAPI in Firebase cloud functions with express by TypeScript.
My code is following.

import * as functions from 'firebase-functions';
import * as express from 'express';

const app = express()

app.post('/', (req, res) => {
    var resText: string = "NotEmpty"
    const text: string = req.body.text

    if (isEmpty(text)) {
        resText = "Empty"
    }
    console.log("text: ", text)
    console.log("resText: ", resText)
    res.send("Echo " + resText)
})

exports.api = functions.https.onRequest(app)

const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    const trimedStr = str.trim()
    const result = (trimedStr === null || trimedStr === "")
    console.log("result: ", result)
    return result
}

Build to transform typescript to javascript worked fine.
However, when I did POST method, following error occurred.

>  TypeError: Cannot read property 'trim' of undefined
>      at isEmpty (/Users/kenny/Test/firebase_functions/functions/lib/index.js:22:27)
>      at app.post (/Users/kenny/Test/firebase_functions/functions/lib/index.js:9:9)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/route.js:137:
13)
>      at Route.dispatch (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/rou
te.js:112:3)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at /Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:281:22
>      at Function.process_params (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/r
outer/index.js:335:12)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:275:
10)
>      at expressInit (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/middleware/in
it.js:40:5)

How can I fix this error ?

Body:
In JavaScript, a truthy value is a value that is considered  true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

so why can't you use like below ?

 if (!text) {
        resText = "Empty"
    }


问:
Java programming, opencv unsatisfied link error
OpenCV libraries gives unsatisfied link error in capturing a video stream.

Where should be the opencv 3.2.0 libraries? What is the correct path for  packages of opencv classes?

Code where to generate this error:

```<code>package opencv;

import org.opencv.core.*;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
public class VideoCap
{

    public static void main (String args[]){

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // error

        VideoCapture camera = new VideoCapture(0);

        if(!camera.isOpened()){
            System.out.println("Error");
        }
    else {
            Mat frame = new Mat();
            while(true){
                if (camera.read(frame)){
                    System.out.println("Frame Obtained");
                    System.out.println("Captured Frame Width " +
                    frame.width() + " Height " + frame.height());
                    Imgcodecs.imwrite("camera.jpg", frame);
                    System.out.println("OK");
                    break;
                }
            }
        }
        camera.release();
    }
}
</code>```

The exception is:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError:
    no opencv_java320 in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at opencv.VideoCap.main(VideoCap.java:9)
</code>```

答:
Try to clone the repository below:

https://github.com/hellonico/opencv4_java_tutorial.git

Add your class in the java folder, and instead of using System.loadLibrary ... use:

```<code>NativeLoader.loadLibrary(Core.NATIVE_LIBRARY_NAME);
</code>```

This will load a properly compiled version of OpenCV to run within the JVM.

Body:
OpenCV libraries gives unsatisfied link error in capturing a video stream.

Where should be the opencv 3.2.0 libraries? What is the correct path for  packages of opencv classes?

Code where to generate this error:

package opencv;

import org.opencv.core.*;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
public class VideoCap
{

    public static void main (String args[]){

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // error

        VideoCapture camera = new VideoCapture(0);

        if(!camera.isOpened()){
            System.out.println("Error");
        }
    else {
            Mat frame = new Mat();
            while(true){
                if (camera.read(frame)){
                    System.out.println("Frame Obtained");
                    System.out.println("Captured Frame Width " +
                    frame.width() + " Height " + frame.height());
                    Imgcodecs.imwrite("camera.jpg", frame);
                    System.out.println("OK");
                    break;
                }
            }
        }
        camera.release();
    }
}

The exception is:

Exception in thread "main" java.lang.UnsatisfiedLinkError:
    no opencv_java320 in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at opencv.VideoCap.main(VideoCap.java:9)

Body:
Try to clone the repository below:

https://github.com/hellonico/opencv4_java_tutorial.git

Add your class in the java folder, and instead of using System.loadLibrary ... use:

NativeLoader.loadLibrary(Core.NATIVE_LIBRARY_NAME);

This will load a properly compiled version of OpenCV to run within the JVM.


问:
How to make a graph (nodes and edges) on Latex?
I new coding in latex and I want to make high-quality graphs (nodes and edges), in particular, I need to make this kind of plots.

Is it that even possible?

答:
That is not only "even possible", that is always possible. This sort of diagram can be easily created using TikZ and similar packages.

If you already have the coordinates of the nodes, the directions of the arrows etc., you may start from this. This is not your diagram, but is a good starting point.

\documentclass[tikz,margin=3]{standalone}
\usetikzlibrary{shadows} % Shadows for nodes
\begin{document}
\begin{tikzpicture}
\tikzset{% This is the style settings for nodes
    dep/.style={circle,minimum size=1cm,fill=orange!20,draw=orange,
                general shadow={fill=gray!60,shadow xshift=1pt,shadow yshift=-1pt}},
    cli/.style={circle,minimum size=1cm,fill=white,draw,
                general shadow={fill=gray!60,shadow xshift=1pt,shadow yshift=-1pt}},
    spl/.style={cli,append after command={
                  node[circle,draw,dotted,
                       minimum size=1.5cm] at (\tikzlastnode.center) {}}},
    c1/.style={-stealth,very thick,red!80!black},
    v2/.style={-stealth,very thick,yellow!65!black},
    v4/.style={-stealth,very thick,purple!70!black}}
\node[dep] (0) at (0,0) {0};
\node[cli] (7) at (-1,-2) {7};
\node[spl] (8) at (2,-2) {8};
\draw[c1] (0) to[bend right] (7);
\draw[v2] (7) -- (8);
\draw[v4] (8) -- (2,-1) -- (0);
\end{tikzpicture}
\end{document}
```

<p><img src="https://i.stack.imgur.com/5IhcC.png" alt="enter image description here"></p>

<p>You can use a <code>matrix</code> or whatever you want to add a legend</p>

<pre class="lang-latex prettyprint-override"><code>\documentclass[tikz,margin=3]{standalone}
\usetikzlibrary{shadows,matrix} % Shadows for nodes
\begin{document}
\begin{tikzpicture}
\tikzset{% This is the style settings for nodes
    dep/.style={circle,minimum size=#1,fill=orange!20,draw=orange,
                general shadow={fill=gray!60,shadow xshift=1pt,shadow yshift=-1pt}},
    dep/.default=1cm,
    cli/.style={circle,minimum size=#1,fill=white,draw,
                general shadow={fill=gray!60,shadow xshift=1pt,shadow yshift=-1pt}},
    cli/.default=1cm,
    spl/.style={cli=#1,append after command={
                  node[circle,draw,dotted,
                       minimum size=1.5cm] at (\tikzlastnode.center) {}}},
    spl/.default=1cm,
    c1/.style={-stealth,very thick,red!80!black},
    v2/.style={-stealth,very thick,yellow!65!black},
    v4/.style={-stealth,very thick,purple!70!black}}
\begin{scope}[local bounding box=graph]
    \node[dep] (0) at (0,0) {0};
    \node[cli] (7) at (-1,-2) {7};
    \node[spl] (8) at (2,-2) {8};
    \draw[c1] (0) to[bend right] (7);
    \draw[v2] (7) -- (8);
    \draw[v4] (8) -- (2,-1) -- (0);
\end{scope}
\matrix[draw,anchor=north west,xshift=1ex,matrix of nodes,row sep=.5ex,
        column 2/.style={text width=2.5cm,align=left,anchor=center}]
at (graph.north east) {
    \draw[c1] (-.5,0) -- (.5,0); & $C_1$\\
    \draw[v2] (-.5,0) -- (.5,0); & $V_2$\\
    \draw[v4] (-.5,0) -- (.5,0); & $V_4$\\
    \draw[dotted] circle (.25);  & Split Delivery\\
    \node[cli=.5cm] {};          & Cliente\\
    \node[dep=.5cm] {};          & Deposito\\
};
\end{tikzpicture}
\end{document}
</code>```

It seems that you haven't known much about TikZ yet, then this question on TeX.SE may be useful to you.

Body:
That is not only "even possible", that is always possible. This sort of diagram can be easily created using TikZ and similar packages.

If you already have the coordinates of the nodes, the directions of the arrows etc., you may start from this. This is not your diagram, but is a good starting point.

\documentclass[tikz,margin=3]{standalone}
\usetikzlibrary{shadows} % Shadows for nodes
\begin{document}
\begin{tikzpicture}
\tikzset{% This is the style settings for nodes
    dep/.style={circle,minimum size=1cm,fill=orange!20,draw=orange,
                general shadow={fill=gray!60,shadow xshift=1pt,shadow yshift=-1pt}},
    cli/.style={circle,minimum size=1cm,fill=white,draw,
                general shadow={fill=gray!60,shadow xshift=1pt,shadow yshift=-1pt}},
    spl/.style={cli,append after command={
                  node[circle,draw,dotted,
                       minimum size=1.5cm] at (\tikzlastnode.center) {}}},
    c1/.style={-stealth,very thick,red!80!black},
    v2/.style={-stealth,very thick,yellow!65!black},
    v4/.style={-stealth,very thick,purple!70!black}}
\node[dep] (0) at (0,0) {0};
\node[cli] (7) at (-1,-2) {7};
\node[spl] (8) at (2,-2) {8};
\draw[c1] (0) to[bend right] (7);
\draw[v2] (7) -- (8);
\draw[v4] (8) -- (2,-1) -- (0);
\end{tikzpicture}
\end{document}

You can use a matrix or whatever you want to add a legend

\documentclass[tikz,margin=3]{standalone}
\usetikzlibrary{shadows,matrix} % Shadows for nodes
\begin{document}
\begin{tikzpicture}
\tikzset{% This is the style settings for nodes
    dep/.style={circle,minimum size=#1,fill=orange!20,draw=orange,
                general shadow={fill=gray!60,shadow xshift=1pt,shadow yshift=-1pt}},
    dep/.default=1cm,
    cli/.style={circle,minimum size=#1,fill=white,draw,
                general shadow={fill=gray!60,shadow xshift=1pt,shadow yshift=-1pt}},
    cli/.default=1cm,
    spl/.style={cli=#1,append after command={
                  node[circle,draw,dotted,
                       minimum size=1.5cm] at (\tikzlastnode.center) {}}},
    spl/.default=1cm,
    c1/.style={-stealth,very thick,red!80!black},
    v2/.style={-stealth,very thick,yellow!65!black},
    v4/.style={-stealth,very thick,purple!70!black}}
\begin{scope}[local bounding box=graph]
    \node[dep] (0) at (0,0) {0};
    \node[cli] (7) at (-1,-2) {7};
    \node[spl] (8) at (2,-2) {8};
    \draw[c1] (0) to[bend right] (7);
    \draw[v2] (7) -- (8);
    \draw[v4] (8) -- (2,-1) -- (0);
\end{scope}
\matrix[draw,anchor=north west,xshift=1ex,matrix of nodes,row sep=.5ex,
        column 2/.style={text width=2.5cm,align=left,anchor=center}]
at (graph.north east) {
    \draw[c1] (-.5,0) -- (.5,0); & $C_1$\\
    \draw[v2] (-.5,0) -- (.5,0); & $V_2$\\
    \draw[v4] (-.5,0) -- (.5,0); & $V_4$\\
    \draw[dotted] circle (.25);  & Split Delivery\\
    \node[cli=.5cm] {};          & Cliente\\
    \node[dep=.5cm] {};          & Deposito\\
};
\end{tikzpicture}
\end{document}

It seems that you haven't known much about TikZ yet, then this question on TeX.SE may be useful to you.


问:
resuming an activity from a notification
I have a notification in the status bar for my app:

```<code>    Notification notification = new Notification(R.drawable.icon, null, System.currentTimeMillis());

    Intent notificationIntent = new Intent(this.parent, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this.parent, 0, notificationIntent, 0);

    ...

    notification.flags = Notification.FLAG_ONGOING_EVENT;
    mNotificationManager.notify(NOTIFICATION_ID, notification);
</code>```

The problem with this is that when you press the home button from the app (pushing it to the background) then press on the notification in the list accessed from the status bar, it starts a fresh copy of the activity. All I want to do is resume the app (like when you longpress the home button and press on the app's icon). Is there a way of creating an Intent to do this?

答:
I've solved this issue by changing the launchMode of my activity to singleTask in the androidManifest.xml file.

The default value for this property is standard, which allows any number of instances to run.

"singleTask" and "singleInstance" activities can only begin a task. They are always at the root of the activity stack. Moreover, the device can hold only one instance of the activity at a time — only one such task. [...]

The "singleTask" and "singleInstance" modes also differ from each other in only one respect: A "singleTask" activity allows other activities to be part of its task. It's always at the root of its task, but other activities (necessarily "standard" and "singleTop" activities) can be launched into that task. A "singleInstance" activity, on the other hand, permits no other activities to be part of its task. It's the only activity in the task. If it starts another activity, that activity is assigned to a different task — as if FLAG_ACTIVITY_NEW_TASK was in the intent.

you can find a detailed explanation in the Android Developers' Guide

I hope this helps

ContentLicense: CC BY-SA 2.5

Body:
I have a notification in the status bar for my app:

    Notification notification = new Notification(R.drawable.icon, null, System.currentTimeMillis());

    Intent notificationIntent = new Intent(this.parent, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this.parent, 0, notificationIntent, 0);

    ...

    notification.flags = Notification.FLAG_ONGOING_EVENT;
    mNotificationManager.notify(NOTIFICATION_ID, notification);

The problem with this is that when you press the home button from the app (pushing it to the background) then press on the notification in the list accessed from the status bar, it starts a fresh copy of the activity. All I want to do is resume the app (like when you longpress the home button and press on the app's icon). Is there a way of creating an Intent to do this?


问:
How to use hibernate-sessions properly?
From what I have read you create a session per request and close the session after the request has finished.

Would this be right usage of sessions in hibernate?

start server and create SessionFactory

user want to query data from database
2.1 Session userSession = MyHibernateClass.getFactory().openSession();

do one query

session.close();

When do I use getCurrentSession() and when openSession() ?

答:
```<code>SessionFactory.openSession()
</code>```

always opens a new session that you have to close once you are done with the operations.
    SessionFactory.getCurrentSession()
returns a session bound to a context - you don't need to close this.
For more detailed information you can follow given link
openSession() v/s getCurrentSession()

Title: How to use hibernate-sessions properly?

Body:
SessionFactory.openSession()

always opens a new session that you have to close once you are done with the operations.
    SessionFactory.getCurrentSession()
returns a session bound to a context - you don't need to close this.
For more detailed information you can follow given link
openSession() v/s getCurrentSession()


问:
Read model with data from multiple aggregate roots (different contexts)
I'm curious to how to join data from multiple aggregate roots in an read model for an event sourced aggregate root. Can try to take a simple example:

If I have an aggregate root called Cart which supports following events in it's event stream (properties in parentheses - keep in mind this is an simple example):

```<code>AddProductToCart(cartId: Int, productId: Int)
RemoveProductFromCart(cartId: Int, productId: Int)
AddUserLicenseToProduct(cartId: Int, productId: Int, userId: Int)
RemoveUserLicenseFromProduct(cartId: Int, productId: Int, userId: Int)
EmptyCart(cartId: Int)
</code>```

It's ok when projecting read models with data coming from this event stream. I can for example project a cart object which looks something like this:

```<code>Cart(cartId: Int, products: List[Product])

Product(productId: Int, userLicenses: List[UserLicense])
UserLicense(userId: Int)
</code>```

But how does one join data from another aggregate root in another context into this cart projection. For example if I wanted to extend the read model with data from the Product aggregate root which lives in another context. Let's say I would like to extend it with productName and productType.

Take into consideration we are working in an distributed system, where Product and Cart would be live in different services/applications.

I suppose one solution would be to include the data in the commands and events. But that doesn't seem to scale very well if one would have larger read models with data from multiple aggregate roots. Also one has to be able to nuke and rebuild the read model.

I suppose another solution would be to duplicate data from other aggregate roots into the storage of other applications/services/contexts. For example duplicate the productName and productType data into storage owned be the Cart application, but not have it be a part of the Cart event stream. The Cart application would then have to listen to events (e.g. ProductCreated, ProductNameChanged) to keep data updated. I guess this might be a viable solution.

答:
This question also comes up with event-driven architectures and not only event-sourcing.  I reckon that you've covered most options in terms of capturing the relevant data from the producer of the event.

Another option would be that an event contain as little data as possible from the related bounded context.  At a minimum that would be an identifier.  However, in most cases some of the data should be denormalized to make sense.  For instance, having the product description denormalized into the Cart and eventual Order would be helpful especially when someone changes the description after I have made my choice.  The description may change from Blue pen to Red pen which would drastically alter what I intended to purchase.  In this case the Product in your Shopping BC may be represented by a value object that contains the Id along with the Description.

If you now would like to augment the read-only data we are left only with the option of retrieving it from the source BC.  This can be done in the read-model using some API (Rest/ACL) and then the data saved.  To make it more fault tolerant one may opt for a messaging/service bus infrastructure to handle the retrieval of the additional data and updating of the relevant read-model record.

Body:
I'm curious to how to join data from multiple aggregate roots in an read model for an event sourced aggregate root. Can try to take a simple example:

If I have an aggregate root called Cart which supports following events in it's event stream (properties in parentheses - keep in mind this is an simple example):

AddProductToCart(cartId: Int, productId: Int)
RemoveProductFromCart(cartId: Int, productId: Int)
AddUserLicenseToProduct(cartId: Int, productId: Int, userId: Int)
RemoveUserLicenseFromProduct(cartId: Int, productId: Int, userId: Int)
EmptyCart(cartId: Int)

It's ok when projecting read models with data coming from this event stream. I can for example project a cart object which looks something like this:

Cart(cartId: Int, products: List[Product])

Product(productId: Int, userLicenses: List[UserLicense])
UserLicense(userId: Int)

But how does one join data from another aggregate root in another context into this cart projection. For example if I wanted to extend the read model with data from the Product aggregate root which lives in another context. Let's say I would like to extend it with productName and productType.

Take into consideration we are working in an distributed system, where Product and Cart would be live in different services/applications.

I suppose one solution would be to include the data in the commands and events. But that doesn't seem to scale very well if one would have larger read models with data from multiple aggregate roots. Also one has to be able to nuke and rebuild the read model.

I suppose another solution would be to duplicate data from other aggregate roots into the storage of other applications/services/contexts. For example duplicate the productName and productType data into storage owned be the Cart application, but not have it be a part of the Cart event stream. The Cart application would then have to listen to events (e.g. ProductCreated, ProductNameChanged) to keep data updated. I guess this might be a viable solution.


问:
I am trying to store current date and time in asyncstorage, but the return value I get is a promise and I can't see the values
I tried passing the values as Json (key-pair values) but I don't get to to see the values in response.</p>

答:
To store current date and time in AsyncStorage you can use an async function,

```<code>StoreDate = async () => {
  await AsyncStorage.setItem('date', new Date());
};
</code>```

To retrieve stored date,

```<code>retrieveDate = async () => {
    const value = await AsyncStorage.getItem('date');
};
</code>```

Body:
To store current date and time in AsyncStorage you can use an async function,

StoreDate = async () => {
  await AsyncStorage.setItem('date', new Date());
};

To retrieve stored date,

retrieveDate = async () => {
    const value = await AsyncStorage.getItem('date');
};


问:
How to limit user commands in Linux
I have a user in a group: "demo".

I want to set the policy that this user can run only 10 commands, like vim, nano, cd, etc.

Or, set the policy to have access on all commands except ssh and cat commands.

答:
I have faced a similar situation at my organization where I had to restrict people to access only certain commands.

So far, I have found 2 different ways to do it.

The only approach

Having a different Shell altogether viz. rbash, lshell, dockersh

Here are my thoughts on the same.

Take the only approach if you want the users to login and execute a certain command and then exit the shell entirely. Its better to you couple it with Rbash.

Out of the 3 shells, I feel lshell would be the easiest to implement especially if you are on Ubuntu and its derivatives. You just have to install a package via apt and then edit the configuration. It is the simplest.

The rbash is good for basic stuff like blocking redirection and certain characters on the cli but to do the advanced stuff like whitelisting certain commands, you would need to go the extra mile.

Dockersh is a completely fresh and modern approach to restricting shells. Here you allow everything but you limit all the user's action to a container.

In my use-case, I had to limit my users to a single command with shell based redirection , piping etc. turned-off hence I chose lshell. Took hardly 5 minutes to configure. Find details here.

Title: How to limit user commands in Linux


问:
Multiline text to fit parent container in React JS
I am using a flexbox layout and am trying to get the text in a specific div to be resized to fit that div.

So for example, if I have code as follows:

```<code><div style={{display: "flex"}}>
   <div style={{flex: 1}}>
      A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
   </div>
   <div style={{flex: 1}}>
      Some other text
   </div>
</div>
</code>```

In reality, the text will be pulled from a database, so will be dynamic in length.

How can I get the text in the first div to automatically adjust to fit the entire div?

Clarification: the div should stay a fixed size and only the text should be downsized to fit the div rather than overflowing the div.

Update

I have also posted a more specific question about a specific module called react-textfit not working the way I would expect it to work.

答:
I am not a reactJs user but I have worked with CSS flex

you can set height of the container to auto so that it changes as we get the content. Also, you should set min-height and max-height properties in css so that if content is less that given length, it appears on min-height and if the content is way to big, it does not exceed the given container height.

In order to disallow content from getting out of the box, you can use overflow:hidden. this will keep the content from getting out of the box.

Hope this gives some help with how you want to proceed.

Body:
I am using a flexbox layout and am trying to get the text in a specific div to be resized to fit that div.

So for example, if I have code as follows:

      A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.

      Some other text

In reality, the text will be pulled from a database, so will be dynamic in length.

How can I get the text in the first div to automatically adjust to fit the entire div?

Clarification: the div should stay a fixed size and only the text should be downsized to fit the div rather than overflowing the div.

Update

I have also posted a more specific question about a specific module called react-textfit not working the way I would expect it to work.


问:
There is string "naveen" , want output as "eennav"
I have string in java "naveen" i want output as "eennav". Please help me out in this. The idea is that the characters are to be ordered in order of frequency, and, where frequencies are the same, alphabetically.

Thanks

I have tried to find duplicates in the string , but am not able to get the required output .

```<code>    String str="naveen";
    int count =0;
    char[] charr=str.toCharArray();
    for(int i=0;i<charr.length;i++) {
        //System.out.println(s[i]);
        for(int j=i+1;j<charr.length;j++) {
            if(charr[i]==(charr[j])) {
            System.out.println(charr[i]);
            }
</code>```

答:
Assuming the question is asking us to take a string containing only lower case letters and organize them by frequency of letters (high to low) and within that by alphabetical order, we can do it as below.
The strategy is first to make a pass through the characters of the input string and count the number of occurrences of each. Then we look through the counts for letters and find the largest. Working from the largest down to 1, we run through the alphabet for characters that occur that many times, and append that many of them to the result string.
There is a little bit of work involved here to convert back and forth from 'a' to 0 and 0 to 'a' and so on to 25 and 'z'.
This approach could be extended, but since the question didn't specify, I chose to make simplifying assumptions. I also did not work on optimizing, just getting it to work.</p>

```<code>public class MyClass {
public static void main(String args[]) {
    String str = "naveen"; //this string may change, but it is assumed to be all lower case letters by this implementation
    int[] counts = new int[26]; //frequency count of letters a to z
    for (int i = 0; i < 26; i++) {
        counts[i] = 0; // intially 0 of any letter
    }
    char[] charr = str.toCharArray();
    for (int i = 0; i < charr.length; i++) {
        counts[(int)(charr[i]) - (int)('a')]++; // increment corresponding spot in counts array, spot 0 for 'a' through 25 for 'z'
    }
    int maxCount = counts[0]; // now find the most occurrences of any letter
    for (int i = 1; i < counts.length; i++) {
        if (counts[i] > maxCount) {
            maxCount = counts[i];
        }
    }
    String result = ""; // string to return
    for (int j = maxCount; j > 0; j--) { // work down from most frequently occuring, within that alphabetically
        for (int i = 0; i < 26; i++) {
            if (counts[i] == j) {
                //System.out.println("there are "+j+" of the letter "+(char)((int)('a'+i)));
                for (int k = 0; k < j; k++) {
                    result = result + (char)((int)('a' + i));
                }
            };
        }
    }
    System.out.println(result);
    }
}
</code>```

Body:
I have string in java "naveen" i want output as "eennav". Please help me out in this. The idea is that the characters are to be ordered in order of frequency, and, where frequencies are the same, alphabetically.

Thanks

I have tried to find duplicates in the string , but am not able to get the required output .

    String str="naveen";
    int count =0;
    char[] charr=str.toCharArray();
    for(int i=0;i<charr.length;i++) {
        //System.out.println(s[i]);
        for(int j=i+1;j<charr.length;j++) {
            if(charr[i]==(charr[j])) {
            System.out.println(charr[i]);
            }

Body:
Assuming the question is asking us to take a string containing only lower case letters and organize them by frequency of letters (high to low) and within that by alphabetical order, we can do it as below.
The strategy is first to make a pass through the characters of the input string and count the number of occurrences of each. Then we look through the counts for letters and find the largest. Working from the largest down to 1, we run through the alphabet for characters that occur that many times, and append that many of them to the result string.
There is a little bit of work involved here to convert back and forth from 'a' to 0 and 0 to 'a' and so on to 25 and 'z'.
This approach could be extended, but since the question didn't specify, I chose to make simplifying assumptions. I also did not work on optimizing, just getting it to work.

public class MyClass {
public static void main(String args[]) {
    String str = "naveen"; //this string may change, but it is assumed to be all lower case letters by this implementation
    int[] counts = new int[26]; //frequency count of letters a to z
    for (int i = 0; i < 26; i++) {
        counts[i] = 0; // intially 0 of any letter
    }
    char[] charr = str.toCharArray();
    for (int i = 0; i < charr.length; i++) {
        counts[(int)(charr[i]) - (int)('a')]++; // increment corresponding spot in counts array, spot 0 for 'a' through 25 for 'z'
    }
    int maxCount = counts[0]; // now find the most occurrences of any letter
    for (int i = 1; i < counts.length; i++) {
        if (counts[i] > maxCount) {
            maxCount = counts[i];
        }
    }
    String result = ""; // string to return
    for (int j = maxCount; j > 0; j--) { // work down from most frequently occuring, within that alphabetically
        for (int i = 0; i < 26; i++) {
            if (counts[i] == j) {
                //System.out.println("there are "+j+" of the letter "+(char)((int)('a'+i)));
                for (int k = 0; k < j; k++) {
                    result = result + (char)((int)('a' + i));
                }
            };
        }
    }
    System.out.println(result);
    }
}


问:
QuitApplication Button on unity
I am trying to create a Quit button in Unity, but when I add my script to the button and click it, it doesn't quit.

Here is my C# script:

```<code>    using UnityEngine;
using System.Collections;

public class Quit_App : MonoBehaviour {
    void OnClick() {
        Application.Quit();
    }
}
</code>```

I have created it and assigned to the canvas using the UI, and I use the Button(Script) box in order to execute this code using the OnClick() box.
There, I selected it as object MyButton and the Quit_App() function using a string name.

答:
First, this answer assumes that your code works and the only problem is that the Application.Quit () command does not execute.

The Application.Quit () command does not work when testing the application in the Unity Editor (for example, by pressing the "Play" button). It would close the Unity Editor.

To test, go to the "Files / Build and Run" menu.

This will build and execute the project and Application.Quit() will be execute properly.

Title: QuitApplication Button on unity

Body:
I am trying to create a Quit button in Unity, but when I add my script to the button and click it, it doesn't quit.

Here is my C# script:

    using UnityEngine;
using System.Collections;

public class Quit_App : MonoBehaviour {
    void OnClick() {
        Application.Quit();
    }
}

I have created it and assigned to the canvas using the UI, and I use the Button(Script) box in order to execute this code using the OnClick() box.
There, I selected it as object MyButton and the Quit_App() function using a string name.


问:
replace single slash with double slash, php
how replace single slash with double slash?
I have this text:

```<code>"/data/folder/"

 and i need get

"//data//folder//"
</code>```

i try with replace, but get error:

```<code>$data = str_replace("\", "\\", $data);
</code>```

答:
Regarding why you are getting an error, backslashes are escape characters in strings wrapped in double quotes ". You need to escape them as well:

```<code>str_replace("\\", "\\\\", $data);
</code>```

from what you are saying, you however probably want to use slashes, not backslashes, as shown by @codaddict.

Body:
how replace single slash with double slash?
I have this text:

"/data/folder/"

 and i need get

"//data//folder//"

i try with replace, but get error:

$data = str_replace("\", "\\", $data);

Body:
Regarding why you are getting an error, backslashes are escape characters in strings wrapped in double quotes ". You need to escape them as well:

str_replace("\\", "\\\\", $data);

from what you are saying, you however probably want to use slashes, not backslashes, as shown by @codaddict.


问:
Filtering a data frame based on user input selected after user uploads data
I am building an app that allows the user to upload a data file and
then analyse the data using a standard method. The analysis is dependent
on one user input parameter which is populated after the file is uploaded.

The process is:

User uploads .csv file.

uiOutput() is populated with the unique levels in a variable of the
uploaded data.

User selects one option in the uiOutput()

User clicks 'Run analysis'.

Table is shown with results.

User can download the analysis results table as a .csv.

Step 4 of the analysis should filter the data by the input from step 3.

I used renderUI in the server function to make the choices based on unique names (levels) in a variable of the file uploaded by the user. Instead of selectInput() in the ui, I have used uiOutput, based on previous answers on SO. This allows the input to be populated based on the uploaded data. But this is actually an output of a renderUI. I would like this option to filter the data, but I don't know how to specify this filtering condition.

The code chunk of interest is #### run analysis based on user input ####

```<code>library(shiny)
library(shinythemes)
library(shinyWidgets)
library(dplyr)
library(DT)
library(shinyjs)
library(dplyr)
library(tidyr)
library(stringr)

data_example <- structure( # save as .csv and upload to app
    list(
        site = c("A", "A", "A"),
        analyte = c("x", "y",
                    "z"),
        QA = c(4L, 6L, 3L),
        A1 = c(2L, 6L, 5L),
        A2 = c(1L, 8L,
               4L),
        A3 = c(8L, 32L, 12L)
    ),
    class = "data.frame",
    row.names = c(NA,-3L)
)

#### Define UI for data upload app ####
ui <- fluidPage(theme = shinytheme("flatly"),
                # set the theme aesthetic

                # App title ----
                tags$h3("demo"),
                # Sidebar layout with input and output definitions ----
                sidebarLayout(
                    sidebarPanel(
                        width = 3,
                        #### conditional panel for surface water QA ######
                        conditionalPanel(
                            condition = "input.conditionedPanels == 1",
                            tags$h4("Load data"),
                            tags$hr(style = "border-color: black;"),
                            fileInput(
                                "file1",
                                "Import file",
                                multiple = FALSE,
                                accept = c("text/csv",
                                           "text/comma-separated-values,text/plain",
                                           ".csv")
                            ),

                            checkboxInput("header", "The dataset has column names", TRUE),
                            radioButtons(
                                "sep",
                                "How are the columns seperated?*",
                                choices = c(
                                    Comma = ",",
                                    Semicolon = ";",
                                    Tab = "\t"
                                ),
                                selected = ",",
                                inline = TRUE
                            ),
                            tags$hr(style = "border-color: black;"),
                            tags$h4("Analysis options"),
                            checkboxInput("show_sw", label = "Show  data", value = TRUE),
                            uiOutput("select_qa_site"),

                            actionButton("run_qa", "Run analysis"),
                            downloadButton("download_qa_sw_table", "Download results")
                        )

                    ),

                    #### Main panel (tabs) for displaying outputs ####
                    mainPanel(
                        useShinyjs(),
                        tabsetPanel(
                            type = "tabs",
                            tabPanel(
                                "QA",
                                br(),
                                tags$h4("Raw data view"),
                                tags$hr(style = "border-color: black;"),
                                dataTableOutput("sw_table"),
                                br(),
                                tags$h4("Analysis view"),
                                tags$hr(style = "border-color: black;"),
                                dataTableOutput("sw_qa_results_table"),
                                value = 1
                            ),
                            id = "conditionedPanels"
                        )

                    )

                ))

server <- function(input, output) {
    #### data input for surface water ####
    data_input <- reactive({
        read.csv(input$file1$datapath,
                 header = input$header,
                 sep = input$sep)
    })

    #### sample site names to choose from and run QA analysis ####
    sw_site_names <- reactive({
        req(input$file1)
        names_sw_data <- colnames(data_input())
        names_sw_data[!(colnames(data_input()) %in% c("site",
                                                      "analyte",
                                                      "QA"))]
    })

    output$select_qa_site <- renderUI({
        # Selecting site names based on variable in uploaded data
        selectInput(
            "Select_site",
            label = h4("Select QA sample site"),
            choices = sw_site_names(),
            selected = NULL
        )
    })

    #### produce data table for raw data inspection  ####
    output$sw_table <- renderDataTable({
        req(input$file1)
        datatable(
            data_input(),
            rownames = FALSE,
            options = list(autoWidth = TRUE, scrollX = TRUE)
        )
    })

    #### show/hide raw data table ####
    observeEvent(input$show_sw, {
        if (input$show_sw)
            show("sw_table")
        else
            hide("sw_table")
    })

    #### run analysis based on user input ####
    qa_table <- eventReactive(input$run_qa, {
        data_input() %>%
            gather(sample_location,
                   value,-c(site, analyte, QA)) %>%
            mutate(
                absolute_diff = abs(value - QA),
                value_mean = (value + QA) / 2,
                RPD = round((absolute_diff / value) * 100, 2)
            ) %>%
            filter() # I would like to filter this data based on input from user #
    })

    #### render results of QA analysis to a table for inspection before downloading ####
    output$sw_qa_results_table <- renderDataTable({
        req(input$file1)
        datatable(
            qa_table(),
            rownames = FALSE,
            options = list(autoWidth = FALSE, scrollX = TRUE)
        )
    })

}

##### Create Shiny app ####
shinyApp(ui, server)

</code>```

I could be just over-engineering the code too, so I'm happy for suggestions that achieve
the same outcome but use a different approach.

I have searched for a solution on SO and do not think this is a duplicate question but
I'm happy to be directed to a solution if it exists already.

Any help is appreciated.

答:
I believe you want to filter by sample_location?

You can do this by having filter(sample_location == input$Select_site)

So your qa_table will be:

```<code>  #### run analysis based on user input ####
  qa_table <- eventReactive(input$run_qa, {
    data_input() %>%
      gather(sample_location,
             value,-c(site, analyte, QA)) %>%
      mutate(
        absolute_diff = abs(value - QA),
        value_mean = (value + QA) / 2,
        RPD = round((absolute_diff / value) * 100, 2)
      ) %>%
      filter(sample_location == input$Select_site)
  })
</code>```

Body:
I am building an app that allows the user to upload a data file and
then analyse the data using a standard method. The analysis is dependent
on one user input parameter which is populated after the file is uploaded.

The process is:

User uploads .csv file.

uiOutput() is populated with the unique levels in a variable of the
uploaded data.

User selects one option in the uiOutput()

User clicks 'Run analysis'.

Table is shown with results.

User can download the analysis results table as a .csv.

Step 4 of the analysis should filter the data by the input from step 3.

I used renderUI in the server function to make the choices based on unique names (levels) in a variable of the file uploaded by the user. Instead of selectInput() in the ui, I have used uiOutput, based on previous answers on SO. This allows the input to be populated based on the uploaded data. But this is actually an output of a renderUI. I would like this option to filter the data, but I don't know how to specify this filtering condition.

The code chunk of interest is #### run analysis based on user input ####

library(shiny)
library(shinythemes)
library(shinyWidgets)
library(dplyr)
library(DT)
library(shinyjs)
library(dplyr)
library(tidyr)
library(stringr)

data_example <- structure( # save as .csv and upload to app
    list(
        site = c("A", "A", "A"),
        analyte = c("x", "y",
                    "z"),
        QA = c(4L, 6L, 3L),
        A1 = c(2L, 6L, 5L),
        A2 = c(1L, 8L,
               4L),
        A3 = c(8L, 32L, 12L)
    ),
    class = "data.frame",
    row.names = c(NA,-3L)
)

#### Define UI for data upload app ####
ui <- fluidPage(theme = shinytheme("flatly"),
                # set the theme aesthetic

                # App title ----
                tags$h3("demo"),
                # Sidebar layout with input and output definitions ----
                sidebarLayout(
                    sidebarPanel(
                        width = 3,
                        #### conditional panel for surface water QA ######
                        conditionalPanel(
                            condition = "input.conditionedPanels == 1",
                            tags$h4("Load data"),
                            tags$hr(style = "border-color: black;"),
                            fileInput(
                                "file1",
                                "Import file",
                                multiple = FALSE,
                                accept = c("text/csv",
                                           "text/comma-separated-values,text/plain",
                                           ".csv")
                            ),

                            checkboxInput("header", "The dataset has column names", TRUE),
                            radioButtons(
                                "sep",
                                "How are the columns seperated?*",
                                choices = c(
                                    Comma = ",",
                                    Semicolon = ";",
                                    Tab = "\t"
                                ),
                                selected = ",",
                                inline = TRUE
                            ),
                            tags$hr(style = "border-color: black;"),
                            tags$h4("Analysis options"),
                            checkboxInput("show_sw", label = "Show  data", value = TRUE),
                            uiOutput("select_qa_site"),

                            actionButton("run_qa", "Run analysis"),
                            downloadButton("download_qa_sw_table", "Download results")
                        )

                    ),

                    #### Main panel (tabs) for displaying outputs ####
                    mainPanel(
                        useShinyjs(),
                        tabsetPanel(
                            type = "tabs",
                            tabPanel(
                                "QA",
                                br(),
                                tags$h4("Raw data view"),
                                tags$hr(style = "border-color: black;"),
                                dataTableOutput("sw_table"),
                                br(),
                                tags$h4("Analysis view"),
                                tags$hr(style = "border-color: black;"),
                                dataTableOutput("sw_qa_results_table"),
                                value = 1
                            ),
                            id = "conditionedPanels"
                        )

                    )

                ))

server <- function(input, output) {
    #### data input for surface water ####
    data_input <- reactive({
        read.csv(input$file1$datapath,
                 header = input$header,
                 sep = input$sep)
    })

    #### sample site names to choose from and run QA analysis ####
    sw_site_names <- reactive({
        req(input$file1)
        names_sw_data <- colnames(data_input())
        names_sw_data[!(colnames(data_input()) %in% c("site",
                                                      "analyte",
                                                      "QA"))]
    })

    output$select_qa_site <- renderUI({
        # Selecting site names based on variable in uploaded data
        selectInput(
            "Select_site",
            label = h4("Select QA sample site"),
            choices = sw_site_names(),
            selected = NULL
        )
    })

    #### produce data table for raw data inspection  ####
    output$sw_table <- renderDataTable({
        req(input$file1)
        datatable(
            data_input(),
            rownames = FALSE,
            options = list(autoWidth = TRUE, scrollX = TRUE)
        )
    })

    #### show/hide raw data table ####
    observeEvent(input$show_sw, {
        if (input$show_sw)
            show("sw_table")
        else
            hide("sw_table")
    })

    #### run analysis based on user input ####
    qa_table <- eventReactive(input$run_qa, {
        data_input() %>%
            gather(sample_location,
                   value,-c(site, analyte, QA)) %>%
            mutate(
                absolute_diff = abs(value - QA),
                value_mean = (value + QA) / 2,
                RPD = round((absolute_diff / value) * 100, 2)
            ) %>%
            filter() # I would like to filter this data based on input from user #
    })

    #### render results of QA analysis to a table for inspection before downloading ####
    output$sw_qa_results_table <- renderDataTable({
        req(input$file1)
        datatable(
            qa_table(),
            rownames = FALSE,
            options = list(autoWidth = FALSE, scrollX = TRUE)
        )
    })

}

##### Create Shiny app ####
shinyApp(ui, server)

I could be just over-engineering the code too, so I'm happy for suggestions that achieve
the same outcome but use a different approach.

I have searched for a solution on SO and do not think this is a duplicate question but
I'm happy to be directed to a solution if it exists already.

Any help is appreciated.

Body:
I believe you want to filter by sample_location?

You can do this by having filter(sample_location == input$Select_site)

So your qa_table will be:

  #### run analysis based on user input ####
  qa_table <- eventReactive(input$run_qa, {
    data_input() %>%
      gather(sample_location,
             value,-c(site, analyte, QA)) %>%
      mutate(
        absolute_diff = abs(value - QA),
        value_mean = (value + QA) / 2,
        RPD = round((absolute_diff / value) * 100, 2)
      ) %>%
      filter(sample_location == input$Select_site)
  })


答:
First thing you need to see why req.body.text is null or undefined, then you do the empty check like below. </p>

```<code>const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    const result = (!str || str.toString().trim() === ""); // converting toString because there chance body.text can be a number
    console.log("result: ", result)
    return result
}
</code>```

Title: How to fix "Cannot read property 'trim' of undefined" error in node

Body:
I'm implementing a simple WebAPI in Firebase cloud functions with express by TypeScript.
My code is following.

import * as functions from 'firebase-functions';
import * as express from 'express';

const app = express()

app.post('/', (req, res) => {
    var resText: string = "NotEmpty"
    const text: string = req.body.text

    if (isEmpty(text)) {
        resText = "Empty"
    }
    console.log("text: ", text)
    console.log("resText: ", resText)
    res.send("Echo " + resText)
})

exports.api = functions.https.onRequest(app)

const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    const trimedStr = str.trim()
    const result = (trimedStr === null || trimedStr === "")
    console.log("result: ", result)
    return result
}

Build to transform typescript to javascript worked fine.
However, when I did POST method, following error occurred.

>  TypeError: Cannot read property 'trim' of undefined
>      at isEmpty (/Users/kenny/Test/firebase_functions/functions/lib/index.js:22:27)
>      at app.post (/Users/kenny/Test/firebase_functions/functions/lib/index.js:9:9)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/route.js:137:
13)
>      at Route.dispatch (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/rou
te.js:112:3)
>      at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
>      at /Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:281:22
>      at Function.process_params (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/r
outer/index.js:335:12)
>      at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:275:
10)
>      at expressInit (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/middleware/in
it.js:40:5)

How can I fix this error ?

Body:
First thing you need to see why req.body.text is null or undefined, then you do the empty check like below.

const isEmpty = (str: string): boolean => {
    console.log("str: ", str, "+++")
    const result = (!str || str.toString().trim() === ""); // converting toString because there chance body.text can be a number
    console.log("result: ", result)
    return result
}


问:
JPanel doesn't repaint well using transparent JFrame
I'm trying to repaint a JPanel over a transparent JFrame but it lets the mark of the previous repaint:

previous repaint keeps showing

I know this is a known problem and there's a similar question already posted, but the answers only explain why it doesn't work and they don't give a solution.

Can anyone please make a change in the code or add some, so it gives the desired effect? (a cross that follows the mouse over a transparent background)

I don't want to take a picture of the desktop and draw it in the JPanel.

The code is the following

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

final class Transparency extends JFrame{
    private NewPanel np;

    Transparency(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setUndecorated(true);
        setLocation(200,200);
        setBackground(new Color(0,0,0,0));

        np = new NewPanel();
        setContentPane(np);

        pack();
        setVisible(true);
    }

    public static void main(String []args){
        Transparency li = new Transparency();
    }
}

final class NewPanel extends JPanel{
    private Point p = new Point(0,0);
    private final int length = 25;

    NewPanel(){
        setPreferredSize(new Dimension(400,400));
        setOpaque(false);
        addMouseMotionListener(new MouseAdapter(){
            public void mouseMoved(MouseEvent e){
                p = e.getPoint();
                repaint();
            }
        });
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        g.setColor(Color.GREEN);
        g.drawLine(p.x-length,p.y,p.x+length,p.y);
        g.drawLine(p.x,p.y-length,p.x,p.y+length);

        g.setColor(Color.WHITE);
        g.drawRect(0,0,399,399);
    }
}
</code>```

答:
Since there is no heavyweight top level component, you will need to manage the background yourself.

Add this to your paintComponent method, right after super.paintComponent:

```<code>g.clearRect(0, 0, getWidth(), getHeight());
</code>```

Body:
I'm trying to repaint a JPanel over a transparent JFrame but it lets the mark of the previous repaint:

previous repaint keeps showing

I know this is a known problem and there's a similar question already posted, but the answers only explain why it doesn't work and they don't give a solution.

Can anyone please make a change in the code or add some, so it gives the desired effect? (a cross that follows the mouse over a transparent background)

I don't want to take a picture of the desktop and draw it in the JPanel.

The code is the following

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

final class Transparency extends JFrame{
    private NewPanel np;

    Transparency(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setUndecorated(true);
        setLocation(200,200);
        setBackground(new Color(0,0,0,0));

        np = new NewPanel();
        setContentPane(np);

        pack();
        setVisible(true);
    }

    public static void main(String []args){
        Transparency li = new Transparency();
    }
}

final class NewPanel extends JPanel{
    private Point p = new Point(0,0);
    private final int length = 25;

    NewPanel(){
        setPreferredSize(new Dimension(400,400));
        setOpaque(false);
        addMouseMotionListener(new MouseAdapter(){
            public void mouseMoved(MouseEvent e){
                p = e.getPoint();
                repaint();
            }
        });
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        g.setColor(Color.GREEN);
        g.drawLine(p.x-length,p.y,p.x+length,p.y);
        g.drawLine(p.x,p.y-length,p.x,p.y+length);

        g.setColor(Color.WHITE);
        g.drawRect(0,0,399,399);
    }
}

Body:
Since there is no heavyweight top level component, you will need to manage the background yourself.

Add this to your paintComponent method, right after super.paintComponent:

g.clearRect(0, 0, getWidth(), getHeight());


问:
Grafana : Network Error: undefined(undefined)
I encounter a problem in creating a Grafana data source , I started my Grafana Server, I choose datatype:InfluxDB, HttpSetting Url : http://localhost:8086, Access: direct...when I click on add data, I got: Test Failed
Network Error: undefined(undefined).
When I change the Access to Proxy I got: Test Failed
Network Error: Bad Gateway(502)

Every help will be appreciated

答:
After searching google again and again.

Here are the several solutions:

Update the "Access" in the data sources.
Try to switch between "Server (Default)" and "Browser"

Check your influxdb query. Sometimes the query is so slow, and grafana timeout in 30 seconds when querying the data

I use this solution to fix my issue. Because I use the regex during search. It is so slow.

Try the following.
Edit the /etc/grafana/grafana.ini:

Find and change the followings to:

```<code># How long the data proxy should wait before timing out default is 30
(seconds)
timeout = 120
</code>```

Body:
After searching google again and again.

Here are the several solutions:

Update the "Access" in the data sources.
Try to switch between "Server (Default)" and "Browser"

Check your influxdb query. Sometimes the query is so slow, and grafana timeout in 30 seconds when querying the data

I use this solution to fix my issue. Because I use the regex during search. It is so slow.

Try the following.
Edit the /etc/grafana/grafana.ini:

Find and change the followings to:

# How long the data proxy should wait before timing out default is 30
(seconds)
timeout = 120


问:
How to store weight values and converting to standard/metric weights?
I'm working on a Vue application, and one of the features deals with weight values. I'm currently storing them in my database as grams, and then converting them to pounds. Eventually I'd like to be able to have the user choose between metric and standard computations. I've created a function that returns four calculations, however they don't seem to add up correctly.

```<code>export const convertToPounds = weight => {
  return (Math.round((weight / 453.592) * 10) / 10).toFixed(2);
};
</code>```

This function is run four times. Once for the total, and three times based on which category the items filter into.

```<code>Total - 4170 grams converts to 9.20 lbs
ValueA - 2700 grams converts to 6.00 lbs
ValueB - 1400 grams converts to 3.10 lbs
ValueC - 70 grams converts to 0.20 lbs
</code>```

Looking at the final conversions though, the three values add up to 9.30 rather than the 9.20 that should be returned.

My question is whether the conversion method is too inaccurate to handle these types of conversions? Or is storing weights in grams not the best way to handle this scenario?

答:
To long fo a comment:

Exact numbers like 9.20are not possible. They are binary rounded to the nearest possible number, here to 9.19999999999999929. That's the reason, that toFixed() returns a string and not a number.

Also functions or expressions provided as answers here do not help:

```<code>value = Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals);
</code>```

If you proof the result by console.log(value.toPrecision(18)) you see, that the functions fails. All rounding functions, that returns a number will fail.

Why toPrecision(18)? Floating numbers are usually implemented as IEEE 754. JavaScript uses double floats with about 16 decimal digits. So 18 digits are a very exact decimal representation of the internal number.

Final note: Use toFixed() only for the final printing.

Body:
I'm working on a Vue application, and one of the features deals with weight values. I'm currently storing them in my database as grams, and then converting them to pounds. Eventually I'd like to be able to have the user choose between metric and standard computations. I've created a function that returns four calculations, however they don't seem to add up correctly.

export const convertToPounds = weight => {
  return (Math.round((weight / 453.592) * 10) / 10).toFixed(2);
};

This function is run four times. Once for the total, and three times based on which category the items filter into.

Total - 4170 grams converts to 9.20 lbs
ValueA - 2700 grams converts to 6.00 lbs
ValueB - 1400 grams converts to 3.10 lbs
ValueC - 70 grams converts to 0.20 lbs

Looking at the final conversions though, the three values add up to 9.30 rather than the 9.20 that should be returned.

My question is whether the conversion method is too inaccurate to handle these types of conversions? Or is storing weights in grams not the best way to handle this scenario?

Body:
To long fo a comment:

Exact numbers like 9.20are not possible. They are binary rounded to the nearest possible number, here to 9.19999999999999929. That's the reason, that toFixed() returns a string and not a number.

Also functions or expressions provided as answers here do not help:

value = Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals);

If you proof the result by console.log(value.toPrecision(18)) you see, that the functions fails. All rounding functions, that returns a number will fail.

Why toPrecision(18)? Floating numbers are usually implemented as IEEE 754. JavaScript uses double floats with about 16 decimal digits. So 18 digits are a very exact decimal representation of the internal number.

Final note: Use toFixed() only for the final printing.


问:
Count a foreach loop and create new element in php
I'm working on a Mega Menu for WooCommerce Product Category. I'm able to get the list of all Subcategories using the code below;

```<code>$parent_id = 37; //ID of the Parent Category
$subCat_of_parent = get_terms('product_cat',array('child_of' => $parent_id));
</code>```

Then used in a html structure as below;

```<code><div class="row">
    <div class="col-md-6">
        <ul>
        <?php
        foreach ($subCat_of_parent as $subcat) {
            ?>
            <li>
                <a href="<?php echo get_category_link($subcat->term_id); ?>"><?php echo $subcat->name; ?></a>
            </li>
            <?php
        }
         ?>
        </ul>
    </div>
</div>
</code>```

This worked by getting all the list of subcategory of the parent category in this format;

```<code><div class="row">
    <div class="col-md-6">
        <ul>
           <li><a>1st subcategory</a></li>
           <li><a>2nd subcategory</a></li>
           <li><a>3rd subcategory</a></li>
           <li><a>4th subcategory</a></li>
           <li><a>5th subcategory</a></li>
           <li><a>6th subcategory</a></li>
        </ul>
    <div>
</div>
</code>```

what i want to achieve is after the 3rd subcategory, it should break and continue on a new column, so that i can get something like this;

```<code><div class="row">
    <div class="col-md-6">
        <ul>
           <li><a>1st subcategory</a></li>
           <li><a>2nd subcategory</a></li>
           <li><a>3rd subcategory</a></li>
        </ul>
    <div>

    <div class="col-md-6">
        <ul>
           <li><a>4th subcategory</a></li>
           <li><a>5th subcategory</a></li>
           <li><a>6th subcategory</a></li>
        </ul>
    <div>
</div>
</code>```

How can i achieve this? Thanks for your help in advance

答:
<?php
$arr = array(1, 2, 3, 4,5,6);
        $count = 0;
?>

    <?php
        foreach ($subCat_of_parent as $subcat)
        {
            // echo "count =".$count;
            if($count%3 == 0)
            {
             echo ('

');
            }
            $count++;
    ?>

                term_id); ?>"><?php echo $subcat->name; ?>

    <?php
            if($count%3 == 0)
            {
             echo ('

');
            }

        }
    ?>

```

Body:
I'm working on a Mega Menu for WooCommerce Product Category. I'm able to get the list of all Subcategories using the code below;

$parent_id = 37; //ID of the Parent Category
$subCat_of_parent = get_terms('product_cat',array('child_of' => $parent_id));

Then used in a html structure as below;

        <?php
        foreach ($subCat_of_parent as $subcat) {
            ?>

                <a href="<?php echo get_category_link($subcat->term_id); ?>"><?php echo $subcat->name; ?>

            <?php
        }
         ?>

This worked by getting all the list of subcategory of the parent category in this format;

1st subcategory

2nd subcategory

3rd subcategory

4th subcategory

5th subcategory

6th subcategory

what i want to achieve is after the 3rd subcategory, it should break and continue on a new column, so that i can get something like this;

1st subcategory

2nd subcategory

3rd subcategory

4th subcategory

5th subcategory

6th subcategory

How can i achieve this? Thanks for your help in advance

Body:
<?php
$arr = array(1, 2, 3, 4,5,6);
        $count = 0;
?>
    <div class="row">
    <?php
        foreach ($subCat_of_parent as $subcat)
        {
            // echo "count =".$count;
            if($count%3 == 0)
            {
             echo ('<div class="col-md-6">
                <ul>');
            }
            $count++;
    ?>
            <li>
                <a href="<?php echo get_category_link($subcat->term_id); ?>"><?php echo $subcat->name; ?></a>
            </li>

    <?php
            if($count%3 == 0)
            {
             echo ('
                </ul></div>');
            }

        }
    ?>
    </div>


问:
NSURLConnection always TRUE
I am checking for server connection with the code below, however 'connection' is always TRUE..

I know that 'initWithRequest:delegate:' is deprecated: and it is recommended to use NSURLSession instead, however I'd prefer continuing using it for simplicity as NSURLSession seems much more complex to implement.

Any advice to make it work?

```<code>NSURL *url = nil;
NSMutableURLRequest *request = nil;

NSString *getURL = [NSString stringWithFormat:@"%@?TEST=%@",URL, str];

url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

if(connection) //Always true!!!
{
    mutableData = [NSMutableData new];
    NSLog(@"SERVER CONNECTION OK");
}
else
{
    NSLog(@"NO SERVER CONNECTION");
}
</code>```

答:
connection is an NSURLConnection object that you created. If it gets created, it will return true.

Problem is you did not handle the response data which can be utilized using these delegates functions:

```<code>-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection;
</code>```

You should put a log in didFailWithError to check whether your connection is successful or not.

I am quite sure you have not tried NSURLSession, but you should because NSURLSession can be written as blocks which makes it easier to write code (no delegates). In truth NSURLSession is a lot simpler and easier to implement than NSURLConnection.

Title: NSURLConnection always TRUE

Body:
I am checking for server connection with the code below, however 'connection' is always TRUE..

I know that 'initWithRequest:delegate:' is deprecated: and it is recommended to use NSURLSession instead, however I'd prefer continuing using it for simplicity as NSURLSession seems much more complex to implement.

Any advice to make it work?

NSURL *url = nil;
NSMutableURLRequest *request = nil;

NSString *getURL = [NSString stringWithFormat:@"%@?TEST=%@",URL, str];

url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

if(connection) //Always true!!!
{
    mutableData = [NSMutableData new];
    NSLog(@"SERVER CONNECTION OK");
}
else
{
    NSLog(@"NO SERVER CONNECTION");
}

Body:
connection is an NSURLConnection object that you created. If it gets created, it will return true.

Problem is you did not handle the response data which can be utilized using these delegates functions:

-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection;

You should put a log in didFailWithError to check whether your connection is successful or not.

I am quite sure you have not tried NSURLSession, but you should because NSURLSession can be written as blocks which makes it easier to write code (no delegates). In truth NSURLSession is a lot simpler and easier to implement than NSURLConnection.


问:
Get Public IP Address on current EC2 Instance
Using Amazon CLI, is there a way to get the public ip address of the current EC2?  I'm just looking for the single string value, so not the json response describe-addresses returns.  </p>

答:
If you are inside the instance -

```<code>$ curl icanhazip.com
162.202.17.123
</code>```

here is one more way

```<code>$ curl -s ifconfig.me
162.202.17.123
</code>```

these methods are not limited to just AWS.

Body:
If you are inside the instance -

$ curl icanhazip.com
162.202.17.123

here is one more way

$ curl -s ifconfig.me
162.202.17.123

these methods are not limited to just AWS.