问:
React Bootstrap - How to manually close OverlayTrigger
I have an OverlayTrigger wrapping a Popover that contains some form inputs and a Button to save the data and close.

```<code>save(e) {
  this.setState({ editing: false })
  this.props.handleUpdate(e);
}

render() {
    return (
      <OverlayTrigger trigger="click"
        rootClose={true}
        onExit={this.save.bind(this) }
        show={this.state.editing}
        overlay={
            <Popover title="Time Entry">
              <FormGroup>
                    <ControlLabel>Data: </ControlLabel>
                    <FormControl type={'number'}/>
              </FormGroup>
              <Button onClick={this.save.bind(this) }>Save</Button>
           </Popover>
        }>
</code>```

I have rootClose = true, and my callback gets executed onExit, but I don't see a way to manually close overlay.  I'm trying to use the show attribute from the Bootstrap Modal that (predictably) doesn't work.

答: Hide function is not a public function on OverlayTrigger. Set <OverlayTrigger rootClose={true}... and then on your onClick event trigger call document.body.click().

Body:
I have an OverlayTrigger wrapping a Popover that contains some form inputs and a Button to save the data and close.

save(e) {
  this.setState({ editing: false })
  this.props.handleUpdate(e);
}

render() {
    return (
      <OverlayTrigger trigger="click"
        rootClose={true}
        onExit={this.save.bind(this) }
        show={this.state.editing}
        overlay={
            <Popover title="Time Entry">
              <FormGroup>
                    <ControlLabel>Data: </ControlLabel>
                    <FormControl type={'number'}/>
              </FormGroup>
              <Button onClick={this.save.bind(this) }>Save</Button>
           </Popover>
        }>

I have rootClose = true, and my callback gets executed onExit, but I don't see a way to manually close overlay.  I'm trying to use the show attribute from the Bootstrap Modal that (predictably) doesn't work.


来源: stackexchange

问:
How to fill web form using javascript
I want to fill the form data using javascript in chrome. I have filled all other fields correctly but the field(html) bellow is not working for me. (there must be other scripts working this form, i don't about that)

```<code><select name="month" class="valid">
<option value="">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">Month</font>
    </font>
</option>
<option value="01">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">January</font>
    </font>
</option>
<option value="02">
    <font style="vertical-align: inherit;">
        <font style="vertical-align: inherit;">February</font>
    </font>
</option>
<option value="03">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">March</font>
    </font>
</option>
</code>```

        Month

        January

            February

        March

i have tried some code but it doesn't work.

```<code>var month = document.querySelector('input[name="month"]');
month.selectedIndex = 3;
</code>```

i am using this script in chrome console, is there any way i can fill this field with javascript?

here is the form link

答:
First, your selector input[name="month"] does not match any elements.

Secondly, once you are able to select the correct element you can set it's value using element.value = 3.

See more about the value property here.

ContentLicense: CC BY-SA 3.0

Title: How to fill web form using javascript

Body:
I want to fill the form data using javascript in chrome. I have filled all other fields correctly but the field(html) bellow is not working for me. (there must be other scripts working this form, i don't about that)

<select name="month" class="valid">
<option value="">
    Month

</option>
<option value="01">
    January

</option>
<option value="02">

        February

</option>
<option value="03">
    March

</option>

        Month

        January

            February

        March

i have tried some code but it doesn't work.

var month = document.querySelector('input[name="month"]');
month.selectedIndex = 3;

i am using this script in chrome console, is there any way i can fill this field with javascript?

here is the form link


问:
Use ExternalProject_Add to include Opus in Android
This is probably quite simple.

I have an Android project that uses NDK. I will like to include the opus source code in the native code. I have tried using the ExternalProject_Add property of CMake but my native code still cannot import headers from the Opus library and fails to build.

Below is my ExternalProject_Add definition:

```<code>ExternalProject_Add(project_opus
  URL https://archive.mozilla.org/pub/opus/opus-1.2.1.tar.gz
  CONFIGURE_COMMAND <SOURCE_DIR>/configure --prefix=<INSTALL_DIR>
  BUILD_COMMAND make
  INSTALL_COMMAND make install
)

ExternalProject_Get_Property(project_opus install_dir)
include_directories(${install_dir}/include)

add_library(opus SHARED IMPORTED)
add_dependencies(opus project_opus)

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} opus oboe OpenSLES)
</code>```

答:
So, here is the CMakeLists.txt for opus:

```<code>cmake_minimum_required(VERSION 3.4.1)
include(ExternalProject)

set(OPUS_ROOT ${Project_BINARY_DIR}/project_opus-prefix/src/project_opus)

ExternalProject_Add(project_opus
  URL https://archive.mozilla.org/pub/opus/opus-1.2.1.tar.gz
  CONFIGURE_COMMAND ""
  INSTALL_COMMAND ""
  BUILD_COMMAND
    ${ANDROID_NDK}/ndk-build
    -C ${OPUS_ROOT}
    NDK_PROJECT_PATH=null
    APP_BUILD_SCRIPT=${Project_SOURCE_DIR}/opus.mk
    NDK_OUT=${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/../..
    NDK_LIBS_OUT=${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/..
    APP_ABI=${ANDROID_ABI}
    NDK_ALL_ABIS=${ANDROID_ABI}
    APP_PLATFORM=${ANDROID_PLATFORM}
  BUILD_BYPRODUCTS ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libopus.so
)

add_library(opus SHARED IMPORTED)
add_dependencies(opus project_opus)

set_target_properties(opus PROPERTIES IMPORTED_LOCATION ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libopus.so )
include_directories(${OPUS_ROOT}/include)

target_link_libraries( # Specifies the target library.
                   native-lib

                   # Links the target library to the log library
                   # included in the NDK.
                   log opus oboe OpenSLES)
</code>```

Next to this file, you must put this opus.mk file which I borrowed from android-ffmpeg-builder on GitHub:

```<code>LOCAL_PATH := .

include $(CLEAR_VARS)

#include the .mk files
include $(LOCAL_PATH)/celt_sources.mk
include $(LOCAL_PATH)/silk_sources.mk
include $(LOCAL_PATH)/opus_sources.mk

MY_MODULE_DIR       := opus

LOCAL_MODULE        := $(MY_MODULE_DIR)

#fixed point sources
SILK_SOURCES += $(SILK_SOURCES_FIXED)

#ARM build
CELT_SOURCES += $(CELT_SOURCES_ARM)
SILK_SOURCES += $(SILK_SOURCES_ARM)
LOCAL_SRC_FILES     := \
    $(CELT_SOURCES) \
    $(SILK_SOURCES) \
    $(OPUS_SOURCES) \
    $(OPUS_SOURCES_FLOAT)

LOCAL_LDLIBS        := -lm -llog

LOCAL_C_INCLUDES    := \
    $(LOCAL_PATH)/include \
    $(LOCAL_PATH)/silk \
    $(LOCAL_PATH)/silk/fixed \
    $(LOCAL_PATH)/silk/float \
    $(LOCAL_PATH)/celt

# don't disable the float api
LOCAL_CFLAGS        := -DNULL=0 -DSOCKLEN_T=socklen_t -DLOCALE_NOT_USED -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64
LOCAL_CFLAGS        += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT=1 -DUSE_ALLOCA -DHAVE_LRINT -DHAVE_LRINTF -O3 -fno-math-errno
LOCAL_CPPFLAGS      := -DBSD=1
LOCAL_CPPFLAGS      += -ffast-math -O3 -funroll-loops

include $(BUILD_SHARED_LIBRARY)
</code>```

On the face of it, this only supports ARM build.

Body:
This is probably quite simple.

I have an Android project that uses NDK. I will like to include the opus source code in the native code. I have tried using the ExternalProject_Add property of CMake but my native code still cannot import headers from the Opus library and fails to build.

Below is my ExternalProject_Add definition:

ExternalProject_Add(project_opus
  URL https://archive.mozilla.org/pub/opus/opus-1.2.1.tar.gz
  CONFIGURE_COMMAND <SOURCE_DIR>/configure --prefix=<INSTALL_DIR>
  BUILD_COMMAND make
  INSTALL_COMMAND make install
)

ExternalProject_Get_Property(project_opus install_dir)
include_directories(${install_dir}/include)

add_library(opus SHARED IMPORTED)
add_dependencies(opus project_opus)

target_link_libraries( # Specifies the target library.
                       native-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} opus oboe OpenSLES)

Body:
So, here is the CMakeLists.txt for opus:

cmake_minimum_required(VERSION 3.4.1)
include(ExternalProject)

set(OPUS_ROOT ${Project_BINARY_DIR}/project_opus-prefix/src/project_opus)

ExternalProject_Add(project_opus
  URL https://archive.mozilla.org/pub/opus/opus-1.2.1.tar.gz
  CONFIGURE_COMMAND ""
  INSTALL_COMMAND ""
  BUILD_COMMAND
    ${ANDROID_NDK}/ndk-build
    -C ${OPUS_ROOT}
    NDK_PROJECT_PATH=null
    APP_BUILD_SCRIPT=${Project_SOURCE_DIR}/opus.mk
    NDK_OUT=${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/../..
    NDK_LIBS_OUT=${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/..
    APP_ABI=${ANDROID_ABI}
    NDK_ALL_ABIS=${ANDROID_ABI}
    APP_PLATFORM=${ANDROID_PLATFORM}
  BUILD_BYPRODUCTS ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libopus.so
)

add_library(opus SHARED IMPORTED)
add_dependencies(opus project_opus)

set_target_properties(opus PROPERTIES IMPORTED_LOCATION ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libopus.so )
include_directories(${OPUS_ROOT}/include)

target_link_libraries( # Specifies the target library.
                   native-lib

                   # Links the target library to the log library
                   # included in the NDK.
                   log opus oboe OpenSLES)

Next to this file, you must put this opus.mk file which I borrowed from android-ffmpeg-builder on GitHub:

LOCAL_PATH := .

include $(CLEAR_VARS)

#include the .mk files
include $(LOCAL_PATH)/celt_sources.mk
include $(LOCAL_PATH)/silk_sources.mk
include $(LOCAL_PATH)/opus_sources.mk

MY_MODULE_DIR       := opus

LOCAL_MODULE        := $(MY_MODULE_DIR)

#fixed point sources
SILK_SOURCES += $(SILK_SOURCES_FIXED)

#ARM build
CELT_SOURCES += $(CELT_SOURCES_ARM)
SILK_SOURCES += $(SILK_SOURCES_ARM)
LOCAL_SRC_FILES     := \
    $(CELT_SOURCES) \
    $(SILK_SOURCES) \
    $(OPUS_SOURCES) \
    $(OPUS_SOURCES_FLOAT)

LOCAL_LDLIBS        := -lm -llog

LOCAL_C_INCLUDES    := \
    $(LOCAL_PATH)/include \
    $(LOCAL_PATH)/silk \
    $(LOCAL_PATH)/silk/fixed \
    $(LOCAL_PATH)/silk/float \
    $(LOCAL_PATH)/celt

# don't disable the float api
LOCAL_CFLAGS        := -DNULL=0 -DSOCKLEN_T=socklen_t -DLOCALE_NOT_USED -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64
LOCAL_CFLAGS        += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT=1 -DUSE_ALLOCA -DHAVE_LRINT -DHAVE_LRINTF -O3 -fno-math-errno
LOCAL_CPPFLAGS      := -DBSD=1
LOCAL_CPPFLAGS      += -ffast-math -O3 -funroll-loops

include $(BUILD_SHARED_LIBRARY)

On the face of it, this only supports ARM build.


问:
Clicking A Link Two Times
I have a link like this :

```<code><a href="#" onclick="renkDegistir()" title="Yaz .......
</code>```

And JS code :

```<code>function renkDegistir()
    {
        $("#cont #main article").addClass("siyah-stil");
    }
</code>```

When click this link siyah-stil class is added to article. But i want to do, if link clicked 2nd time remove siyah-stil class.

In summary ,

```<code>on first click : addClass("siyah-stil");
on second click : removeClass("siyah-stil");
</code>```

答:
Here you go:

JQuery - toggleClass

ContentLicense: CC BY-SA 2.5

Title: Clicking A Link Two Times

Body:
I have a link like this :

<a href="#" onclick="renkDegistir()" title="Yaz .......

And JS code :

function renkDegistir()
    {
        $("#cont #main article").addClass("siyah-stil");
    }

When click this link siyah-stil class is added to article. But i want to do, if link clicked 2nd time remove siyah-stil class.

In summary ,

on first click : addClass("siyah-stil");
on second click : removeClass("siyah-stil");

Body:
Here you go:

JQuery - toggleClass


问:
Jquery find element with data starting with some value
I'm looking for a sintax to search inside data of a element starting with a given value, with or without an underscore after it. For example if a give a number like 3:

```<code><span data-filter="3_1"></span>   // I NEED TRUE
<span data-filter="3"></span>   // I NEED TRUE
<span data-filter="33_1"></span>   // I NEED FALSE
<span data-filter="1_3"></span>   // I NEED FALSE
</code>```

$(span[filter^="3"]) doesn't work for 3° example.

Fiddle example: https://jsfiddle.net/fdphzogc/1/

Of course i've inserted an example like 3, but it can be another number with more digits like 465_12, where 465 is what i'm looking for

答:
If I'm correct, you want all  which have a data-filter that either has a 3 or, start with 3_

For the data-filter="3" you can use

```<code>$('span[data-filter="3"]')
</code>```

For the data-filter="3_ .... " you can use:

```<code>$('span[data-filter^="3_"]')
</code>```

Both together:

```<code>$('span[data-filter="3"],span[data-filter^="3_"]')
</code>```

In a demo:

span { display: block; }
span[data-filter="3"],
span[data-filter^="3_"] {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span data-filter="3_1">3_1</span>
<span data-filter="3">3</span>
<span data-filter="33_1">33_1</span>
<span data-filter="1_3">1_3</span></code>```

Body:
I'm looking for a sintax to search inside data of a element starting with a given value, with or without an underscore after it. For example if a give a number like 3:

   // I NEED TRUE
   // I NEED TRUE
   // I NEED FALSE
   // I NEED FALSE

$(span[filter^="3"]) doesn't work for 3° example.

Fiddle example: https://jsfiddle.net/fdphzogc/1/

Of course i've inserted an example like 3, but it can be another number with more digits like 465_12, where 465 is what i'm looking for

Body:
If I'm correct, you want all <span> which have a data-filter that either has a 3 or, start with 3_

For the data-filter="3" you can use

$('span[data-filter="3"]')

For the data-filter="3_ .... " you can use:

$('span[data-filter^="3_"]')

Both together:

$('span[data-filter="3"],span[data-filter^="3_"]')

In a demo:

span { display: block; }
span[data-filter="3"],
span[data-filter^="3_"] {
  color: red;
}

<span data-filter="3_1">3_1</span>
<span data-filter="3">3</span>
<span data-filter="33_1">33_1</span>
<span data-filter="1_3">1_3</span>


问:
How does Java guarantee callback is called when future.isDone() in ListenableFuture
when going through the ListenableFutre interface, it notes in the doc that

addListener()

Registers a listener to be run on the given executor. The listener
  will run when the Future's computation is complete or, if the
  computation is already complete, immediately.`

Since Future.get() is a blocking call, how does Java guarantee certain future is Done? are they spinning on this? I understand that with Framework like dagger producers, it is kinda easy to understand (once task is done, write to something, the monitoring thread will be notified). in ListenableFuture case, does jvm support something like this out of box?

using wait()/notify() like mechanism ?

FollowUp Question: as all of you put, it is the caller actually guarantee the listener to be run, normal case to use a ListenableFuture
would be ListenableFuture future = Caller.call(), with caller and callee in different threads or even in different JVMs, how is this done in java? the listener in stored in both the caller thread and callee thread ? or using remote reigstery when in differnt JVMs?

答:
I'd like to add answers.

Guava does not garantee it.
If you down JVM or JVM is crashed no listeners would be invoked.
If you shutdown executor without cancelling futures, no listeners would be invoked too. I mean this case:

```<code>ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        t.setDaemon(false);
        return t;
    }
});
ListenableFuture<?> listenableFuture = JdkFutureAdapters.listenInPoolThread(
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("run!!!");
            }
        }),
        executorService
);
Futures.addCallback(listenableFuture, new FutureCallback<Object>() {

    @Override
    public void onSuccess(@Nullable Object result) {
        System.out.println("onSuccess");
    }

    @Override
    public void onFailure(Throwable t) {
        System.out.println("onFailure");
    }
});
MoreExecutors.shutdownAndAwaitTermination(executorService, 3, TimeUnit.SECONDS);
</code>```

I didn't see "onSuccess" or "onFailure", did you?

In usual workflow when JVM is running, Guava uses CAS to invoke listeners exactly once, you can see it in source code too.

Body:
I'd like to add answers.

Guava does not garantee it.
If you down JVM or JVM is crashed no listeners would be invoked.
If you shutdown executor without cancelling futures, no listeners would be invoked too. I mean this case:

ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        t.setDaemon(false);
        return t;
    }
});
ListenableFuture<?> listenableFuture = JdkFutureAdapters.listenInPoolThread(
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("run!!!");
            }
        }),
        executorService
);
Futures.addCallback(listenableFuture, new FutureCallback<Object>() {

    @Override
    public void onSuccess(@Nullable Object result) {
        System.out.println("onSuccess");
    }

    @Override
    public void onFailure(Throwable t) {
        System.out.println("onFailure");
    }
});
MoreExecutors.shutdownAndAwaitTermination(executorService, 3, TimeUnit.SECONDS);

