问:
Inconsistency in Java Script and Python Result for encoding URLs
I am trying to programmatically generate URLs  using Python. It works when using Java Script method ( encodeURIComponent ) but doesn't give same output when using Python ( urllib.urlencode )

This is the schema :

```<code>{
    "page": {
        "filters": {
            "power": {
                "keywordArray": [{
                    "keyword": "random word",
                    "isNegated": false
                }],
                "date": {
                    "from": "2019-04-22T08:00:00.000Z",
                    "to": "2019-05-22T08:00:00.000Z"
                }
            }
        }
    }
}
</code>```

I successfully tried Java Script method encodeURIComponent using ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
):

```<code>console.log(encodeURIComponent('({"page":{"filters":{"power":{"keywordArray":[{"keyword":"random word", "isNegated":False}],"date":{"from":"2019-04-22T08:00:00.000Z","to":"2019-05-22T08:00:00.000Z"}}}}})'));

(%7B%22page%22%3A%7B%22filters%22%3A%7B%22power%22%3A%7B%22keywordArray%22%3A%5B%7B%22keyword%22%3A%22random%20word%22%2C%20%22isNegated%22%3AFalse%7D%5D%2C%22date%22%3A%7B%22from%22%3A%222019-04-22T08%3A00%3A00.000Z%22%2C%22to%22%3A%222019-05-22T08%3A00%3A00.000Z%22%7D%7D%7D%7D%7D)
</code>```

I am not able to generate same output using Python :

```<code>params = {
    "page": {
        "filters": {
            "power": {
                "keywordArray": [{
                    "keyword": "random word",
                    "isNegated": False
                }],
                "date": {
                    "from": "2019-04-22T08:00:00.000Z",
                    "to": "2019-05-22T08:00:00.000Z"
                }
            }
        }
    }
}
urllib.urlencode(params )

Output :
'page=%7B%27filters%27%3A+%7B%27power%27%3A+%7B%27date%27%3A+%7B%27to%27%3A+%272019-05-22T08%3A00%3A00.000Z%27%2C+%27from%27%3A+%272019-04-22T08%3A00%3A00.000Z%27%7D%2C+%27keywordArray%27%3A+%5B%7B%27keyword%27%3A+%27random+word%27%2C+%27isNegated%27%3A+False%7D%5D%7D%7D%7D'
</code>```

The output using Python is different than that using Java Script (which is correct )

答:
In javascript, you are encoding the whole object as a string for the url, while Python, urllib.urlencode "convert[s] a mapping object or a sequence of two-element tuples to a “percent-encoded” string". That is, the object passed will be interpreted as an url like

```<code>page => <restOfTheObject>
</code>```

To have the same behaviour as in javascript, you should first convert the object to a json string, and then pass it to urllib.parse.quote

```<code>import urllib.parse
import json

params = {
    "page": {
        "filters": {
            "power": {
                "keywordArray": [{
                    "keyword": "random word",
                    "isNegated": False
                }],
                "date": {
                    "from": "2019-04-22T08:00:00.000Z",
                    "to": "2019-05-22T08:00:00.000Z"
                }
            }
        }
    }
}
urllib.parse.quote(json.dumps(params, separators=(',', ':')))
</code>```

Body:
I am trying to programmatically generate URLs  using Python. It works when using Java Script method ( encodeURIComponent ) but doesn't give same output when using Python ( urllib.urlencode )

This is the schema :

{
    "page": {
        "filters": {
            "power": {
                "keywordArray": [{
                    "keyword": "random word",
                    "isNegated": false
                }],
                "date": {
                    "from": "2019-04-22T08:00:00.000Z",
                    "to": "2019-05-22T08:00:00.000Z"
                }
            }
        }
    }
}

I successfully tried Java Script method encodeURIComponent using ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
):

console.log(encodeURIComponent('({"page":{"filters":{"power":{"keywordArray":[{"keyword":"random word", "isNegated":False}],"date":{"from":"2019-04-22T08:00:00.000Z","to":"2019-05-22T08:00:00.000Z"}}}}})'));

(%7B%22page%22%3A%7B%22filters%22%3A%7B%22power%22%3A%7B%22keywordArray%22%3A%5B%7B%22keyword%22%3A%22random%20word%22%2C%20%22isNegated%22%3AFalse%7D%5D%2C%22date%22%3A%7B%22from%22%3A%222019-04-22T08%3A00%3A00.000Z%22%2C%22to%22%3A%222019-05-22T08%3A00%3A00.000Z%22%7D%7D%7D%7D%7D)

I am not able to generate same output using Python :

params = {
    "page": {
        "filters": {
            "power": {
                "keywordArray": [{
                    "keyword": "random word",
                    "isNegated": False
                }],
                "date": {
                    "from": "2019-04-22T08:00:00.000Z",
                    "to": "2019-05-22T08:00:00.000Z"
                }
            }
        }
    }
}
urllib.urlencode(params )

Output :
'page=%7B%27filters%27%3A+%7B%27power%27%3A+%7B%27date%27%3A+%7B%27to%27%3A+%272019-05-22T08%3A00%3A00.000Z%27%2C+%27from%27%3A+%272019-04-22T08%3A00%3A00.000Z%27%7D%2C+%27keywordArray%27%3A+%5B%7B%27keyword%27%3A+%27random+word%27%2C+%27isNegated%27%3A+False%7D%5D%7D%7D%7D'

The output using Python is different than that using Java Script (which is correct )

Body:
In javascript, you are encoding the whole object as a string for the url, while Python, urllib.urlencode "convert[s] a mapping object or a sequence of two-element tuples to a “percent-encoded” string". That is, the object passed will be interpreted as an url like

page => <restOfTheObject>

To have the same behaviour as in javascript, you should first convert the object to a json string, and then pass it to urllib.parse.quote

import urllib.parse
import json

params = {
    "page": {
        "filters": {
            "power": {
                "keywordArray": [{
                    "keyword": "random word",
                    "isNegated": False
                }],
                "date": {
                    "from": "2019-04-22T08:00:00.000Z",
                    "to": "2019-05-22T08:00:00.000Z"
                }
            }
        }
    }
}
urllib.parse.quote(json.dumps(params, separators=(',', ':')))


来源: stackexchange

问:
Adding ffmpeg to clion project
I would liket to add ffmpeg to Clion but I have some problems with it.
My MakeLists.txt looks liek this:

```<code>cmake_minimum_required(VERSION 3.10)
project(ffmpeg)

set(CMAKE_CXX_STANDARD 11)

include_directories(libs/ffmpeg/)
include_directories(libs/ffmpeg/include/libavutil/)
include_directories(libs/ffmpeg/include/libaccodec/)
include_directories(libs/ffmpeg/include/libavdevice/)
include_directories(libs/ffmpeg/include/libavfilter/)
include_directories(libs/ffmpeg/include/libavformat/)

include_directories(libs/ffmpeg/include/)
link_directories(libs/ffmpeg/lib/)

set(SOURCE_FILES main.cpp)

add_executable(ffmpeg main.cpp)

target_link_libraries(
        ffmpeg
        avcodec
        avdevice
        avfilter
        avformat
        avresample
        avutil
        postproc
        swresample
        swscale
)
</code>```

I am not sure if I added the libraries and includes in the right way, beacause in my simple main.cpp it can't resolve avcodec_configuration().
My project layout looks as follows:

```<code>  ffmpeg
    -libs
      -include
        -libavcodec
        .
        .
        .
      -lib
        -avcodec.lib
    -main.cpp
</code>```

EDIT:
Now all includes are found by the compiler. BUt if I compile I get following error:

```<code>c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/bin/ld.exe: cannot find -lavresample
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [ffmpeg.exe] Error 1
mingw32-make.exe[1]: *** [CMakeFiles/ffmpeg.dir/all] Error 2
mingw32-make.exe: *** [all] Error 2
CMakeFiles\ffmpeg.dir\build.make:96: recipe for target 'ffmpeg.exe' failed
CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/ffmpeg.dir/all' failed
Makefile:82: recipe for target 'all' failed
</code>```

答:
I don't recommend to hardcode paths to the headers/libraries in your CMakeLists.txt; this is not portable.

Search for a ready FindFFmpeg.cmake (maybe this one will work?),

add it to your project directory (e.g. into a cmake/ subdirectory),

and connect it to CMAKE_MODULE_PATH. E.g. list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake").

Then refer to ${FFMPEG_LIBRARIES}, ${FFMPEG_INCLUDE_DIRS} and ${FFMPEG_DEFINITIONS}.

Sometimes you have to fix up the FindXXX.cmake modules.

ContentLicense: CC BY-SA 4.0

Title: Adding ffmpeg to clion project

Body:
I would liket to add ffmpeg to Clion but I have some problems with it.
My MakeLists.txt looks liek this:

cmake_minimum_required(VERSION 3.10)
project(ffmpeg)

set(CMAKE_CXX_STANDARD 11)

include_directories(libs/ffmpeg/)
include_directories(libs/ffmpeg/include/libavutil/)
include_directories(libs/ffmpeg/include/libaccodec/)
include_directories(libs/ffmpeg/include/libavdevice/)
include_directories(libs/ffmpeg/include/libavfilter/)
include_directories(libs/ffmpeg/include/libavformat/)

include_directories(libs/ffmpeg/include/)
link_directories(libs/ffmpeg/lib/)

set(SOURCE_FILES main.cpp)

