问:
theme and mode path infer issue with ace.js and Angular
Sorry, the question unfortunately hasn't got much detail as I am not sure what exactly is required to explain the issue. To start with, I am trying to use ng2-ace-editor in my Angular application. My setup is not standard though. Details are in this other related problem - application can't find a .js file

In summary, if I explicitly include ace.js in my top level html then things work. But I don't want to do that as I want to use only the bundles created by Angular. But if I use only the bundles then I get the following error when I run the application -

```<code>ace.js:1 Unable to infer path to ace from script src, use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes or with webpack use ace/webpack-resolver
f @ ace.js:1
t.loadModule @ ace.js:1
setTheme @ ace.js:1
setTheme @ ace.js:1
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.setTheme @ component.js:117
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.init @ component.js:48
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.ngOnInit @ component.js:40
checkAndUpdateDirectiveInline @ core.js:9250
checkAndUpdateNodeInline @ core.js:10514
checkAndUpdateNode @ core.js:10476
debugCheckAndUpdateNode @ core.js:11109
debugCheckDirectivesFn @ core.js:11069
eval @ NewPracticeQuestionComponent.html:188
debugUpdateDirectives @ core.js:11061
checkAndUpdateView @ core.js:10458
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callViewAction @ core.js:10699
execEmbeddedViewsAction @ core.js:10662
checkAndUpdateView @ core.js:10459
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callWithDebugContext @ core.js:11351
debugCheckAndUpdateView @ core.js:11029
push../node_modules/@angular/core/fesm5/core.js.ViewRef_.detectChanges @ core.js:8845
(anonymous) @ core.js:4581
push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:4581
(anonymous) @ core.js:4473
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
onInvoke @ core.js:3824
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3738
next @ core.js:4473
schedulerFn @ core.js:3555
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:209
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:147
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:80
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:55
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3539
checkStable @ core.js:3793
onHasTask @ core.js:3837
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:441
push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:461
push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:285
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:205
drainMicroTaskQueue @ zone.js:595
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:500
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
Show 26 more frames
ace.js:1 GET http://localhost:9000/theme-monokai.js net::ERR_ABORTED 404 (Not Found)
t.loadScript @ ace.js:1
t.loadModule @ ace.js:1
setTheme @ ace.js:1
setTheme @ ace.js:1
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.setTheme @ component.js:117
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.init @ component.js:48
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.ngOnInit @ component.js:40
checkAndUpdateDirectiveInline @ core.js:9250
checkAndUpdateNodeInline @ core.js:10514
checkAndUpdateNode @ core.js:10476
debugCheckAndUpdateNode @ core.js:11109
debugCheckDirectivesFn @ core.js:11069
eval @ NewPracticeQuestionComponent.html:188
debugUpdateDirectives @ core.js:11061
checkAndUpdateView @ core.js:10458
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callViewAction @ core.js:10699
execEmbeddedViewsAction @ core.js:10662
checkAndUpdateView @ core.js:10459
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callWithDebugContext @ core.js:11351
debugCheckAndUpdateView @ core.js:11029
push../node_modules/@angular/core/fesm5/core.js.ViewRef_.detectChanges @ core.js:8845
(anonymous) @ core.js:4581
push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:4581
(anonymous) @ core.js:4473
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
onInvoke @ core.js:3824
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3738
next @ core.js:4473
schedulerFn @ core.js:3555
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:209
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:147
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:80
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:55
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3539
checkStable @ core.js:3793
onHasTask @ core.js:3837
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:441
push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:461
push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:285
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:205
drainMicroTaskQueue @ zone.js:595
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:500
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
Show 26 more frames
414ede0a-7ac6-4556-a68b-bfcd8c991283:1 Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:9000/worker-javascript.js' failed to load.
    at blob:http://localhost:9000/414ede0a-7ac6-4556-a68b-bfcd8c991283:1:1
</code>```

Further analysis shows that the error is thrown from the following piece of code in ace.js.

```<code>exports.loadModule = function(moduleName, onLoad) {
    var module, moduleType;
    if (Array.isArray(moduleName)) {
        moduleType = moduleName[0];
        moduleName = moduleName[1];
    }

    try {
        module = require(moduleName);
    } catch (e) {}
    if (module && !exports.$loading[moduleName])
        return onLoad && onLoad(module);

    if (!exports.$loading[moduleName])
        exports.$loading[moduleName] = [];

    exports.$loading[moduleName].push(onLoad);

    if (exports.$loading[moduleName].length > 1)
        return;

    var afterLoad = function() {
        require([moduleName], function(module) {
            exports._emit("load.module", {name: moduleName, module: module});
            var listeners = exports.$loading[moduleName];
            exports.$loading[moduleName] = null;
            listeners.forEach(function(onLoad) {
                onLoad && onLoad(module);
            });
        });
    };

    if (!exports.get("packaged"))
        return afterLoad();

    net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad);
    reportErrorIfPathIsNotConfigured();
};

var reportErrorIfPathIsNotConfigured = function() {
    if (
        !options.basePath && !options.workerPath
        && !options.modePath && !options.themePath
        && !Object.keys(options.$moduleUrls).length
    ) {
        console.error(
            "Unable to infer path to ace from script src,",
            "use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes",
            "or with webpack use ace/webpack-resolver"
        );
        reportErrorIfPathIsNotConfigured = function() {};
    }
};
</code>```

What is causing the issue? I suppose Angular uses webpack. What is this ace/webpack-resolver thing? How do I solve the issue?

答:
I finally was able to make my code work. My setup is different.

The reason adding script tag explicitly made my code work is because By default ace detcts the url for dynamic loading by finding the script node for ace.js. This doesn't work if ace.js is not loaded with a separate script tag, and in this case it is required to set url explicitely (https://ace.c9.io/#nav=howto). As I am loading modes and themes without using script, I had to use basePath etc. (see answer further).

I build my Angular application and the it is served from my Play server. The angular build is stored in Play's /public/ui folder. The requests should be in format /assets/ui/.. which gets mapped to /public/ui/... due to a rule in Play routes file

```<code>GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)
</code>```

When I ran the code, I got error.

```<code>Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:9000/worker-javascript.js' failed to load.
    at blob:http://localhost:9000/3df21e42-fecb-4026-8bd6-f2b0d1d0540a:1:1
Earlier, I also got error `Unable to infer path to ace from script src, use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes or with webpack use ace/webpack-resolver`
</code>```

It seems ng-ace-editor imports .js scripts (theme, mode, worker) based on the theme and mode of the editor. The theme and mode .js files can be included in scripts.js but some worker-.js files can't be (I don't know why, maybe because worker ones are loaded dynamically using importScript).

The scripts section in Angular.json is (this will all get bundled in scripts.js in Angular's final bundle)

```<code>"scripts": [
              "./node_modules/ace-builds/src/ace.js",
              "./node_modules/ace-builds/src/theme-eclipse.js",
              "./node_modules/ace-builds/src/theme-monokai.js",
              "./node_modules/ace-builds/src/mode-html.js"
            ]]
</code>```

To include worker-.js files, I added this rule because it seems angular-cli can't load from node_modules. So I had to copy the files from node modules to root of my ui build - How to include assets from node_modules in angular cli project

```<code>"assets": [
              "src/assets",
              "src/favicon.ico",
              {
                "glob": "**/*",
                "input": "./node_modules/ace-builds/src/",
                "output": "/"
              }
            ],
</code>```

When I executed the code, I found error that http://localhost:9000/worker-javascript.js can't be loaded. I realised that my files are loaded in /assets/ui/ path and not in the server's root directory. So I set ace.js's basepath to /assets/ui in the component's .ts file

```<code>import * as ace from 'ace-builds/src-noconflict/ace';
    ace.config.set('basePath', '/assets/ui/');
    ace.config.set('modePath', '');
    ace.config.set('themePath', '');
</code>```

In summary basePath seem to be what is used to load scripts dynamically (eg worker scripts). modePath and themePath are / as the mode and theme scripts are bundled in scripts.js and my index.html correctly loaded scripts.js using

Body:
Sorry, the question unfortunately hasn't got much detail as I am not sure what exactly is required to explain the issue. To start with, I am trying to use ng2-ace-editor in my Angular application. My setup is not standard though. Details are in this other related problem - application can't find a .js file

In summary, if I explicitly include ace.js in my top level html then things work. But I don't want to do that as I want to use only the bundles created by Angular. But if I use only the bundles then I get the following error when I run the application -

ace.js:1 Unable to infer path to ace from script src, use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes or with webpack use ace/webpack-resolver
f @ ace.js:1
t.loadModule @ ace.js:1
setTheme @ ace.js:1
setTheme @ ace.js:1
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.setTheme @ component.js:117
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.init @ component.js:48
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.ngOnInit @ component.js:40
checkAndUpdateDirectiveInline @ core.js:9250
checkAndUpdateNodeInline @ core.js:10514
checkAndUpdateNode @ core.js:10476
debugCheckAndUpdateNode @ core.js:11109
debugCheckDirectivesFn @ core.js:11069
eval @ NewPracticeQuestionComponent.html:188
debugUpdateDirectives @ core.js:11061
checkAndUpdateView @ core.js:10458
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callViewAction @ core.js:10699
execEmbeddedViewsAction @ core.js:10662
checkAndUpdateView @ core.js:10459
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callWithDebugContext @ core.js:11351
debugCheckAndUpdateView @ core.js:11029
push../node_modules/@angular/core/fesm5/core.js.ViewRef_.detectChanges @ core.js:8845
(anonymous) @ core.js:4581
push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:4581
(anonymous) @ core.js:4473
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
onInvoke @ core.js:3824
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3738
next @ core.js:4473
schedulerFn @ core.js:3555
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:209
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:147
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:80
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:55
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3539
checkStable @ core.js:3793
onHasTask @ core.js:3837
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:441
push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:461
push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:285
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:205
drainMicroTaskQueue @ zone.js:595
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:500
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
Show 26 more frames
ace.js:1 GET http://localhost:9000/theme-monokai.js net::ERR_ABORTED 404 (Not Found)
t.loadScript @ ace.js:1
t.loadModule @ ace.js:1
setTheme @ ace.js:1
setTheme @ ace.js:1
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.setTheme @ component.js:117
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.init @ component.js:48
push../node_modules/ng2-ace-editor/src/component.js.AceEditorComponent.ngOnInit @ component.js:40
checkAndUpdateDirectiveInline @ core.js:9250
checkAndUpdateNodeInline @ core.js:10514
checkAndUpdateNode @ core.js:10476
debugCheckAndUpdateNode @ core.js:11109
debugCheckDirectivesFn @ core.js:11069
eval @ NewPracticeQuestionComponent.html:188
debugUpdateDirectives @ core.js:11061
checkAndUpdateView @ core.js:10458
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callViewAction @ core.js:10699
execEmbeddedViewsAction @ core.js:10662
checkAndUpdateView @ core.js:10459
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callViewAction @ core.js:10699
execComponentViewsAction @ core.js:10641
checkAndUpdateView @ core.js:10464
callWithDebugContext @ core.js:11351
debugCheckAndUpdateView @ core.js:11029
push../node_modules/@angular/core/fesm5/core.js.ViewRef_.detectChanges @ core.js:8845
(anonymous) @ core.js:4581
push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.tick @ core.js:4581
(anonymous) @ core.js:4473
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
onInvoke @ core.js:3824
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.run @ core.js:3738
next @ core.js:4473
schedulerFn @ core.js:3555
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:209
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:147
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:80
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:55
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3539
checkStable @ core.js:3793
onHasTask @ core.js:3837
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.hasTask @ zone.js:441
push../node_modules/zone.js/dist/zone.js.ZoneDelegate._updateTaskCount @ zone.js:461
push../node_modules/zone.js/dist/zone.js.Zone._updateTaskCount @ zone.js:285
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:205
drainMicroTaskQueue @ zone.js:595
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:500
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
Show 26 more frames
414ede0a-7ac6-4556-a68b-bfcd8c991283:1 Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:9000/worker-javascript.js' failed to load.
    at blob:http://localhost:9000/414ede0a-7ac6-4556-a68b-bfcd8c991283:1:1

Further analysis shows that the error is thrown from the following piece of code in ace.js.

exports.loadModule = function(moduleName, onLoad) {
    var module, moduleType;
    if (Array.isArray(moduleName)) {
        moduleType = moduleName[0];
        moduleName = moduleName[1];
    }

    try {
        module = require(moduleName);
    } catch (e) {}
    if (module && !exports.$loading[moduleName])
        return onLoad && onLoad(module);

    if (!exports.$loading[moduleName])
        exports.$loading[moduleName] = [];

    exports.$loading[moduleName].push(onLoad);

    if (exports.$loading[moduleName].length > 1)
        return;

    var afterLoad = function() {
        require([moduleName], function(module) {
            exports._emit("load.module", {name: moduleName, module: module});
            var listeners = exports.$loading[moduleName];
            exports.$loading[moduleName] = null;
            listeners.forEach(function(onLoad) {
                onLoad && onLoad(module);
            });
        });
    };

    if (!exports.get("packaged"))
        return afterLoad();

    net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad);
    reportErrorIfPathIsNotConfigured();
};