I didn't see "onSuccess" or "onFailure", did you?

In usual workflow when JVM is running, Guava uses CAS to invoke listeners exactly once, you can see it in source code too.


问:
Autolayout with specific constraints
I have problem or maybe wrong understanding of constraints in general with view controller form photo below.

I already implemented scroll view and it is working properly. Photo below showing Content View with two subviews (with the same name: View). What I would like to achieve is to set first View (the blue one) to be exactly on edges of the screen and second one (green view) to be visible only when user scroll down on this page. Is it possible to achieve these just using autolayuots or I need to do some hard code work. What is the best approaches for solving this taking in account that I need this app to work with all king of iPhones.

At the bottom of the green view is located tab bar but it is not visible on this photo.

答:
This is pretty straight-forward...

Pin your scroll view to Zero on all four sides.

set Blue Top, Leading and Trailing all to Zero to superview (the scroll view)

set Blue width equal to scroll view width

set Blue height equal to scroll view height

set Green width and height each equal to Blue width and height

set Green "center horizontally" to Blue

set Green Top to Zero from Blue bottom (vertical spacing)

set Green Bottom to Zero to superview (the scroll view)

That should do it :)

Edit: whoops, corrected step 4 (Blue height should be equal to scroll view height, not multiplied by 0.5)

Title: Autolayout with specific constraints


问:
Stylize text in td elements
I have a failty big table to do.
I always found difficult in stylizing them so I can assume mine is a basic question.
I have some TDs with fairly long text in it. Currently the table style is set with "white-space: nowrap".