add_executable(ffmpeg main.cpp)

target_link_libraries(
        ffmpeg
        avcodec
        avdevice
        avfilter
        avformat
        avresample
        avutil
        postproc
        swresample
        swscale
)

I am not sure if I added the libraries and includes in the right way, beacause in my simple main.cpp it can't resolve avcodec_configuration().
My project layout looks as follows:

  ffmpeg
    -libs
      -include
        -libavcodec
        .
        .
        .
      -lib
        -avcodec.lib
    -main.cpp

EDIT:
Now all includes are found by the compiler. BUt if I compile I get following error:

c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/bin/ld.exe: cannot find -lavresample
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [ffmpeg.exe] Error 1
mingw32-make.exe[1]: *** [CMakeFiles/ffmpeg.dir/all] Error 2
mingw32-make.exe: *** [all] Error 2
CMakeFiles\ffmpeg.dir\build.make:96: recipe for target 'ffmpeg.exe' failed
CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/ffmpeg.dir/all' failed
Makefile:82: recipe for target 'all' failed


问:
Jenkins Multibranch project are not triggered when a SNAPSHOT is built
I have in Jenkins (v2.164.3) different maven projects, which reside in our local gitlab server.

All projects define the following Jenkinsfile:

```<code>node {
    stage('git') {
        checkout scm
    }
    stage('compile') {
        withMaven(mavenSettingsConfig: 'e228f408-7768-4374-b8e1-259321e2fa99') {
            bat "mvn clean compile"
        }
    }
    stage('test') {
        withMaven(mavenSettingsConfig: 'e228f408-7768-4374-b8e1-259321e2fa99') {
            bat "mvn test"
        }
    }
    stage('install') {
        withMaven(mavenSettingsConfig: 'e228f408-7768-4374-b8e1-259321e2fa99') {
            bat "mvn install -DskipTests"
        }
    }
}
</code>```

in the configuration of the multibranch project, the option Build whenever a SNAPSHOT dependency is built is checked. (The same option in the configuration of the several branches is not checked)

Unfortunately this check seems to be ignored in my case, as when a project (projectX) is build (e.g. the develop branch, that creates a SNAPSHOT jar), all downstream projects (withe their develop branch), that define a dependency in their pom to projectX, are not triggered.

What is wrong ? Or do I need to check the option in all branches of the multibranch project ? Or do I need to change something in my Jenkinsfile ?

Thanks

答:
Please see the Pipeline Maven Plugin FAQ > My downstream pipelines don't get triggered even if I use "Build whenever a SNAPSHOT dependency is built"

To configure the Jenkins Pipeline Maven integration to trigger downstream pipelines on "mvn install":

Either change the global configuration:

Navigate to "Manage Jenkins / Global Tools Configuration"

Click on "Add Publisher" and select "Pipeline Graph Publisher"

In the section "Downstream Pipeline Triggers", change the the "Maven lifecycle threshold" from "deploy" to "install"
 Global Configuration > Trigger Downstream Pipelines > Maven lifecycle threshold">

Or in the script of the upstream pipeline, configure withMaven(options: [pipelineGraphPublisher(lifecycleThreshold: 'install')]) {...}

Note: regarding your declaration mavenSettingsConfig: 'e228f408-...', please note that you can declare the Maven settings either globally or at the folder level as documented on Jenkins Pipeline Maven Integration > Features > Maven Settings

Body:
I have in Jenkins (v2.164.3) different maven projects, which reside in our local gitlab server.

All projects define the following Jenkinsfile:

node {
    stage('git') {
        checkout scm
    }
    stage('compile') {
        withMaven(mavenSettingsConfig: 'e228f408-7768-4374-b8e1-259321e2fa99') {
            bat "mvn clean compile"
        }
    }
    stage('test') {
        withMaven(mavenSettingsConfig: 'e228f408-7768-4374-b8e1-259321e2fa99') {
            bat "mvn test"
        }
    }
    stage('install') {
        withMaven(mavenSettingsConfig: 'e228f408-7768-4374-b8e1-259321e2fa99') {
            bat "mvn install -DskipTests"
        }
    }
}

in the configuration of the multibranch project, the option Build whenever a SNAPSHOT dependency is built is checked. (The same option in the configuration of the several branches is not checked)

Unfortunately this check seems to be ignored in my case, as when a project (projectX) is build (e.g. the develop branch, that creates a SNAPSHOT jar), all downstream projects (withe their develop branch), that define a dependency in their pom to projectX, are not triggered.

What is wrong ? Or do I need to check the option in all branches of the multibranch project ? Or do I need to change something in my Jenkinsfile ?

Thanks

Body:
Please see the Pipeline Maven Plugin FAQ > My downstream pipelines don't get triggered even if I use "Build whenever a SNAPSHOT dependency is built"

To configure the Jenkins Pipeline Maven integration to trigger downstream pipelines on "mvn install":

Either change the global configuration:

Navigate to "Manage Jenkins / Global Tools Configuration"

Click on "Add Publisher" and select "Pipeline Graph Publisher"

In the section "Downstream Pipeline Triggers", change the the "Maven lifecycle threshold" from "deploy" to "install"

Or in the script of the upstream pipeline, configure withMaven(options: [pipelineGraphPublisher(lifecycleThreshold: 'install')]) {...}

Note: regarding your declaration mavenSettingsConfig: 'e228f408-...', please note that you can declare the Maven settings either globally or at the folder level as documented on Jenkins Pipeline Maven Integration > Features > Maven Settings


问:
Fibonacci Recursive returns endless number
My code results with endless number "2", I don't understand why.

Also my tutor told me to add validation for negative values - I don't know how to do it.

```<code>    public class FibonacciRecursive {

   public static void main(String[] args) {
        int fibonacciNumberOrder = 10;
        do {
            System.out.print(fibonacci(fibonacciNumberOrder) + " ");

        } while (true);
    }

    public static long fibonacci(int fibonacciNumberInOrder) {
        if (fibonacciNumberInOrder == 0) {
            return 0;
        }
        if (fibonacciNumberInOrder <= 2) {
            return 1;
        }
        long fibonacci = fibonacci(-1) + fibonacci(-2);
        return fibonacci;
    }
}
</code>```

edit:
When I changed that line

```<code>long fibonacci = fibonacci(-1) + fibonacci(-2);
</code>```

to:

```<code>long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);
</code>```

It prints endless "55"

How should I change my code to make it work?

答:
You are recursing with constants! Change this

```<code>long fibonacci = fibonacci(-1) + fibonacci(-2);
</code>```

to

```<code>long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);
</code>```

And, in your while loop in main - you need to modify fibonacciNumberInOrder

```<code>int fibonacciNumberOrder = 1;
do {
    System.out.print(fibonacci(fibonacciNumberOrder) + " ");
    fibonacciNumberOrder++;
} while (true);
</code>```

Body:
My code results with endless number "2", I don't understand why.

Also my tutor told me to add validation for negative values - I don't know how to do it.

    public class FibonacciRecursive {

   public static void main(String[] args) {
        int fibonacciNumberOrder = 10;
        do {
            System.out.print(fibonacci(fibonacciNumberOrder) + " ");

        } while (true);
    }

    public static long fibonacci(int fibonacciNumberInOrder) {
        if (fibonacciNumberInOrder == 0) {
            return 0;
        }
        if (fibonacciNumberInOrder <= 2) {
            return 1;
        }
        long fibonacci = fibonacci(-1) + fibonacci(-2);
        return fibonacci;
    }
}

edit:
When I changed that line

long fibonacci = fibonacci(-1) + fibonacci(-2);

to:

long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);

It prints endless "55"

How should I change my code to make it work?

Body:
You are recursing with constants! Change this

long fibonacci = fibonacci(-1) + fibonacci(-2);

to

long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);

And, in your while loop in main - you need to modify fibonacciNumberInOrder

int fibonacciNumberOrder = 1;
do {
    System.out.print(fibonacci(fibonacciNumberOrder) + " ");
    fibonacciNumberOrder++;
} while (true);


问:
Bot framework - Skype for business
I need to develop bot framework with Skype for business Channel.
Customer has many software custom on sfb and don't want to migrate ti Microsoft Teams.
Can I develop Microsoft Teams bot and use on Skype for business?
Can I plug bot framework in another way on Skype for business?
Thanks a lot.</p>

答:
You can, but I wouldn't.

It's currently possible, but:

Skype for Business channel in Bot Framework is being deprecated on June 30, 2019.

No new bots will be able to add Skype for Business channel after that date. Existing bots will continue to work until October 31, 2019. Microsoft Teams is the preferred communication tool from Microsoft. Learn how to connect your bot to Microsoft Teams.

There is no other way to use Bot Framework with Skype for Business.

Title: Bot framework - Skype for business


答:
It happens because you calculate the Fibonacci number with constants instead of relative numbers to passed ones through, which is the point of recursion.

```<code>public static long fibonacci(int fibonacciNumberInOrder) {
    if (fibonacciNumberInOrder == 0) {
        return 0;
    }
    if (fibonacciNumberInOrder <= 2) {
        return 1;
    }
    long fibonacci = fibonacci(fibonacciNumberInOrder - 1) + fibonacci(fibonacciNumberInOrder - 2);
    return fibonacci;
}
</code>```

The key changed line is:

```<code>long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);
</code>```

Title: Fibonacci Recursive returns endless number

Body:
It happens because you calculate the Fibonacci number with constants instead of relative numbers to passed ones through, which is the point of recursion.