var reportErrorIfPathIsNotConfigured = function() {
    if (
        !options.basePath && !options.workerPath
        && !options.modePath && !options.themePath
        && !Object.keys(options.$moduleUrls).length
    ) {
        console.error(
            "Unable to infer path to ace from script src,",
            "use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes",
            "or with webpack use ace/webpack-resolver"
        );
        reportErrorIfPathIsNotConfigured = function() {};
    }
};

What is causing the issue? I suppose Angular uses webpack. What is this ace/webpack-resolver thing? How do I solve the issue?

Body:
I finally was able to make my code work. My setup is different.

The reason adding script tag explicitly made my code work is because By default ace detcts the url for dynamic loading by finding the script node for ace.js. This doesn't work if ace.js is not loaded with a separate script tag, and in this case it is required to set url explicitely (https://ace.c9.io/#nav=howto). As I am loading modes and themes without using script, I had to use basePath etc. (see answer further).

I build my Angular application and the it is served from my Play server. The angular build is stored in Play's /public/ui folder. The requests should be in format /assets/ui/.. which gets mapped to /public/ui/... due to a rule in Play routes file

GET     /assets/*file               controllers.Assets.versioned(path="/public", file: Asset)

When I ran the code, I got error.

Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:9000/worker-javascript.js' failed to load.
    at blob:http://localhost:9000/3df21e42-fecb-4026-8bd6-f2b0d1d0540a:1:1
Earlier, I also got error `Unable to infer path to ace from script src, use ace.config.set('basePath', 'path') to enable dynamic loading of modes and themes or with webpack use ace/webpack-resolver`

It seems ng-ace-editor imports .js scripts (theme, mode, worker) based on the theme and mode of the editor. The theme and mode .js files can be included in scripts.js but some worker-.js files can't be (I don't know why, maybe because worker ones are loaded dynamically using importScript).

The scripts section in Angular.json is (this will all get bundled in scripts.js in Angular's final bundle)

"scripts": [
              "./node_modules/ace-builds/src/ace.js",
              "./node_modules/ace-builds/src/theme-eclipse.js",
              "./node_modules/ace-builds/src/theme-monokai.js",
              "./node_modules/ace-builds/src/mode-html.js"
            ]]

To include worker-.js files, I added this rule because it seems angular-cli can't load from node_modules. So I had to copy the files from node modules to root of my ui build - How to include assets from node_modules in angular cli project

"assets": [
              "src/assets",
              "src/favicon.ico",
              {
                "glob": "**/*",
                "input": "./node_modules/ace-builds/src/",
                "output": "/"
              }
            ],

When I executed the code, I found error that http://localhost:9000/worker-javascript.js can't be loaded. I realised that my files are loaded in /assets/ui/ path and not in the server's root directory. So I set ace.js's basepath to /assets/ui in the component's .ts file

import * as ace from 'ace-builds/src-noconflict/ace';
    ace.config.set('basePath', '/assets/ui/');
    ace.config.set('modePath', '');
    ace.config.set('themePath', '');

In summary basePath seem to be what is used to load scripts dynamically (eg worker scripts). modePath and themePath are / as the mode and theme scripts are bundled in scripts.js and my index.html correctly loaded scripts.js using <script> tag and are available at root level need to copy worker-.js files outside node_modules as angular_cli can't copy assets from node_modules


来源: stackexchange

问:
Kotlin continuation doesn't resume
I'm trying to get my head around suspendCoroutine and suspendCancellableCoroutine. I think they could be useful in the following case:

When the coroutine is launched, check if the user is logged in.

If not, ask for credentials and pause the currently executing coroutine.

When the credentials are submitted, resume the coroutine from the same line where it was suspended.

This compiles but never makes it past "delay over", i.e. the continuation never resumes:

```<code>import kotlinx.coroutines.*

fun main(args: Array<String>) {
    println("Hello, world!")

    runBlocking {
        launch {
            postComment()
        }
    }
}

var isLoggedIn = false
var loginContinuation: CancellableContinuation<Unit>? = null

suspend fun postComment() {
    if (!isLoggedIn) {
        showLoginForm()

        suspendCancellableCoroutine<Unit> {
            loginContinuation = it
        }
    }

    // call the api or whatever
    delay(1000)

    println("comment posted!")
}

suspend fun showLoginForm() {
    println("show login form")

    // simulate delay while user enters credentials
    delay(1000)
    println("delay over")
    isLoggedIn = true

    // resume coroutine on submit
    loginContinuation?.resume(Unit) { println("login cancelled") }
}
</code>```

I've tried everything I can think of, including moving the call to suspendCancellableCoroutine outside of the login check, wrapping the contents of showLoginForm in withContext(Dispatchers.IO),  using coroutineScope.launch(newSingleThreadContext("MyOwnThread"), etc. The impression I get from reading the internet is that this is a valid use case. What am I doing wrong?

答:
First of all, you misunderstand the concept of suspend functions. Calling function showLoginForm() does not start a new coroutine. Code in a single coroutine is always executed sequentially - at first you call showLoginForm(), it delays, it does not resume any continuations because loginContinuation is null, and then suspendCancellableCoroutine suspends your coroutine forever and causes a deadlock.

Starting a new coroutine that executes showLoginForm() can make your code work:

```<code>suspend fun CoroutineScope.postComment() {
    if (!isLoggedIn) {
        launch {
            showLoginForm()
        }

        suspendCancellableCoroutine<Unit> {
            loginContinuation = it
        }
    }

    // call the api or whatever
    delay(1000)

    println("comment posted!")
}
</code>```

This code still can fail (*), but in this particular case it does not. Working version of this code can look like this:

```<code>import kotlin.coroutines.*
import kotlinx.coroutines.*

fun main(args: Array<String>) {
    println("Hello, world!")

    runBlocking {
        postComment()
    }
}

var isLoggedIn = false

suspend fun CoroutineScope.postComment() {
    if (!isLoggedIn) {
        suspendCancellableCoroutine<Unit> { continuation ->
            launch {
                showLoginForm(continuation)
            }
        }
    }
    delay(1000)
    println("comment posted!")
}

suspend fun showLoginForm(continuation: CancellableContinuation<Unit>) {
    println("show login form")
    delay(1000)
    println("delay over")
    isLoggedIn = true
    continuation.resume(Unit) { println("login cancelled") }
}
</code>```

Also, in your example suspending coroutines is not needed. Why do we need another coroutine if we can just execute its code in the same coroutine? We need to wait until it finishes anyway. Since coroutines execute code sequentially, we will go to the code after if branch only after showLoginForm() finishes:

```<code>var isLoggedIn = false

suspend fun postComment() {
    if (!isLoggedIn) {
        showLoginForm()
    }
    delay(1000)
    println("comment posted!")
}

suspend fun showLoginForm() {
    println("show login form")
    delay(1000)
    println("delay over")
    isLoggedIn = true
}
</code>```

This approach is the best for your example, where all code is sequential.