What I want to achieve is to split these td text into a fixed number of "lines" (let's say 3) so the row may be taller mut the single cell is somewhat smaller.

white space normal:

```<code>--------
- text -
- text -
- text -
- text -
- text -
--------
</code>```

white-space: nowrap

```<code>---------------------------------
- text text text text text text -
---------------------------------
</code>```

I want:

```<code>-------------
- text text -
- text text -
- text      -
-------------
</code>```

答:
Specify a width on your columns to determine how much text to fit in there. I have created a JS Fiddle with 3 examples of how this works:

https://jsfiddle.net/2rhzymwc/

```<code><table class="wrap-width">
<tr>
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</td>
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</td>
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</td>
</tr>
</table>

.wrap-width td {
  width: 100px;
}
</code>```

EDIT:

With respect to your comment, do you mean longer as in specifying the height to be slightly longer than the content? Or that the width/height of one cell should be longer than the others? It is quite unclear what you are asking for, check out these further examples:

https://jsfiddle.net/jz8gn8ax/

Title: Stylize text in td elements

Body:
I have a failty big table to do.
I always found difficult in stylizing them so I can assume mine is a basic question.
I have some TDs with fairly long text in it. Currently the table style is set with "white-space: nowrap".

What I want to achieve is to split these td text into a fixed number of "lines" (let's say 3) so the row may be taller mut the single cell is somewhat smaller.

white space normal:

--------
- text -
- text -
- text -
- text -
- text -
--------

white-space: nowrap

---------------------------------
- text text text text text text -
---------------------------------

I want:

-------------
- text text -
- text text -
- text      -
-------------

Body:
Specify a width on your columns to determine how much text to fit in there. I have created a JS Fiddle with 3 examples of how this works:

https://jsfiddle.net/2rhzymwc/

<table class="wrap-width">
<tr>
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</td>
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</td>
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</td>
</tr>
</table>

.wrap-width td {
  width: 100px;
}

EDIT:

With respect to your comment, do you mean longer as in specifying the height to be slightly longer than the content? Or that the width/height of one cell should be longer than the others? It is quite unclear what you are asking for, check out these further examples:

https://jsfiddle.net/jz8gn8ax/


问:
Angular queryParamMap is empty, then populated
I have created a new module in my app so I can separate parts that do not have to communicate and created an new.module.ts with its own routing module and components :

new-routing.module.ts:

```<code>const exportRoutes: Routes = [
  {
    path: 'export',
    component: ExportsComponent
  }
]

@NgModule({
  imports: [RouterModule.forRoot(exportRoutes)],
  exports: [RouterModule]
})
export class ExportRoutingModule {}
</code>```

new.module.ts:

```<code>import { Router } from '@angular/router'
import { BrowserModule } from '@angular/platform-browser'

// Routing Module
import { NewRoutingModule } from './new-routing.module'

@NgModule({
  imports: [..., ExportRoutingModule, ...],
  declarations: [ExportsComponent],
  bootstrap: [ExportsComponent]
})
</code>```

I have a simple index.html:

```<code><body class="app">
  <router-outlet></router-outlet> // outlet is here because I read that I needed it to be able to use activated route, I actually just want the query params
</body>
</code>```

and finally, where the problem lies, my component :

```<code>export class MyComponent implements OnInit {

constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit() {this.activatedRoute.queryParamMap.subscribe(
(params: ParamMap) => console.log(params)
// Do stuff with params => error)}
</code>```

When I navigate to http://localhost:4200/export?firstParam=1.00,2.00,3.00 in my console, the params are logued twice, once empty, once populated as such :

```<code>ParamsAsMap {params: {…}}
keys:(...) // empty
params:{} // empty

core.js:3565 Angular is running in the development mode. Call enableProdMode() to enable the production mode.

ParamsAsMap {params: {…}}
keys:Array(3)
params:{firstParam: "1.00,2.00,3.00", secondParam: "bla"}
</code>```

This cause my component to throw error since I need those params to display my component and the first time they are logued they are empty so :

Why are they loggued twice ?

Why is my code executed before my params observable has a value ?

Could I get rid of the router outlet (which I don't really need since I have no routing involved with this module, I just used it because I read that I couldn't use activatedRoute without it; I just want the query params from my url

Thanks for your help

答:
I'll offer 2 solutions to this problem, first, using the skip operator :

Since Activated Route is a BehaviorSubject so first we'll get an empty value, then the actual queryparams so we can skip the first value :

(note, this solution uses lettable operators, hence the pipe(), if you are not using lettable operators you can just chain it like you would do any other rxjs operators : .skip(1)

```<code>export class MyComponent implements OnInit {

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit()
    {this.activatedRoute.queryParamMap.pipe(skip(1)).subscribe(
    (params: ParamMap) => console.log(params)}
</code>```

Second solution, use a regular javascript function to retrieve the params :

```<code>ngOnInit() {
  const token = this.getParameterByName('access_token');
  console.log(token);
}

getParameterByName(name: any) {
  let url = window.location.href;
  name = name.replace(/[[]]/g, "\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
  results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/+/g, " "));
}
</code>```

I'll point you to this stackoverflow answer for the original code

Body:
I have created a new module in my app so I can separate parts that do not have to communicate and created an new.module.ts with its own routing module and components :

new-routing.module.ts:

const exportRoutes: Routes = [
  {
    path: 'export',
    component: ExportsComponent
  }
]

@NgModule({
  imports: [RouterModule.forRoot(exportRoutes)],
  exports: [RouterModule]
})
export class ExportRoutingModule {}

new.module.ts:

import { Router } from '@angular/router'
import { BrowserModule } from '@angular/platform-browser'

// Routing Module
import { NewRoutingModule } from './new-routing.module'

@NgModule({
  imports: [..., ExportRoutingModule, ...],
  declarations: [ExportsComponent],
  bootstrap: [ExportsComponent]
})

I have a simple index.html:

  <router-outlet></router-outlet> // outlet is here because I read that I needed it to be able to use activated route, I actually just want the query params

and finally, where the problem lies, my component :

export class MyComponent implements OnInit {

constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit() {this.activatedRoute.queryParamMap.subscribe(
(params: ParamMap) => console.log(params)
// Do stuff with params => error)}

When I navigate to http://localhost:4200/export?firstParam=1.00,2.00,3.00 in my console, the params are logued twice, once empty, once populated as such :

ParamsAsMap {params: {…}}
keys:(...) // empty
params:{} // empty

core.js:3565 Angular is running in the development mode. Call enableProdMode() to enable the production mode.

ParamsAsMap {params: {…}}
keys:Array(3)
params:{firstParam: "1.00,2.00,3.00", secondParam: "bla"}

This cause my component to throw error since I need those params to display my component and the first time they are logued they are empty so :

Why are they loggued twice ?

Why is my code executed before my params observable has a value ?

Could I get rid of the router outlet (which I don't really need since I have no routing involved with this module, I just used it because I read that I couldn't use activatedRoute without it; I just want the query params from my url

Thanks for your help

Body:
I'll offer 2 solutions to this problem, first, using the skip operator :

Since Activated Route is a BehaviorSubject so first we'll get an empty value, then the actual queryparams so we can skip the first value :

(note, this solution uses lettable operators, hence the pipe(), if you are not using lettable operators you can just chain it like you would do any other rxjs operators : .skip(1)

export class MyComponent implements OnInit {

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit()
    {this.activatedRoute.queryParamMap.pipe(skip(1)).subscribe(
    (params: ParamMap) => console.log(params)}

Second solution, use a regular javascript function to retrieve the params :

ngOnInit() {
  const token = this.getParameterByName('access_token');
  console.log(token);
}

getParameterByName(name: any) {
  let url = window.location.href;
  name = name.replace(/[[]]/g, "\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
  results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/+/g, " "));
}

I'll point you to this stackoverflow answer for the original code


问:
R replacing names in a dataset
I have this R script for data mining:

```<code>`FAO_AreaName <-"TLS"
news_url <-   paste0("http://www.fao.org/countryprofiles/common/allnews/en/?iso3=", FAO_AreaName,"&allnews=no&limit=2")
news <- fromJSON(news_url)
title <- news[3]
date <- news[6]
FAO_AreaName_1 <- news[5]
content_TLS <- news[5]
TLS <- cbind(FAO_AreaName, FAO_AreaName_1, date, title, content_TLS)
</code>```

`

In this example, TLS stands for "Timor-Leste".
I am using the following packages:
rvest,
stringr,
tidyr,
data.table,
plyr,
xml2,
selectr,
tibble,
purrr,
datapasta,

jsonlite.

In any case, I have a long .csv list of country name codes (e.g. USA, ISR, ITA, etc) I should replace to TLS to complete the script.
Any suggestion before starting replacing manually?

答:
Wrap it in a function:</p>

```<code>do_my_task <- function(FAO_AreaName) {
    news_url <-   paste0("http://www.fao.org/countryprofiles/common/allnews/en/?iso3=", FAO_AreaName,"&allnews=no&limit=2")
    news <- fromJSON(news_url)
    title <- news[3]
    date <- news[6]
    FAO_AreaName_1 <- news[5]
    content_TLS <- news[5]
    cbind(FAO_AreaName, FAO_AreaName_1, date, title, content_TLS)
}

areas <- c("TLS", "USA", ...)
my_datasets <- lapply(areas, do_my_task)
</code>```

Title: R replacing names in a dataset

Body:
I have this R script for data mining:

`FAO_AreaName <-"TLS"
news_url <-   paste0("http://www.fao.org/countryprofiles/common/allnews/en/?iso3=", FAO_AreaName,"&allnews=no&limit=2")
news <- fromJSON(news_url)
title <- news[3]
date <- news[6]
FAO_AreaName_1 <- news[5]
content_TLS <- news[5]
TLS <- cbind(FAO_AreaName, FAO_AreaName_1, date, title, content_TLS)

`

In this example, TLS stands for "Timor-Leste".
I am using the following packages:
rvest,
stringr,
tidyr,
data.table,
plyr,
xml2,
selectr,
tibble,
purrr,
datapasta,

jsonlite.

In any case, I have a long .csv list of country name codes (e.g. USA, ISR, ITA, etc) I should replace to TLS to complete the script.
Any suggestion before starting replacing manually?

Body:
Wrap it in a function:

do_my_task <- function(FAO_AreaName) {
    news_url <-   paste0("http://www.fao.org/countryprofiles/common/allnews/en/?iso3=", FAO_AreaName,"&allnews=no&limit=2")
    news <- fromJSON(news_url)
    title <- news[3]
    date <- news[6]
    FAO_AreaName_1 <- news[5]
    content_TLS <- news[5]
    cbind(FAO_AreaName, FAO_AreaName_1, date, title, content_TLS)
}

areas <- c("TLS", "USA", ...)
my_datasets <- lapply(areas, do_my_task)


问:
Write single value on firebase database without deleting the existing ones
I'am trying to add a single value my database without deleting the existing ones because I need them all. The structure is something like that /user/fav_post/{post_id_1,post_id_2,...}. The "fav_post" initially is empty and as the time goes by the user adds more fav_posts.

One way that solves this problem is downloading all favorite posts, putting them in a HashMap, add the new post and the push them to the database but this does not seem very optimal.

So what I am trying to achieve is to have all the favorite posts and to display them to the user.

```<code> mDatabase.child("USERS")
       .child(currentUser.getUid())
       .child("favorites")
       .setValue(postID);
</code>```

Edit: The end result should be like

Ther end result I want to be like that
root

```<code>-User

--FavPosts

---postID1(String)
</code>```

And when the user favorites another post the result should be like that:

```<code>root
-User

--FavPosts

---postID1(String)

---postID2(String)
</code>```

答: setValue() will overwrite the entire contents of the location.  If you want to just add or update child values, use updateChildren() instead.</p>

Body:
I'am trying to add a single value my database without deleting the existing ones because I need them all. The structure is something like that /user/fav_post/{post_id_1,post_id_2,...}. The "fav_post" initially is empty and as the time goes by the user adds more fav_posts.

One way that solves this problem is downloading all favorite posts, putting them in a HashMap, add the new post and the push them to the database but this does not seem very optimal.

So what I am trying to achieve is to have all the favorite posts and to display them to the user.

 mDatabase.child("USERS")
       .child(currentUser.getUid())
       .child("favorites")
       .setValue(postID);

Edit: The end result should be like

Ther end result I want to be like that
root

-User

--FavPosts

---postID1(String)

And when the user favorites another post the result should be like that:

root
-User

--FavPosts

---postID1(String)

---postID2(String)


问:
FTP login using Shell class in VBScript stopped working after changing credentials
I had a Windows server uploading certain files to a web server using VBScript for a few years now with no issues. I now moved my website to a new server and for some reason the script stopped working...the below excerpt throws an error "Object required" for instance:

```<code>strFTP = "ftp://" & strFTPUser & ":" & strFTPPass & "@" & strFTPHost & strFTPDir
Set objFTP = oShell.NameSpace(strFTP)

'Make new folder on FTP site
objFTP.NewFolder "FTP Backup"
If Err.Number <> 0 Then
    Wscript.Echo "Error after FTP create: " & Err.Description
End If
</code>```

I only changed the login variables so I'm guessing something is differently configured on the new server. Can someone suggest what to do? Lots of cron type services depend on this. Thank you

答:
As you have a @ in a username, which has a special meaning in an URL (separator of credentials and a hostname), you need to URL-encode it to %40:

```<code>strFTPUser = "user%40domain"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I had a Windows server uploading certain files to a web server using VBScript for a few years now with no issues. I now moved my website to a new server and for some reason the script stopped working...the below excerpt throws an error "Object required" for instance:

strFTP = "ftp://" & strFTPUser & ":" & strFTPPass & "@" & strFTPHost & strFTPDir
Set objFTP = oShell.NameSpace(strFTP)

'Make new folder on FTP site
objFTP.NewFolder "FTP Backup"
If Err.Number <> 0 Then
    Wscript.Echo "Error after FTP create: " & Err.Description
End If

I only changed the login variables so I'm guessing something is differently configured on the new server. Can someone suggest what to do? Lots of cron type services depend on this. Thank you

Body:
As you have a @ in a username, which has a special meaning in an URL (separator of credentials and a hostname), you need to URL-encode it to %40:

strFTPUser = "user%40domain"


问:
JSON string decoding issue using Newtonsoft and C#
In the (abridged) deserialized json string below, I have a problem reading the "href" field (VS2017, C#).

```<code>"version": "2.0",
"label": "Production from aquaculture excluding hatcheries and nurseries (from 2008 onwards)",
"href": "http://ec.europa.eu/eurostat/wdds/rest/data/v2.1/json/en/fish_aq2a?precision=1&species=SAL&aquaenv=SEA&fishreg=0&fishreg=10&fishreg=27&fishreg=5&fishreg=9&fishreg=37&fishreg=34&fishreg=NSP&fishreg=4&fishreg=1&unit=EUR&unit=EUR_T&unit=TLW&aquameth=CAG",...
</code>```

I am using a C# class with the fields for the first three items:

```<code>public string Version { get; set; }
public string Label { get; set; }
public string EurostatURL { get; set; }
</code>```

No problem retrieving the Version and Label, but the EurostatURL field is always empty. As far as I can see, it's a string field like the two preceding ones, only longer and with the http prefix, but I can work out why that would make any difference. Any help much appreciated.

答:
How can the deserializer know that href is EurostatURL? Tell it so, or rename your class.

Rename

```<code>public string Version { get; set; }
public string Label { get; set; }
public string Href { get; set; }
</code>```

Property

```<code>public string Version { get; set; }
public string Label { get; set; }
[JsonProperty("href")]
public string EurostatURL{ get; set; }
</code>```

Body:
In the (abridged) deserialized json string below, I have a problem reading the "href" field (VS2017, C#).

"version": "2.0",
"label": "Production from aquaculture excluding hatcheries and nurseries (from 2008 onwards)",
"href": "http://ec.europa.eu/eurostat/wdds/rest/data/v2.1/json/en/fish_aq2a?precision=1&species=SAL&aquaenv=SEA&fishreg=0&fishreg=10&fishreg=27&fishreg=5&fishreg=9&fishreg=37&fishreg=34&fishreg=NSP&fishreg=4&fishreg=1&unit=EUR&unit=EUR_T&unit=TLW&aquameth=CAG",...

I am using a C# class with the fields for the first three items:

public string Version { get; set; }
public string Label { get; set; }
public string EurostatURL { get; set; }

No problem retrieving the Version and Label, but the EurostatURL field is always empty. As far as I can see, it's a string field like the two preceding ones, only longer and with the http prefix, but I can work out why that would make any difference. Any help much appreciated.

Body:
How can the deserializer know that href is EurostatURL? Tell it so, or rename your class.

Rename

public string Version { get; set; }
public string Label { get; set; }
public string Href { get; set; }

Property

public string Version { get; set; }
public string Label { get; set; }
[JsonProperty("href")]
public string EurostatURL{ get; set; }


答:
You must specify the JSON property you want to reference :</p>

```<code>[JsonProperty("href")]
public string EurostatURL { get; set; }
</code>```

Title: JSON string decoding issue using Newtonsoft and C#

Body:
You must specify the JSON property you want to reference :

[JsonProperty("href")]
public string EurostatURL { get; set; }


问:
Search output of p4 command
I am trying to perform an action depending on the output of perforce commands. But it seems that pipping and greping/acking the command doesn't appear to pickup the output

e.g.

```<code>p4 sync -n $HOME/... | grep -c up
/homedirectory/... - file(s) up-to-date.
0

p4 sync -n $HOME/... | grep -c nope
/homedirectory/... - file(s) up-to-date.
0
</code>```

Further example of what i'm trying to do:

```<code>if ( `p4 sync -n $HOME/... | grep -c "no such file"` == 0 ) then
    if command
else
    do else command
endif
</code>```

Is there anyway to read the output of a perforce command without having to write to a file then read the output? Ideally the command would be a single line.

答:
grep isn't working because the "empty" messages like no such file and up-to-date go to stderr.  As @heemayl suggested one way to fix that is to do a redirect.

You can also fix this in a shell-independent way by using the -s or -e flags to p4:

```<code>C:\Perforce\test>p4 -s sync
error: File(s) up-to-date.
exit: 0

C:\Perforce\test>p4 -e sync
error: File(s) up-to-date.
code0 554768772 (sub 388 sys 6 gen 17 args 1 sev 2 uniq 6532)
... code0 554768772
... fmt0 [%argc% - file(s)|File(s)] up-to-date.
... argc

exit: 0
</code>```

Both of these flags redirect all output to stdout and also prepend every message with debugging information about the message itself.  If you're trying to grep for a particular message, for example, you can use the -e flag and grep for its unique code rather than the string.

Using the -F flag lets you reformat the output to include particular elements from the message dict that you see with -e, so if you want just the code:

```<code>C:\Perforce\test>p4 -F %code0% sync
554768772
</code>```

If you're trying to capture elements of the actual output, like file names, -F is even more useful:

```<code>C:\Perforce\test>p4 -F %localPath% sync -n ...#1
c:\Perforce\test\0.f1
c:\Perforce\test\1.15
c:\Perforce\test\1.18
c:\Perforce\test\2.f1
c:\Perforce\test\2.f2
</code>```

Title: Search output of p4 command

Body:
I am trying to perform an action depending on the output of perforce commands. But it seems that pipping and greping/acking the command doesn't appear to pickup the output

e.g.

p4 sync -n $HOME/... | grep -c up
/homedirectory/... - file(s) up-to-date.
0

p4 sync -n $HOME/... | grep -c nope
/homedirectory/... - file(s) up-to-date.
0

Further example of what i'm trying to do:

if ( `p4 sync -n $HOME/... | grep -c "no such file"` == 0 ) then
    if command
else
    do else command
endif

Is there anyway to read the output of a perforce command without having to write to a file then read the output? Ideally the command would be a single line.

Body:
grep isn't working because the "empty" messages like no such file and up-to-date go to stderr.  As @heemayl suggested one way to fix that is to do a redirect.

You can also fix this in a shell-independent way by using the -s or -e flags to p4:

C:\Perforce\test>p4 -s sync
error: File(s) up-to-date.
exit: 0

C:\Perforce\test>p4 -e sync
error: File(s) up-to-date.
code0 554768772 (sub 388 sys 6 gen 17 args 1 sev 2 uniq 6532)
... code0 554768772
... fmt0 [%argc% - file(s)|File(s)] up-to-date.
... argc

exit: 0

Both of these flags redirect all output to stdout and also prepend every message with debugging information about the message itself.  If you're trying to grep for a particular message, for example, you can use the -e flag and grep for its unique code rather than the string.

Using the -F flag lets you reformat the output to include particular elements from the message dict that you see with -e, so if you want just the code:

C:\Perforce\test>p4 -F %code0% sync
554768772

If you're trying to capture elements of the actual output, like file names, -F is even more useful:

C:\Perforce\test>p4 -F %localPath% sync -n ...#1
c:\Perforce\test\0.f1
c:\Perforce\test\1.15
c:\Perforce\test\1.18
c:\Perforce\test\2.f1
c:\Perforce\test\2.f2


问:
JUnit 5 Gradle: Do test classes really have to be suffixed with "Test(s)"?
It appears as if JUnit 5 tests aren't found if the file- and class name does not end with "Test" or "Tests" when using Gradle. Is it possible to configure Gradle to treat everything in the test directory as test classes?

答:
From this doc, note that there is a plugin called 'junit-platform-gradle-plugin'. The salient part is the following:

junitPlatform {
    filters {
        includeClassNamePattern '.*'
    }
}
```

<p>(as opposed to <code>'.*TestCase'</code>)</p>

<p>Here is the full <code>build.gradle</code> file (and an example that runs tests named <code>ExampleTestCase</code> and <code>Example2</code>):</p>

<pre class="lang-groovy prettyprint-override"><code>apply plugin: 'java'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.2'
    }
}

apply plugin: 'org.junit.platform.gradle.plugin'

repositories {
    jcenter()
}

ext.junitJupiterVersion  = '5.0.2'

dependencies {
    testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
    testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")
}

junitPlatform {
    filters {
        includeClassNamePattern '.*'
    }
}
</code>```

Body:
From this doc, note that there is a plugin called 'junit-platform-gradle-plugin'. The salient part is the following:

junitPlatform {
    filters {
        includeClassNamePattern '.*'
    }
}

(as opposed to '.*TestCase')

Here is the full build.gradle file (and an example that runs tests named ExampleTestCase and Example2):

apply plugin: 'java'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.2'
    }
}

apply plugin: 'org.junit.platform.gradle.plugin'

repositories {
    jcenter()
}

ext.junitJupiterVersion  = '5.0.2'

dependencies {
    testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
    testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")
}

junitPlatform {
    filters {
        includeClassNamePattern '.*'
    }
}


问:
PHP — Convert milliseconds to Hours : Minutes : Seconds.fractional
I've got a script that takes in a value in seconds (to 2 decimal points of fractional seconds):

```<code>$seconds_input = 23.75
</code>```

I then convert it to milliseconds:

```<code>$milliseconds = $seconds_input * 1000; // --> 23750
</code>```

And then I want to format it like so:

```<code>H:M:S.x // --> 0:0:23.75
</code>```

Where 'x' is the fraction of the second (however many places after the decimal there are).

Any help? I can't seem to wrap my mind around this. I tried using gmdate() but it kept lopping off the fractional seconds.

Thanks.

答:
Edit: Well, I was a bit hasty.  Here's one way to do what you're asking:

```<code>function formatMilliseconds($milliseconds) {
    $seconds = floor($milliseconds / 1000);
    $minutes = floor($seconds / 60);
    $hours = floor($minutes / 60);
    $milliseconds = $milliseconds % 1000;
    $seconds = $seconds % 60;
    $minutes = $minutes % 60;

    $format = '%u:%02u:%02u.%03u';
    $time = sprintf($format, $hours, $minutes, $seconds, $milliseconds);
    return rtrim($time, '0');
}
</code>```

Body:
I've got a script that takes in a value in seconds (to 2 decimal points of fractional seconds):

$seconds_input = 23.75

I then convert it to milliseconds:

$milliseconds = $seconds_input * 1000; // --> 23750

And then I want to format it like so:

H:M:S.x // --> 0:0:23.75

Where 'x' is the fraction of the second (however many places after the decimal there are).

Any help? I can't seem to wrap my mind around this. I tried using gmdate() but it kept lopping off the fractional seconds.

Thanks.

Body:
Edit: Well, I was a bit hasty.  Here's one way to do what you're asking:

function formatMilliseconds($milliseconds) {
    $seconds = floor($milliseconds / 1000);
    $minutes = floor($seconds / 60);
    $hours = floor($minutes / 60);
    $milliseconds = $milliseconds % 1000;
    $seconds = $seconds % 60;
    $minutes = $minutes % 60;

    $format = '%u:%02u:%02u.%03u';
    $time = sprintf($format, $hours, $minutes, $seconds, $milliseconds);
    return rtrim($time, '0');
}


问:
how to get pdftk to burst to source file name plus page number?
How can I use pdftk to burst to the same filename as the source file plus a number?

Sample input

```<code>source.pdf
</code>```

Desired output

```<code>source-1.pdf (it is ok if page number has leading zeroes, but not required)
source-2.pdf
</code>```

Maybe I could use a .bat file to substitute the source filename?  I have no idea how to do this.  Any help at all is appreciated.

答:
Install pdftk server version

Allow for adding the path to environment variables

This can be done like the following:

Open windows cmd prompt

pdftk source.pdf burst

or

pdftk source.pdf burst output -%d.pdf

Body:
How can I use pdftk to burst to the same filename as the source file plus a number?

Sample input

source.pdf

Desired output

source-1.pdf (it is ok if page number has leading zeroes, but not required)
source-2.pdf

Maybe I could use a .bat file to substitute the source filename?  I have no idea how to do this.  Any help at all is appreciated.


问:
Invalid 'await' of a non-Promise value (Bluebird promise)
When I tslint my whole project using tslint --project tsconfig.json src/**/*.ts I get lots of tslint errors like these:

Invalid 'await' of a non-Promise value.

These errors pops up in every line where I am awaiting a Bluebird promise. I wonder what I should do to avoid these warnings? At runtime I don't face any issues, however I assume that there is a good reason to fix these issues?

For instance I am using the amqplib library which uses Bluebird for all promises. And every time I await one of the promise based methods I will get a tslint error:

```<code>const queueInfo: Replies.AssertQueue = await this.channel.assertQueue(this.jobQueueName);
</code>```

Question:

What is the best way for awaiting non-Promise values like Bluebird promises?

答:
You can convert any "thenable" object (with a least a then() method) to a native Promise using Promise.resolve.

```<code>const queueInfo: Replies.AssertQueue = await Promise.resolve(this.channel.assertQueue(this.jobQueueName));
</code>```

Alternative syntax (a little bit less efficient because of the closure) :

```<code>const queueInfo: Replies.AssertQueue = await Promise.resolve().then(() =>
    this.channel.assertQueue(this.jobQueueName)
);
</code>```

Body:
When I tslint my whole project using tslint --project tsconfig.json src/**/*.ts I get lots of tslint errors like these:

Invalid 'await' of a non-Promise value.

These errors pops up in every line where I am awaiting a Bluebird promise. I wonder what I should do to avoid these warnings? At runtime I don't face any issues, however I assume that there is a good reason to fix these issues?

For instance I am using the amqplib library which uses Bluebird for all promises. And every time I await one of the promise based methods I will get a tslint error:

const queueInfo: Replies.AssertQueue = await this.channel.assertQueue(this.jobQueueName);

Question:

What is the best way for awaiting non-Promise values like Bluebird promises?

Body:
You can convert any "thenable" object (with a least a then() method) to a native Promise using Promise.resolve.

const queueInfo: Replies.AssertQueue = await Promise.resolve(this.channel.assertQueue(this.jobQueueName));

Alternative syntax (a little bit less efficient because of the closure) :

const queueInfo: Replies.AssertQueue = await Promise.resolve().then(() =>
    this.channel.assertQueue(this.jobQueueName)
);


问:
Check if array is an ordered subset
I want to find out if an array is an ordered subset of another array:

[1,2] is an ordered subset of [1,2,3]

[1,3] is an ordered subset of [1,2,3]

[2,1] is not an ordered subset of [1,2,3]

I've found some solutions to this, but every solution ignores the order. Every method I've seen so far ignores the order of the arrays:

```<code>[1,2,3] - [2,1] #=> [3]
[1,2,3] & [2,1] #=> [1,2]
[1,2,3].to_set.superset?([2,1].to_set) #=> true
</code>```

Update:
Based on the discussion below, I've updated my question.

答:
```<code>a = [1,2,3]
b = [2,1]

p a.each_cons(b.size).any?{|slice| slice == b} # => false
</code>```

Title: Check if array is an ordered subset

Body:
I want to find out if an array is an ordered subset of another array:

[1,2] is an ordered subset of [1,2,3]

[1,3] is an ordered subset of [1,2,3]

[2,1] is not an ordered subset of [1,2,3]

I've found some solutions to this, but every solution ignores the order. Every method I've seen so far ignores the order of the arrays:

[1,2,3] - [2,1] #=> [3]
[1,2,3] & [2,1] #=> [1,2]
[1,2,3].to_set.superset?([2,1].to_set) #=> true

Update:
Based on the discussion below, I've updated my question.


问:
Subclass QPushbutton with different args
How can I subclass the QPushbutton in Pyside but require an arg. In my example I need the arg to be a list of ints [0,0,0].

My goal is to make it so i can create MyButton like this:

```<code># GOAL
MyButton([0,255,0])
</code>```

When the arguement containing the list of values is passed in, it should set the value self._data. I'm not sure if i have this setup correctly, so any corrections are appreciated.

```<code>class MyButton(QtGui.QPushButton):

    def __init__(self, *args, **kwargs):
        super(MyButton, self).__init__(*args, **kwargs)

        self._data = stuff

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, value):
        self._data = value

MyButton([0,255,0])
</code>```

Updated: I noticed though when i pass that value into my Init it doesn't appear to trigger the setter for that property?? Why is that? If you test the code below, you'll see the color of the button isn't set when it's instantiated. How do i fix that?

```<code>import os
import sys
import json
from PySide import QtCore, QtGui

class QColorSwatch(QtGui.QPushButton):

    colorClicked = QtCore.Signal(list)
    colorChanged = QtCore.Signal(list)

    def __init__(self, stuff, *args, **kwargs):
        super(QColorSwatch, self).__init__(*args, **kwargs)

        self._color = stuff
        self.setMaximumWidth(22)
        self.setMaximumHeight(22)
        self.setAutoFillBackground(True)
        self.pressed.connect(self.color_clicked)

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, value):
        self._color = value
        pixmap = QtGui.QPixmap(self.size())
        pixmap.fill(QtGui.QColor(value[0], value[1], value[2]))
        self.setIcon(pixmap)
        self.colorChanged.emit(value)
        # swatch.setIconSize(pixmap.size() - QtCore.QSize(6,6))

    def color_clicked(self):
        self.colorClicked.emit(self.color)

class ExampleWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(ExampleWindow, self).__init__(parent)
        self.resize(300, 200)

        self.ui_swatch = QColorSwatch([255,0,0])

        # main layout
        main_layout = QtGui.QVBoxLayout()
        main_layout.setContentsMargins(5,5,5,5)
        main_layout.setSpacing(5)
        main_layout.addWidget(self.ui_swatch)

        main_widget = QtGui.QWidget()
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)

        # Signals
        self.ui_swatch.colorClicked.connect(self.color_clicked)
        self.ui_swatch.colorChanged.connect(self.color_changed)

    def color_clicked(self, col):
        print 'CLICKED:', col
        self.ui_swatch.color = [255,0,0]

    def color_changed(self, col):
        print 'CHANGED:', col

def main():
    app = QtGui.QApplication(sys.argv)
    ex = ExampleWindow()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

答:
You have to put stuff as a parameter.

```<code>class MyButton(QtGui.QPushButton):
    def __init__(self, stuff, *args, **kwargs):
        super(MyButton, self).__init__(*args, **kwargs)

        self._data = stuff

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, value):
        self._data = value

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    mainWin = MyButton([0,255,0])
    print(mainWin.data)
    mainWin.show()
    sys.exit(app.exec_())
</code>```

Update:

You have to use self.color to use the setter.

```<code>class QColorSwatch(QtGui.QPushButton):

    colorClicked = QtCore.Signal(list)
    colorChanged = QtCore.Signal(list)

    def __init__(self, stuff, *args, **kwargs):
        super(QColorSwatch, self).__init__(*args, **kwargs)
        self._color = None
        self.color = stuff
        self.setMaximumWidth(22)
        self.setMaximumHeight(22)
        self.setAutoFillBackground(True)
        self.pressed.connect(self.color_clicked)

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, value):
        self._color = value
        pixmap = QtGui.QPixmap(self.size())
        pixmap.fill(QtGui.QColor(value[0], value[1], value[2]))
        self.setIcon(pixmap)
        self.colorChanged.emit(value)
        # swatch.setIconSize(pixmap.size() - QtCore.QSize(6,6))

    def color_clicked(self):
        self.colorClicked.emit(self.color)
</code>```

Body:
How can I subclass the QPushbutton in Pyside but require an arg. In my example I need the arg to be a list of ints [0,0,0].

My goal is to make it so i can create MyButton like this:

# GOAL
MyButton([0,255,0])

When the arguement containing the list of values is passed in, it should set the value self._data. I'm not sure if i have this setup correctly, so any corrections are appreciated.

class MyButton(QtGui.QPushButton):

    def __init__(self, *args, **kwargs):
        super(MyButton, self).__init__(*args, **kwargs)

        self._data = stuff

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, value):
        self._data = value

MyButton([0,255,0])

Updated: I noticed though when i pass that value into my Init it doesn't appear to trigger the setter for that property?? Why is that? If you test the code below, you'll see the color of the button isn't set when it's instantiated. How do i fix that?

import os
import sys
import json
from PySide import QtCore, QtGui

class QColorSwatch(QtGui.QPushButton):

    colorClicked = QtCore.Signal(list)
    colorChanged = QtCore.Signal(list)

    def __init__(self, stuff, *args, **kwargs):
        super(QColorSwatch, self).__init__(*args, **kwargs)

        self._color = stuff
        self.setMaximumWidth(22)
        self.setMaximumHeight(22)
        self.setAutoFillBackground(True)
        self.pressed.connect(self.color_clicked)

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, value):
        self._color = value
        pixmap = QtGui.QPixmap(self.size())
        pixmap.fill(QtGui.QColor(value[0], value[1], value[2]))
        self.setIcon(pixmap)
        self.colorChanged.emit(value)
        # swatch.setIconSize(pixmap.size() - QtCore.QSize(6,6))

    def color_clicked(self):
        self.colorClicked.emit(self.color)

class ExampleWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(ExampleWindow, self).__init__(parent)
        self.resize(300, 200)

        self.ui_swatch = QColorSwatch([255,0,0])

        # main layout
        main_layout = QtGui.QVBoxLayout()
        main_layout.setContentsMargins(5,5,5,5)
        main_layout.setSpacing(5)
        main_layout.addWidget(self.ui_swatch)

        main_widget = QtGui.QWidget()
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)

        # Signals
        self.ui_swatch.colorClicked.connect(self.color_clicked)
        self.ui_swatch.colorChanged.connect(self.color_changed)

    def color_clicked(self, col):
        print 'CLICKED:', col
        self.ui_swatch.color = [255,0,0]

    def color_changed(self, col):
        print 'CHANGED:', col

def main():
    app = QtGui.QApplication(sys.argv)
    ex = ExampleWindow()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Body:
You have to put stuff as a parameter.

class MyButton(QtGui.QPushButton):
    def __init__(self, stuff, *args, **kwargs):
        super(MyButton, self).__init__(*args, **kwargs)

        self._data = stuff

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, value):
        self._data = value

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    mainWin = MyButton([0,255,0])
    print(mainWin.data)
    mainWin.show()
    sys.exit(app.exec_())

Update:

You have to use self.color to use the setter.

class QColorSwatch(QtGui.QPushButton):

    colorClicked = QtCore.Signal(list)
    colorChanged = QtCore.Signal(list)

    def __init__(self, stuff, *args, **kwargs):
        super(QColorSwatch, self).__init__(*args, **kwargs)
        self._color = None
        self.color = stuff
        self.setMaximumWidth(22)
        self.setMaximumHeight(22)
        self.setAutoFillBackground(True)
        self.pressed.connect(self.color_clicked)

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, value):
        self._color = value
        pixmap = QtGui.QPixmap(self.size())
        pixmap.fill(QtGui.QColor(value[0], value[1], value[2]))
        self.setIcon(pixmap)
        self.colorChanged.emit(value)
        # swatch.setIconSize(pixmap.size() - QtCore.QSize(6,6))

    def color_clicked(self):
        self.colorClicked.emit(self.color)