public static long fibonacci(int fibonacciNumberInOrder) {
    if (fibonacciNumberInOrder == 0) {
        return 0;
    }
    if (fibonacciNumberInOrder <= 2) {
        return 1;
    }
    long fibonacci = fibonacci(fibonacciNumberInOrder - 1) + fibonacci(fibonacciNumberInOrder - 2);
    return fibonacci;
}

The key changed line is:

long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);


问:
error_logger "deadlock" problem
I added an event handler to redirect error_logger reports to syslog. The handler looks like this:

```<code>handle_event({info_msg, _Gleader, {_Pid, Format, Data}}, #state{info_logger=Logger}=State) ->
    syslog_write("I", Logger, Format, Data),
    {ok, State};
handle_event({error, _Gleader, {_Pid, Format, Data}}, #state{error_logger=Logger}=State) ->
    syslog_write("E", Logger, Format, Data),
    {ok, State};
handle_event(_Event, State) ->
    {ok, State}.

syslog_write(Prefix, Facility, Format, Data) ->
    Cmd = try
              Message = lists:flatten(io_lib:format(Format, Data)),
              lists:flatten(io_lib:format("logger -t essmsd -p ~s.Debug \'<~s> ~s\'",
                                           [Facility, Prefix, Message]))
          catch
              _:_ ->
                  lists:flatten(io_lib:format("logger -t essmsd -p ~s.Debug \'~p\'",
                                              [Facility, [Prefix, Format, Data]]))
          end,
    os:cmd(Cmd).
</code>```

I used logger command to write to syslog files. It works at first, but after running for one or two days, the error_logger stopped working. It outputs nothing (when I invoke error_logger:info_msg("test") on the console, it only returns an ok) no matter what the input, neither to the log file, nor to the console.

Any suggestions? thx in advance.

update: I put traces in syslog_write and error_logger:info_msg, and I got the following:

```<code>(essmsd@xx.xx.xx.xx)11> dbg:tracer(), dbg:p(all, c), dbg:tpl(error_logger, info_msg, x). {ok,[{matched,'essmsd@xx.xx.xx.xx',2},{saved,x}]}

(essmsd@xx.xx.xx.xx)12> error_logger:info_msg("xx").
ok
(<0.1735.0>) call error_logger:info_msg("xx")

(essmsd@xx.xx.xx.xx)13>
(<0.1735.0>) call error_logger:info_msg("xx",[])
(<0.1735.0>) returned from error_logger:info_msg/2 -> ok
(<0.1735.0>) returned from error_logger:info_msg/1 -> ok
</code>```

Which means the error_logger:info_msg is being called, but it never output anything but returned an ok!

答:
The question is:

Does error_logger stop handling messages or does your syslogd cause problems?

You need to debug it, if you have a system where it already stopped working use:

```<code>dbg:tracer(),dbg:p(all,c),dbg:tpl(Mod,Func,x)
</code>```

For all relevant functions in your module on a shell connected to your node.

For details see How to refine the debugging? and Using trace and dbg in Erlang.

Then you can see what is actually happeing and if your syslog_write function is still called and with what parameters.

BTW what sometimes can be the reason for syslog "problems": when you look at the log file with less or tail and keep it running.  Then once the log files get rotated you still have the old file open and it looks like logging just stopped.  In reality it is going to a different file.

ContentLicense: CC BY-SA 3.0

Title: error_logger "deadlock" problem

Body:
I added an event handler to redirect error_logger reports to syslog. The handler looks like this:

handle_event({info_msg, _Gleader, {_Pid, Format, Data}}, #state{info_logger=Logger}=State) ->
    syslog_write("I", Logger, Format, Data),
    {ok, State};
handle_event({error, _Gleader, {_Pid, Format, Data}}, #state{error_logger=Logger}=State) ->
    syslog_write("E", Logger, Format, Data),
    {ok, State};
handle_event(_Event, State) ->
    {ok, State}.

syslog_write(Prefix, Facility, Format, Data) ->
    Cmd = try
              Message = lists:flatten(io_lib:format(Format, Data)),
              lists:flatten(io_lib:format("logger -t essmsd -p ~s.Debug \'<~s> ~s\'",
                                           [Facility, Prefix, Message]))
          catch
              _:_ ->
                  lists:flatten(io_lib:format("logger -t essmsd -p ~s.Debug \'~p\'",
                                              [Facility, [Prefix, Format, Data]]))
          end,
    os:cmd(Cmd).

I used logger command to write to syslog files. It works at first, but after running for one or two days, the error_logger stopped working. It outputs nothing (when I invoke error_logger:info_msg("test") on the console, it only returns an ok) no matter what the input, neither to the log file, nor to the console.

Any suggestions? thx in advance.

update: I put traces in syslog_write and error_logger:info_msg, and I got the following:

(essmsd@xx.xx.xx.xx)11> dbg:tracer(), dbg:p(all, c), dbg:tpl(error_logger, info_msg, x). {ok,[{matched,'essmsd@xx.xx.xx.xx',2},{saved,x}]}

(essmsd@xx.xx.xx.xx)12> error_logger:info_msg("xx").
ok
(<0.1735.0>) call error_logger:info_msg("xx")

(essmsd@xx.xx.xx.xx)13>
(<0.1735.0>) call error_logger:info_msg("xx",[])
(<0.1735.0>) returned from error_logger:info_msg/2 -> ok
(<0.1735.0>) returned from error_logger:info_msg/1 -> ok

Which means the error_logger:info_msg is being called, but it never output anything but returned an ok!

Body:
The question is:

Does error_logger stop handling messages or does your syslogd cause problems?

You need to debug it, if you have a system where it already stopped working use:

dbg:tracer(),dbg:p(all,c),dbg:tpl(Mod,Func,x)

For all relevant functions in your module on a shell connected to your node.

For details see How to refine the debugging? and Using trace and dbg in Erlang.

Then you can see what is actually happeing and if your syslog_write function is still called and with what parameters.

BTW what sometimes can be the reason for syslog "problems": when you look at the log file with less or tail and keep it running.  Then once the log files get rotated you still have the old file open and it looks like logging just stopped.  In reality it is going to a different file.


问:
WebLogic 12c - Destination unreachable exception
First, I had installed jdk 1.6.0_43 and oracle weblogic 12.1.1, I was successfully able to deploy my application.

I then upgraded both my jdk (1.7.0_60) and weblogic (12.1.2), but was unable to deploy my application.

Now, I downgraded my weblogic (12.1.1) but retained my jdk 1.7.0_60, but i was still not able to deploy my application successfully.

In both the failure cases, I got the same error with the following message. Is there something with respect to java 7 I should be aware of? I tried searching for this a lot, but in vain..

```<code> [exec] javax.naming.CommunicationException [Root exception is java.net.ConnectException: t3://localhost:9991: Destination unreachable; nested exception is:
 [exec] java.net.ConnectException: Connection refused: connect; No available router to destination]
</code>```

答:
I had a similar issue with my Weblogic server while building with maven

If you're using maven, make sure in your maven settings.xml file, the value for: <weblogic.admin.url></weblogic.admin.url> is the same what you have for listen-address></listen-address> your weblogic config.xml

My problem was that my settings.xml had my local IP address where as weblogic config.xml had localhost.

Body:
First, I had installed jdk 1.6.0_43 and oracle weblogic 12.1.1, I was successfully able to deploy my application.

I then upgraded both my jdk (1.7.0_60) and weblogic (12.1.2), but was unable to deploy my application.

Now, I downgraded my weblogic (12.1.1) but retained my jdk 1.7.0_60, but i was still not able to deploy my application successfully.

In both the failure cases, I got the same error with the following message. Is there something with respect to java 7 I should be aware of? I tried searching for this a lot, but in vain..

 [exec] javax.naming.CommunicationException [Root exception is java.net.ConnectException: t3://localhost:9991: Destination unreachable; nested exception is:
 [exec] java.net.ConnectException: Connection refused: connect; No available router to destination]


问:
How to select multiple pattern from dataset in R
I have a dataset (data) with list of email ids:

```<code>email=c("susgho.agency@gmail.com","suagencyter.m@gmail.com",
        "duff.abcnkhgt@gmail.com","ftyhabcdfg@gmail.com",
        "gjhfhg1-ail.com","gjhgkjhgbrt.gh@aol.com")
</code>```

I have another dataset - (disp) with list of pattern:

```<code>pattern=c(".agency",".abc","1-ail.com"))
</code>```

I want to see if the pattern matches with the emails.
the expected output should be as follows:

```<code>email                         pattern
susgho.agency@gmail.com       .agency
suagencyter.m@gmail.com
duff.abcnkhgt@gmail.com       .abc
ftyhabcdfg@gmail.com
gjhfhg1-ail.com               1-ail.com
gjhgkjhgbrt.gh@aol.com
</code>```

I am using for loop but it is taking forever to execute.

```<code>w <- NULL
for(i in 1:nrow(disp))
{
  w1 <- as.character(disp[i,1])
  w2 <- data[grep(w1, data$email),]
  if(nrow(w2) > 0)
  {
    w2$pattern <- w1
    w <- rbind(w, w2)
  }
  else
    w <- rbind(w, w2)
}
</code>```

Any help would e highly appreciated. tia!

答:
You could do:

```<code>df$pattern[max.col(-attr(adist(df2$pattern,df$email,counts = T),'counts')[,,3])] = as.character(df2$pattern)
df
                    email   pattern
1 susgho.agency@gmail.com   .agency
2 suagencyter.m@gmail.com      <NA>
3 duff.abcnkhgt@gmail.com      .abc
4    ftyhabcdfg@gmail.com      <NA>
5         gjhfhg1-ail.com 1-ail.com
</code>```

or you could do

```<code>merge(df,stack(setNames(Vectorize(grep)(df2$pattern,df,value=T,fixed=T),df2$pattern)),by.x="email",by.y = "values",all=T)
                    email       ind
1 duff.abcnkhgt@gmail.com      .abc
2    ftyhabcdfg@gmail.com      <NA>
3         gjhfhg1-ail.com 1-ail.com
4 suagencyter.m@gmail.com      <NA>
5 susgho.agency@gmail.com   .agency
</code>```

Data:

```<code>df=read.table(text="email
           susgho.agency@gmail.com
           suagencyter.m@gmail.com
           duff.abcnkhgt@gmail.com
           ftyhabcdfg@gmail.com
           gjhfhg1-ail.com",h=T)

df2=read.table(text=" pattern
              .agency
              .abc
              1-ail.com",h=T)
</code>```

Body:
I have a dataset (data) with list of email ids:

email=c("susgho.agency@gmail.com","suagencyter.m@gmail.com",
        "duff.abcnkhgt@gmail.com","ftyhabcdfg@gmail.com",
        "gjhfhg1-ail.com","gjhgkjhgbrt.gh@aol.com")

I have another dataset - (disp) with list of pattern:

pattern=c(".agency",".abc","1-ail.com"))

I want to see if the pattern matches with the emails.
the expected output should be as follows:

email                         pattern
susgho.agency@gmail.com       .agency
suagencyter.m@gmail.com
duff.abcnkhgt@gmail.com       .abc
ftyhabcdfg@gmail.com
gjhfhg1-ail.com               1-ail.com
gjhgkjhgbrt.gh@aol.com

I am using for loop but it is taking forever to execute.

w <- NULL
for(i in 1:nrow(disp))
{
  w1 <- as.character(disp[i,1])
  w2 <- data[grep(w1, data$email),]
  if(nrow(w2) > 0)
  {
    w2$pattern <- w1
    w <- rbind(w, w2)
  }
  else
    w <- rbind(w, w2)
}

Any help would e highly appreciated. tia!

Body:
You could do:

df$pattern[max.col(-attr(adist(df2$pattern,df$email,counts = T),'counts')[,,3])] = as.character(df2$pattern)
df
                    email   pattern
1 susgho.agency@gmail.com   .agency
2 suagencyter.m@gmail.com      <NA>
3 duff.abcnkhgt@gmail.com      .abc
4    ftyhabcdfg@gmail.com      <NA>
5         gjhfhg1-ail.com 1-ail.com

or you could do

merge(df,stack(setNames(Vectorize(grep)(df2$pattern,df,value=T,fixed=T),df2$pattern)),by.x="email",by.y = "values",all=T)
                    email       ind
1 duff.abcnkhgt@gmail.com      .abc
2    ftyhabcdfg@gmail.com      <NA>
3         gjhfhg1-ail.com 1-ail.com
4 suagencyter.m@gmail.com      <NA>
5 susgho.agency@gmail.com   .agency

Data:

df=read.table(text="email
           susgho.agency@gmail.com
           suagencyter.m@gmail.com
           duff.abcnkhgt@gmail.com
           ftyhabcdfg@gmail.com
           gjhfhg1-ail.com",h=T)

df2=read.table(text=" pattern
              .agency
              .abc
              1-ail.com",h=T)


问:
How to create a Python subprocess to do latent class analysis in R?
I am trying to do a latent class analysis for survey data from another team. I am primary a Python user but one of the more appropriate tool is poLCA in R. So, I am trying to create a Python subprocess that create the script to run in R, create a result dataframe, and run the rest of the analysis in Python.

The problem I am running into now is that I have trouble creating a formula to be used in poLCA from all the columns in the dataframe, which can be close to a thousands.

In Python, I can do the following:

formula = '+'.join(dataframe.columns.tolist)+'~1'
```

but in the poLCA syntax, I will be doing:
cbind(col1, col2, ..., coln)~1
without the quotation mark, which I am not sure how to creat such a thing in Python.

I think if I can create the formula using Python, then I will be able to complete the whole process in Python as well.
Anyone know of a way as to how to do this? Thanks in advance.

答: create the R syntax as a string in python - and then use as.formula() in R on the string.</p>

Body:
I am trying to do a latent class analysis for survey data from another team. I am primary a Python user but one of the more appropriate tool is poLCA in R. So, I am trying to create a Python subprocess that create the script to run in R, create a result dataframe, and run the rest of the analysis in Python.

The problem I am running into now is that I have trouble creating a formula to be used in poLCA from all the columns in the dataframe, which can be close to a thousands.

In Python, I can do the following:

formula = '+'.join(dataframe.columns.tolist)+'~1'

but in the poLCA syntax, I will be doing:
cbind(col1, col2, ..., coln)~1
without the quotation mark, which I am not sure how to creat such a thing in Python.

I think if I can create the formula using Python, then I will be able to complete the whole process in Python as well.
Anyone know of a way as to how to do this? Thanks in advance.


问:
Playing sound on UIButton pressed with different tags
I am trying to implement a xylophone where I want to play different sounds on tap of different buttons which I merged it to one IBAction function and have differentiated with different tags.

```<code>@IBAction func keysPressed(_ sender: UIButton) {
}
</code>```

I am importing AVFoundation but not getting the exact function to call to play sounds

I need a function which I can call in each If else statement differentiating buttons with tags to play sounds.

答:
Assuming this is a question on how to get different buttons to play different sounds, you could subclass UIButton to include a field for tracking which note it is, and call the correct function based on that.

```<code>class XyloKey: UIButton {
    var note: String
}
</code>```

And then in your view controller:

```<code>let key = XyloKey()
key.note = "C5"
key.addTarget(self, action: #selector(playNote(_:)), for: .touchUpInside)

</code>```

And assuming you name your files by note name (e.g. "note_C5.mp3").

```<code>func playNote(_ sender: XyloKey) {
    let url = NSBundle.mainBundle().URLForResource("note_\(sender.note)", withExtension: "mp3")
    playSound(url)
}
</code>```

Where playSound plays the sound of the passed file. See the link passed in the flag above for details.

Body:
I am trying to implement a xylophone where I want to play different sounds on tap of different buttons which I merged it to one IBAction function and have differentiated with different tags.

@IBAction func keysPressed(_ sender: UIButton) {
}

I am importing AVFoundation but not getting the exact function to call to play sounds

I need a function which I can call in each If else statement differentiating buttons with tags to play sounds.

Body:
Assuming this is a question on how to get different buttons to play different sounds, you could subclass UIButton to include a field for tracking which note it is, and call the correct function based on that.

class XyloKey: UIButton {
    var note: String
}

And then in your view controller:

let key = XyloKey()
key.note = "C5"
key.addTarget(self, action: #selector(playNote(_:)), for: .touchUpInside)

And assuming you name your files by note name (e.g. "note_C5.mp3").

func playNote(_ sender: XyloKey) {
    let url = NSBundle.mainBundle().URLForResource("note_\(sender.note)", withExtension: "mp3")
    playSound(url)
}

Where playSound plays the sound of the passed file. See the link passed in the flag above for details.


问:
How to extract strings before and after whitespace, special characters?
I have a dataframe "trial_df" with below column values as below:

```<code>Names

GHAITHA & AL MOOSA
ASEEL ELECTRONICS T
SUNRISE SUPERMARKET-QU
EMARAT-AL SAFIYAH(6735
LULU CENTRE LLC EFT TE
MAX
THEMAX
THE LULU
GHAITHA 123
SUNRISE %$#
</code>```

Requirement :

1) Extract only strings before and after whitespace, special characters.

For eg: "ASEEL ELECTRONICS T" will become "ASEEL ELECTRONICS

2) But only on below conditions :

a) the second string length should be greater than 2

b) the second string should be alphanumeric

Eg : 'GHAITHA & AL MOOSA' will be just 'GHAITHA' as the second string after white space is '&' ( both conditions fails : Not alphanumeric and length is not greater than 2)

Eg: 'MAX' will be 'MAX' as its only one string. similarly 'THE LULU' will be same as its already just 2 strings.

Final output :

```<code>Names

GHAITHA
ASEEL ELECTRONICS
SUNRISE SUPERMARKET-QU
EMARAT
LULU CENTRE
MAX
THEMAX
THE LULU
GHAITHA
SUNRISE
</code>```

My function to do the requirement :

```<code>def remove_strings(df, col):
    for i in df.index:
        x = df.at[i, col]
        x = x.split(' ')
        if len(x) > 1:
            if len(x[1]) > 2:
                x[1] = ''.join(e for e in x[1] if e.isalnum())
                x = ' '.join(x[0:2])
                df.at[i, col] = x
            else:
                df.at[i, col] = x[0]
        else:
            df.at[i, col] = df.at[i, col]

#calling my function
remove_strings(df=trial_df, col='Names')
</code>```

Issue with my function : Though it solves the requirement, but its not well optimized.
My data is of more than 1 million rows, so its looping that many times which is very time consuming.
Is there a very good optimized way to solve my requirement ?

答:
The expression we might be wishing to design here is quite complicated. Maybe, it would be best to break down the task, then we would design much simpler expressions. For instance, THE LULU case can be simply ruled out before we run it through the regex engine.

My partial try for an expression is:

```<code>^([A-Z\s]{3,}?)(&.+|\s[A-Z]{1}$|-.+|\s[A-Z]{3}\s.+|\s[0-9].+|\s[~!@#$%^&*]+.+)$
</code>```

But, I'm quite sure that it won't work in some other inputs that we may have and not listed here.

DEMO

The idea would have three steps:

We take those which are simple to find/filter out, such as "THE LULU"

We add a capturing group with most amount of boundaries ^([A-Z\s]{3,}?)

We add another group with sub-expressions connected with logical ORs and filter out what we wish to be out at the end of our string.

Body:
I have a dataframe "trial_df" with below column values as below:

Names

GHAITHA & AL MOOSA
ASEEL ELECTRONICS T
SUNRISE SUPERMARKET-QU
EMARAT-AL SAFIYAH(6735
LULU CENTRE LLC EFT TE
MAX
THEMAX
THE LULU
GHAITHA 123
SUNRISE %$#

Requirement :

1) Extract only strings before and after whitespace, special characters.

For eg: "ASEEL ELECTRONICS T" will become "ASEEL ELECTRONICS

2) But only on below conditions :

a) the second string length should be greater than 2

b) the second string should be alphanumeric

Eg : 'GHAITHA & AL MOOSA' will be just 'GHAITHA' as the second string after white space is '&' ( both conditions fails : Not alphanumeric and length is not greater than 2)

Eg: 'MAX' will be 'MAX' as its only one string. similarly 'THE LULU' will be same as its already just 2 strings.

Final output :

Names

GHAITHA
ASEEL ELECTRONICS
SUNRISE SUPERMARKET-QU
EMARAT
LULU CENTRE
MAX
THEMAX
THE LULU
GHAITHA
SUNRISE

My function to do the requirement :

def remove_strings(df, col):
    for i in df.index:
        x = df.at[i, col]
        x = x.split(' ')
        if len(x) > 1:
            if len(x[1]) > 2:
                x[1] = ''.join(e for e in x[1] if e.isalnum())
                x = ' '.join(x[0:2])
                df.at[i, col] = x
            else:
                df.at[i, col] = x[0]
        else:
            df.at[i, col] = df.at[i, col]

#calling my function
remove_strings(df=trial_df, col='Names')

Issue with my function : Though it solves the requirement, but its not well optimized.
My data is of more than 1 million rows, so its looping that many times which is very time consuming.
Is there a very good optimized way to solve my requirement ?

Body:
The expression we might be wishing to design here is quite complicated. Maybe, it would be best to break down the task, then we would design much simpler expressions. For instance, THE LULU case can be simply ruled out before we run it through the regex engine.

My partial try for an expression is:

^([A-Z\s]{3,}?)(&.+|\s[A-Z]{1}$|-.+|\s[A-Z]{3}\s.+|\s[0-9].+|\s[~!@#$%^&*]+.+)$

But, I'm quite sure that it won't work in some other inputs that we may have and not listed here.

DEMO

The idea would have three steps:

We take those which are simple to find/filter out, such as "THE LULU"

We add a capturing group with most amount of boundaries ^([A-Z\s]{3,}?)

We add another group with sub-expressions connected with logical ORs and filter out what we wish to be out at the end of our string.


问:
rewrite module.exports into export default but preserve possibility to import single entity
Is it possible to achieve same functionality as:

```<code>module.exports = {
  a: 1,
  b: 2
}
</code>```

...which later allows:

import { a } from 'path/to/module'

by using ES6 modules like (or export default):

```<code>export const moduleName = {
  a: 1,
  b: 2
}
</code>```

so that later rather than importing whole module into other one, only part of it will be imported

答:
Use named exports instead:

```<code>export const a = 1;
export const b = 2;
</code>```

Note that although this allows the consumer to do something like import { a } from ..., you're now not actually destructuring an object with an a property there, like you were doing originally with the module.exports syntax, you're just extracting the named export.

You can still export a default object in addition to using named exports, if you wanted:

```<code>export default { c: 'c', d: 'd' }
</code>```

and then you can import with

```<code>import obj from '...';
const { c } = obj;
</code>```

Body:
Is it possible to achieve same functionality as:

module.exports = {
  a: 1,
  b: 2
}

...which later allows:

import { a } from 'path/to/module'

by using ES6 modules like (or export default):

export const moduleName = {
  a: 1,
  b: 2
}

so that later rather than importing whole module into other one, only part of it will be imported

Body:
Use named exports instead:

export const a = 1;
export const b = 2;

Note that although this allows the consumer to do something like import { a } from ..., you're now not actually destructuring an object with an a property there, like you were doing originally with the module.exports syntax, you're just extracting the named export.

You can still export a default object in addition to using named exports, if you wanted:

export default { c: 'c', d: 'd' }

and then you can import with

import obj from '...';
const { c } = obj;


问:
How to actually sort a list in junit test in Eclipse?
How would I go about setting this JUnit test to actually sort correctly?

I tried a bunch of different ways of setting up the test but it still isn't working. For example, trying to remove the main parameters to add later doesn't work. I've tried tweaking parts to make it work but it just fails.

```<code>       void test() {
        int [] input = new int[]{6,1,7,3,8,2,5,4};
        input.sort(input);
        assertEquals("1:2:3:4:5:6:7:8:",(input));
    }
         // Things I have tried
        //int[] result = new Computers().printArray(input);
        //input.sort(input);
        //assertEquals("1:2:3:4:5:6:7:8:",(input));
        //input.sort(input);
        //assertEquals(expected,numbers);
        //int [] input = new int[]{6,1,7,3,8,2,5,4};
        //Computers sort = new Computers();
        //assertEquals("1:2:3:4:5:6:7:8:",(input));
        //int[] numbers = {6,1,7,3,8,2,5,4};
        //int[] expected = {1,2,3,4,5,6,7,8};
</code>```

}

```<code>        Here is my sort in Computers class

          public void sort(int arr[])
        {
            int n = arr.length;
            for (int i = 0; i < n-1; i++)
                for (int j = 0; j < n-i-1; j++)
                    if (arr[j] > arr[j+1])
                    {
                        int temp = arr[j];
                        arr[j] = arr[j+1];
                        arr[j+1] = temp;
                    }
        }
    static void printArray(int arr[]) {
            int n = arr.length;
            for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
            System.out.println();
        }
</code>```

Cannot invoke sort(int[]) on the array type int[]
Cannot make a static reference to the non-static method sort(int[]) from the type Computers

So I don't know how exactly I should set up this sort to work properly.

答:
I suggest using Hamcrest:</p>

```<code>import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.Assert.assertThat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.hamcrest.collection.IsEmptyCollection;
import org.junit.Test;

public class AssertLists {

     @Test
        public void testAssertList() {

            List<Integer> actual = Arrays.asList(1,2,3,4,5,6);
            List<Integer> expected = Arrays.asList(1,2,3,4,5,6);

            //1. Test equal.
            assertThat(actual, is(expected));

            //2. Check List Size
            assertThat(actual, hasSize(6));

            assertThat(actual.size(), is(6));

            //3.  List order

            // Ensure Correct order
            assertThat(expected, contains(1,2,3,4,5,6));

            // Can be any order
            assertThat(expected, hasItems(3,2,6));

            //4. check empty list
            assertThat(actual, not(IsEmptyCollection.empty()));

            assertThat(new ArrayList<>(), IsEmptyCollection.empty());

        }

}
</code>```

Body:
How would I go about setting this JUnit test to actually sort correctly?

I tried a bunch of different ways of setting up the test but it still isn't working. For example, trying to remove the main parameters to add later doesn't work. I've tried tweaking parts to make it work but it just fails.

       void test() {
        int [] input = new int[]{6,1,7,3,8,2,5,4};
        input.sort(input);
        assertEquals("1:2:3:4:5:6:7:8:",(input));
    }
         // Things I have tried
        //int[] result = new Computers().printArray(input);
        //input.sort(input);
        //assertEquals("1:2:3:4:5:6:7:8:",(input));
        //input.sort(input);
        //assertEquals(expected,numbers);
        //int [] input = new int[]{6,1,7,3,8,2,5,4};
        //Computers sort = new Computers();
        //assertEquals("1:2:3:4:5:6:7:8:",(input));
        //int[] numbers = {6,1,7,3,8,2,5,4};
        //int[] expected = {1,2,3,4,5,6,7,8};

}

        Here is my sort in Computers class

          public void sort(int arr[])
        {
            int n = arr.length;
            for (int i = 0; i < n-1; i++)
                for (int j = 0; j < n-i-1; j++)
                    if (arr[j] > arr[j+1])
                    {
                        int temp = arr[j];
                        arr[j] = arr[j+1];
                        arr[j+1] = temp;
                    }
        }
    static void printArray(int arr[]) {
            int n = arr.length;
            for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
            System.out.println();
        }

Cannot invoke sort(int[]) on the array type int[]
Cannot make a static reference to the non-static method sort(int[]) from the type Computers

So I don't know how exactly I should set up this sort to work properly.

Body:
I suggest using Hamcrest:

import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.Assert.assertThat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.hamcrest.collection.IsEmptyCollection;
import org.junit.Test;

public class AssertLists {

     @Test
        public void testAssertList() {

            List<Integer> actual = Arrays.asList(1,2,3,4,5,6);
            List<Integer> expected = Arrays.asList(1,2,3,4,5,6);

            //1. Test equal.
            assertThat(actual, is(expected));

            //2. Check List Size
            assertThat(actual, hasSize(6));

            assertThat(actual.size(), is(6));

            //3.  List order

            // Ensure Correct order
            assertThat(expected, contains(1,2,3,4,5,6));

            // Can be any order
            assertThat(expected, hasItems(3,2,6));

            //4. check empty list
            assertThat(actual, not(IsEmptyCollection.empty()));

            assertThat(new ArrayList<>(), IsEmptyCollection.empty());

        }

}


问:
Missing semicolon error when running SWIG on c++ header file that uses namespace std
I want to generate a wrapper file for Java from a c++ header file that uses namespace std and also includes some libraries. When I tried running swig it gives me a syntax error saying a semicolon is missing, even when my header file is from a large code base and it compiles and runs perfectly fine.

I tried including the line "using namespace std" in the .i file required by swig, and also including the libraries like    that were included in the .h file, but the same error still exists.

This is my AdaptationPlanner.h file

// some code ...
#include <string>
#include <vector>
#include <set>
using namespace std; //line 68
// more code ...
```

<p>And here is my AdaptationPlanner.i file</p>

```/* AdaptationPlanner.i */
%module AdaptationPlanner
%{
/* Includes the header in the wrapper code */
#include "AdaptationPlanner.h"
%}

/* Parse the header file to generate wrappers */
%include "AdaptationPlanner.h"

```

<p>And here is the error message swig gives:</p>

```AdaptationPlanner.h:68: Error: Syntax error - possibly a missing semicolon.
```

答:
```<code>/* AdaptationPlanner.i */
%module AdaptationPlanner
%{
/* Includes the header in the wrapper code */
#include "AdaptationPlanner.h"
using namespace std; /* <--- */
%}

/* Parse the header file to generate wrappers */
%include "AdaptationPlanner.h"
</code>```

<p>I can't really tell why you are having an issue like that. However, care to try the above solution? Just explicitly mention the namespace in the interface file as well. </p>

Body:
I want to generate a wrapper file for Java from a c++ header file that uses namespace std and also includes some libraries. When I tried running swig it gives me a syntax error saying a semicolon is missing, even when my header file is from a large code base and it compiles and runs perfectly fine.

I tried including the line "using namespace std" in the .i file required by swig, and also including the libraries like    that were included in the .h file, but the same error still exists.

This is my AdaptationPlanner.h file

// some code ...
#include <string>
#include <vector>
#include <set>
using namespace std; //line 68
// more code ...

And here is my AdaptationPlanner.i file

/* AdaptationPlanner.i */
%module AdaptationPlanner
%{
/* Includes the header in the wrapper code */
#include "AdaptationPlanner.h"
%}

/* Parse the header file to generate wrappers */
%include "AdaptationPlanner.h"

And here is the error message swig gives:

AdaptationPlanner.h:68: Error: Syntax error - possibly a missing semicolon.

Body:
/* AdaptationPlanner.i */
%module AdaptationPlanner
%{
/* Includes the header in the wrapper code */
#include "AdaptationPlanner.h"
using namespace std; /* <--- */
%}

/* Parse the header file to generate wrappers */
%include "AdaptationPlanner.h"

I can't really tell why you are having an issue like that. However, care to try the above solution? Just explicitly mention the namespace in the interface file as well.


问:
required country combobox
In my project I hava one field that is country name.Till now I am inserting the country name on textfield. I want the combobox which already contain all the country name. Is there any combobox like that in java? </p>

答:
There isn't a pre-populated JComboBox with all the countries, but you can easily find a list of countries on the web, declare them as a constant array, and use that array to populate a JComboBox or whatever you choose to use. Although a constant array is probably bad practice, because the list will probably change slowly over time.

A better approach would be to get them from Java using code like this: http://www.java2s.com/Code/Java/I18N/Getalistofcountrynames.htm

However that does rely on the JDK you are using in production being up-to-date with the current list of countries. And while you are waiting for a JDK to be released with a new country list when it changes, your app will use the incorrect old list (for a few days at least). So you might want to read them from a file or database instead.

Title: required country combobox


问:
How can I read and write from/to a JSON file in a github pages repo?
Preface: I'm a novice programmer at best.
I'm trying to make a github pages page and I'd like it to store some data on a JSON within the same repo. All it needs to do is wait for a button press on the webpage and then increment a value in the JSON file, then write the new value to the JSON in the repo.

testCounter.html which contains the script

<!DOCTYPE html>

<button>Increment</button>

...

```

<p>testJSON.json which contains the data for the counter</p>

```{"counter": 0}
```

I'd like any user with the page open to see it continuously update even if they didn't click the button, thus the infinite loop. Any time the button is clicked, the number should be increased by 1 and written to the JSON file.

答:
Github Pages is designed for hosting simple static websites and supports no form of server-side code, so there is no means to do this which is either trivial or doesn't have other issues.

Github does have an API so you could possibly build a single page application which allows someone to OAuth against Github and then issue a pull request which updates the counter when you approve it. This is unlikely to be practical for your needs.

You should find a hosting service more suitable to your needs.

Body:
Preface: I'm a novice programmer at best.
I'm trying to make a github pages page and I'd like it to store some data on a JSON within the same repo. All it needs to do is wait for a button press on the webpage and then increment a value in the JSON file, then write the new value to the JSON in the repo.

testCounter.html which contains the script

<!DOCTYPE html>

<button>Increment</button>

...

testJSON.json which contains the data for the counter

{"counter": 0}

I'd like any user with the page open to see it continuously update even if they didn't click the button, thus the infinite loop. Any time the button is clicked, the number should be increased by 1 and written to the JSON file.


问:
How to show category subcategory based on array
I have an array that consists of some data to show the category and subcategories.

```<code>{id: "5", parent_id: "0", lable: "Movie"}
{id: "20", parent_id: "5", lable: "Action"}
{id: "15", parent_id: "43", lable: "J.K Rowling"}
{id: "43", parent_id: "0", lable: "Book"}
{id: "20", parent_id: "2", lable: "James Bond Series"}
{id: "3", parent_id: "0", lable: "Music"}
{id: "39", parent_id: "15", lable: "Harry Potter Series"}
</code>```

I want to sort and show this data something like this :

```<code>> Movie
>> Action
>>>James Bond Series

>Book
>>J.K Rowling
>>>Harry Potter Series
</code>```

答:
Just use filter function like below for every category and subcategory:

var arr = [{id: "5", parent_id: "0", lable: "Movie"},
{id: "20", parent_id: "5", lable: "Action"},
{id: "15", parent_id: "43", lable: "J.K Rowling"},
{id: "43", parent_id: "0", lable: "Book"},
{id: "20", parent_id: "2", lable: "James Bond Series"},
{id: "3", parent_id: "0", lable: "Music"},
{id: "39", parent_id: "15", lable: "Harry Potter Series"}];

function isParent(element, index, array) {
  return (element.parent_id == "0");
}

let filtered = arr.filter(isParent);

console.log(filtered);```

Body:
I have an array that consists of some data to show the category and subcategories.

{id: "5", parent_id: "0", lable: "Movie"}
{id: "20", parent_id: "5", lable: "Action"}
{id: "15", parent_id: "43", lable: "J.K Rowling"}
{id: "43", parent_id: "0", lable: "Book"}
{id: "20", parent_id: "2", lable: "James Bond Series"}
{id: "3", parent_id: "0", lable: "Music"}
{id: "39", parent_id: "15", lable: "Harry Potter Series"}

I want to sort and show this data something like this :

> Movie
>> Action
>>>James Bond Series

>Book
>>J.K Rowling
>>>Harry Potter Series


问:
How to send a mail using Outlook template using Python?
I had created an Outlook template. Now I have to send that mail to many users. want to prepare a script that will fetch the CSV file which includes emails list and send it to them.

Outlook Template contains Coloured fonts and underlined text with multiple font sizes.

答:
Use the smtplib that comes with python. Note that this will require your email account allows smtp, which is not necessarily enabled by default.

```<code>SERVER = "smtp.example.com"
FROM = "yourEmail@example.com"
TO = ["listOfEmails"] # must be a list

SUBJECT = "Subject"
TEXT = "Your Text"

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
</code>```

EDIT: this example uses reserved domains like described in RFC2606

```<code>SERVER = "smtp.example.com"
FROM = "johnDoe@example.com"
TO = ["JaneDoe@example.com"] # must be a list

SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp of example.com."

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()
</code>```

Body:
Use the smtplib that comes with python. Note that this will require your email account allows smtp, which is not necessarily enabled by default.

SERVER = "smtp.example.com"
FROM = "yourEmail@example.com"
TO = ["listOfEmails"] # must be a list

SUBJECT = "Subject"
TEXT = "Your Text"

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

EDIT: this example uses reserved domains like described in RFC2606

SERVER = "smtp.example.com"
FROM = "johnDoe@example.com"
TO = ["JaneDoe@example.com"] # must be a list

SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp of example.com."

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()


问:
Union Find to See if Shape Goes on One Side or the Other
I'm quite new to graphs and want to figure out my segmentation fault problem. My output is already correct but for some reason, as numShapes approach a higher number ~40, a segmentation fault error occurs.

Program Details:
The circuit has two sides and you must determine if each shape can fit into side one, if it can't, determine if it can fit into side two, if it can't again, output none. No shape (with their specific X & Y Spacings) must be overlapping.

Thank you.

Code

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;

int numShapes, XSpacing,YSpacing;
vector<int> Dimension(2,0);

string delimiter(string temp);
void main_pr();
bool bounded(struct Graph* graph,vector<int> coordinates, int N);

struct Edge{
    int src, dest, part;
    int Xll, Yll;
    int Xur, Yur;
};

struct Graph{
    int V, E;
    struct Edge* edge;
};

struct Graph* createGraph(int V, int E){
    struct Graph* graph =
           (struct Graph*) malloc( sizeof(struct Graph) );
    graph->V = V;
    graph->E = E;
    graph->edge =
        (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );

    return graph;
}

int find(int parent[], int i){
    if (parent[i] == -1)
        return i;
    return find(parent, parent[i]);
}

// A utility function to do union of two subsets
void Union(int parent[], int x, int y){
    int xset = find(parent, x);
    int yset = find(parent, y);
    if(xset!=yset){
       parent[xset] = yset;
    }
}

struct Graph* graph;
struct Graph* graph2;

int main(){
int check = 0;
char _temp;
string temp;
string temp1,temp2;

for(int j=0;j<4;j++){
    while(_temp != '='){
        cin>>_temp;
    }
    _temp=0;
    cin>>temp;
    switch(j){
        case 0:
             numShapes = stoi(temp);
             if(numShapes == 0){
                 cout<<"Program terminating...\n";
                 return 0;
             }
        case 1:
             XSpacing = stoi(temp);
        case 2:
             YSpacing = stoi(temp);
        case 3:
            if(j==3)
            for(int i=0;i<temp.size();i++){
                if(temp[i] == 'x')
                    check = 1;
                if(check == 0)
                    temp1.push_back(temp[i]);
                else{
                    if(temp[i] != 'x')
                    temp2.push_back(temp[i]);
                }
        }
    }
}

 Dimension[0]=stoi(temp1);
 Dimension[1]=stoi(temp2);

   main_pr();

return 0;
}

void main_pr(){
string temp;
vector<int> coordinates(4,0);
graph = createGraph(numShapes, numShapes);
graph2 = createGraph(numShapes, numShapes);
int a = 1;
int b = 1;
int check = 0;

for(int i=0; i<numShapes; i++){
        for(int j=0; j<4; j++){
            cin>>temp;
            switch(j){
                case 0:
                    coordinates[0] = stoi(delimiter(temp));
                    break;
                case 1:
                    coordinates[1] = stoi(delimiter(temp));
                    break;
                case 2:
                    coordinates[2] = stoi(delimiter(temp));
                    break;
                case 3:
                    coordinates[3] = stoi(temp);
                    break;
            }
        }
    if(i == 0){
    graph->V = 2;
    graph->E = 2;
    graph->edge[0].src = 0;
    graph->edge[0].dest = 1;
    graph->edge[0].Xll = coordinates[0];
    graph->edge[0].Yll = coordinates[1];
    graph->edge[0].Xur = coordinates[2];
    graph->edge[0].Yur = coordinates[3];
    cout<<"Side 1\n";
    }
    else if(bounded(graph,coordinates,a) == true){
        graph->V = a+2;
        graph->E = a+2;
        graph->edge[a].src = a;
        graph->edge[a].dest = a+1;
        graph->edge[a].Xll = coordinates[0];
        graph->edge[a].Yll = coordinates[1];
        graph->edge[a].Xur = coordinates[2];
        graph->edge[a].Yur = coordinates[3];
        a++;
        cout<<"Side 1\n";
    }
    else if(check == 0){
        graph2->V = 2;
        graph2->E = 2;
        graph2->edge[0].src = 0;
        graph2->edge[0].dest = 1;
        graph2->edge[0].Xll = coordinates[0];
        graph2->edge[0].Yll = coordinates[1];
        graph2->edge[0].Xur = coordinates[2];
        graph2->edge[0].Yur = coordinates[3];
        cout<<"Side 2\n";
        check = 1;
    }
    else if(bounded(graph2,coordinates,b) == true){
        graph->V = b+2;
        graph->E = b+2;
        graph2->edge[b].src = b;
        graph2->edge[b].dest = b+1;
        graph2->edge[b].Xll = coordinates[0];
        graph2->edge[b].Yll = coordinates[1];
        graph2->edge[b].Xur = coordinates[2];
        graph2->edge[b].Yur = coordinates[3];
        b++;
        cout<<"Side 2\n";
    }
    else{
        cout<<"None\n";
    }
}

}

bool bounded(struct Graph* graph,vector<int> coordinates, int N){
int *parent = (int*) malloc( graph->V * sizeof(int) );
int x = XSpacing - 1;
int y = YSpacing - 1;
int const Length = Dimension[0];
int const Height = Dimension[1];
int Xll = coordinates[0];
int Yll = coordinates[1];
int Xur = coordinates[2];
int Yur = coordinates[3];

memset(parent, -1, sizeof(int) * graph->V);

    for(int i = 0; i < graph->E; ++i)
    {
        int A = find(parent, graph->edge[i].src);
        int B = find(parent, graph->edge[i].dest);

                if(Xll >= graph->edge[i].Xll-x && Xur <= graph->edge[i].Xur+x)
                    if(Yll >= graph->edge[i].Yll-y && Yur <= graph->edge[i].Yur+y)
                        return false;

                if((Yll >= graph->edge[i].Yll-y && Yll <= graph->edge[i].Yur+y) || (Yur >= graph->edge[i].Yll-y && Yur <= graph->edge[i].Yur+y)){             //if on the right
                    if(Xll >= graph->edge[i].Xll-x && Xll <= graph->edge[i].Xur+x)
                        return false;
                    if(Xur <= graph->edge[i].Xur+x && Xur >= graph->edge[i].Xll-x)
                        return false;
                }

                if((Xll >= graph->edge[i].Xll-x && Xll <= graph->edge[i].Xur+x) || (Xur >= graph->edge[i].Xll-x && Xur <= graph->edge[i].Xur+x)){             //if on the right
                    if(Yll >= graph->edge[i].Yll-y && Yll <= graph->edge[i].Yur+y)
                        return false;
                    if(Yur <= graph->edge[i].Yur+y && Yur >= graph->edge[i].Yll-y)
                        return false;
                }

        if(A == B)
            return true;

        Union(parent, A, B);
    }
    cout<<endl;

return 0;
}

string delimiter(string temp){

    if(temp.back() == ',')
        temp.pop_back();

return temp;
}
</code>```

Input

```<code>NumShapes=8
XSpacing=10
YSpacing=2
Dimension=100x30
10, 4, 20, 6
25, 5, 55, 8
10, 8, 15, 12
0, 20, 20, 22
0, 20, 10, 22
0, 10, 5, 15
25, 27, 75, 28
25, 10, 55, 13
</code>```

Output

```<code>SIDE1
SIDE2
SIDE1
SIDE1
SIDE2
SIDE2
SIDE1
SIDE1
</code>```

答: Replaced all malloc bits of codes to new. Segmentation Fault problem is now gone.</p>

Body:
I'm quite new to graphs and want to figure out my segmentation fault problem. My output is already correct but for some reason, as numShapes approach a higher number ~40, a segmentation fault error occurs.

Program Details:
The circuit has two sides and you must determine if each shape can fit into side one, if it can't, determine if it can fit into side two, if it can't again, output none. No shape (with their specific X & Y Spacings) must be overlapping.

Thank you.

Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;

int numShapes, XSpacing,YSpacing;
vector<int> Dimension(2,0);

string delimiter(string temp);
void main_pr();
bool bounded(struct Graph* graph,vector<int> coordinates, int N);

struct Edge{
    int src, dest, part;
    int Xll, Yll;
    int Xur, Yur;
};

struct Graph{
    int V, E;
    struct Edge* edge;
};

struct Graph* createGraph(int V, int E){
    struct Graph* graph =
           (struct Graph*) malloc( sizeof(struct Graph) );
    graph->V = V;
    graph->E = E;
    graph->edge =
        (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );

    return graph;
}

int find(int parent[], int i){
    if (parent[i] == -1)
        return i;
    return find(parent, parent[i]);
}

// A utility function to do union of two subsets
void Union(int parent[], int x, int y){
    int xset = find(parent, x);
    int yset = find(parent, y);
    if(xset!=yset){
       parent[xset] = yset;
    }
}

struct Graph* graph;
struct Graph* graph2;

int main(){
int check = 0;
char _temp;
string temp;
string temp1,temp2;

for(int j=0;j<4;j++){
    while(_temp != '='){
        cin>>_temp;
    }
    _temp=0;
    cin>>temp;
    switch(j){
        case 0:
             numShapes = stoi(temp);
             if(numShapes == 0){
                 cout<<"Program terminating...\n";
                 return 0;
             }
        case 1:
             XSpacing = stoi(temp);
        case 2:
             YSpacing = stoi(temp);
        case 3:
            if(j==3)
            for(int i=0;i<temp.size();i++){
                if(temp[i] == 'x')
                    check = 1;
                if(check == 0)
                    temp1.push_back(temp[i]);
                else{
                    if(temp[i] != 'x')
                    temp2.push_back(temp[i]);
                }
        }
    }
}

 Dimension[0]=stoi(temp1);
 Dimension[1]=stoi(temp2);

   main_pr();

return 0;
}

void main_pr(){
string temp;
vector<int> coordinates(4,0);
graph = createGraph(numShapes, numShapes);
graph2 = createGraph(numShapes, numShapes);
int a = 1;
int b = 1;
int check = 0;

for(int i=0; i<numShapes; i++){
        for(int j=0; j<4; j++){
            cin>>temp;
            switch(j){
                case 0:
                    coordinates[0] = stoi(delimiter(temp));
                    break;
                case 1:
                    coordinates[1] = stoi(delimiter(temp));
                    break;
                case 2:
                    coordinates[2] = stoi(delimiter(temp));
                    break;
                case 3:
                    coordinates[3] = stoi(temp);
                    break;
            }
        }
    if(i == 0){
    graph->V = 2;
    graph->E = 2;
    graph->edge[0].src = 0;
    graph->edge[0].dest = 1;
    graph->edge[0].Xll = coordinates[0];
    graph->edge[0].Yll = coordinates[1];
    graph->edge[0].Xur = coordinates[2];
    graph->edge[0].Yur = coordinates[3];
    cout<<"Side 1\n";
    }
    else if(bounded(graph,coordinates,a) == true){
        graph->V = a+2;
        graph->E = a+2;
        graph->edge[a].src = a;
        graph->edge[a].dest = a+1;
        graph->edge[a].Xll = coordinates[0];
        graph->edge[a].Yll = coordinates[1];
        graph->edge[a].Xur = coordinates[2];
        graph->edge[a].Yur = coordinates[3];
        a++;
        cout<<"Side 1\n";
    }
    else if(check == 0){
        graph2->V = 2;
        graph2->E = 2;
        graph2->edge[0].src = 0;
        graph2->edge[0].dest = 1;
        graph2->edge[0].Xll = coordinates[0];
        graph2->edge[0].Yll = coordinates[1];
        graph2->edge[0].Xur = coordinates[2];
        graph2->edge[0].Yur = coordinates[3];
        cout<<"Side 2\n";
        check = 1;
    }
    else if(bounded(graph2,coordinates,b) == true){
        graph->V = b+2;
        graph->E = b+2;
        graph2->edge[b].src = b;
        graph2->edge[b].dest = b+1;
        graph2->edge[b].Xll = coordinates[0];
        graph2->edge[b].Yll = coordinates[1];
        graph2->edge[b].Xur = coordinates[2];
        graph2->edge[b].Yur = coordinates[3];
        b++;
        cout<<"Side 2\n";
    }
    else{
        cout<<"None\n";
    }
}

}

bool bounded(struct Graph* graph,vector<int> coordinates, int N){
int *parent = (int*) malloc( graph->V * sizeof(int) );
int x = XSpacing - 1;
int y = YSpacing - 1;
int const Length = Dimension[0];
int const Height = Dimension[1];
int Xll = coordinates[0];
int Yll = coordinates[1];
int Xur = coordinates[2];
int Yur = coordinates[3];

memset(parent, -1, sizeof(int) * graph->V);

    for(int i = 0; i < graph->E; ++i)
    {
        int A = find(parent, graph->edge[i].src);
        int B = find(parent, graph->edge[i].dest);

                if(Xll >= graph->edge[i].Xll-x && Xur <= graph->edge[i].Xur+x)
                    if(Yll >= graph->edge[i].Yll-y && Yur <= graph->edge[i].Yur+y)
                        return false;

                if((Yll >= graph->edge[i].Yll-y && Yll <= graph->edge[i].Yur+y) || (Yur >= graph->edge[i].Yll-y && Yur <= graph->edge[i].Yur+y)){             //if on the right
                    if(Xll >= graph->edge[i].Xll-x && Xll <= graph->edge[i].Xur+x)
                        return false;
                    if(Xur <= graph->edge[i].Xur+x && Xur >= graph->edge[i].Xll-x)
                        return false;
                }

                if((Xll >= graph->edge[i].Xll-x && Xll <= graph->edge[i].Xur+x) || (Xur >= graph->edge[i].Xll-x && Xur <= graph->edge[i].Xur+x)){             //if on the right
                    if(Yll >= graph->edge[i].Yll-y && Yll <= graph->edge[i].Yur+y)
                        return false;
                    if(Yur <= graph->edge[i].Yur+y && Yur >= graph->edge[i].Yll-y)
                        return false;
                }

        if(A == B)
            return true;

        Union(parent, A, B);
    }
    cout<<endl;

return 0;
}

string delimiter(string temp){

    if(temp.back() == ',')
        temp.pop_back();

return temp;
}

Input

NumShapes=8
XSpacing=10
YSpacing=2
Dimension=100x30
10, 4, 20, 6
25, 5, 55, 8
10, 8, 15, 12
0, 20, 20, 22
0, 20, 10, 22
0, 10, 5, 15
25, 27, 75, 28
25, 10, 55, 13

Output

SIDE1
SIDE2
SIDE1
SIDE1
SIDE2
SIDE2
SIDE1
SIDE1


问:
jQuery, get ID of a textarea
I've got a form with a text field defined as follow:

```<code><textarea style="height: 60px; width: 100%;" name="F3414" id="F3414" rows="6" cols="80" wrap="virtual" class="frmTxa fckEditor"></textarea>
</code>```

I need, using jQuery, to get the textarea id (in that case, F3414).

I've tried:

```<code>$('textarea .fckEditor').attr('id');
$('.fckEditor').attr('id'); / ... with no luck.
</code>```

Any idea?

Thanks a lot

答:
```<code>alert($('textarea.fckEditor').attr('id'));
</code>```

you have a space between textarea .fckEditor in your original question, does removing it make a difference

Working Example : here

Title: jQuery, get ID of a textarea

Body:
I've got a form with a text field defined as follow:

<textarea style="height: 60px; width: 100%;" name="F3414" id="F3414" rows="6" cols="80" wrap="virtual" class="frmTxa fckEditor"></textarea>

I need, using jQuery, to get the textarea id (in that case, F3414).

I've tried:

$('textarea .fckEditor').attr('id');
$('.fckEditor').attr('id'); / ... with no luck.

Any idea?

Thanks a lot

Body:
alert($('textarea.fckEditor').attr('id'));

you have a space between textarea .fckEditor in your original question, does removing it make a difference

Working Example : here


问:
How to remove several elements of a list by the index which can be changed each time?
I have a list like below:

```<code>A =  [1, 2, 3, 4]
</code>```

After using enumerate I have the following list:

```<code>A = [(0, 1), (1, 2), (2, 3), (3, 4)]
</code>```

After checking a condition, I realized that I don't need the elements with index 0 and 2.
It means that my condition returns a list like below which can be different each time:

```<code>condA = [(0, 1), (2, 3)]
</code>```

I know that I can use del or .pop() to remove an element from a list.
However, I was wondering how can I read the numbers like (0) and (2) in my condA list and remove those elements from my original list.
I don't want to enter the 0 and 2 in my code because each time they would be different.

The result would be like this:

```<code>A_reduced = [2, 4]

</code>```

答:
If you want to delete elements from list inside loop, you should iterate from last to first:

```<code>for i in range(len(A) - 1, -1, -1):
    if true:  # replace with condition
        del A[i]
</code>```

Upd.

You can also use list comprehension for this, but you should invert you condition (A[i][0] != 11 => A[i][0] == 11):

```<code>A = [A[i] for i in range(len(A)) if inverted_condition]
</code>```

Body:
I have a list like below:

A =  [1, 2, 3, 4]

After using enumerate I have the following list:

A = [(0, 1), (1, 2), (2, 3), (3, 4)]

After checking a condition, I realized that I don't need the elements with index 0 and 2.
It means that my condition returns a list like below which can be different each time:

condA = [(0, 1), (2, 3)]

I know that I can use del or .pop() to remove an element from a list.
However, I was wondering how can I read the numbers like (0) and (2) in my condA list and remove those elements from my original list.
I don't want to enter the 0 and 2 in my code because each time they would be different.

The result would be like this:

A_reduced = [2, 4]

Body:
If you want to delete elements from list inside loop, you should iterate from last to first:

for i in range(len(A) - 1, -1, -1):
    if true:  # replace with condition
        del A[i]

Upd.

You can also use list comprehension for this, but you should invert you condition (A[i][0] != 11 => A[i][0] == 11):

A = [A[i] for i in range(len(A)) if inverted_condition]


答:
IIUC maybe a function is the correct way:

```<code>A =  [1, 2, 3, 4]

def remove_items(lis, idx):
    lis2=lis.copy()
    [lis2.pop(i) for i in idx]
    return lis2

A_reduced=remove_items(A,[0,2])
</code>```

Output:

```<code>Out[32]: [2, 3]
</code>```

You can add any list of indexes you want, and it'll drop them from the list. (If they exist)

Edit: Adjusted to your new values, and modified the function so you also keep your original list (if that's needed)

Title: How to remove several elements of a list by the index which can be changed each time?

Body:
IIUC maybe a function is the correct way:

A =  [1, 2, 3, 4]

def remove_items(lis, idx):
    lis2=lis.copy()
    [lis2.pop(i) for i in idx]
    return lis2

A_reduced=remove_items(A,[0,2])

Output:

Out[32]: [2, 3]

You can add any list of indexes you want, and it'll drop them from the list. (If they exist)

Edit: Adjusted to your new values, and modified the function so you also keep your original list (if that's needed)