(*) - This code still can cause deadlock if suspendCancellableCoroutine is invoked after showLoginForm finishes - for example, if you remove delay call in showLoginForm or if you use a multithreaded dispatcher - in JVM there is no guarantee that suspendCancellableCoroutine will be invoked earlier than showLoginForm. Moreover, loginContinuation is not @Volatile, so with multithreaded dispatcher the code can fail also from visibility issues - thread that executes showLoginForm may observe that loginContinuation is null.

ContentLicense: CC BY-SA 4.0

Title: Kotlin continuation doesn't resume

Body:
I'm trying to get my head around suspendCoroutine and suspendCancellableCoroutine. I think they could be useful in the following case:

When the coroutine is launched, check if the user is logged in.

If not, ask for credentials and pause the currently executing coroutine.

When the credentials are submitted, resume the coroutine from the same line where it was suspended.

This compiles but never makes it past "delay over", i.e. the continuation never resumes:

import kotlinx.coroutines.*

fun main(args: Array<String>) {
    println("Hello, world!")

    runBlocking {
        launch {
            postComment()
        }
    }
}

var isLoggedIn = false
var loginContinuation: CancellableContinuation<Unit>? = null

suspend fun postComment() {
    if (!isLoggedIn) {
        showLoginForm()

        suspendCancellableCoroutine<Unit> {
            loginContinuation = it
        }
    }

    // call the api or whatever
    delay(1000)

    println("comment posted!")
}

suspend fun showLoginForm() {
    println("show login form")

    // simulate delay while user enters credentials
    delay(1000)
    println("delay over")
    isLoggedIn = true

    // resume coroutine on submit
    loginContinuation?.resume(Unit) { println("login cancelled") }
}

I've tried everything I can think of, including moving the call to suspendCancellableCoroutine outside of the login check, wrapping the contents of showLoginForm in withContext(Dispatchers.IO),  using coroutineScope.launch(newSingleThreadContext("MyOwnThread"), etc. The impression I get from reading the internet is that this is a valid use case. What am I doing wrong?

Body:
First of all, you misunderstand the concept of suspend functions. Calling function showLoginForm() does not start a new coroutine. Code in a single coroutine is always executed sequentially - at first you call showLoginForm(), it delays, it does not resume any continuations because loginContinuation is null, and then suspendCancellableCoroutine suspends your coroutine forever and causes a deadlock.

Starting a new coroutine that executes showLoginForm() can make your code work:

suspend fun CoroutineScope.postComment() {
    if (!isLoggedIn) {
        launch {
            showLoginForm()
        }

        suspendCancellableCoroutine<Unit> {
            loginContinuation = it
        }
    }

    // call the api or whatever
    delay(1000)

    println("comment posted!")
}

This code still can fail (*), but in this particular case it does not. Working version of this code can look like this:

import kotlin.coroutines.*
import kotlinx.coroutines.*

fun main(args: Array<String>) {
    println("Hello, world!")

    runBlocking {
        postComment()
    }
}

var isLoggedIn = false

suspend fun CoroutineScope.postComment() {
    if (!isLoggedIn) {
        suspendCancellableCoroutine<Unit> { continuation ->
            launch {
                showLoginForm(continuation)
            }
        }
    }
    delay(1000)
    println("comment posted!")
}

suspend fun showLoginForm(continuation: CancellableContinuation<Unit>) {
    println("show login form")
    delay(1000)
    println("delay over")
    isLoggedIn = true
    continuation.resume(Unit) { println("login cancelled") }
}

Also, in your example suspending coroutines is not needed. Why do we need another coroutine if we can just execute its code in the same coroutine? We need to wait until it finishes anyway. Since coroutines execute code sequentially, we will go to the code after if branch only after showLoginForm() finishes:

var isLoggedIn = false

suspend fun postComment() {
    if (!isLoggedIn) {
        showLoginForm()
    }
    delay(1000)
    println("comment posted!")
}

suspend fun showLoginForm() {
    println("show login form")
    delay(1000)
    println("delay over")
    isLoggedIn = true
}

This approach is the best for your example, where all code is sequential.

(*) - This code still can cause deadlock if suspendCancellableCoroutine is invoked after showLoginForm finishes - for example, if you remove delay call in showLoginForm or if you use a multithreaded dispatcher - in JVM there is no guarantee that suspendCancellableCoroutine will be invoked earlier than showLoginForm. Moreover, loginContinuation is not @Volatile, so with multithreaded dispatcher the code can fail also from visibility issues - thread that executes showLoginForm may observe that loginContinuation is null.


问:
How to merge branch with trunk using SVN in android studio
I would like to commit my changes in the branch and add those changes to the trunk version using the built-in svn tool in Android Studio. How can I do it?

Should I expect this kind of feature from this built-in tool or should I use an external tool like TurtoiseSVN?

答:
How to create SVN branch directly in AS

Download SVN plugin from File -> Settings -> plugins -> Marketplace -> "Subversion"

Enable VCS in VCS tab if not already enabled

VCS -> Browse VCS repository -> Browns SVN repository

Right click the folder/repo you want to branch, click "Branch or Tag..."

Select parent folder so that repos become siblings (or as you wish)

Name the folder with ending -your-feature (or as you wish)

Checkout your newly created branch

Run to check if the branch works fine on its own (on linux/ios "chmod a+rx android/gradlew" might be necessary)

Your commits will now only be to the current branch

How to merge SVN branch back to trunk/main repo