问:
FCM + Ionic/Cordova + Crosswalk - Same notifications received multiple times in intervals
My Android Ionic app receives the same push notifications multiple times in random intervals (mostly around 3-5 minutes) for hours. I'm using the plugin https://github.com/fechanique/cordova-plugin-fcm for FCM. But its not about the callback onNotification() being triggered multiple times - there are real notifications popping up in the statusbar. It does not matter if I use https://cordova-plugin-fcm.appspot.com/ or my node.js server to send the notifications. It's always the same: minutes after the "original and correct" push a duplicate is received and this repeats for a indeterminate time. It's driving me insane and I can't find the root of the problem. Has anyone experienced this problem as well?
Thanks in advance!

EDIT: My app is using crosswalk. I've noticed that if I remove crosswalk new notifications work as expected and will only be received once. At least it seems to be related. I will investigate this further.

EDIT2:  Another similar app has the same setup (fcm + crosswalk) and is working fine. I don't see a difference that could lead to such a behavior tho :/

答: Problem solved: There seems to be a bug at the Firebase/Google backend with one of our apps. Creating a new one solved the issue.</p>


问:
How to do C++ style destructors in C#?
I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away.

The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.

In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.

Is there any way to for a using block to be automatically used in C#?

Many thanks.

UPDATE:

I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.

Here's the bug I found, reduced to the essentials...

```<code>try
{
    PleaseDisposeMe a = new PleaseDisposeMe();
    throw new Exception();
    a.Dispose();
}
catch (Exception ex)
{
    Log(ex);
}

// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();
</code>```

Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?

答:
@Quarrelsome

If will get called when the object is moved out of scope and is tidied by the garbage collector.

This statement is misleading and how I read it incorrect: There is absolutely no guarantee when the finalizer will be called.  You are absolutely correct that billpg should implement a finalizer; however it will not be called automaticly when the object goes out of scope like he wants.  Evidence, the first bullet point under Finalize operations have the following limitations.

In fact Microsoft gave a grant to Chris Sells to create an implementation of .NET that used reference counting instead of garbage collection Link.  As it turned out there was a considerable performance hit.

OwnerDisplayName: billpg

Title: How to do C++ style destructors in C#?

Body:
I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away.

The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.

In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.

Is there any way to for a using block to be automatically used in C#?

Many thanks.

UPDATE:

I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.

Here's the bug I found, reduced to the essentials...

try
{
    PleaseDisposeMe a = new PleaseDisposeMe();
    throw new Exception();
    a.Dispose();
}
catch (Exception ex)
{
    Log(ex);
}

// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();

Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?

LastEditorDisplayName: billpg

OwnerDisplayName: Andrew Burns


问:
Very Advanced Javascript WYSIWYG editor
I need a solution where a user could enter the URL of a web page in my system. The page would load, and then the user could click a certain section that he wants to change. So basically what I need is, a way to display a web page inside my app (could possibly be done with frames but I'd prefer not to have a horizontal scroll bar), and then another way to let users select a block of text or a page element.

I.e if a block of text is in a div, hovering above the text would outline that div using a faint green color (hovering away would remove this border/outline), and clicking the text would draw a solid green border around it to show that its been selected, and then some content on my page will show the id of the div, and let the user specify some other info that i need.

So I probably need a way to get all the
s,
s, s,
s and any other 'container' tags, and then have the ability to cause hovering/clicking of them to change their style.border property, and the ability to retrieve their id/name,

For a block of text the border could probably work, but what about images and such? Also, what if a
 doesn't have an ID/Name, how could it be specified?

答:
This is a very general question. There are lots of content management systems around, that provides something like this.

Also, what if a
 doesn't have an ID/Name, how could it be specified?

You can identify a node in the DOM by an XPath path. Traverse upwards through the parentNode to create the path.

For a block of text the border could probably work, but what about images and such?

You can set the border property of almost all elements in html.

OwnerDisplayName: Click Upvote

Title: Very Advanced Javascript WYSIWYG editor

LastEditorDisplayName: Tom

Body:
This is a very general question. There are lots of content management systems around, that provides something like this.

Also, what if a <div> doesn't have an ID/Name, how could it be specified?

You can identify a node in the DOM by an XPath path. Traverse upwards through the parentNode to create the path.

For a block of text the border could probably work, but what about images and such?

You can set the border property of almost all elements in html.

OwnerDisplayName: troelskn


问:
how to query child objects in mongodb
I'm new to mongodb and am trying to query child objects. I have a collection of States, and each State has child Cities. One of the Cities has a Name property that is null, which is causing errors in my app. How would I query the State collections to find child Cities that have a name == null?</p>

答:
Assuming your "states" collection is like:

```<code>{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
</code>```

The query to find states with null cities would be:

```<code>db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
</code>```

It is a common mistake to query for nulls as:

```<code>db.states.find({"cities.name" : null});
</code>```

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

Title: how to query child objects in mongodb

Body:
Assuming your "states" collection is like:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistake to query for nulls as:

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.


问:
How to delete indexedDB?
I'm working in a project which involves using IndexedDB.
As I'm begining to know this technology, I need to be able to delete an indexedDB by hand so I can start over.

I found the way to do it in Firefox, but I can't find the way for Google Chrome.

I tried deleting the content of this folder (I'm using Mac):

{home}/Library/Application Support/Google/Chrome/Default/IndexedDB

but it seems Chrome stil have the DB anywhere so I can't start over.

答:
Chrome -> Inspector Window -> Application -> look at left hand menu -> Storage -> IndexedDB

You have to be on your application's page though.  Also I think Safari expires IDB data after 7 days or something.

Title: How to delete indexedDB?


问:
Multiplying parenthesis to get a polynomial in python
I was asked to do the newton polynomial interpolation and I was able to write the main code.
https://en.wikipedia.org/wiki/Newton_polynomial
But there is still one small thing that I am not able to get around since a couple of days, after reading I found a way to do it using Sympy, but I am not allowed to use anything other than basic numpy.
Now my problem is that I trying to multiply something like this

p(x)=j(x-q)(x-w)(x-e)+k(x-w)(x-e)+l(x-e)+d

to get this p(x)=ax³+bx²+cx+d , so I amlooking for the polynomial coefficients a,b,c,d

for example:

p(x)=5-7(x+1)+9(x+1)(x)-7(x+1)(x)(x-1)=-7x³+9x²+9x-2

of course I am looking for the general case, not only for ploynomials from third degree.
Any tip would be much appreciated, I am really stuck at this since a couple of days.
and Sorry for the sloppy writing of notation, but it seems stackoverflow doesn't accept latex and I am not able to post a picture because I don't have rhe required reputation. (if there is other solutuions to post it properly please tell me and I'll just post it again)

Thanks in advance :)

答:
One way of doing it is to represent a polinomial as an array where a[0]..a[n] where a[i] is the constant that you multipliy (x^i). The function will be something like p(x) = a[0] + a[1]*x + a[2]* (x**2)....

Now to add two polinomials in this representation you just need to pad the shorter one with 0s and add the values at matching indices.

If you want to multiply a polinomial by k*(x**z) you need to multiply every value by k and insert z zeros in front( a[0:0] = [0.] * z).

Using these two operations you can resolve the equation and get the coefficients you want.


问:
Group subscription duration by month and year in mysql
I have a table of subscriptions, storing user id, subscription end date, program id. One user can be subscribed to many programs, but for the scope of the problem the latest date is considered as the end date of the subscription. The goal is to find the number of users whose subscription is ending for each month of each year.  To illustrate it:

```<code>-------------------------------------------
| user_id | program_id |  end_date        |
-------------------------------------------
|    1    |     1      |  2015-12-10      |
|    1    |     2      |  2017-08-27      |
|    2    |     1      |  2017-09-20      |
|    3    |     2      |  2017-10-01      |
|    2    |     3      |  2017-09-18      |
|    5    |     12     |  2017-10-22      |
|    4    |     3      |  2017-10-10      |
|    3    |     8      |  2018-11-15      |
-------------------------------------------
</code>```

Intermediate result show when will the subscription end for each user (only month is needed):

```<code>------------------------------
| user_id |   enddate        |
------------------------------
|    1    |   2017-08        |
|    2    |   2017-09        |
|    3    |   2018-11        |
|    4    |   2017-10        |
|    5    |   2017-10        |
------------------------------
</code>```

This was achieved with the query:

```<code>Select user_id, DATE_FORMAT(max(end_date), '%Y-%m') AS as enddate
From subscription
Group by user_id
Order by end_date desc;
</code>```

The final result must further filter the list, showing only how many users will be left with no subscription in each month, like this:

```<code>------------------------------
| count   |  month, year     |
------------------------------
|    1    |   2017-08        |
|    1    |   2017-09        |
|    2    |   2017-10        |
|    1    |  2018-11         |
------------------------------
</code>```

This is where I am stuck with no mysql ideas. Iterating through the results and counting is out of the question.

答:
Try this - </p>

```<code>Select COUNT(*), DATE_FORMAT(MAX(end_date), '%Y-%m') AS as enddate
From subscription
Group by user_id
Order by end_date desc;
</code>```

Body:
I have a table of subscriptions, storing user id, subscription end date, program id. One user can be subscribed to many programs, but for the scope of the problem the latest date is considered as the end date of the subscription. The goal is to find the number of users whose subscription is ending for each month of each year.  To illustrate it:

-------------------------------------------
| user_id | program_id |  end_date        |
-------------------------------------------
|    1    |     1      |  2015-12-10      |
|    1    |     2      |  2017-08-27      |
|    2    |     1      |  2017-09-20      |
|    3    |     2      |  2017-10-01      |
|    2    |     3      |  2017-09-18      |
|    5    |     12     |  2017-10-22      |
|    4    |     3      |  2017-10-10      |
|    3    |     8      |  2018-11-15      |
-------------------------------------------

Intermediate result show when will the subscription end for each user (only month is needed):

------------------------------
| user_id |   enddate        |
------------------------------
|    1    |   2017-08        |
|    2    |   2017-09        |
|    3    |   2018-11        |
|    4    |   2017-10        |
|    5    |   2017-10        |
------------------------------

This was achieved with the query:

Select user_id, DATE_FORMAT(max(end_date), '%Y-%m') AS as enddate
From subscription
Group by user_id
Order by end_date desc;

The final result must further filter the list, showing only how many users will be left with no subscription in each month, like this:

------------------------------
| count   |  month, year     |
------------------------------
|    1    |   2017-08        |
|    1    |   2017-09        |
|    2    |   2017-10        |
|    1    |  2018-11         |
------------------------------

This is where I am stuck with no mysql ideas. Iterating through the results and counting is out of the question.

Body:
Try this -

Select COUNT(*), DATE_FORMAT(MAX(end_date), '%Y-%m') AS as enddate
From subscription
Group by user_id
Order by end_date desc;


答:
Multiplying two polynomials x(x-1) is the same as convolving their coefficients:

```<code># x     => [1, 0]
# (x-1) => [1, -1]
numpy.convolve([1, 0], [1, -1])  # [1, -1, 0] => x^2 - x + 0
</code>```

This means you can solve the problem using

```<code>import numpy

def mult(a, b):
    """
    Polynomial multiplication is simply a convolution
    """
    return numpy.convolve(a, b)

def add(a, b):
    """
    Addition is a bit complex as a and b may have different lengths.
    Simply prepend zeros to the shorter one
    """

    if len(a) < len(b):
        a = numpy.insert(a, 0, [0] * (len(b) - len(a)))
    if len(b) < len(a):
        b = numpy.insert(b, 0, [0] * (len(a) - len(b)))

    return a + b

# p(x)=5-7(x+1)+9(x+1)(x)-7(x+1)(x)(x-1)=-7x³+9x²+9x-2
add(
    add(
        numpy.array([5]),
        mult([-7], [1, 1]),
    ),
    add(
        mult([9], mult([1, 1], [1, 0])),
        mult([-7], mult([1, 1], mult([1, 0], [1, -1])))
    )
)
</code>```

yields

```<code>array([-7,  9,  9, -2])  # => -7x^3 + 9x^2 + 9x - 2
</code>```

Title: Multiplying parenthesis to get a polynomial in python

Body:
I was asked to do the newton polynomial interpolation and I was able to write the main code.
https://en.wikipedia.org/wiki/Newton_polynomial
But there is still one small thing that I am not able to get around since a couple of days, after reading I found a way to do it using Sympy, but I am not allowed to use anything other than basic numpy.
Now my problem is that I trying to multiply something like this

p(x)=j(x-q)(x-w)(x-e)+k(x-w)(x-e)+l(x-e)+d

to get this p(x)=ax³+bx²+cx+d , so I amlooking for the polynomial coefficients a,b,c,d

for example:

p(x)=5-7(x+1)+9(x+1)(x)-7(x+1)(x)(x-1)=-7x³+9x²+9x-2

of course I am looking for the general case, not only for ploynomials from third degree.
Any tip would be much appreciated, I am really stuck at this since a couple of days.
and Sorry for the sloppy writing of notation, but it seems stackoverflow doesn't accept latex and I am not able to post a picture because I don't have rhe required reputation. (if there is other solutuions to post it properly please tell me and I'll just post it again)

Thanks in advance :)

Body:
Multiplying two polynomials x(x-1) is the same as convolving their coefficients:

# x     => [1, 0]
# (x-1) => [1, -1]
numpy.convolve([1, 0], [1, -1])  # [1, -1, 0] => x^2 - x + 0

This means you can solve the problem using

import numpy

def mult(a, b):
    """
    Polynomial multiplication is simply a convolution
    """
    return numpy.convolve(a, b)

def add(a, b):
    """
    Addition is a bit complex as a and b may have different lengths.
    Simply prepend zeros to the shorter one
    """

    if len(a) < len(b):
        a = numpy.insert(a, 0, [0] * (len(b) - len(a)))
    if len(b) < len(a):
        b = numpy.insert(b, 0, [0] * (len(a) - len(b)))

    return a + b

# p(x)=5-7(x+1)+9(x+1)(x)-7(x+1)(x)(x-1)=-7x³+9x²+9x-2
add(
    add(
        numpy.array([5]),
        mult([-7], [1, 1]),
    ),
    add(
        mult([9], mult([1, 1], [1, 0])),
        mult([-7], mult([1, 1], mult([1, 0], [1, -1])))
    )
)

yields

array([-7,  9,  9, -2])  # => -7x^3 + 9x^2 + 9x - 2


问:
Cant return manually generated id
I am trying to return the value of new_id but with no success. Any help?

```<code>create or replace FUNCTION create_election (name        VARCHAR,
                             description VARCHAR,
                           type          VARCHAR,
                           subtype       VARCHAR,
                           started_at    VARCHAR,
                           ended_at      VARCHAR)
RETURN INT
IS
v_id int;
BEGIN
    INSERT INTO election VALUES  (
          (  SELECT nvl(max(id)+1, 0) AS new_id FROM  election ) ,
          name,  description,  type, subtype, started_at, ended_at,
          0,  0,  0
) RETURNING new_id into v_id ;
END;
</code>```

--- UPDATE ---
I choose the solution based on best practices. Thx for the help.

答:
```<code>create or replace FUNCTION create_election (name        VARCHAR,
                             description VARCHAR,
                           type          VARCHAR,
                           subtype       VARCHAR,
                           started_at    VARCHAR,
                           ended_at      VARCHAR)
RETURN INT
IS
  v_id int;
  new_id int;
BEGIN
    INSERT INTO election VALUES  (
          nvl(  (SELECT max(id)+1 AS new_id FROM  election) ,1 ),
          name,  description,  type, subtype, started_at, ended_at,
          0,  0,  0
) RETURNING new_id into v_id ;

  return v_id;
END;
</code>```

Title: Cant return manually generated id

Body:
I am trying to return the value of new_id but with no success. Any help?

create or replace FUNCTION create_election (name        VARCHAR,
                             description VARCHAR,
                           type          VARCHAR,
                           subtype       VARCHAR,
                           started_at    VARCHAR,
                           ended_at      VARCHAR)
RETURN INT
IS
v_id int;
BEGIN
    INSERT INTO election VALUES  (
          (  SELECT nvl(max(id)+1, 0) AS new_id FROM  election ) ,
          name,  description,  type, subtype, started_at, ended_at,
          0,  0,  0
) RETURNING new_id into v_id ;
END;

--- UPDATE ---
I choose the solution based on best practices. Thx for the help.


问:
TwinCAT 3 visualize FTP Server
Is there any way to visualize the connection (and download a file) from a FTP server?
All this in TwinCAT 3.

I am trying to download a file from a FTP server. However I can't seem to find a correct visualisation.

I found a demo code on the site of Beckhoff where they download a file from a server, but this is meant for an actual PLC.

Kind regards!

答:
By utilizing TF6300, you can implement a FTP-client using TwinCAT3. For download of a file from an FTP-server, Beckhoff has a good example here for an implementation of a file download. This is possible to do with any ADS-capable device, for instance TwinCAT3. You can install this on your PC, it doesn't need to an actual PLC. To visualize this, I'd just go along and visualize some of the variables that are instantiated when you instantiate the function blocks that you need for the required functionality. If you for instance instantiate the FB "FB_FTP_FileDownload", you have access to the output variable "nProgress", which shows the current status of the data transmission in percent. Regarding the visualization, there are many ways to do it. You can for example:
- Implement this directly with a TwinCAT3 visu (using ADS as middleware)
- Use adslib.dll (or any other ads implementation) for your own HMI
- Use any other middleware (OPC-UA) and publish your data to your HMI

The outputs from the function blocks required for a file-download (FB_FTP_Open, FB_FTP_FileDownload, FB_FTP_Close) will give you all the information that you need to show the status of a download.

Title: TwinCAT 3 visualize FTP Server


问:
Ajax doesn't post data
[SOLVED]

That was THE most difficult bug ever - all due to copy/paste stuff up.

This:

```<code>$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
</code>```

should have been that:

```<code>$('#errors'+bUID).append('<ul id="error_list'+bUID+'"></ul>');
</code>```

The damn '+bUID+' was pasted AFTER the " , not BEFORE!

Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))