Go back to your trunk/main repo (or check it out if you haven't already)

VCS -> "Integrate project..."

Change "Source 2" to the branch you want to merge from

Resolve conflicts if any

Commit changes to trunk

SVN switch branches

Can be done using VCS -> "Update project..." -> Update/switch to another branch

Or better still can be to just have one main/trunk project and one branch project

Reference

I personally did it slightly different than the official docs. But basically making a branch is just copying the folder as I understand it.
Merging on the other hand seems a little more complicated, as every reference of change has to be present. For instance deleting or moving a folder has to be a committed change, it can not just be done without a reference in SVN.

Also their way is to keep the main folders current name but making some subfolders name indicating that it is a branch.

SVN intellij branching

SVN intellij merging

ContentLicense: CC BY-SA 3.0


问:
Terraform: store the contents of a set of files into a single variable
This is in TF V0.12 if that helps
In a directory, I have a variable number of single-line files.

I need to somehow read the contents of them all concatenating them with a newline between and store the result into a single variable. (not an array of strings)
I know I can get the list of files to read using:

```<code>locals{
  my files=tolist(fileset("${var.file_path}", "**")) }
</code>```

And if I only had a single file I know I can read in the contents by using

```<code>locals {
  file_value=file("${var.file_path}\\${local.my_files}") # if there was only a single file
}
</code>```

But my brains just turned to cotton wool how I can do the read for multiple,  I feel like I should be using a count and a concatenate within a null resource but can't seem to work the logic out.
Is that the right path or how should I be doing it?

答:
Thank you @mon that reminded me I should always KISS

Removing the complexity I ended up

```<code>resource "null_resource" "concatenate_my_files" {
  provisioner "local-exec" {
    working_dir = var.file_path
    command = <<EOF
cat * > my_temp_file
EOF
  }
}
</code>```

I can then read this in as previous.

Body:
This is in TF V0.12 if that helps
In a directory, I have a variable number of single-line files.

I need to somehow read the contents of them all concatenating them with a newline between and store the result into a single variable. (not an array of strings)
I know I can get the list of files to read using:

locals{
  my files=tolist(fileset("${var.file_path}", "**")) }

And if I only had a single file I know I can read in the contents by using

locals {
  file_value=file("${var.file_path}\\${local.my_files}") # if there was only a single file
}

But my brains just turned to cotton wool how I can do the read for multiple,  I feel like I should be using a count and a concatenate within a null resource but can't seem to work the logic out.
Is that the right path or how should I be doing it?

Body:
Thank you @mon that reminded me I should always KISS

Removing the complexity I ended up

resource "null_resource" "concatenate_my_files" {
  provisioner "local-exec" {
    working_dir = var.file_path
    command = <<EOF
cat * > my_temp_file
EOF
  }
}

I can then read this in as previous.


问:
Method that performs operations inside an array
I have an array a=[1, 2, 'N']. I would like a method to do if a[2] = 'N', increase a[1] by 1.
I tried this:

```<code>def change
  if self[2] == 'N'
    self[1] += 1
  end
end

a.change
</code>```

It gives me an error: undefined method `change' for [1, 2, "N"]:Array

What am I doing wrong?

答:
a = [1, 2, 'N']</p>

```<code>puts a

class Array
    def change()
      if self[2] == 'N'
        self[1] += 1
      end
    end
end

a.change

puts a
</code>```

Body:
I have an array a=[1, 2, 'N']. I would like a method to do if a[2] = 'N', increase a[1] by 1.
I tried this:

def change
  if self[2] == 'N'
    self[1] += 1
  end
end

a.change

It gives me an error: undefined method `change' for [1, 2, "N"]:Array

What am I doing wrong?

Body:
a = [1, 2, 'N']

puts a

class Array
    def change()
      if self[2] == 'N'
        self[1] += 1
      end
    end
end

a.change

puts a


问:
What is the reason to initialize or assign an empty string literal to a pointer to char in C, or a pointer to const char in C++?
My question is actually quite simply for those who might know about it, but I ask because I'm not aware of this technique already.

What is the reason for initializing or assigning an empty string literal to a pointer to char in C, or a pointer to const char in C++?

Like f.e.:

```<code>char* p = "";
</code>```

or

```<code>char* p;
p = "";
</code>```

Or, as suggested in the comments, in C++:

```<code>const char* p = "";
</code>```

or

```<code>const char* p;
p = "";
</code>```

I do often see this technique, but don't understand why someone shall assign an empty string literal to a char pointer (or pointer to const char for C++) or where this is coming from.

I have read Initialize a string in C to empty string, but this question is focused on initializing a char array with an empty string.

And I have also read: Initializing a string with the empty string, but this question covers an incorrect approach to assign an empty string to a pointer earlier returned by a malloc() function.

答:
```<code>const char *p = "";
</code>```

Yields a valid null-terminated string (representing an empty string). Hence it may be used in functions accepting c-style strings, etc.

This is different from eg.:

```<code>const char *p = nullptr;
</code>```

Which isn't a valid string, and will fail in most functions accepting c-style strings (eg. std::string(nullptr) will yield UB, a crash most likely).

I wouldn't call it a programming technique.

Body:
My question is actually quite simply for those who might know about it, but I ask because I'm not aware of this technique already.

What is the reason for initializing or assigning an empty string literal to a pointer to char in C, or a pointer to const char in C++?

Like f.e.:

char* p = "";

or

char* p;
p = "";

Or, as suggested in the comments, in C++:

const char* p = "";

or

const char* p;
p = "";

I do often see this technique, but don't understand why someone shall assign an empty string literal to a char pointer (or pointer to const char for C++) or where this is coming from.

I have read Initialize a string in C to empty string, but this question is focused on initializing a char array with an empty string.

And I have also read: Initializing a string with the empty string, but this question covers an incorrect approach to assign an empty string to a pointer earlier returned by a malloc() function.

Body:
const char *p = "";

Yields a valid null-terminated string (representing an empty string). Hence it may be used in functions accepting c-style strings, etc.

This is different from eg.:

const char *p = nullptr;

Which isn't a valid string, and will fail in most functions accepting c-style strings (eg. std::string(nullptr) will yield UB, a crash most likely).

I wouldn't call it a programming technique.


问:
How to get text content of one h3 at a time in javascript?
I am having difficulty to get text content of h1 at a time when I click on any button element . Can anyone help me out please?     </p>

```<code>    <div id="makeSelection" ><h1>Text Content 1</h1>
    <button onclick="eveent()">Click Me</button>
    </div>
    <div id="makeSelection" ><h1>Text Content 2</h1>
        <button onclick="eveent()">Click Me</button>
    </div>
    <div id="makeSelection" ><h1>Text Content 3</h1>
        <button onclick="eveent()">Click Me</button>
    </div>

     function eveent(){

        var text = document.getElementById('makeSelection').textContent;

        console.log(text);

                    }
</code>```

答:
I would suggest to make addEventListener in javascript and clear the click event from HTML template..

Then use eveent.bind(this, item.textContent) to bind the particular item which was listened in click event.

Edit:

If you want to add event listener to a button, then get the button like, (Assuming you have class name for each div as makeSelection and not same id's repeated.

```<code>const selection = document.querySelectorAll(".makeSelection button");
</code>```

Then make an event listener like,

```<code>item.addEventListener('click', eveent.bind(this,item.previousElementSibling.textContent))
</code>```

Through item.previousElementSibling.textContent , we are passing the textContent of h1 tag..

const selection = document.querySelectorAll(".makeSelection button");

function eveent(clickedItem){
  console.log(clickedItem)
}

selection.forEach((item,i) => {
  item.addEventListener('click', eveent.bind(this,item.previousElementSibling.textContent))
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="makeSelection" >
  <h1>Text Content 1</h1>
   <button>Click Me</button>
 </div>
 <div class="makeSelection">
   <h1>Text Content 2</h1>
   <button>Click Me</button>
 </div>
 <div class="makeSelection">
   <h1>Text Content 3</h1>
   <button>Click Me</button>
 </div></code>```

Body:
I am having difficulty to get text content of h1 at a time when I click on any button element . Can anyone help me out please?

Text Content 1

    <button onclick="eveent()">Click Me</button>

Text Content 2

        <button onclick="eveent()">Click Me</button>

Text Content 3

        <button onclick="eveent()">Click Me</button>

     function eveent(){

        var text = document.getElementById('makeSelection').textContent;

        console.log(text);

                    }

Body:
I would suggest to make addEventListener in javascript and clear the click event from HTML template..

Then use eveent.bind(this, item.textContent) to bind the particular item which was listened in click event.

Edit:

If you want to add event listener to a button, then get the button like, (Assuming you have class name for each div as makeSelection and not same id's repeated.

const selection = document.querySelectorAll(".makeSelection button");

Then make an event listener like,

item.addEventListener('click', eveent.bind(this,item.previousElementSibling.textContent))

Through item.previousElementSibling.textContent , we are passing the textContent of h1 tag..

const selection = document.querySelectorAll(".makeSelection button");

function eveent(clickedItem){
  console.log(clickedItem)
}

selection.forEach((item,i) => {
  item.addEventListener('click', eveent.bind(this,item.previousElementSibling.textContent))
})

<div class="makeSelection" >
  <h1>Text Content 1</h1>
   <button>Click Me</button>
 </div>
 <div class="makeSelection">
   <h1>Text Content 2</h1>
   <button>Click Me</button>
 </div>
 <div class="makeSelection">
   <h1>Text Content 3</h1>
   <button>Click Me</button>
 </div>


问:
How to define a route with loadChildren property (lazy) inside an Angular library?
We have a large Angular 8 app that we want to split into several parts (libraries). We would like each library to define its own routes without losing lazy-loading ability. But we are facing compilation error.

Library routing module:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'app1',
    loadChildren: () => import('./modules/demo/demo.module').then(m => m.DemoModule)
  },
  {
    path: '',
    redirectTo: 'app1',
    pathMatch: 'full',
  }
];

// @dynamic
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MyLibraryRoutingModule { }
</code>```

Here is the first error we ran into:

Lambda not supported

This is the reason why we added the // @dynamic flag. But then we got the following error:

"ERROR: You must set "output.dir" instead of "output.file" when generating multiple chunks."

And we don't clearly understand the point.

I came across this post from Google staff which suggests that we are doing something wrong...

Could anyone confirm and ideally explain why that it is definitively no way to define lazy-routes from a library?

答:
import { ApplicationModule } from './application.module';
...
export function getAppModule() {
    return ApplicationModule;
}
...
loadChildren: getAppModule
```

Body:
We have a large Angular 8 app that we want to split into several parts (libraries). We would like each library to define its own routes without losing lazy-loading ability. But we are facing compilation error.

Library routing module:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'app1',
    loadChildren: () => import('./modules/demo/demo.module').then(m => m.DemoModule)
  },
  {
    path: '',
    redirectTo: 'app1',
    pathMatch: 'full',
  }
];

// @dynamic
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MyLibraryRoutingModule { }

Here is the first error we ran into:

Lambda not supported

This is the reason why we added the // @dynamic flag. But then we got the following error:

"ERROR: You must set "output.dir" instead of "output.file" when generating multiple chunks."

And we don't clearly understand the point.

I came across this post from Google staff which suggests that we are doing something wrong...

Could anyone confirm and ideally explain why that it is definitively no way to define lazy-routes from a library?


问:
Connect Hbase Stand Alone in Virtualbox VM from Windows 10 with Java application
i´m trying to connect (and create new table) to HBase intalled in a Ubuntu VM using a Java app running in Windows 10.

I´m sure that HBase is working and java code too because if i send it directly in the Intellij installed inside VM it´s works, but if i launch java app in Windows (host maquine) returns this error:

"Exception in thread "main" org.apache.hadoop.hbase.client.RetriesExhaustedException: Failed after attempts=5, exceptions:
2020-02-17T15:38:25.890Z, RpcRetryingCaller{globalStartTime=1581953902178, pause=100, maxAttempts=5}, org.apache.hadoop.hbase.MasterNotRunningException: java.net.ConnectException: Call to danny-VirtualBox/192.168.56.101:16000 failed on connection exception: org.apache.hbase.thirdparty.io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: danny-VirtualBox/192.168.56.101:16000"

I have this code:

```<code>    public static void main(String[] args) throws Exception {

    Configuration con = HBaseConfiguration.create();

    con.clear();
    con.set("hbase.zookeeper.quorum", "192.168.56.101");
    con.set("hbase.master", "192.168.56.101:16000");
    con.set("hbase.zookeeper.property.clientport", "2181");
    con.set("hbase.client.retries.number", "4");
    con.set("hbase.rpc.timeout", "3000");
    con.set("hbase.security.authentication", "simple");
    con.set("zookeeper.znode.parent", "/hbase");

    Connection conn = ConnectionFactory.createConnection(con);
    Admin admin  = conn.getAdmin();

    // Instantiating table descriptor class
    HTableDescriptor tableDescriptor = new
            HTableDescriptor(TableName.valueOf("emp2"));

    // Adding column families to table descriptor
    tableDescriptor.addFamily(new HColumnDescriptor("personal"));
    tableDescriptor.addFamily(new HColumnDescriptor("professional"));

    // Execute the table through admin
    admin.createTable(tableDescriptor);
    System.out.println(" Table created ");}
</code>```

I´m sure that Host can "see" VM because i can open HBase Web panel in Windows

(http://192.168.56.101:16010/master-status)

So, i think problem is ports or something about net security but i could not resolve the issues. Colud you help me?

IP windows machine: 192.168.56.1
IP VM: 192.168.56.101

I have modify host file in vm (hbase machine) with this values:

答:
Finally i resolved the issue, you have to edit hosts file in HBase server to change the line:

127.0.0.1 localhost
for
192.168.56.101 nameServer

Body:
i´m trying to connect (and create new table) to HBase intalled in a Ubuntu VM using a Java app running in Windows 10.

I´m sure that HBase is working and java code too because if i send it directly in the Intellij installed inside VM it´s works, but if i launch java app in Windows (host maquine) returns this error:

"Exception in thread "main" org.apache.hadoop.hbase.client.RetriesExhaustedException: Failed after attempts=5, exceptions:
2020-02-17T15:38:25.890Z, RpcRetryingCaller{globalStartTime=1581953902178, pause=100, maxAttempts=5}, org.apache.hadoop.hbase.MasterNotRunningException: java.net.ConnectException: Call to danny-VirtualBox/192.168.56.101:16000 failed on connection exception: org.apache.hbase.thirdparty.io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: danny-VirtualBox/192.168.56.101:16000"

I have this code:

    public static void main(String[] args) throws Exception {

    Configuration con = HBaseConfiguration.create();

    con.clear();
    con.set("hbase.zookeeper.quorum", "192.168.56.101");
    con.set("hbase.master", "192.168.56.101:16000");
    con.set("hbase.zookeeper.property.clientport", "2181");
    con.set("hbase.client.retries.number", "4");
    con.set("hbase.rpc.timeout", "3000");
    con.set("hbase.security.authentication", "simple");
    con.set("zookeeper.znode.parent", "/hbase");

    Connection conn = ConnectionFactory.createConnection(con);
    Admin admin  = conn.getAdmin();

    // Instantiating table descriptor class
    HTableDescriptor tableDescriptor = new
            HTableDescriptor(TableName.valueOf("emp2"));

    // Adding column families to table descriptor
    tableDescriptor.addFamily(new HColumnDescriptor("personal"));
    tableDescriptor.addFamily(new HColumnDescriptor("professional"));

    // Execute the table through admin
    admin.createTable(tableDescriptor);
    System.out.println(" Table created ");}

I´m sure that Host can "see" VM because i can open HBase Web panel in Windows

(http://192.168.56.101:16010/master-status)

So, i think problem is ports or something about net security but i could not resolve the issues. Colud you help me?

IP windows machine: 192.168.56.1
IP VM: 192.168.56.101

I have modify host file in vm (hbase machine) with this values:


问:
Is there a script to delete a row based on a particular cell value
I'm trying to find a script for a button so that when I press it, if a certain cell contains any number that's less than 5, the row it's on is deleted. For instance, cell G13 is <5 so delete row.

I can't find anything online for this type of script - is this possible?

答:
Small sample:

Delete a row if a cell value is <5:

```<code>function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var cell = sheet.getRange("G13");
  var cellContent = cell.getValue();
  if (cellContent < 5){
    var row = cell.getRow();
    sheet.deleteRow(row);
  }
}
</code>```

UPDATE:

Delete all rows where  a cell value in a certain column is <5:

```<code>function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var columnG = sheet.getRange(1,7, sheet.getLastRow(), 1).getValues();
  for (var i = 0; i < columnG.length; i++){
    var cellContent = columnG[i][0];
    if (cellContent < 5){
      var row = i+1;
      sheet.deleteRow(row);
    }
  }
}
</code>```

I recommend you to study the Apps Script documentation to gain a deeper understanding.

Body:
Small sample:

Delete a row if a cell value is <5:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var cell = sheet.getRange("G13");
  var cellContent = cell.getValue();
  if (cellContent < 5){
    var row = cell.getRow();
    sheet.deleteRow(row);
  }
}

UPDATE:

Delete all rows where  a cell value in a certain column is <5:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var columnG = sheet.getRange(1,7, sheet.getLastRow(), 1).getValues();
  for (var i = 0; i < columnG.length; i++){
    var cellContent = columnG[i][0];
    if (cellContent < 5){
      var row = i+1;
      sheet.deleteRow(row);
    }
  }
}

I recommend you to study the Apps Script documentation to gain a deeper understanding.


问:
Redirect several HTTP servers to HTTPS in nginx
I have an application that serves different pages(connects to a different DB) based on the subdomain name.

So, let's say I have subdomains docs-for-app1.domain.com, docs-for-app2.domain.com and docs-for-app3.domain.com. They use the same PHP code, so I'd like to configure only one server in nginx.

The configuration for this scenario can look like this:

```<code>server {
    listen 80;
    listen [::]:80;

    root /var/www/html/docs/;

    index index.php;

    server_name docs-for-app1.domain.com docs-for-app2.domain.com docs-for-app3.domain.com;

######################## REDIRECT ############################
##############################################################
    if ($http_x_forwarded_proto = "http") {
        return 301 https://$server_name$request_uri;
    }
##############################################################

    location / {
            try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.3-fpm.sock;
            fastcgi_read_timeout 10m;
    }

    location ~ /\.ht {
            deny all;
    }
}
</code>```

Everything works fine except one thing. My firewall with proxy server is not able to redirect HTTP to HTTPS. I have to do it in the nginx server. As you can see I've tried to do it (marked part of the cfg) but it doesn't work as I expect. The problem is that $server_name always returns name docs-for-app1.domain.com no matter the real host name.

What is the right way to do this redirection?

答:
$server_name

name of the server which accepted a request

To redirect to the 'requested' host use the $host variable;

```<code>return 301 https://$host$request_uri;
</code>```

$host

in this order of precedence: host name from the request line, or host name from the “Host” request header field, or the server name matching a request

Body:
I have an application that serves different pages(connects to a different DB) based on the subdomain name.

So, let's say I have subdomains docs-for-app1.domain.com, docs-for-app2.domain.com and docs-for-app3.domain.com. They use the same PHP code, so I'd like to configure only one server in nginx.

The configuration for this scenario can look like this:

server {
    listen 80;
    listen [::]:80;

    root /var/www/html/docs/;

    index index.php;

    server_name docs-for-app1.domain.com docs-for-app2.domain.com docs-for-app3.domain.com;

######################## REDIRECT ############################
##############################################################
    if ($http_x_forwarded_proto = "http") {
        return 301 https://$server_name$request_uri;
    }
##############################################################

    location / {
            try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.3-fpm.sock;
            fastcgi_read_timeout 10m;
    }

    location ~ /\.ht {
            deny all;
    }
}

Everything works fine except one thing. My firewall with proxy server is not able to redirect HTTP to HTTPS. I have to do it in the nginx server. As you can see I've tried to do it (marked part of the cfg) but it doesn't work as I expect. The problem is that $server_name always returns name docs-for-app1.domain.com no matter the real host name.

What is the right way to do this redirection?

Body:
$server_name

name of the server which accepted a request

To redirect to the 'requested' host use the $host variable;

return 301 https://$host$request_uri;

$host

in this order of precedence: host name from the request line, or host name from the “Host” request header field, or the server name matching a request


问:
What canvas am I drawing to in myLocationOverylay
I am using the MyLocationOverlay in Google Maps API and I don't understand what canvas I should pass to drawMyLocation. Here is some of my code:

```<code>import android.content.Context;
import android.graphics.Canvas;

import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

public class MyLocationDot extends MyLocationOverlay {
    private MapView mMapView;

    public MyLocationDot(Context context, MapView mapView) {
        super(context, mapView);
        mMapView = mapView;
    }

    protected void drawMyLocation(Canvas canvas) {
        super.drawMyLocation(canvas, mMapView, getLastFix(), getMyLocation(), 0);
    }

}
</code>```

And in my onCreate() of the map activity:

```<code>// my location
        myLocation = new MyLocationDot(this, mapView);
        myLocation.enableMyLocation();
        myLocation.runOnFirstFix(new Runnable() {
            public void run() {
                myLocation.drawMyLocation(WhatCanvas??);
            }
        });
</code>```

答:
Unless I'm wrong you don't explicitly pass a Canvas: you pass your overlay to the MapActivity and it deals with that for you.

EDIT: so something like this.

```<code> mapView = (MapView) findViewById(R.id.map);
 me = new MyLocationDot(this, mapView);
 mapView.getOverlays().add(me);
</code>```

Body:
I am using the MyLocationOverlay in Google Maps API and I don't understand what canvas I should pass to drawMyLocation. Here is some of my code:

import android.content.Context;
import android.graphics.Canvas;

import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

public class MyLocationDot extends MyLocationOverlay {
    private MapView mMapView;

    public MyLocationDot(Context context, MapView mapView) {
        super(context, mapView);
        mMapView = mapView;
    }

    protected void drawMyLocation(Canvas canvas) {
        super.drawMyLocation(canvas, mMapView, getLastFix(), getMyLocation(), 0);
    }

}

And in my onCreate() of the map activity:

// my location
        myLocation = new MyLocationDot(this, mapView);
        myLocation.enableMyLocation();
        myLocation.runOnFirstFix(new Runnable() {
            public void run() {
                myLocation.drawMyLocation(WhatCanvas??);
            }
        });

Body:
Unless I'm wrong you don't explicitly pass a Canvas: you pass your overlay to the MapActivity and it deals with that for you.

EDIT: so something like this.

 mapView = (MapView) findViewById(R.id.map);
 me = new MyLocationDot(this, mapView);
 mapView.getOverlays().add(me);


问:
Failed Deployment in App Engine Google Cloud
I am deploying my nodejs application in google cloud app engine but it is giving error
This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time.
This request may thus take longer and use more CPU than a typical request for your application. -- when making request.

I had also saw some stackoverflow answers, but they didn't worked for me.

my app.yaml have this config

runtime: nodejs10

Can anyone help me out

答:
You could add the following to your app.yaml:

```<code>inbound_services:
- warmup
</code>```

And then implement a handler that will catch all warmup requests, so that your application doesn't get the full load. The full explanation is given here. Another detailed post about this topic can be found here.

Additionally you can also add automatic scaling options. You can play a bit with those to find the optimum for your application. Especially the latency related variables are important. Good to note that they can be set in a standard GAE environment.

```<code>automatic_scaling:
  min_idle_instances: automatic
  max_idle_instances: automatic
  min_pending_latency: automatic
  max_pending_latency: automatic
</code>```

More scaling options can be found here.

Body:
You could add the following to your app.yaml:

inbound_services:
- warmup

And then implement a handler that will catch all warmup requests, so that your application doesn't get the full load. The full explanation is given here. Another detailed post about this topic can be found here.

Additionally you can also add automatic scaling options. You can play a bit with those to find the optimum for your application. Especially the latency related variables are important. Good to note that they can be set in a standard GAE environment.

automatic_scaling:
  min_idle_instances: automatic
  max_idle_instances: automatic
  min_pending_latency: automatic
  max_pending_latency: automatic

More scaling options can be found here.


问:
template with specified mode does not match problem
I need to calculate a few values and store them in a variable. I pass a document node into xsl:apply-templates and specify the mode:

```<code><xsl:variable as="xs:string*" name="checkAccidentalsVisibility">
    <xsl:apply-templates  mode="checkAccidentalsVisibility" select="$extractMainVersion"/>
</xsl:variable>
</code>```

But the template for this mode does not match:

```<code><xsl:template match="body//@accid[not(parent::accid/@func[. = 'caution'] or ancestor::note[@grace])]" mode="checkAccidentalsVisibility" >...
</code>```

The identity transform template is specified like this, bcs I don't need to copy the xml tree.

```<code><xsl:template match="node() | @*" mode="extractMainVersion changeAccid">
    <xsl:copy>
        <xsl:apply-templates mode="#current" select="node() | @*"/>
    </xsl:copy>
</xsl:template>
</code>```

The value of $checkAccidentalsVisibility is the text node. For instance, applied on this XML I get an example:

```<code><?xml version="1.0" encoding="UTF-8"?>
    <mei meiversion="3.0.0" xml:id="dme92517025-f4c2-4231-a1c3-b70f02802d61" xmlns="http://www.music-encoding.org/ns/mei">
        <meiHead meiversion="3.0.0">
            <fileDesc>
                <titleStmt>
                    <title label="NMA digital" type="unit">an example</title>
                </titleStmt>
                <pubStmt/>
            </fileDesc>
        </meiHead>
        <music meiversion="3.0.0">
            <body>
                <mdiv n="2a" xml:id="mdiv_">
                    <score xml:id="score_">
                        <section label="menuetto_A" xml:id="section_A_m1-5">
                            <measure n="1" xml:id="m1_k_">
                                <staff n="1" xml:id="staff_108">
                                    <layer n="1" xml:id="layer_114">
                                        <note accid.ges="f" dur="2" oct="4" pname="e" tstamp="1" xml:id="note_120"/>
                                        <choice xml:id="choice_132">
                                            <sic xml:id="corr_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132">
                                                    <accid accid="f"  xml:id="accid_138"/>
                                                </note>
                                            </sic>
                                            <orig xml:id="orig_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132b">
                                                    <accid accid="f"  xml:id="accid_138b"/>
                                                </note>
                                            </orig>
                                        </choice>
                                    </layer>
                                </staff>
                            </measure>
                        </section>
                    </score>
                </mdiv>
            </body>
        </music>
    </mei>
</code>```

I am expecting a sequence of @xml:id-values which I derive from my calculations.

答:
The whole xslt is quite large and modularized. I do not know how is it possible to post here all the content... E.g. this is the main stylesheet:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet exclude-result-prefixes="xs xd mei dme map" version="3.0" xmlns:dme="http://www.mozarteum.at/ns/dme" xmlns:map="http://www.w3.org/2005/xpath-functions/map" xmlns:mei="http://www.music-encoding.org/ns/mei" xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xpath-default-namespace="http://www.music-encoding.org/ns/mei">

    <xsl:include href="modules/basic.xsl"/>
    <xsl:include href="modules/extractMainVersion.xsl"/>
    <xsl:include href="modules/check_contextNote.xsl"/>
    <xsl:include href="modules/changeAccid.xsl"/>

    <xsl:variable as="xs:string*" name="checkAccidentalsVisibility">
        <xsl:variable name="extractMainVersion">
            <xsl:apply-templates mode="extractMainVersion" select="."/>
        </xsl:variable>
        <xsl:apply-templates  mode="checkAccidentalsVisibility" select="$extractMainVersion//@accid"/>
    </xsl:variable>

    <xd:doc>
        <xd:desc/>
    </xd:doc>
    <xsl:template match="/">
        <xsl:apply-templates mode="changeAccid" select="."/>
    </xsl:template>

</xsl:stylesheet>
</code>```

The template

```<code><xsl:template match="body//@accid[not(parent::accid/@func[. = 'caution'] or ancestor::note[@grace])]" mode="checkAccidentalsVisibility" >...
</code>```

is placed in check_contextNote.xsl. And this is the only template with the mode checkAccidentalsVisibility but it calls plenty of other templates and functions later.

Originally, I didn't have the $checkAccidentalsVisibility and did not need to have various modes and the template was matched well. Later, I needed to change the program logic and separate the following:

Change the original document-node() based on the calculated values

The values should be calculated from the modified document-node() (that is what the $extractMainVersion contains)

So I added three modes. Two of them I added to the identity transform template (originally, it was set to #all). This is basic.xsl:

```<code>   <xsl:stylesheet exclude-result-prefixes="xs xd mei dme map" version="3.0" xmlns:dme="http://www.mozarteum.at/ns/dme" xmlns:map="http://www.w3.org/2005/xpath-functions/map" xmlns:mei="http://www.music-encoding.org/ns/mei" xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xpath-default-namespace="http://www.music-encoding.org/ns/mei">

        <xsl:output encoding="UTF-8" indent="yes" method="xml"/>
        <xsl:strip-space elements="*"/>

        <xsl:template match="node() | @*" mode="extractMainVersion changeAccid">
            <xsl:copy>
                <xsl:apply-templates mode="#current" select="node() | @*"/>
            </xsl:copy>
        </xsl:template>

    </xsl:stylesheet>
</code>```

Body:
I need to calculate a few values and store them in a variable. I pass a document node into xsl:apply-templates and specify the mode:

<xsl:variable as="xs:string*" name="checkAccidentalsVisibility">
    <xsl:apply-templates  mode="checkAccidentalsVisibility" select="$extractMainVersion"/>
</xsl:variable>

But the template for this mode does not match:

<xsl:template match="body//@accid[not(parent::accid/@func[. = 'caution'] or ancestor::note[@grace])]" mode="checkAccidentalsVisibility" >...

The identity transform template is specified like this, bcs I don't need to copy the xml tree.

<xsl:template match="node() | @*" mode="extractMainVersion changeAccid">
    <xsl:copy>
        <xsl:apply-templates mode="#current" select="node() | @*"/>
    </xsl:copy>
</xsl:template>

The value of $checkAccidentalsVisibility is the text node. For instance, applied on this XML I get an example:

<?xml version="1.0" encoding="UTF-8"?>
    <mei meiversion="3.0.0" xml:id="dme92517025-f4c2-4231-a1c3-b70f02802d61" xmlns="http://www.music-encoding.org/ns/mei">
        <meiHead meiversion="3.0.0">
            <fileDesc>
                <titleStmt>
                    <title label="NMA digital" type="unit">an example</title>
                </titleStmt>
                <pubStmt/>
            </fileDesc>
        </meiHead>
        <music meiversion="3.0.0">

                <mdiv n="2a" xml:id="mdiv_">
                    <score xml:id="score_">

                            <measure n="1" xml:id="m1_k_">
                                <staff n="1" xml:id="staff_108">
                                    <layer n="1" xml:id="layer_114">
                                        <note accid.ges="f" dur="2" oct="4" pname="e" tstamp="1" xml:id="note_120"/>
                                        <choice xml:id="choice_132">
                                            <sic xml:id="corr_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132">
                                                    <accid accid="f"  xml:id="accid_138"/>
                                                </note>
                                            </sic>
                                            <orig xml:id="orig_132">
                                                <note dur="4" oct="4" pname="e" tstamp="3" xml:id="note_132b">
                                                    <accid accid="f"  xml:id="accid_138b"/>
                                                </note>
                                            </orig>
                                        </choice>
                                    </layer>
                                </staff>
                            </measure>

                    </score>
                </mdiv>

        </music>
    </mei>

I am expecting a sequence of @xml:id-values which I derive from my calculations.

Body:
The whole xslt is quite large and modularized. I do not know how is it possible to post here all the content... E.g. this is the main stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet exclude-result-prefixes="xs xd mei dme map" version="3.0" xmlns:dme="http://www.mozarteum.at/ns/dme" xmlns:map="http://www.w3.org/2005/xpath-functions/map" xmlns:mei="http://www.music-encoding.org/ns/mei" xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xpath-default-namespace="http://www.music-encoding.org/ns/mei">

    <xsl:include href="modules/basic.xsl"/>
    <xsl:include href="modules/extractMainVersion.xsl"/>
    <xsl:include href="modules/check_contextNote.xsl"/>
    <xsl:include href="modules/changeAccid.xsl"/>

    <xsl:variable as="xs:string*" name="checkAccidentalsVisibility">
        <xsl:variable name="extractMainVersion">
            <xsl:apply-templates mode="extractMainVersion" select="."/>
        </xsl:variable>
        <xsl:apply-templates  mode="checkAccidentalsVisibility" select="$extractMainVersion//@accid"/>
    </xsl:variable>

    <xd:doc>
        <xd:desc/>
    </xd:doc>
    <xsl:template match="/">
        <xsl:apply-templates mode="changeAccid" select="."/>
    </xsl:template>

</xsl:stylesheet>

The template

<xsl:template match="body//@accid[not(parent::accid/@func[. = 'caution'] or ancestor::note[@grace])]" mode="checkAccidentalsVisibility" >...

is placed in check_contextNote.xsl. And this is the only template with the mode checkAccidentalsVisibility but it calls plenty of other templates and functions later.

Originally, I didn't have the $checkAccidentalsVisibility and did not need to have various modes and the template was matched well. Later, I needed to change the program logic and separate the following:

Change the original document-node() based on the calculated values

The values should be calculated from the modified document-node() (that is what the $extractMainVersion contains)

So I added three modes. Two of them I added to the identity transform template (originally, it was set to #all). This is basic.xsl:

   <xsl:stylesheet exclude-result-prefixes="xs xd mei dme map" version="3.0" xmlns:dme="http://www.mozarteum.at/ns/dme" xmlns:map="http://www.w3.org/2005/xpath-functions/map" xmlns:mei="http://www.music-encoding.org/ns/mei" xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xpath-default-namespace="http://www.music-encoding.org/ns/mei">

        <xsl:output encoding="UTF-8" indent="yes" method="xml"/>
        <xsl:strip-space elements="*"/>

        <xsl:template match="node() | @*" mode="extractMainVersion changeAccid">
            <xsl:copy>
                <xsl:apply-templates mode="#current" select="node() | @*"/>
            </xsl:copy>
        </xsl:template>

    </xsl:stylesheet>


问:
Maven surefire tests - includes and excludes
I have a class A.java and two test classes, ATest.java and AITests.java. The ITest is for integration. The tests must be performed as:

When no Maven profile is selected only the Atest must be tested.

When the itests profile is activated the both tests (ATest and AITest) must be tested.

The problems is, when I use the command

```<code>mvn -P itests test
</code>```

then only the ATest is tested, without the AITest. But I have no idea what I am missing here. Any hint?

My pom.xml is:

```<code>...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M4</version>
            <configuration>
                <excludes>
                    <exclude>**/*ITest.java</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>itests</id>
        <activation>
            <property>
                <name>itests</name>
                <value>true</value>
            </property>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M4</version>
                    <configuration>
                        <includes>
                            <include>**/*Test.java</include>
                        </includes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
...
</code>```

答:
For integration tests, please use the Maven failsafe plugin:

https://maven.apache.org/surefire/maven-failsafe-plugin/

You can skip it on the command line if you prefer.

Body:
I have a class A.java and two test classes, ATest.java and AITests.java. The ITest is for integration. The tests must be performed as:

When no Maven profile is selected only the Atest must be tested.

When the itests profile is activated the both tests (ATest and AITest) must be tested.

The problems is, when I use the command

mvn -P itests test

then only the ATest is tested, without the AITest. But I have no idea what I am missing here. Any hint?

My pom.xml is:

...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M4</version>
            <configuration>
                <excludes>
                    <exclude>**/*ITest.java</exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>itests</id>
        <activation>
            <property>
                <name>itests</name>
                <value>true</value>
            </property>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.0.0-M4</version>
                    <configuration>
                        <includes>
                            <include>**/*Test.java</include>
                        </includes>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
...


问:
How to get rid of special tags by using BeautifulSoup?
```<code>from bs4 import BeautifulSoup
import requests

url = 'https://www.jisilu.cn/data/cf/cf_list/?'
res = requests.get(url)
soup = BeautifulSoup(res.content, 'html.parser')
print(soup)
</code>```

I try to use BeautifulSoup to get data. However 'html.parser' does not filter bunch of  tags at the end. How to get rid of these tags.

```<code>{"page":1,"rows":[{"id":"160142","cell":{"fund_id":"160142", ...  ,"daily_spread":"-0.07%"}}],"total":42}</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span>
</code>```

答:
No need to parse the html. It's a json structure, so read that in with .json()

```<code>import requests

url = 'https://www.jisilu.cn/data/cf/cf_list/?'
res = requests.get(url).json()
print (res)
</code>```

Body:
from bs4 import BeautifulSoup
import requests

url = 'https://www.jisilu.cn/data/cf/cf_list/?'
res = requests.get(url)
soup = BeautifulSoup(res.content, 'html.parser')
print(soup)

I try to use BeautifulSoup to get data. However 'html.parser' does not filter bunch of  tags at the end. How to get rid of these tags.

{"page":1,"rows":[{"id":"160142","cell":{"fund_id":"160142", ...  ,"daily_spread":"-0.07%"}}],"total":42}

Body:
No need to parse the html. It's a json structure, so read that in with .json()

import requests

url = 'https://www.jisilu.cn/data/cf/cf_list/?'
res = requests.get(url).json()
print (res)


问:
VBA multiple if else if statement with range and text
would you anyone pls help me with this. when i run the marcos, i got wrong number of arguments and invalid property </p>

```<code>If Range(("K2") = "Technical", ("J2") = "Band 23", ("J2") = "Band 24") Then
    Range("U2").Value = "Core Team Trained"
    Else: If Range(("K2") = "Technical", ("J2") = "Band 25", "Band 26", "Band 30") Then Range("U2").Value = "PL Trained"
    Else: If Range(("K2") = "Management", ("J2") = "Band 25", "Band 26", "Band 30", "Band 31", "Band 40") Then Range("U2").Value = "Champion Trained"
    Else: If Range(("K2") = "Project Mgm", ("J2") = "Band 21", "Band 22", "Band 23") Then Range("U2").Value = "CORE TEAM MEMBER TRAINED"
    Else: If Range(("K2") = "Project Mgm", ("J2") = "Band 24") Then Range("U2").Value = "PL TRAINED"
    Else: If Range(("K2") = "Project Mgm", ("J2") = "Band 25") Then Range("U2").Value = "PL CERTIFIED"
    Else: If Range(("K2") = "Project Mgm", ("J2") = "Band 26") Then Range("U2").Value = "SME TRAINED"
    Else: If Range(("K2") = "Project Mgm", ("J2") = "Band 30") Then Range("U2").Value = "SME CERTIFIED"

End If

End Sub
</code>```

答:
To get you started, I would advise using a Select Case structure and make sure to at least use a Worksheet reference to avoid the implicit ActiveSheet. You never know where your code may get accessed from.

```<code>Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")

With ws
    Select Case .Range("K2").Value
    Case "Technical"
        Select Case CLng(Right(.Range("J2").Value, 2))
        Case 23, 24
            .Range("U2").Value = "Core Team Trained"
        Case 25, 26, 30
            .Range("U2").Value = "PL Trained"
        End Select
    Case "Management"
        Select Case CLng(Right(.Range("J2").Value, 2))
        Case 25, 26, 30, 31, 40
            .Range("U2").Value = "Champion Trained"
        End Select
    Case "Project Mgm"
        Select Case CLng(Right(.Range("J2").Value, 2))
        Case 21 - 23
            .Range("U2").Value = "CORE TEAM MEMBER TRAINED"
        Case 24
            .Range("U2").Value = "PL TRAINED"
        Case 25
            .Range("U2").Value = "PL CERTIFIED"
        Case 26
            .Range("U2").Value = "SME TRAINED"
        Case 30
            .Range("U2").Value = "SME CERTIFIED"
        End Select
    End Select
End With

End Sub
</code>```

Not the shortest of codes, but clarity does come a long way.

Body:
would you anyone pls help me with this. when i run the marcos, i got wrong number of arguments and invalid property

If Range(("K2") = "Technical", ("J2") = "Band 23", ("J2") = "Band 24") Then
    Range("U2").Value = "Core Team Trained"
    Else: If Range(("K2") = "Technical", ("J2") = "Band 25", "Band 26", "Band 30") Then Range("U2").Value = "PL Trained"
    Else: If Range(("K2") = "Management", ("J2") = "Band 25", "Band 26", "Band 30", "Band 31", "Band 40") Then Range("U2").Value = "Champion Trained"
    Else: If Range(("K2") = "Project Mgm", ("J2") = "Band 21", "Band 22", "Band 23") Then Range("U2").Value = "CORE TEAM MEMBER TRAINED"
    Else: If Range(("K2") = "Project Mgm", ("J2") = "Band 24") Then Range("U2").Value = "PL TRAINED"
    Else: If Range(("K2") = "Project Mgm", ("J2") = "Band 25") Then Range("U2").Value = "PL CERTIFIED"
    Else: If Range(("K2") = "Project Mgm", ("J2") = "Band 26") Then Range("U2").Value = "SME TRAINED"
    Else: If Range(("K2") = "Project Mgm", ("J2") = "Band 30") Then Range("U2").Value = "SME CERTIFIED"

End If

End Sub

Body:
To get you started, I would advise using a Select Case structure and make sure to at least use a Worksheet reference to avoid the implicit ActiveSheet. You never know where your code may get accessed from.

Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")

With ws
    Select Case .Range("K2").Value
    Case "Technical"
        Select Case CLng(Right(.Range("J2").Value, 2))
        Case 23, 24
            .Range("U2").Value = "Core Team Trained"
        Case 25, 26, 30
            .Range("U2").Value = "PL Trained"
        End Select
    Case "Management"
        Select Case CLng(Right(.Range("J2").Value, 2))
        Case 25, 26, 30, 31, 40
            .Range("U2").Value = "Champion Trained"
        End Select
    Case "Project Mgm"
        Select Case CLng(Right(.Range("J2").Value, 2))
        Case 21 - 23
            .Range("U2").Value = "CORE TEAM MEMBER TRAINED"
        Case 24
            .Range("U2").Value = "PL TRAINED"
        Case 25
            .Range("U2").Value = "PL CERTIFIED"
        Case 26
            .Range("U2").Value = "SME TRAINED"
        Case 30
            .Range("U2").Value = "SME CERTIFIED"
        End Select
    End Select
End With

End Sub

Not the shortest of codes, but clarity does come a long way.


问:
How to post the time ReactJs
I explain my problem of the day

in the following code, I post objects

my question, is it possible to post the time at which the post was made?

```<code>postbackend = () =>{
const config = {
method: "POST",
headers: {
  "Content-Type": "application/json",
},
body: JSON.stringify({...this.state, items:this.props.items}),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
  if (res.error) {
    alert(res.error);
  } else {
    alert(`ajouté avec l'ID ${res}!`);
  }
}).catch(e => {
  console.error(e);
}).finally(()=>this.setState({ redirect: true }));
}
</code>```

I would simply like to recover the time at which the post was made
Do you have an idea of how to fix this? Neff

答:
If you want to send the time with the request you could just add it to the body of the request like so:

```<code>JSON.stringify({...this.state, items:this.props.items, postTime: Date.now()})
</code>```

Date.now() returns the time in milliseconds since 1st January 1970.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date

If you want to format it to a string you can do the following:

const dateNow = Date.now(); // Date in milliseconds since 1st January 1970
const date = new Date(dateNow); //Creates a date object from the milliseconds

console.log(dateNow);
console.log(date);
console.log(date.toLocaleString('en-GB', { timeZone: 'UTC' }));```