Here's the js:

```<code>$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    e.preventDefault();
    submitForm(bUID);
    alert(bUID);
});

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();
    alert(bUID);

    // also tried this
    var post_data = {
    'name': $('#name'+bUID).val(),
    'email': $('#email'+bUID).val(),
    'message': $('#message'+bUID).val(),
    'code': $('#code'+bUID).val(),
    'buid': bUID,
    };
    alert(Object.keys(post_data).length);

    // ALSO tried this instead of ajax:
    //$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
    alert(response);
    $.ajax({
        dataType: "json",
        type: "post",
        data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
        //data: post_data,
        url:   $('#contact_form'+bUID).attr('action'),
        success: function(response) {
            if (typeof response !== 'undefined' && response.length > 0) {
                if (response[0] == "success") {
                    $('#success'+bUID).append('<p>Success</p>');
                }
                else {
                    $('#errors'+bUID).append('<p>' + js_errors + '</p>');
                    $('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
                    $.each(response, function(i, v){
                        if (i > 0) {
                            $('#error_list'+bUID).append('<li>' + v + '</li>');
                        }
                    });
                }
            }
        }
    });
}
</code>```

here's the action in view.php:

```<code><?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>

<form id="contact_form<?php echo $bUID; ?>"
    class="contact-form"
    enctype="multipart/form-data"
    action="<?php echo $formAction?>"
    method="post"
    accept-charset="utf-8">

    <?php echo $bUID; ?><br />
    <input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">

   ...etc.
</code>```

and here's the controller.php:

```<code>public function action_submit($token = false, $bID = false)
{
    $this->form_errors = array();
    array_push($this->form_errors, "error");
    array_push($this->form_errors, $_POST['name']);
    array_push($this->form_errors, $_POST['email']);
    array_push($this->form_errors, $_POST['message']);
    array_push($this->form_errors, $_POST['code']);
    array_push($this->form_errors, $_POST['buid']);
    echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
    exit;
}
</code>```

it gets all data and shows it in alert but then trows the following error in the console:

```<code>Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg@gmail.commm","gggggggggggggggggggggggg","gggg","171"]
    at r (jquery.js:2)
    at Function.each (jquery.js:2)
    at Object.success (view.js:132)
    at j (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at x (jquery.js:5)
    at XMLHttpRequest.b (jquery.js:5)
</code>```

Line 132 of the js file is this: $.each(response, function(i, v){

I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg@gmail.commm,gggggggggggggggggggggg,gggg,171", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!

What's wrong here? Why doesn't the form get posted?

Thank you very much.

答:
Just use

```<code>    data: form.serializeArray()
</code>```

Like this:

```<code>$.ajax({
url: 'url to post data',
dataType: "json",
method: "post",
data: form.serializeArray(),
 success: function(data) {
   // another staff here, you can write console.log(data) to see what server responded
 },
 fail: function(data) {
     console.log(data) // if any error happens it will show in browsers console
  }
});
</code>```

Another tips: in server side you can use http_response_code(200) for success, http_response_code(400) for errors, http_response_code(403) if authorisation is required

Title: Ajax doesn't post data

Body:
[SOLVED]

That was THE most difficult bug ever - all due to copy/paste stuff up.

This:

$('#errors'+bUID).append('

');

should have been that:

$('#errors'+bUID).append('

');

The damn '+bUID+' was pasted AFTER the " , not BEFORE!

Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))

Here's the js:

$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    e.preventDefault();
    submitForm(bUID);
    alert(bUID);
});

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();
    alert(bUID);

    // also tried this
    var post_data = {
    'name': $('#name'+bUID).val(),
    'email': $('#email'+bUID).val(),
    'message': $('#message'+bUID).val(),
    'code': $('#code'+bUID).val(),
    'buid': bUID,
    };
    alert(Object.keys(post_data).length);

    // ALSO tried this instead of ajax:
    //$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
    alert(response);
    $.ajax({
        dataType: "json",
        type: "post",
        data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
        //data: post_data,
        url:   $('#contact_form'+bUID).attr('action'),
        success: function(response) {
            if (typeof response !== 'undefined' && response.length > 0) {
                if (response[0] == "success") {
                    $('#success'+bUID).append('
Success
');
                }
                else {
                    $('#errors'+bUID).append('
' + js_errors + '
');
                    $('#errors'+bUID).append('

');
                    $.each(response, function(i, v){
                        if (i > 0) {
                            $('#error_list'+bUID).append('
' + v + '
');
                        }
                    });
                }
            }
        }
    });
}

here's the action in view.php:

<?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>

<form id="contact_form<?php echo $bUID; ?>"
    class="contact-form"
    enctype="multipart/form-data"
    action="<?php echo $formAction?>"
    method="post"
    accept-charset="utf-8">

    <?php echo $bUID; ?>

    <input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">

   ...etc.

and here's the controller.php:

public function action_submit($token = false, $bID = false)
{
    $this->form_errors = array();
    array_push($this->form_errors, "error");
    array_push($this->form_errors, $_POST['name']);
    array_push($this->form_errors, $_POST['email']);
    array_push($this->form_errors, $_POST['message']);
    array_push($this->form_errors, $_POST['code']);
    array_push($this->form_errors, $_POST['buid']);
    echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
    exit;
}

it gets all data and shows it in alert but then trows the following error in the console:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg@gmail.commm","gggggggggggggggggggggggg","gggg","171"]
    at r (jquery.js:2)
    at Function.each (jquery.js:2)
    at Object.success (view.js:132)
    at j (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at x (jquery.js:5)
    at XMLHttpRequest.b (jquery.js:5)

Line 132 of the js file is this: $.each(response, function(i, v){

I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg@gmail.commm,gggggggggggggggggggggg,gggg,171", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!

What's wrong here? Why doesn't the form get posted?

Thank you very much.

Body:
Just use

    data: form.serializeArray()

Like this:

$.ajax({
url: 'url to post data',
dataType: "json",
method: "post",
data: form.serializeArray(),
 success: function(data) {
   // another staff here, you can write console.log(data) to see what server responded
 },
 fail: function(data) {
     console.log(data) // if any error happens it will show in browsers console
  }
});

Another tips: in server side you can use http_response_code(200) for success, http_response_code(400) for errors, http_response_code(403) if authorisation is required


问:
Conditionally choose a value on the left hand side of an assignment statement?
Is it possible to conditionally choose a value on the left hand side of an assignment statement (in C#)?

If I was assigning one of two values to a single variable, I could do this:

```<code>var1 = (mode == "A" ?
          someList.Any(itm => itm.prop == value) :
          someList.Any(itm => itm.prop == value2)  );

or

var1 = someList.Any(itm => itm.prop == (mode == "A" ? value : value2));
</code>```

But suppose I want to populate one of two variables with a value:

```<code>if (mode == "A")
    var1 = someList.Any(itm => itm.prop == value);

if (mode == "B")
    var2 = someList.Any(itm => itm.prop == value);
</code>```

Is there any way to do this in one line? (non working) example:

```<code>(mode == "A" ? var1 : var2) = someList.Any(itm => itm.prop == value);
</code>```

[I know I can introduce a variable and assign it to var1 or var2 before getting from somelist

```<code>var temp = (mode == "A" ? var1 : var2);
temp = someList.Any(itm => itm.prop == value);
</code>```

]

UPDATE
@HimBromBeere - I know that there are restrictions on the target of an assignment, and I don't need to do this, I just wondered if it was possible, in the same way that usage of the conditional operator is possible.

The code snippets were meant to illustrate and further explain the question.

...But I succeeded in getting two wonderful, useful nuggets of information from @EricLippert and @Servy: The ConditionalAssignment / SelectVariable function and the C# ref function.

I'll probably never use them (Eric - I'll stick to IF), but it helps me to grow.

Thanks everyone for all the useful feedback.

答:
Yes, you can create a variable that is itself a reference to another variable (rather than one that holds a value).  You can also write a method that returns a reference to one of a choice of variables based on some condition.</p>

```<code>ref bool SelectVariable(ref bool a, ref bool b)
{
    if (mode == "A")
        return ref a;
    else
        return ref b;
}
ref bool referenceToVariable = ref SelectVariable(ref var1, ref var2);
referenceToVariable = someList.Any(itm => itm.prop == value);
</code>```

Body:
Is it possible to conditionally choose a value on the left hand side of an assignment statement (in C#)?

If I was assigning one of two values to a single variable, I could do this:

var1 = (mode == "A" ?
          someList.Any(itm => itm.prop == value) :
          someList.Any(itm => itm.prop == value2)  );

or

var1 = someList.Any(itm => itm.prop == (mode == "A" ? value : value2));

But suppose I want to populate one of two variables with a value:

if (mode == "A")
    var1 = someList.Any(itm => itm.prop == value);

if (mode == "B")
    var2 = someList.Any(itm => itm.prop == value);

Is there any way to do this in one line? (non working) example:

(mode == "A" ? var1 : var2) = someList.Any(itm => itm.prop == value);

[I know I can introduce a variable and assign it to var1 or var2 before getting from somelist

var temp = (mode == "A" ? var1 : var2);
temp = someList.Any(itm => itm.prop == value);

]

UPDATE
@HimBromBeere - I know that there are restrictions on the target of an assignment, and I don't need to do this, I just wondered if it was possible, in the same way that usage of the conditional operator is possible.

The code snippets were meant to illustrate and further explain the question.

...But I succeeded in getting two wonderful, useful nuggets of information from @EricLippert and @Servy: The ConditionalAssignment / SelectVariable function and the C# ref function.

I'll probably never use them (Eric - I'll stick to IF), but it helps me to grow.

Thanks everyone for all the useful feedback.

Body:
Yes, you can create a variable that is itself a reference to another variable (rather than one that holds a value).  You can also write a method that returns a reference to one of a choice of variables based on some condition.

ref bool SelectVariable(ref bool a, ref bool b)
{
    if (mode == "A")
        return ref a;
    else
        return ref b;
}
ref bool referenceToVariable = ref SelectVariable(ref var1, ref var2);
referenceToVariable = someList.Any(itm => itm.prop == value);