I hope that helps you out.

Title: How to post the time ReactJs

Body:
I explain my problem of the day

in the following code, I post objects

my question, is it possible to post the time at which the post was made?

postbackend = () =>{
const config = {
method: "POST",
headers: {
  "Content-Type": "application/json",
},
body: JSON.stringify({...this.state, items:this.props.items}),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
  if (res.error) {
    alert(res.error);
  } else {
    alert(`ajouté avec l'ID ${res}!`);
  }
}).catch(e => {
  console.error(e);
}).finally(()=>this.setState({ redirect: true }));
}

I would simply like to recover the time at which the post was made
Do you have an idea of how to fix this? Neff

Body:
If you want to send the time with the request you could just add it to the body of the request like so:

JSON.stringify({...this.state, items:this.props.items, postTime: Date.now()})

Date.now() returns the time in milliseconds since 1st January 1970.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date

If you want to format it to a string you can do the following:

const dateNow = Date.now(); // Date in milliseconds since 1st January 1970
const date = new Date(dateNow); //Creates a date object from the milliseconds

console.log(dateNow);
console.log(date);
console.log(date.toLocaleString('en-GB', { timeZone: 'UTC' }));

I hope that helps you out.


问:
How can I parse email text for components like <salutation><signature><reply text> etc?
I'm writing an application that analyzes emails and it would save me a bunch of time if I could use a python library that would parse email text down into named components like <salutation><signature><reply text> etc.

For example, the following text "Hi Dave,\nLets meet up this Tuesday\nCheers, Tom\n\nOn Sunday, 15 May 2011 at 5:02 PM, Dave Trindall wrote: Hey Tom,\nHow about we get together ..." would be parsed as

```<code>Salutation: "Hi Dave,\n"
Body: "Lets meet up this Tuesday\n"
Signature: "Cheers, Tom\n\n"
Reply Text: "On Sunday, 15 May 2011 at 5:02 PM, Dave Trindal wrote: ..."
</code>```

I know there's no perfect solution for this kind of problem, but even a library that does good approximation would help. Where can I find one?

答:
If you score each line based on the types of words it contains you may get a fairly good indication.

E.G. A line with greeting words near the start is the salutation (also salutations may have phrases that refer to the past tense e.g. it was good to see you last time)

A Body will typically contain words such as "movie, concert" etc. It will also contain verbs (go to, run, walk, etc) and questions marks and offerings (e.g. want to, can we, should we, prefer..).
Check out http://nodebox.net/code/index.php/Linguistics#verb_conjugation
http://ogden.basic-english.org/
http://osteele.com/projects/pywordnet/

the signature will contain closing words.

If you find a datasource that has messages of the structure you want you could do some frequency analysis to see how often each word occurs in each section.

Each word would get a score [salutation score, body score, signature score,..]
e.g. hello could occur 900 times in the salutation, 10 times in the body, and 3 times in the signature.
this means hello would get assigned [900, 10, 3, ..]
cheers might get assigned [10,3,100,..]

now you will have a large list of about 500,000 words.
words that don't have a large range aren't useful.
e.g. catch might have [100,101,80..] = range of 21
(it was good to catch up, wanna go catch a fish, catch you later). catch can occur anywhere.

Now you can reduce the number of words down to about 10,000

now for each line, give the line a score also of the form [salutation score, body score, signature score,..]

this score is calculated by adding the vector scores of each word.

e.g. a sentence "hello cheers for giving me your number" could be:
[900, 10, 3, ..] + [10,3,100,..] + .. + .. + = [900+10+..,10+3+..,3+100,..]
=[1023,900,500,..] say

then because the biggest number is at the start in the salutation score position, this sentence is a salutation.

then if you had to score one of your lines to see what component the line should be in, for each word you would add on its score

Good luck, there is always a trade-off between computation complexity and accuracy. If you can find a good set of words and make a good model to base you calculations it will help.

Title: How can I parse email text for components like <salutation><body><signature><reply text> etc?

Body:
I'm writing an application that analyzes emails and it would save me a bunch of time if I could use a python library that would parse email text down into named components like <salutation><signature><reply text> etc.

For example, the following text "Hi Dave,\nLets meet up this Tuesday\nCheers, Tom\n\nOn Sunday, 15 May 2011 at 5:02 PM, Dave Trindall wrote: Hey Tom,\nHow about we get together ..." would be parsed as

Salutation: "Hi Dave,\n"
Body: "Lets meet up this Tuesday\n"
Signature: "Cheers, Tom\n\n"
Reply Text: "On Sunday, 15 May 2011 at 5:02 PM, Dave Trindal wrote: ..."

I know there's no perfect solution for this kind of problem, but even a library that does good approximation would help. Where can I find one?


问:
Pycharm Django Project using Vagrant Server: Error Package requirements are not satisfied
I am trying to start a Django Project using Vagrant and PyCharm Professional edition. I am using a Windows computer and my Vagrant file looks like this https://gist.github.com/LondonAppDev/d990ab5354673582c35df1ee277d6c24

Below is my project just in case (not really required to answer this question )
https://github.com/samirtendulkar/profiles-rest-api

Now through Pycharm Terminal I added

```<code>vagrant init
vagrant up
vagrant ssh
vagrant@ubuntu-xenial:/$ mkvirtualenv profiles_app_venv --python=python3
(profiles_app_venv) vagrant@ubuntu-xenial:/$ pip install django==1.11
(profiles_app_venv) vagrant@ubuntu-xenial:/$ pip install djangorestframework==3.6.2
</code>```

Then I added a src folder in my root project and started making another app

Then I created a requirements.txt

```<code>(name_of_env) vagrant@ubuntu-xenial:/vagrant/$ pip freeze > requirements.txt
</code>```

See Image below. I know that this is because my project in running on my Vagrant server and my Pycharm is running on my host server. But I am losing out on all of Pycharm's best features. How can I override this

Any Idea What I need to do here

答:
Here is what you need to do:

Ensure all the packages are listed in Project Interpreter settings.

In PyCharm, go to File | Invalidate Caches/Restart

Click on Invalidate and Restart.

Wait for IDE to finish updating.

You should be good as long as you are pointing to the correct interpreter and the packages are in the interpreter

Body:
I am trying to start a Django Project using Vagrant and PyCharm Professional edition. I am using a Windows computer and my Vagrant file looks like this https://gist.github.com/LondonAppDev/d990ab5354673582c35df1ee277d6c24

Below is my project just in case (not really required to answer this question )
https://github.com/samirtendulkar/profiles-rest-api

Now through Pycharm Terminal I added

vagrant init
vagrant up
vagrant ssh
vagrant@ubuntu-xenial:/$ mkvirtualenv profiles_app_venv --python=python3
(profiles_app_venv) vagrant@ubuntu-xenial:/$ pip install django==1.11
(profiles_app_venv) vagrant@ubuntu-xenial:/$ pip install djangorestframework==3.6.2

Then I added a src folder in my root project and started making another app

Then I created a requirements.txt

(name_of_env) vagrant@ubuntu-xenial:/vagrant/$ pip freeze > requirements.txt

See Image below. I know that this is because my project in running on my Vagrant server and my Pycharm is running on my host server. But I am losing out on all of Pycharm's best features. How can I override this

Any Idea What I need to do here


问:
Is view.leadingAnchor.constraint higher precedence than view.trailingAnchor.constraint?
I have my ViewController code as below

```<code>class ViewController: UIViewController {

    override func viewDidLoad() {
    super.viewDidLoad()
        view.backgroundColor = .white
        let titleLabel = UILabel()
        titleLabel.text = "Hello World!"

        view.addSubview(titleLabel)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            titleLabel.topAnchor.constraint(equalTo: view.topAnchor),
            titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            titleLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }
}
</code>```

I'm expecting my "Hello World!" to be center aligned. Why wasn't it center aligned? (Vertically it is centered, but horizontally it is aligned to left as shown below.)

p/s: If I remove itleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor), then it is aligned right.

答:
Until and unless we are not changing priority of constraint the default priority is 1000 for all. So no precedence setting automatically.

For your code, add this line and it will work.

```<code>    titleLabel.textAlignment = .center
</code>```

Body:
I have my ViewController code as below

class ViewController: UIViewController {

    override func viewDidLoad() {
    super.viewDidLoad()
        view.backgroundColor = .white
        let titleLabel = UILabel()
        titleLabel.text = "Hello World!"

        view.addSubview(titleLabel)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            titleLabel.topAnchor.constraint(equalTo: view.topAnchor),
            titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            titleLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }
}

I'm expecting my "Hello World!" to be center aligned. Why wasn't it center aligned? (Vertically it is centered, but horizontally it is aligned to left as shown below.)

p/s: If I remove itleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor), then it is aligned right.

Body:
Until and unless we are not changing priority of constraint the default priority is 1000 for all. So no precedence setting automatically.

For your code, add this line and it will work.

    titleLabel.textAlignment = .center


问:
Remove array item if it has a duplicate id
I have an array with the following values:

```<code>expandedComponents: {
  components: [
    {componentName: "hero", componentId: "hero-5856bvC6"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "footer", componentId: "footer-cUSAiiVd"}
  ]
}
</code>```

I want to filter out any array items with a duplicate componentId.

```<code>this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);

removeDuplicatesBy(keyFn, array) {
  var set = new Set();
  return array.filter(function(x) {
    var key = keyFn(x), isNew = !set.has(key);
    if (isNew) set.add(key);
    return isNew;
  });
 }
</code>```

However nothing seems to be happening and the duplicate features fields still persists. How do I fix this?

答:
The issue is that filter returns a new array and does not modify the incoming array.

You could try something like

```<code>this.expandedComponents = this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);
</code>```

Body:
I have an array with the following values:

expandedComponents: {
  components: [
    {componentName: "hero", componentId: "hero-5856bvC6"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "features", componentId: "features-iAnIKgJN"},
    {componentName: "features", componentId: "features-ncf3WpTA"},
    {componentName: "footer", componentId: "footer-cUSAiiVd"}
  ]
}

I want to filter out any array items with a duplicate componentId.

this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);

removeDuplicatesBy(keyFn, array) {
  var set = new Set();
  return array.filter(function(x) {
    var key = keyFn(x), isNew = !set.has(key);
    if (isNew) set.add(key);
    return isNew;
  });
 }

However nothing seems to be happening and the duplicate features fields still persists. How do I fix this?

Body:
The issue is that filter returns a new array and does not modify the incoming array.

You could try something like

this.expandedComponents = this.removeDuplicatesBy(x => x.componentId, this.expandedComponents['components']);