问:
Can I use functions in Coq as constructors?
I am trying to write a function to determine whether a number is odd and return it if it is, and not if it is not. In order to do this, I have matched the number with an odd function that returns true if it is odd. How can I use this as a constructor?
enter image description here</p>

答:
You cannot use any function as if it were a constructor in a match clause.  Only the constructors that appear in the declaration of a data type can be used in this fashion.  However, the oddb function returns a boolean, which is a data type defined by constructors, and thus you are allowed to match on its result:

```<code>match oddb n with
| true  => (* return something *)
| false => (* return something else *)
end
</code>```

You can actually write this more verbose form as a regular if-then-else expression as found in other functional programming languages. When you write

```<code>if oddb n then
  (* return something *)
else
  (* return something else *)
</code>```

Coq automatically translates your input into the form above.

Body:
You cannot use any function as if it were a constructor in a match clause.  Only the constructors that appear in the declaration of a data type can be used in this fashion.  However, the oddb function returns a boolean, which is a data type defined by constructors, and thus you are allowed to match on its result:

match oddb n with
| true  => (* return something *)
| false => (* return something else *)
end

You can actually write this more verbose form as a regular if-then-else expression as found in other functional programming languages. When you write

if oddb n then
  (* return something *)
else
  (* return something else *)

Coq automatically translates your input into the form above.


来源: stackexchange

问:
Apple Music API - How to get user identifier?
I am trying to retrieve the user's information after getting the Music Token from the Apple Music API. It seems that the /me endpoint is not available for queries other than the storefront (https://api.music.apple.com/v1/me/storefront).

Problem is, I need to identify each user with a unique ID, so I need to retrieve any good information to do that (for example, the email address could be a good starting point).

From the Apple Music API developer page, I can't find any endpoint to do so. Is there something I am missing?

Thank you :)

答: No, you're not missing anything. It's really frustrating that you can't get any user data from the api, because it probably means you'll have to also provide another sign-on method like Google or email/password to get information. Apple has just released its own SSO here, but I think the user would still have to authenticate that and MusicKit.</p>

ContentLicense: CC BY-SA 4.0


问:
spring boot execution of two dependent methods
I am developping an application using spring boot as framework. I have 2 methods the first one is deleting data from the database and the other one is deleting folder from the disk, so if i delete from the database and i can't delete from the disc all the operation will fail. So how can i do that with springboot ? </p>

```<code>@Override
public ResponseEntity<?> delete(Long id) {
    return libelleRepository.findById(id).map(libelle -> {
        libelleRepository.delete(libelle);
        return ResponseEntity.ok().build();
    }).orElseThrow(() -> new GeneralResourceNotFoundException("Libelle not found with id " + id));

}
</code>```

答:
You can use the Spring's @Transactional for doing this.

Here is the sample code what I have tried. It performs a Database operation followed by a file operation in my example I'm trying to create a file. First am creating the file before performing the database operation and used TransactionSynchronizationAdapter to make sure the transaction is complete before commiting.

Code:

@Autowired
    private UserService userService;

    @Transactional
    public String doFileOperation() {

        File testFile = new File("C:\\test.txt");
        TxnListener transactionListener = new TxnListener(testFile);
        TransactionSynchronizationManager.registerSynchronization(transactionListener);
        // DB Operation
        userService.addUser();
        // File Operation
        List<String> lines = Arrays.asList("1st line", "2nd line");

        try {
            Files.write(Paths.get(testFile.getPath()),
                    lines,
                    StandardCharsets.UTF_8,
                    StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }
```

<pre class="lang-java prettyprint-override"><code>public class TxnListener extends TransactionSynchronizationAdapter {
    private File outputFile;

    public TxnListener(File outputFile) {
        this.outputFile = outputFile;
    }

    @Override
    public void afterCompletion(int status) {
        if (STATUS_COMMITTED != status) {
            if (outputFile.exists()) {
                if (!outputFile.delete()) {
                    System.out.println("Could not delete File" + outputFile.getPath() + " after failed transaction");
                }
            }
        }
    }
}
</code>```

In case of exception during the Database operation afterCompletion will be called and the file will be deleted.

This way you can maintain the atomicity of the operation.

Body:
I am developping an application using spring boot as framework. I have 2 methods the first one is deleting data from the database and the other one is deleting folder from the disk, so if i delete from the database and i can't delete from the disc all the operation will fail. So how can i do that with springboot ?

@Override
public ResponseEntity<?> delete(Long id) {
    return libelleRepository.findById(id).map(libelle -> {
        libelleRepository.delete(libelle);
        return ResponseEntity.ok().build();
    }).orElseThrow(() -> new GeneralResourceNotFoundException("Libelle not found with id " + id));

}

Body:
You can use the Spring's @Transactional for doing this.

Here is the sample code what I have tried. It performs a Database operation followed by a file operation in my example I'm trying to create a file. First am creating the file before performing the database operation and used TransactionSynchronizationAdapter to make sure the transaction is complete before commiting.

Code:

@Autowired
    private UserService userService;

    @Transactional
    public String doFileOperation() {

        File testFile = new File("C:\\test.txt");
        TxnListener transactionListener = new TxnListener(testFile);
        TransactionSynchronizationManager.registerSynchronization(transactionListener);
        // DB Operation
        userService.addUser();
        // File Operation
        List<String> lines = Arrays.asList("1st line", "2nd line");

        try {
            Files.write(Paths.get(testFile.getPath()),
                    lines,
                    StandardCharsets.UTF_8,
                    StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

public class TxnListener extends TransactionSynchronizationAdapter {
    private File outputFile;

    public TxnListener(File outputFile) {
        this.outputFile = outputFile;
    }

    @Override
    public void afterCompletion(int status) {
        if (STATUS_COMMITTED != status) {
            if (outputFile.exists()) {
                if (!outputFile.delete()) {
                    System.out.println("Could not delete File" + outputFile.getPath() + " after failed transaction");
                }
            }
        }
    }
}

In case of exception during the Database operation afterCompletion will be called and the file will be deleted.

This way you can maintain the atomicity of the operation.


问:
when is exhaustive so else is redundant?
I am new to kotlin and I created a method that contains the when statement and IntelliJ suggesting me to remove the else branch.
I am not really sure why. Any idea why I need to remove the else branch here?
This is the code:</p>

```<code>    companion object{
    @Synchronized fun getDriver(
        url: String,
        desiredCapabilities: DesiredCapabilities,
        mobilePlatform: MobilePlatform)
        : AppiumDriver<WebElement> =
        when(mobilePlatform){
            MobilePlatform.ANDROID -> AndroidDriver<WebElement>(URL(url), desiredCapabilities)
            MobilePlatform.IOS -> IOSDriver<WebElement>(URL(url), desiredCapabilities)
            else -> throw RuntimeException("Cannot get the driver")
        }
}
</code>```

答:
To utilize else block you can try something like:

```<code>    enum class PaymentStatus(val value: Int) {
     PAID(1),
     UNPAID(2)
 }

    fun f(x: Int) {
    val foo = when (x) {
        PaymentStatus.PAID.value -> "PAID"
        PaymentStatus.UNPAID.value -> "UNPAID"

        else -> throw IllegalStateException()
    }
}
</code>```

OR

create factory method create in the companion object of enum class:

```<code>enum class PaymentStatus(val value: Int) {
    PAID(1),
    UNPAID(2);

    companion object {
        fun create(x: Int): PaymentStatus {
            return when (x) {
                1 -> PAID
                2 -> UNPAID
                else -> throw IllegalStateException()
            }
        }
    }
}

fun f(x: Int) {
    val foo = when (PaymentStatus.create(x)) {
        PaymentStatus.PAID -> "PAID"
        PaymentStatus.UNPAID -> "UNPAID"
    }
}
</code>```

Check here more details

Body:
I am new to kotlin and I created a method that contains the when statement and IntelliJ suggesting me to remove the else branch.
I am not really sure why. Any idea why I need to remove the else branch here?
This is the code:

    companion object{
    @Synchronized fun getDriver(
        url: String,
        desiredCapabilities: DesiredCapabilities,
        mobilePlatform: MobilePlatform)
        : AppiumDriver<WebElement> =
        when(mobilePlatform){
            MobilePlatform.ANDROID -> AndroidDriver<WebElement>(URL(url), desiredCapabilities)
            MobilePlatform.IOS -> IOSDriver<WebElement>(URL(url), desiredCapabilities)
            else -> throw RuntimeException("Cannot get the driver")
        }
}

Body:
To utilize else block you can try something like:

    enum class PaymentStatus(val value: Int) {
     PAID(1),
     UNPAID(2)
 }

    fun f(x: Int) {
    val foo = when (x) {
        PaymentStatus.PAID.value -> "PAID"
        PaymentStatus.UNPAID.value -> "UNPAID"

        else -> throw IllegalStateException()
    }
}

OR

create factory method create in the companion object of enum class:

enum class PaymentStatus(val value: Int) {
    PAID(1),
    UNPAID(2);

    companion object {
        fun create(x: Int): PaymentStatus {
            return when (x) {
                1 -> PAID
                2 -> UNPAID
                else -> throw IllegalStateException()
            }
        }
    }
}

fun f(x: Int) {
    val foo = when (PaymentStatus.create(x)) {
        PaymentStatus.PAID -> "PAID"
        PaymentStatus.UNPAID -> "UNPAID"
    }
}

Check here more details


问:
openthread/environment docker rsyslogd: imklog: cannot open kernel log (/proc/kmsg): Operation not permitted
I am running openthread/environment:latest docker image (as of 2019-06-15)

When starting on a fresh ubuntu 18.04 with docker 18.09 using the command

ubuntu@ip-172-31-37-198:~$ docker run -it --rm openthread/environment bash

I get the following output

Stopping system message bus dbus                            [ OK ]

Starting system message bus dbus                            [ OK ]

Starting enhanced syslogd rsyslogd

rsyslogd: imklog: cannot open kernel log (/proc/kmsg): Operation not permitted

rsyslogd: activation of module imklog failed [v8.32.0 try http://www.rsyslog.com/e/2145 ]

Anyone knows whether this is related to ubuntu setup or the docker container or how to fix.

答:
@Reto's answer will work, but you will be editing that file every time you build your container. Put this in your Dockerfile and you're all set. The edit will be performed automatically while the container is being built.

```<code>RUN sed -i '/imklog/s/^/#/' /etc/rsyslog.conf
</code>```

Body:
@Reto's answer will work, but you will be editing that file every time you build your container. Put this in your Dockerfile and you're all set. The edit will be performed automatically while the container is being built.

RUN sed -i '/imklog/s/^/#/' /etc/rsyslog.conf


问:
Getting access token for Auth0 with Express
in my Express app I have to get access token for Auth0. In the documentation, they have an example for pure Node JS with a request:

var request = require("request");

var options = { method: 'POST',
  url: 'https://XXX.eu.auth0.com/oauth/token',
  headers: { 'content-type': 'application/json' },
  body: '{"client_id":"XXX","client_secret":"XXX","audience":"http://localhost:3001/","grant_type":"client_credentials"}' };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
```

<p>But when I'm trying to do the same in a next way:</p>

<pre class="lang-js prettyprint-override"><code>app.post('/token', function(options, res) {
  return res.json()
});
</code>```

I'm getting "UnauthorizedError: No authorization token was found".

How can I do it properly?

答:
Are you sure that you have enabled client_credentials grant type in your app?
Go to application / advanced / grant types and enable client_credentials

See picture here

Body:
in my Express app I have to get access token for Auth0. In the documentation, they have an example for pure Node JS with a request:

var request = require("request");

var options = { method: 'POST',
  url: 'https://XXX.eu.auth0.com/oauth/token',
  headers: { 'content-type': 'application/json' },
  body: '{"client_id":"XXX","client_secret":"XXX","audience":"http://localhost:3001/","grant_type":"client_credentials"}' };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});

But when I'm trying to do the same in a next way:

app.post('/token', function(options, res) {
  return res.json()
});

I'm getting "UnauthorizedError: No authorization token was found".

How can I do it properly?


问:
How do you balance fun feature creep with time constraints?
I enjoy programming, usually.  Tedious stuff is easy to get done as quickly and correctly as possible so I can get through it and not have to see it again.

But a lot of my coding is fun and when I get in the 'zone' I just really enjoy myself.

Which is where I make the mistake of spending too much time, perhaps adding features, perhaps writing it in a cool or elegant manner, or just doing neat prototypes.

How do you recognize this is happening before it exceeds your time frame?

What do you do before starting a potentially fun piece of code, or during, to get back on track?

When is it ok to let yourself go "hog wild" and just enjoy it without worrying about consequences?

-Adam

答: Give yourself a hard deadline--even for your own projects. Otherwise, you'll just keep tweaking and adding features ad infinitum.</p>

OwnerDisplayName: Adam Davis

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dF


问:
Why is a ConcurrentModificationException thrown and how to debug it
I am using a Collection (a HashMap used indirectly by the JPA, it so happens), but apparently randomly the code throws a ConcurrentModificationException. What is causing it and how do I fix this problem? By using some synchronization, perhaps?

Here is the full stack-trace:

```<code>Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$ValueIterator.next(Unknown Source)
        at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
        at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
        at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
        at org.hibernate.engine.Cascade.cascade(Cascade.java:130)
</code>```

答:
This is not a synchronization problem.  This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.

```<code>Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Entry item = it.next();
    map.remove(item.getKey());
}
</code>```

This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.

The correct approach would be

```<code>Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Entry item = it.next();
    it.remove();
}
</code>```

Assuming this iterator supports the remove() operation.

Body:
I am using a Collection (a HashMap used indirectly by the JPA, it so happens), but apparently randomly the code throws a ConcurrentModificationException. What is causing it and how do I fix this problem? By using some synchronization, perhaps?

Here is the full stack-trace:

Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
        at java.util.HashMap$ValueIterator.next(Unknown Source)
        at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
        at org.hibernate.engine.Cascade.cascadeCollectionElements(Cascade.java:296)
        at org.hibernate.engine.Cascade.cascadeCollection(Cascade.java:242)
        at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:219)
        at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
        at org.hibernate.engine.Cascade.cascade(Cascade.java:130)

LastEditorDisplayName: Rich B

Body:
This is not a synchronization problem.  This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Entry item = it.next();
    map.remove(item.getKey());
}

This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.

The correct approach would be

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Entry item = it.next();
    it.remove();
}

Assuming this iterator supports the remove() operation.

OwnerDisplayName: Robin


问:
Using Openmp 4/5 in Visual Studio 2019 using clang-cl
I am trying to run a simple project with OpenMP. Since Visual Studio only supports OpenMP 2 so I try to compile and run the project using LLVM clang-cl that comes with Visual Studio 2019. The compilation part seems to be ok, but in the link phase, the linker cannot resolve the OMP functions.

This is my code, there is only 1 file:

```<code>#include <stdio.h>

void fn() {
    #pragma omp parallel num_threads(5)
    {
        int i;
        #pragma omp task depend(in : i)
        for (i = 0; i < 1; i++) {
            printf("task\n");
        }
    }
}

int main() {
    printf("hello\n");
    fn();
}
</code>```

My Visual Studio project properties:

Windows SDK version: 10.0(latest installed version) (10.0.18362.0)

Platform toolset: LLVM (clang-cl)

C/c++ - Command Line - Additional Options: /Zc:twoPhase- -Xclang -fopenmp -v

Linker - Additional Dependencies: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm\lib\libomp.lib and C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm\lib\libiomp5md.lib

Linker - Additional Library Directories: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm\lib

Linker - Command Lines - Additional Options: -fopenmp -verbose

Error log when running the project

```<code>1>lld-link : error : undefined symbol: __kmpc_global_thread_num
1>>>> referenced by D:\Repositories\Test-clang\Test-clang\Source.cpp:4
1>>>>               x64\Debug\Source.obj:(void __cdecl fn(void))
1>
1>lld-link : error : undefined symbol: __kmpc_push_num_threads
1>>>> referenced by D:\Repositories\Test-clang\Test-clang\Source.cpp:7
1>>>>               x64\Debug\Source.obj:(void __cdecl fn(void))
1>
1>lld-link : error : undefined symbol: __kmpc_fork_call
1>>>> referenced by D:\Repositories\Test-clang\Test-clang\Source.cpp:7
1>>>>               x64\Debug\Source.obj:(void __cdecl fn(void))
1>
1>lld-link : error : undefined symbol: __kmpc_omp_task_alloc
1>>>> referenced by D:\Repositories\Test-clang\Test-clang\Source.cpp:10
1>>>>               x64\Debug\Source.obj:(.omp_outlined._debug__)
1>
1>lld-link : error : undefined symbol: __kmpc_omp_task_with_deps
1>>>> referenced by D:\Repositories\Test-clang\Test-clang\Source.cpp:10
1>>>>               x64\Debug\Source.obj:(.omp_outlined._debug__)
1>Done building project "Test-clang.vcxproj" -- FAILED.
</code>```

I am using Visual Studio Community 2019. So how do I config the project in order to OpenMP work?

I have also tried to compile like in this answer and it works.

```<code>clang -fopenmp -o Source.obj -c Source.cpp
clang -fopenmp -o Source.exe Source.obj
</code>```

It works for clang-cl too

```<code>clang-cl -Xclang -fopenmp -o Source.obj -c Source.cpp
clang-cl /clang:-fopenmp -o Source.exe Source.obj -v
</code>```

But I don't know how to make Visual Studio build the project using the above way.

答: have you added the library to your project dependencies?

Body:
I am trying to run a simple project with OpenMP. Since Visual Studio only supports OpenMP 2 so I try to compile and run the project using LLVM clang-cl that comes with Visual Studio 2019. The compilation part seems to be ok, but in the link phase, the linker cannot resolve the OMP functions.

This is my code, there is only 1 file:

#include <stdio.h>

void fn() {
    #pragma omp parallel num_threads(5)
    {
        int i;
        #pragma omp task depend(in : i)
        for (i = 0; i < 1; i++) {
            printf("task\n");
        }
    }
}

int main() {
    printf("hello\n");
    fn();
}

My Visual Studio project properties:

Windows SDK version: 10.0(latest installed version) (10.0.18362.0)

Platform toolset: LLVM (clang-cl)

C/c++ - Command Line - Additional Options: /Zc:twoPhase- -Xclang -fopenmp -v

Linker - Additional Dependencies: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm\lib\libomp.lib and C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm\lib\libiomp5md.lib

Linker - Additional Library Directories: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm\lib

Linker - Command Lines - Additional Options: -fopenmp -verbose

Error log when running the project

1>lld-link : error : undefined symbol: __kmpc_global_thread_num
1>>>> referenced by D:\Repositories\Test-clang\Test-clang\Source.cpp:4
1>>>>               x64\Debug\Source.obj:(void __cdecl fn(void))
1>
1>lld-link : error : undefined symbol: __kmpc_push_num_threads
1>>>> referenced by D:\Repositories\Test-clang\Test-clang\Source.cpp:7
1>>>>               x64\Debug\Source.obj:(void __cdecl fn(void))
1>
1>lld-link : error : undefined symbol: __kmpc_fork_call
1>>>> referenced by D:\Repositories\Test-clang\Test-clang\Source.cpp:7
1>>>>               x64\Debug\Source.obj:(void __cdecl fn(void))
1>
1>lld-link : error : undefined symbol: __kmpc_omp_task_alloc
1>>>> referenced by D:\Repositories\Test-clang\Test-clang\Source.cpp:10
1>>>>               x64\Debug\Source.obj:(.omp_outlined._debug__)
1>
1>lld-link : error : undefined symbol: __kmpc_omp_task_with_deps
1>>>> referenced by D:\Repositories\Test-clang\Test-clang\Source.cpp:10
1>>>>               x64\Debug\Source.obj:(.omp_outlined._debug__)
1>Done building project "Test-clang.vcxproj" -- FAILED.

I am using Visual Studio Community 2019. So how do I config the project in order to OpenMP work?

I have also tried to compile like in this answer and it works.

clang -fopenmp -o Source.obj -c Source.cpp
clang -fopenmp -o Source.exe Source.obj

It works for clang-cl too

clang-cl -Xclang -fopenmp -o Source.obj -c Source.cpp
clang-cl /clang:-fopenmp -o Source.exe Source.obj -v

But I don't know how to make Visual Studio build the project using the above way.


问:
Can I generate the spring boot configuration metadata as a .properties file
If I include spring-boot-configuration-processor as a dependency, my build will produce a json file like this:

```<code>{
  "groups": [
    {
      "name": "attachments",
      "type": "com.example.config.AttachmentsSettings",
      "sourceType": "com.example.config.AttachmentsSettings"
    }
  ],
  "properties": [
    {
      "name": "attachments.max-size",
      "type": "java.lang.Integer",
      "sourceType": "com.example.config.AttachmentsSettings",
      "defaultValue": 1024
    },
    {
      "name": "attachments.min-size",
      "type": "java.lang.Integer",
      "sourceType": "com.example.config.AttachmentsSettings"
    },
    {
      "name": "attachments.invalid-chars",
      "type": "java.lang.String",
      "sourceType": "com.example.config.AttachmentsSettings",
      "defaultValue": "abc"
    }
  ],
  "hints": []
}
</code>```

I want to additionally produce a properties file that lists all the properties with their default values like this:

```<code>attachments.max-size=1024
attachments.invalid-chars=abc
# attachments.min-size=
</code>```

Ideally, I'd also like it to list the properties that don't have a default value, but commented out.

Is it possible to do something like this already using Spring Boot? Or will I need to write something myself?

答:
I can extend the ConfigurationMetadataAnnotationProcessor like this:

```<code>@SupportedAnnotationTypes({ "*" })
public class MyConfigurationMetadataAnnotationProcessor extends ConfigurationMetadataAnnotationProcessor {

    @Override
    public synchronized void init(ProcessingEnvironment env) {
        super.init(env);

        Field metadataStoreField = ReflectionUtils.findField(ConfigurationMetadataAnnotationProcessor.class, "metadataStore");
        ReflectionUtils.makeAccessible(metadataStoreField);
        ReflectionUtils.setField(metadataStoreField, this, new MyMetadataStore(env));
    }

    private class MyMetadataStore extends MetadataStore {

        static final String METADATA_PROPERTIES_PATH = "META-INF/spring-configuration-metadata.properties";
        private final ProcessingEnvironment environment;

        public MyMetadataStore(ProcessingEnvironment environment) {
            super(environment);
            this.environment = environment;
        }

        @Override
        public void writeMetadata(ConfigurationMetadata metadata) throws IOException {
            if (!metadata.getItems().isEmpty()) {
                try (OutputStream outputStream = createMetadataPropertiesResource().openOutputStream()) {
                    outputStream.write(getProps(metadata).getBytes(StandardCharsets.UTF_8));
                }
            }
        }

        private String getProps(ConfigurationMetadata metadata) {
            return metadata.getItems().stream()
                    .filter(item -> item.isOfItemType(ItemMetadata.ItemType.PROPERTY))
                    .map(item -> nonNull(item.getDefaultValue()) ?
                            item.getName() + "=" + item.getDefaultValue() :
                            "# " + item.getName() + "=")
                    .collect(Collectors.joining("\n"));
        }

        private FileObject createMetadataPropertiesResource() throws IOException {
            return this.environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PROPERTIES_PATH);
        }
    }
}
</code>```

Then add it as a service in the META-INF directory:

where the Processor file has a single line:
com.my.package.MyConfigurationMetadataAnnotationProcessor

I need to compile it in 2 stages - first compile the processor class, then use it to process the annotations - as described in this SO answer.

Body:
If I include spring-boot-configuration-processor as a dependency, my build will produce a json file like this:

{
  "groups": [
    {
      "name": "attachments",
      "type": "com.example.config.AttachmentsSettings",
      "sourceType": "com.example.config.AttachmentsSettings"
    }
  ],
  "properties": [
    {
      "name": "attachments.max-size",
      "type": "java.lang.Integer",
      "sourceType": "com.example.config.AttachmentsSettings",
      "defaultValue": 1024
    },
    {
      "name": "attachments.min-size",
      "type": "java.lang.Integer",
      "sourceType": "com.example.config.AttachmentsSettings"
    },
    {
      "name": "attachments.invalid-chars",
      "type": "java.lang.String",
      "sourceType": "com.example.config.AttachmentsSettings",
      "defaultValue": "abc"
    }
  ],
  "hints": []
}

I want to additionally produce a properties file that lists all the properties with their default values like this:

attachments.max-size=1024
attachments.invalid-chars=abc
# attachments.min-size=

Ideally, I'd also like it to list the properties that don't have a default value, but commented out.

Is it possible to do something like this already using Spring Boot? Or will I need to write something myself?

Body:
I can extend the ConfigurationMetadataAnnotationProcessor like this:

@SupportedAnnotationTypes({ "*" })
public class MyConfigurationMetadataAnnotationProcessor extends ConfigurationMetadataAnnotationProcessor {

    @Override
    public synchronized void init(ProcessingEnvironment env) {
        super.init(env);

        Field metadataStoreField = ReflectionUtils.findField(ConfigurationMetadataAnnotationProcessor.class, "metadataStore");
        ReflectionUtils.makeAccessible(metadataStoreField);
        ReflectionUtils.setField(metadataStoreField, this, new MyMetadataStore(env));
    }

    private class MyMetadataStore extends MetadataStore {

        static final String METADATA_PROPERTIES_PATH = "META-INF/spring-configuration-metadata.properties";
        private final ProcessingEnvironment environment;

        public MyMetadataStore(ProcessingEnvironment environment) {
            super(environment);
            this.environment = environment;
        }

        @Override
        public void writeMetadata(ConfigurationMetadata metadata) throws IOException {
            if (!metadata.getItems().isEmpty()) {
                try (OutputStream outputStream = createMetadataPropertiesResource().openOutputStream()) {
                    outputStream.write(getProps(metadata).getBytes(StandardCharsets.UTF_8));
                }
            }
        }

        private String getProps(ConfigurationMetadata metadata) {
            return metadata.getItems().stream()
                    .filter(item -> item.isOfItemType(ItemMetadata.ItemType.PROPERTY))
                    .map(item -> nonNull(item.getDefaultValue()) ?
                            item.getName() + "=" + item.getDefaultValue() :
                            "# " + item.getName() + "=")
                    .collect(Collectors.joining("\n"));
        }

        private FileObject createMetadataPropertiesResource() throws IOException {
            return this.environment.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", METADATA_PROPERTIES_PATH);
        }
    }
}

Then add it as a service in the META-INF directory:

where the Processor file has a single line:
com.my.package.MyConfigurationMetadataAnnotationProcessor

I need to compile it in 2 stages - first compile the processor class, then use it to process the annotations - as described in this SO answer.


问:
how to convert linq query into lambda expression
I have written Linq Query that i wanted to make it Lambda Expression. how to write the Lambda Expression in place of return statement
Linq Query. entities tables are entities.Users,entities.Users,entities.ponds

Query Expression :

```<code>from pond in Ponds
join customerdevice in CustomerDevices on pond.Imei equals customerdevice.Imei
join user in Users on customerdevice.CustomerId equals user.CustomerId
where user.Username=="user1"
select new { temp = pond.Temp, imei = pond.Imei,timestamp=pond.Timestatmp }
</code>```

Lambda Expression :

```<code> public async Task<IHttpActionResult> GetAllData(int deviceid)
        {
            using (smartpondEntities entities = new smartpondEntities())
            {
                try
                {
                    return Ok(await entities.ponds.Where(u=>u.deviceid==deviceid).OrderByDescending(u => u.timestatmp).ToListAsync());
                }
                catch (Exception Ex)
                {
                    return BadRequest("Sorry Error Found!!!");
                }
            }
        }
</code>```

答:
You lamda should be :

```<code>var ponds = from pond in Ponds
join customerdevice in CustomerDevices on pond.Imei equals customerdevice.Imei
join user in Users on customerdevice.CustomerId equals user.CustomerId
where user.Username=="user1"
select new { temp = pond.Temp, imei = pond.Imei,timestamp=pond.Timestatmp }
</code>```

Then query (I replaced deviceid with imei).

```<code>return Ok(await entities.ponds.Where(u=>u.imei==deviceid).OrderByDescending(u => u.timestatmp).ToListAsync());
</code>```

Body:
I have written Linq Query that i wanted to make it Lambda Expression. how to write the Lambda Expression in place of return statement
Linq Query. entities tables are entities.Users,entities.Users,entities.ponds

Query Expression :

from pond in Ponds
join customerdevice in CustomerDevices on pond.Imei equals customerdevice.Imei
join user in Users on customerdevice.CustomerId equals user.CustomerId
where user.Username=="user1"
select new { temp = pond.Temp, imei = pond.Imei,timestamp=pond.Timestatmp }

Lambda Expression :

 public async Task<IHttpActionResult> GetAllData(int deviceid)
        {
            using (smartpondEntities entities = new smartpondEntities())
            {
                try
                {
                    return Ok(await entities.ponds.Where(u=>u.deviceid==deviceid).OrderByDescending(u => u.timestatmp).ToListAsync());
                }
                catch (Exception Ex)
                {
                    return BadRequest("Sorry Error Found!!!");
                }
            }
        }

Body:
You lamda should be :

var ponds = from pond in Ponds
join customerdevice in CustomerDevices on pond.Imei equals customerdevice.Imei
join user in Users on customerdevice.CustomerId equals user.CustomerId
where user.Username=="user1"
select new { temp = pond.Temp, imei = pond.Imei,timestamp=pond.Timestatmp }

Then query (I replaced deviceid with imei).

return Ok(await entities.ponds.Where(u=>u.imei==deviceid).OrderByDescending(u => u.timestatmp).ToListAsync());


问:
Parsing from json call to map in flutter
Hi the following dart code in flutter, make a rest call to a node.js server returning a map of values in a map. When I run the code, however, the exception below is raised. How can I go about solving this?
Below is an example of json values returning from the rest server in node.js.

Dart Code:

```<code>  static Future<Map> Ricerca(Utente u, int IdCantiere, String NomeCantiere,
      String RagioneSociale, bool isUtente) async {

    Map ret;
    Map map = {
      'IdUtente': u.GetIdUtente(),
      'IdCantiere': IdCantiere,
      'NomeCantiere': NomeCantiere,
      'RagioneSociale': RagioneSociale,
      'CheckBoxCantieriCreatiDaUtenteLoggato': isUtente
    };
    String value = await apiRequest("/cantieri/ricerca", map);

    ret = json.decode(value);
          return ret;
  }
</code>```

Exception:

```<code>[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
#0      CantiereController.Ricerca (package:MyApp/Controller/Cantiere.dart:28:5)
<asynchronous suspension>
#1      Cantiere.ricerca (package:MyApp/Model/Cantiere.dart:18:142)
#2      inizializzaValori (package:MyApp/View/Cantieri/training_screen.dart:25:38)
<asynchronous suspension>
#3      _TrainingScreenState.initState (package:MyApp/View/Cantieri/training_screen.dart:47:5)
#4      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
#5      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
#6      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#7      MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5551:32)
#8      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#9      Element.updateChild (package:flutter/src/widgets/framework.dart:2988<…>MyApp
</code>```

ApiRest.dart Code:

```<code>Future<String> apiRequest(String urlpassed, Map jsonMap) async {
  //Give server and port
  String server = await Storage.leggi("Server");
  String porta = await Storage.leggi("Porta");

  var url=""+server+":"+porta;

  url=url+urlpassed;
  HttpClient httpClient = new HttpClient();

  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();

  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}
</code>```

JSON Example:

```<code>[
    {
        "IdCantiere": 4,
        "IdCliente": 40,
        "Filiale": "SEDE",
        "RagioneSociale": "dsdso",
        "NomeCantiere": "sala sdsd",
        "DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "sddsdsd"
    },
    {
        "IdCantiere": 5,
        "IdCliente": 204,
        "Filiale": "SEDE",
        "RagioneSociale": "sdsds",
        "NomeCantiere": "manutenzione allarme",
        "DataCreazioneCantiere": "2017-08-04T18:27:42.017Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "manutenzione impianto allarme AVS"
    },
    {
        "IdCantiere": 6,
        "IdCliente": 140,
        "Filiale": "SEDE",
        "RagioneSociale": "Psdsddo",
        "NomeCantiere": "Ristrutturazione terremoto",
        "DataCreazioneCantiere": "2017-08-07T17:45:15.347Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "        stampato 10/01/19"
    }
]
</code>```

答:
Try</p>

```<code>Map<String, dynamic> ret = json.decode(value);
</code>```

Body:
Hi the following dart code in flutter, make a rest call to a node.js server returning a map of values in a map. When I run the code, however, the exception below is raised. How can I go about solving this?
Below is an example of json values returning from the rest server in node.js.

Dart Code:

  static Future<Map> Ricerca(Utente u, int IdCantiere, String NomeCantiere,
      String RagioneSociale, bool isUtente) async {

    Map ret;
    Map map = {
      'IdUtente': u.GetIdUtente(),
      'IdCantiere': IdCantiere,
      'NomeCantiere': NomeCantiere,
      'RagioneSociale': RagioneSociale,
      'CheckBoxCantieriCreatiDaUtenteLoggato': isUtente
    };
    String value = await apiRequest("/cantieri/ricerca", map);

    ret = json.decode(value);
          return ret;
  }

Exception:

[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'
#0      CantiereController.Ricerca (package:MyApp/Controller/Cantiere.dart:28:5)
<asynchronous suspension>
#1      Cantiere.ricerca (package:MyApp/Model/Cantiere.dart:18:142)
#2      inizializzaValori (package:MyApp/View/Cantieri/training_screen.dart:25:38)
<asynchronous suspension>
#3      _TrainingScreenState.initState (package:MyApp/View/Cantieri/training_screen.dart:47:5)
#4      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
#5      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
#6      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#7      MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5551:32)
#8      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
#9      Element.updateChild (package:flutter/src/widgets/framework.dart:2988<…>MyApp

ApiRest.dart Code:

Future<String> apiRequest(String urlpassed, Map jsonMap) async {
  //Give server and port
  String server = await Storage.leggi("Server");
  String porta = await Storage.leggi("Porta");

  var url=""+server+":"+porta;

  url=url+urlpassed;
  HttpClient httpClient = new HttpClient();

  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
  request.headers.set('content-type', 'application/json');
  request.add(utf8.encode(json.encode(jsonMap)));
  HttpClientResponse response = await request.close();

  String reply = await response.transform(utf8.decoder).join();
  httpClient.close();
  return reply;
}

JSON Example:

[
    {
        "IdCantiere": 4,
        "IdCliente": 40,
        "Filiale": "SEDE",
        "RagioneSociale": "dsdso",
        "NomeCantiere": "sala sdsd",
        "DataCreazioneCantiere": "2017-08-04T18:20:31.333Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "sddsdsd"
    },
    {
        "IdCantiere": 5,
        "IdCliente": 204,
        "Filiale": "SEDE",
        "RagioneSociale": "sdsds",
        "NomeCantiere": "manutenzione allarme",
        "DataCreazioneCantiere": "2017-08-04T18:27:42.017Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "manutenzione impianto allarme AVS"
    },
    {
        "IdCantiere": 6,
        "IdCliente": 140,
        "Filiale": "SEDE",
        "RagioneSociale": "Psdsddo",
        "NomeCantiere": "Ristrutturazione terremoto",
        "DataCreazioneCantiere": "2017-08-07T17:45:15.347Z",
        "Tipologia": "Consuntivo",
        "StatoCantiere": "Chiuso",
        "StatoFatturazione": 1,
        "DescrizioneEstesa": "        stampato 10/01/19"
    }
]

Body:
Try

Map<String, dynamic> ret = json.decode(value);


问:
A problem of multithread epoll in linux
I have a multithread linux program which uses epoll(7).  The epoll(7) man page says when one of its fds gets closed, this fd will be automatically removed from the epoll set.  My question is what if a fd of the epoll set gets closed in one thread while the epoll set is being polled in another thread concurrently without synchronization.  Will the program get corrupted or will the kernel synchronize this access automatically?

Thanks

Feng

答:
The fds in an epoll set are maintained by the kernel, so you are safe - the kernel handles any necessary synchronization.

That said, there remains the possibility that an event on the fd comes in on the other thread just before the fd is closed. Thus it might be possible to have an event from an fd which no longer appears to be in the set. With a carefully designed program this shouldn't cause a problem.

ContentLicense: CC BY-SA 3.0

Title: A problem of multithread epoll in linux


问:
Loop in python from user input
I trying to get a python text to speech program running infinitely until user decides to quit, any help would be greatly appreciated

Here's my code:

```<code># IMPORT
import gtts as gTTS
import os

# TTS

myText = input("Enter your text: ")

language = 'en'

output = gTTS.gTTS(text=myText, lang=language, slow=False,)

output.save("output.mp3")

os.system("start output.mp3")

# Restart

def get_answer(prompt):
    answer = input(prompt)
    # 1 while not (answer == "yes" or answer == "no"
    # 2 while answer not in ("yes", "no"):
    # 3 while answer not in ["yes", "no"]:
    while answer not in ("yes", "no"):
        answer = input(prompt)
    return answer

print(get_answer("yes or no? "))
</code>```

答:
<pre class="lang-py prettyprint-override"><code># IMPORT
import gtts as gTTS
import os

# FUNCTIONS
def get_answer(prompt):
    answer = input(prompt)
    # 1 while not (answer == "yes" or answer == "no"
    # 2 while answer not in ("yes", "no"):
    # 3 while answer not in ["yes", "no"]:
    while answer not in ("yes", "no"):
        answer = input(prompt)
    return answer

# TTS
while True:
    myText = input("Enter your text: ")

    language = 'en'

    output = gTTS.gTTS(text=myText, lang=language, slow=False,)

    output.save("output.mp3")

    os.system("start output.mp3")

    # Restart
    if get_answer("quit (yes or no?): ") == yes: break #break out of the loop

</code>```

Title: Loop in python from user input

Body:
I trying to get a python text to speech program running infinitely until user decides to quit, any help would be greatly appreciated

Here's my code:

# IMPORT
import gtts as gTTS
import os

# TTS

myText = input("Enter your text: ")

language = 'en'

output = gTTS.gTTS(text=myText, lang=language, slow=False,)

output.save("output.mp3")

os.system("start output.mp3")

# Restart

def get_answer(prompt):
    answer = input(prompt)
    # 1 while not (answer == "yes" or answer == "no"
    # 2 while answer not in ("yes", "no"):
    # 3 while answer not in ["yes", "no"]:
    while answer not in ("yes", "no"):
        answer = input(prompt)
    return answer

print(get_answer("yes or no? "))


问:
How should I add css classes to Flask wtform "labels"
I am experimenting with Flask and flask-user.  The Registration template calls render_field()  on a few items, one is email.  for example, in my editied copy of registration.html there is:

```<code>            {% if user_manager.USER_ENABLE_EMAIL %}
                {{ render_field(form.email, tabindex=220) }}
            {% endif %}
</code>```

This yields:

```<code><div class="form-group  ">
    <label for="email" class="control-label">Email</label>
    <input class="form-control" id="email" name="email" required="" tabindex="220" type="text" value="">
</div>
</code>```

How can I add classes to the label tag only?

I've looked at the wtforms code but if there is an answer in there it's not jumping out at me.  I see what appears to be the kwargs passed to render_field being added to the input tag but I am not seeing anything touching the label.

答: I found this.  I was looking for render_field in *.py files. I now see that it is defined in the _macros.html file in the flask_user/templates dir.

Body:
I am experimenting with Flask and flask-user.  The Registration template calls render_field()  on a few items, one is email.  for example, in my editied copy of registration.html there is:

            {% if user_manager.USER_ENABLE_EMAIL %}
                {{ render_field(form.email, tabindex=220) }}
            {% endif %}

This yields:

    Email
    <input class="form-control" id="email" name="email" required="" tabindex="220" type="text" value="">

How can I add classes to the label tag only?

I've looked at the wtforms code but if there is an answer in there it's not jumping out at me.  I see what appears to be the kwargs passed to render_field being added to the input tag but I am not seeing anything touching the label.


问:
ionic 4: android permission not working after prod built
I am using @ionic-native/android-permissions.
My code in app.component.ts:

```<code>this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.RECORD_AUDIO).then(
          (result)=>{
       if(!result.hasPermission)
       {
         this.androidPermissions.requestPermissions(
           [this.androidPermissions.PERMISSION.RECORD_AUDIO,
             this.androidPermissions.PERMISSION.GET_ACCOUNTS]
            ).then(()=>{
             // this.rootPage = HomePage;
             window.location.reload();
            });

   }
     });
</code>```

It is working when I do :

ionic cordova run android

or

ionic cordova build android

or

ionic cordova build android --release

But the app is not asking for permission if I add --prod. i.e. :

ionic cordova run android --prod

or

ionic cordova build android --prod --release

So the device mic is not working for the app.

答:
I had this issue, and i solved it by adding permissions to config.xml
then, popup will show and ask client for permissions.
add permissions to config.xml</p>

```<code><platform name="android">
....
<config-file parent="/manifest" target="AndroidManifest.xml" xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-feature android:name="android.hardware.microphone" android:required="true" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</config-file>
....
</platform>
</code>```

Body:
I am using @ionic-native/android-permissions.
My code in app.component.ts:

this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.RECORD_AUDIO).then(
          (result)=>{
       if(!result.hasPermission)
       {
         this.androidPermissions.requestPermissions(
           [this.androidPermissions.PERMISSION.RECORD_AUDIO,
             this.androidPermissions.PERMISSION.GET_ACCOUNTS]
            ).then(()=>{
             // this.rootPage = HomePage;
             window.location.reload();
            });

   }
     });

It is working when I do :

ionic cordova run android

or

ionic cordova build android

or

ionic cordova build android --release

But the app is not asking for permission if I add --prod. i.e. :

ionic cordova run android --prod

or

ionic cordova build android --prod --release

So the device mic is not working for the app.

Body:
I had this issue, and i solved it by adding permissions to config.xml
then, popup will show and ask client for permissions.
add permissions to config.xml

<platform name="android">
....
<config-file parent="/manifest" target="AndroidManifest.xml" xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-feature android:name="android.hardware.microphone" android:required="true" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</config-file>
....
</platform>


问:
SQL Query to truncate table in IBM DB2
Can any one give me the syntax to truncate a table in IBM DB2.

I m running the following command: truncate table tableName immediate;

The eror is DB2

SQLCODE=-104, SQLSTATE=42601, SQLERRMC=table;truncate ;JOIN , DRIVER=3.50.152
   Message: An unexpected token "table" was found following "truncate ".  Expected tokens may include:  "JOIN ".. SQLCODE=-104, SQLSTATE=42601, DRIVER=3.50.152

The syntax matches the one specified in the reference docs of IBM : http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db29.doc.sqlref/db2z_sql_truncate.htm

答:
This is the exact reference documentation available for TRUNCATE in DB2 from 9.7 version

DB2 Reference for TRUNCATE

Title: SQL Query to truncate table in IBM DB2


问:
Convert a Quartz Scheduler to unix cron scheduler
I have a quick question please, i should convert some Quartz Scheduler to unix machine cron.
The Quartz Scheduler is 0 30 11-18/22 * * ? and when i put it in the site : http://www.cronmaker.com/ it shows me that the cron is running every 11h30 of every day.
So for me 0 30 11-18/22 * * is equals to 0 30 11 * *  , is this correct ?

Thank you

答:
For every day run at 11:30 you should rewrite the above Quartz Scheduler like:</p>

```<code>30 11 * * * /path/to/the/job
</code>```

Body:
For every day run at 11:30 you should rewrite the above Quartz Scheduler like:

30 11 * * * /path/to/the/job


问:
Testing Angular component with unsubscribe Error during cleanup of component
I'm testing a component which subscribe router params. Every test pass and everything works fine. But if I look in the console, I can see an error:

Error during cleanup of component ApplicationViewComponent
  localConsole.(anonymous function) @ context.js:232

Do you know why this occurs?

I tried removing the unsubscribe() from ngOnDestroy() method and the error disappears.

Is karma/jasmine supporting unsubscribe() automatically?

Here is the component and tests

Component

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Rx'

import { AppService } from 'app.service';

@Component({
  selector: 'app-component',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  private routeSubscription: Subscription;

  // Main ID
  public applicationId: string;

  constructor(
    private route: ActivatedRoute,
    private _service: AppService
  ) { }

  ngOnInit() {
    this.routeSubscription = this.route.params.subscribe(params => {
      this.applicationId = params['id'];

      this.getDetails();
      this.getList();
    });
  }

  getDetails() {
    this._service.getDetails(this.applicationId).subscribe(
      result => {
        console.log(result);
      },
      error => {
        console.error(error);
      },
      () => {
        console.info('complete');
      }
    );
  }

  getList(notifyWhenComplete = false) {
    this._service.getList(this.applicationId).subscribe(
      result => {
        console.log(result);
      },
      error => {
        console.error(error);
      },
      () => {
        console.info('complete');
      }
    );
  }

  ngOnDestroy() {
    this.routeSubscription.unsubscribe();
  }

}
</code>```

Component spec file

```<code>import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
  async,
  fakeAsync,
  ComponentFixture,
  TestBed,
  tick,
  inject
} from '@angular/core/testing';
import {
  RouterTestingModule
} from '@angular/router/testing';
import {
  HttpModule
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Router, ActivatedRoute } from '@angular/router';

// Components
import { AppComponent } from './app.component';

// Service
import { AppService } from 'app.service';
import { AppServiceStub } from './app.service.stub';

let comp:    AppComponent;
let fixture: ComponentFixture<AppComponent>;
let service: AppService;

let expectedApplicationId = 'abc123';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [RouterTestingModule, HttpModule],
      providers: [
        FormBuilder,
        {
          provide: ActivatedRoute,
          useValue: {
            params:  Observable.of({id: expectedApplicationId})
          }
        },
        {
          provide: AppService,
          useClass: AppServiceStub
        }
      ],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

  tests();
});

function tests() {
  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.componentInstance;

    service = TestBed.get(AppService);
  });

  /*
  *   COMPONENT BEFORE INIT
  */
  it(`should be initialized`, () => {
    expect(fixture).toBeDefined();
    expect(comp).toBeDefined();
  });

  /*
  *   COMPONENT INIT
  */

  it(`should retrieve param id from ActivatedRoute`, async(() => {
    fixture.detectChanges();

    expect(comp.applicationId).toEqual(expectedApplicationId);
  }));

  it(`should get the details after ngOnInit`, async(() => {
    spyOn(comp, 'getDetails');
    fixture.detectChanges();

    expect(comp.getDetails).toHaveBeenCalled();
  }));

  it(`should get the list after ngOnInit`, async(() => {
    spyOn(comp, 'getList');
    fixture.detectChanges();

    expect(comp.getList).toHaveBeenCalled();
  }));
}
</code>```

service.stub

```<code>import { Observable } from 'rxjs/Observable';

export class AppServiceStub {
  getList(id: string) {
    return Observable.from([
      {
        id: "7a0c6610-f59b-4cd7-b649-1ea3cf72347f",
        name: "item 1"
      },
      {
        id: "f0354c29-810e-43d8-8083-0712d1c412a3",
        name: "item 2"
      },
      {
        id: "2494f506-009a-4af8-8ca5-f6e6ba1824cb",
        name: "item 3"
      }
    ]);
  }
  getDetails(id: string) {
    return Observable.from([
      {
        id: id,
        name: "detailed item 1"
      }
    ]);
  }
}
</code>```

答:
As explained by @randomPoison, the error is triggered when the component that uses unsubscribe is not initialised. However, calling fixture.detectChanges() is a solution for when the error is in the spec file of the respective component.

But we might also be dealing with a FooComponent that creates BarComponent and BarComponent uses unsubscribe in its ngOnDestroy. Proper mocking must be done.

I'd suggest a different approach to the subscription cleanup, one that is declarative and won't trigger such problems. Here's an example:

export class BazComponent implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject();

  ngOnInit(): void {
    someObservable$
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe(...);
  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }
}
```

More on this approach here

Body:
I'm testing a component which subscribe router params. Every test pass and everything works fine. But if I look in the console, I can see an error:

Error during cleanup of component ApplicationViewComponent
  localConsole.(anonymous function) @ context.js:232

Do you know why this occurs?

I tried removing the unsubscribe() from ngOnDestroy() method and the error disappears.

Is karma/jasmine supporting unsubscribe() automatically?

Here is the component and tests

Component

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Rx'

import { AppService } from 'app.service';

@Component({
  selector: 'app-component',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  private routeSubscription: Subscription;

  // Main ID
  public applicationId: string;

  constructor(
    private route: ActivatedRoute,
    private _service: AppService
  ) { }

  ngOnInit() {
    this.routeSubscription = this.route.params.subscribe(params => {
      this.applicationId = params['id'];

      this.getDetails();
      this.getList();
    });
  }

  getDetails() {
    this._service.getDetails(this.applicationId).subscribe(
      result => {
        console.log(result);
      },
      error => {
        console.error(error);
      },
      () => {
        console.info('complete');
      }
    );
  }

  getList(notifyWhenComplete = false) {
    this._service.getList(this.applicationId).subscribe(
      result => {
        console.log(result);
      },
      error => {
        console.error(error);
      },
      () => {
        console.info('complete');
      }
    );
  }

  ngOnDestroy() {
    this.routeSubscription.unsubscribe();
  }

}

Component spec file

import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
  async,
  fakeAsync,
  ComponentFixture,
  TestBed,
  tick,
  inject
} from '@angular/core/testing';
import {
  RouterTestingModule
} from '@angular/router/testing';
import {
  HttpModule
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Router, ActivatedRoute } from '@angular/router';

// Components
import { AppComponent } from './app.component';

// Service
import { AppService } from 'app.service';
import { AppServiceStub } from './app.service.stub';

let comp:    AppComponent;
let fixture: ComponentFixture<AppComponent>;
let service: AppService;

let expectedApplicationId = 'abc123';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [RouterTestingModule, HttpModule],
      providers: [
        FormBuilder,
        {
          provide: ActivatedRoute,
          useValue: {
            params:  Observable.of({id: expectedApplicationId})
          }
        },
        {
          provide: AppService,
          useClass: AppServiceStub
        }
      ],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

  tests();
});

function tests() {
  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.componentInstance;

    service = TestBed.get(AppService);
  });

  /*
  *   COMPONENT BEFORE INIT
  */
  it(`should be initialized`, () => {
    expect(fixture).toBeDefined();
    expect(comp).toBeDefined();
  });

  /*
  *   COMPONENT INIT
  */

  it(`should retrieve param id from ActivatedRoute`, async(() => {
    fixture.detectChanges();

    expect(comp.applicationId).toEqual(expectedApplicationId);
  }));

  it(`should get the details after ngOnInit`, async(() => {
    spyOn(comp, 'getDetails');
    fixture.detectChanges();

    expect(comp.getDetails).toHaveBeenCalled();
  }));

  it(`should get the list after ngOnInit`, async(() => {
    spyOn(comp, 'getList');
    fixture.detectChanges();

    expect(comp.getList).toHaveBeenCalled();
  }));
}

service.stub

import { Observable } from 'rxjs/Observable';

export class AppServiceStub {
  getList(id: string) {
    return Observable.from([
      {
        id: "7a0c6610-f59b-4cd7-b649-1ea3cf72347f",
        name: "item 1"
      },
      {
        id: "f0354c29-810e-43d8-8083-0712d1c412a3",
        name: "item 2"
      },
      {
        id: "2494f506-009a-4af8-8ca5-f6e6ba1824cb",
        name: "item 3"
      }
    ]);
  }
  getDetails(id: string) {
    return Observable.from([
      {
        id: id,
        name: "detailed item 1"
      }
    ]);
  }
}

Body:
As explained by @randomPoison, the error is triggered when the component that uses unsubscribe is not initialised. However, calling fixture.detectChanges() is a solution for when the error is in the spec file of the respective component.

But we might also be dealing with a FooComponent that creates BarComponent and BarComponent uses unsubscribe in its ngOnDestroy. Proper mocking must be done.

I'd suggest a different approach to the subscription cleanup, one that is declarative and won't trigger such problems. Here's an example:

export class BazComponent implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject();

  ngOnInit(): void {
    someObservable$
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe(...);
  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }
}

More on this approach here


问:
How can I increment by 1 the amount of lines I want to skip in a batch file?
```<code>@echo off
cls
setlocal EnableDelayedExpansion

set "cmd=findstr /R /N "^^" Contas.csv | find /C ":""

for /f %%a in ('!cmd!') do set number=%%a

set /A number=%number%-1
</code>```

<p>for each interation I want it to increase skip by 1(starts at 1, then 2,3,4,5...) </p>

```<code>for /f "skip=1" %%U IN (Contas.csv) DO (
if not defined line set "line=%%U"
echo !line!

pause
)
</code>```

答:
Based upon your comment, and as SendKey is not a batch file command, here's my interpretation of the methodology I think you require:

@Echo Off
Set "cmnd="%__APPDIR__%find.exe" /V /N ""<"Contas.csv""
SetLocal EnableDelayedExpansion
For /F "Skip=1Tokens=1*Delims=]" %%G In ('"!cmnd!"')Do (
    Echo=%%H
    "%__APPDIR__%timeout.exe" 1 /NoBreak>NUL
)
EndLocal
```

<p>I have skipped the first line, using <code>Skip=1</code>, <em>which I assume is your header</em>, (if you don't wish to skip a header line, then remove <code>Skip=1</code>).</p>

<p>Additionally, I have used <code>Echo=</code> to output each line, <em>including any empty ones, (you may be wishing to use <code>SendKey</code> here)</em>.</p>

<p>Finally I have used <code>Timeout</code> with a <code>1</code> second delay, <em>to allow you to see the effect of each line being output individually, (this may not be required if you're not using <code>Echo=</code>)</em>.
<HR>
If you'd like to include the record numbers too then a small adjustment to the <code>Delims</code> and <code>Echo=</code> is necessary:</p>

<pre class="lang-bat prettyprint-override"><code>@Echo Off
Set "cmnd="%__APPDIR__%find.exe" /V /N ""<"Contas.csv""
SetLocal EnableDelayedExpansion
For /F "Skip=1Tokens=1*Delims=[]" %%G In ('"!cmnd!"')Do (
    Echo %%G    %%H
    "%__APPDIR__%timeout.exe" 1 /NoBreak>NUL
)
EndLocal
</code>```

In both cases, if you're not interested in using robust code, you can change "%__APPDIR__%find.exe" to Find and "%__APPDIR__%timeout.exe" to Timeout

Body:
@echo off
cls
setlocal EnableDelayedExpansion

set "cmd=findstr /R /N "^^" Contas.csv | find /C ":""

for /f %%a in ('!cmd!') do set number=%%a

set /A number=%number%-1

for each interation I want it to increase skip by 1(starts at 1, then 2,3,4,5...)

for /f "skip=1" %%U IN (Contas.csv) DO (
if not defined line set "line=%%U"
echo !line!

pause
)

Body:
Based upon your comment, and as SendKey is not a batch file command, here's my interpretation of the methodology I think you require:

@Echo Off
Set "cmnd="%__APPDIR__%find.exe" /V /N ""<"Contas.csv""
SetLocal EnableDelayedExpansion
For /F "Skip=1Tokens=1*Delims=]" %%G In ('"!cmnd!"')Do (
    Echo=%%H
    "%__APPDIR__%timeout.exe" 1 /NoBreak>NUL
)
EndLocal

I have skipped the first line, using Skip=1, which I assume is your header, (if you don't wish to skip a header line, then remove Skip=1).

Additionally, I have used Echo= to output each line, including any empty ones, (you may be wishing to use SendKey here).

Finally I have used Timeout with a 1 second delay, to allow you to see the effect of each line being output individually, (this may not be required if you're not using Echo=).

If you'd like to include the record numbers too then a small adjustment to the Delims and Echo= is necessary:

@Echo Off
Set "cmnd="%__APPDIR__%find.exe" /V /N ""<"Contas.csv""
SetLocal EnableDelayedExpansion
For /F "Skip=1Tokens=1*Delims=[]" %%G In ('"!cmnd!"')Do (
    Echo %%G    %%H
    "%__APPDIR__%timeout.exe" 1 /NoBreak>NUL
)
EndLocal

In both cases, if you're not interested in using robust code, you can change "%__APPDIR__%find.exe" to Find and "%__APPDIR__%timeout.exe" to Timeout


问:
Impute categorical missing values in scikit-learn
I've got pandas data with some columns of text type. There are some NaN values along with these text columns. What I'm trying to do is to impute those NaN's by sklearn.preprocessing.Imputer (replacing NaN by the most frequent value). The problem is in implementation.
Suppose there is a Pandas dataframe df with 30 columns, 10 of which are of categorical nature.
Once I run:

```<code>from sklearn.preprocessing import Imputer
imp = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)
imp.fit(df)
</code>```

Python generates an error: 'could not convert string to float: 'run1'', where 'run1' is an ordinary (non-missing) value from the first column with categorical data.

Any help would be very welcome

答:
You could try the following:</p>

```<code>replace = df.<yourcolumn>.value_counts().argmax()

df['<yourcolumn>'].fillna(replace, inplace=True)

</code>```

Body:
I've got pandas data with some columns of text type. There are some NaN values along with these text columns. What I'm trying to do is to impute those NaN's by sklearn.preprocessing.Imputer (replacing NaN by the most frequent value). The problem is in implementation.
Suppose there is a Pandas dataframe df with 30 columns, 10 of which are of categorical nature.
Once I run:

from sklearn.preprocessing import Imputer
imp = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)
imp.fit(df)

Python generates an error: 'could not convert string to float: 'run1'', where 'run1' is an ordinary (non-missing) value from the first column with categorical data.

Any help would be very welcome

Body:
You could try the following:

replace = df.<yourcolumn>.value_counts().argmax()

df['<yourcolumn>'].fillna(replace, inplace=True)


问:
How to build this Laravel Eloquent Query
I want to build a nested array from a simple table with Laravel Eloquent, but i couldn't.

So basically below is a snap shot of my table

and this is the array I want to build

答:
You can use some methods from collection :

```<code>$result = $data->groupBy(['market_id', 'base_currency', 'currency_id'])
    ->map(function ($item) {
        return $item->map(function ($item) {
            return $item->map(function ($item) {
                return $item->map(function ($item) {
                    return $item['currency_id'];
                });
            })->flatten();
        })->sortKeys();
    });

dd($result->toArray());
</code>```

```<code>array:1 [
  1 => array:2 [
    1 => array:2 [
      0 => 2
      1 => 3
    ]
    2 => array:2 [
      0 => 1
      1 => 2
    ]
  ]
]
</code>```

Explanation

groupBy

The groupBy method groups the collection's items by a given key. Multiple grouping criteria may be passed as an array. Each array element will be applied to the corresponding level within a multi-dimensional array:

```<code>$data->groupBy(['market_id', 'base_currency', 'currency_id']);
</code>```

map

The map method iterates through the collection and passes each value to the given callback.

```<code>->map(function ($item) {
    return $item;
});
</code>```

flatten

The flatten method flattens a multi-dimensional collection into a single dimension:

```<code>->flatten()
</code>```

sortKeys

The sortKeys method sorts the collection by the keys of the underlying associative array:

```<code>->sortKeys()
</code>```

Body:
You can use some methods from collection :

$result = $data->groupBy(['market_id', 'base_currency', 'currency_id'])
    ->map(function ($item) {
        return $item->map(function ($item) {
            return $item->map(function ($item) {
                return $item->map(function ($item) {
                    return $item['currency_id'];
                });
            })->flatten();
        })->sortKeys();
    });

dd($result->toArray());

array:1 [
  1 => array:2 [
    1 => array:2 [
      0 => 2
      1 => 3
    ]
    2 => array:2 [
      0 => 1
      1 => 2
    ]
  ]
]

Explanation

groupBy

The groupBy method groups the collection's items by a given key. Multiple grouping criteria may be passed as an array. Each array element will be applied to the corresponding level within a multi-dimensional array:

$data->groupBy(['market_id', 'base_currency', 'currency_id']);

map

The map method iterates through the collection and passes each value to the given callback.

->map(function ($item) {
    return $item;
});

flatten

The flatten method flattens a multi-dimensional collection into a single dimension:

->flatten()

sortKeys

The sortKeys method sorts the collection by the keys of the underlying associative array:

->sortKeys()


问:
Callapse list: Keep open only the active one open
This works fine on my app but for some reason I could not get it to work correctly here. Anyway my question is, when I click on a list title I want to close the previously opened one and keep only the active one open. Currently it opens everything I click, but keeps everything open as well. Any ideas on how I can achieve this?

$('.cl-item:not(.cl-item-no-sub) > .cl-label-wrap .cl-label-title').click(function() {
    $(this).parent().parent().toggleClass('cl-item-open');
});
$('.cl-item:not(.cl-item-no-sub) > .cl-label-wrap .cl-label-icon').click(function() {
    $(this).parent().parent().toggleClass('cl-item-open');
})

$('.cl-item').each(function(){
    console.log ($(this).find('> ul').length);
    if ( $(this).find('> ul').length === 0 ) {
        $(this).addClass('cl-item-no-sub');
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>$li-padding: 7px;
$li-padding-tools: 10px;
$cascade-padding: 25px;
$bg-level-1: #dadada;
$bg-level-2: #ffffff;
$bg-level-3: #ffffff;
$color-tools: #9e9e9e;
$toggle-width: 1.5em;

.cl-start-wrap {
    list-style: none;
    padding: 0;
    margin: 30px;
    width: 300px;
    ul {
        list-style: none;
        padding: 0;
        margin: 0;
    }
    > li {
        > .cl-label-wrap {
            padding: $li-padding 0 $li-padding $cascade-padding*0;
            margin: 1px 0;
            background: $bg-level-1;
            &:hover {
                background: darken($bg-level-1, 5%);
            }
        }
        > ul > li {
            > .cl-label-wrap {
                padding: $li-padding 0 $li-padding $cascade-padding*1;
                background: $bg-level-2;
                &:hover {
                    background: darken($bg-level-2, 5%);
                }
            }
            > ul > li {
                > .cl-label-wrap {
                    padding: $li-padding 0 $li-padding $cascade-padding*2;
                    background: $bg-level-3;
                    &:hover {
                        background: darken($bg-level-3, 5%);
                    }
                }
            }
        }
    }
}

.cl-item {
    > ul {

    }
    > .cl-label-wrap {
        .cl-label-title {
            cursor: pointer;
        }
        .cl-label-icon {
            cursor: pointer;
            text-align: center;
            &:before {
                cursor: pointer;
                display: inline-block;
                font: normal normal normal 14px/1 FontAwesome;
                font-size: inherit;
                text-rendering: auto;
                -webkit-font-smoothing: antialiased;
            }
        }
        .cl-label-tools {
            a {
                color: $color-tools;
                &:hover {
                    color: darken($color-tools, 10%);
                }
            }
        }
    }
}
.cl-item:not(.cl-item-open) {
    > ul {
        display: none;
    }
    > .cl-label-wrap {
        .cl-label-icon {
            &:before {
                content: "\f0da";
            }
        }
    }
}
.cl-item.cl-item-open {
    > .cl-label-wrap {
        .cl-label-icon {
            &:before {
                content: "\f0d7";
            }
        }
    }
}
.cl-item.cl-item-no-sub {
    > .cl-label-wrap {
        .cl-label-title {
            cursor: default;
        }
        .cl-label-icon {
            &:before {
                content: "";
            }
        }
    }
}

// Label-Flexbox
.cl-label-wrap {
    display: table-cell;
    -ms-display: flex;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: flex-start;
    align-content: stretch;
    align-items: flex-start;
    .cl-label-title {
        order: 1;
        flex: 1 1 auto;
        align-self: auto;
    }
    .cl-label-icon {
        order: 0;
        flex: 0 1 $toggle-width;
        align-self: auto;
    }
    .cl-label-tools {
        order: 2;
        flex: 0 1 auto;
        align-self: auto;
        white-space: nowrap;
        padding: 0 $li-padding-tools;
    }
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

            Label 1

                    Label 1.1

                            Label 1.1.1

                            Label 1.1.2

                            Label 1.1.3

                    Label 1.2

            Label 2

                    Label 2.1

                    Label 2.2

                    Label 2.3

            Label 3

```

答:
Use the siblings function to close everything but the current item:

```<code>$('.cl-item:not(.cl-item-no-sub) > .cl-label-wrap .cl-label-title,
   .cl-item:not(.cl-item-no-sub) > .cl-label-wrap .cl-label-icon').click(
  function() {
    var parent = $(this).parent().parent();
    parent.siblings().removeClass("cl-item-open");
    parent.toggleClass('cl-item-open');
  }
);
</code>```

Body:
This works fine on my app but for some reason I could not get it to work correctly here. Anyway my question is, when I click on a list title I want to close the previously opened one and keep only the active one open. Currently it opens everything I click, but keeps everything open as well. Any ideas on how I can achieve this?

$('.cl-item:not(.cl-item-no-sub) > .cl-label-wrap .cl-label-title').click(function() {
    $(this).parent().parent().toggleClass('cl-item-open');
});
$('.cl-item:not(.cl-item-no-sub) > .cl-label-wrap .cl-label-icon').click(function() {
    $(this).parent().parent().toggleClass('cl-item-open');
})

$('.cl-item').each(function(){
    console.log ($(this).find('> ul').length);
    if ( $(this).find('> ul').length === 0 ) {
        $(this).addClass('cl-item-no-sub');
    }
})

$li-padding: 7px;
$li-padding-tools: 10px;
$cascade-padding: 25px;
$bg-level-1: #dadada;
$bg-level-2: #ffffff;
$bg-level-3: #ffffff;
$color-tools: #9e9e9e;
$toggle-width: 1.5em;

.cl-start-wrap {
    list-style: none;
    padding: 0;
    margin: 30px;
    width: 300px;
    ul {
        list-style: none;
        padding: 0;
        margin: 0;
    }
    > li {
        > .cl-label-wrap {
            padding: $li-padding 0 $li-padding $cascade-padding*0;
            margin: 1px 0;
            background: $bg-level-1;
            &:hover {
                background: darken($bg-level-1, 5%);
            }
        }
        > ul > li {
            > .cl-label-wrap {
                padding: $li-padding 0 $li-padding $cascade-padding*1;
                background: $bg-level-2;
                &:hover {
                    background: darken($bg-level-2, 5%);
                }
            }
            > ul > li {
                > .cl-label-wrap {
                    padding: $li-padding 0 $li-padding $cascade-padding*2;
                    background: $bg-level-3;
                    &:hover {
                        background: darken($bg-level-3, 5%);
                    }
                }
            }
        }
    }
}

.cl-item {
    > ul {

    }
    > .cl-label-wrap {
        .cl-label-title {
            cursor: pointer;
        }
        .cl-label-icon {
            cursor: pointer;
            text-align: center;
            &:before {
                cursor: pointer;
                display: inline-block;
                font: normal normal normal 14px/1 FontAwesome;
                font-size: inherit;
                text-rendering: auto;
                -webkit-font-smoothing: antialiased;
            }
        }
        .cl-label-tools {
            a {
                color: $color-tools;
                &:hover {
                    color: darken($color-tools, 10%);
                }
            }
        }
    }
}
.cl-item:not(.cl-item-open) {
    > ul {
        display: none;
    }
    > .cl-label-wrap {
        .cl-label-icon {
            &:before {
                content: "\f0da";
            }
        }
    }
}
.cl-item.cl-item-open {
    > .cl-label-wrap {
        .cl-label-icon {
            &:before {
                content: "\f0d7";
            }
        }
    }
}
.cl-item.cl-item-no-sub {
    > .cl-label-wrap {
        .cl-label-title {
            cursor: default;
        }
        .cl-label-icon {
            &:before {
                content: "";
            }
        }
    }
}

// Label-Flexbox
.cl-label-wrap {
    display: table-cell;
    -ms-display: flex;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    justify-content: flex-start;
    align-content: stretch;
    align-items: flex-start;
    .cl-label-title {
        order: 1;
        flex: 1 1 auto;
        align-self: auto;
    }
    .cl-label-icon {
        order: 0;
        flex: 0 1 $toggle-width;
        align-self: auto;
    }
    .cl-label-tools {
        order: 2;
        flex: 0 1 auto;
        align-self: auto;
        white-space: nowrap;
        padding: 0 $li-padding-tools;
    }
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

            Label 1

                    Label 1.1

                            Label 1.1.1

                            Label 1.1.2

                            Label 1.1.3

                    Label 1.2

            Label 2

                    Label 2.1

                    Label 2.2

                    Label 2.3

            Label 3

Body:
Use the siblings function to close everything but the current item:

$('.cl-item:not(.cl-item-no-sub) > .cl-label-wrap .cl-label-title,
   .cl-item:not(.cl-item-no-sub) > .cl-label-wrap .cl-label-icon').click(
  function() {
    var parent = $(this).parent().parent();
    parent.siblings().removeClass("cl-item-open");
    parent.toggleClass('cl-item-open');
  }
);


问:
How to find a pair of hunted values for a given value with lopps?
I am trying to write a function that gets a list of numbers and an integer and returns a tuple that containing pair of numbers from the list whose sum is the must closest to the number the function received.
for example: closest([10,22,28,29,30,40], 54) --> (22,30)
It is important for me to do this in loop and in time complexity of  O(n).
The problem with my code is that the loop does not want to rerun the list end for any value I take from the beginning of the list...
I would appreciate help :)
Thanks for the helpers!</p>

```<code>def closest(lst, x):
    max_num = 0
    cur = lst[0]
    final = 0
    my_tup = ()
    for num in lst[::-1]:
        max_num = cur + num
        if max_num <= x:
            if max_num > final:
                final = max_num
                my_tup = (cur, num)
            else:
                cur = lst[1]

    return my_tup

print(closest([10,22,28,29,30,40], 54))  ---> return: (22,29)
</code>```

答:
Since you require tuples of exactly 2 elements this can be done with numpy to find the pair of points that are closest to x. Do the outer addition of the list with itself, find the closest absolute distance to x.

```<code>import numpy as np

def closest(lst, x):
    arr = np.array(lst)
    mat = np.abs(x - (arr[:, None] + arr)).astype(float)
    mat[np.diag_indices_from(mat)] = np.NaN # Exclude tuples of same point with itself
    i,j = np.unravel_index(np.nanargmin(mat), mat.shape)

    return arr[i], arr[j]

closest([10,22,28,29,30,40], 54)
(22, 30)

closest([10,27,28,29,30,40], 54)
(27, 28)
</code>```

Body:
I am trying to write a function that gets a list of numbers and an integer and returns a tuple that containing pair of numbers from the list whose sum is the must closest to the number the function received.
for example: closest([10,22,28,29,30,40], 54) --> (22,30)
It is important for me to do this in loop and in time complexity of  O(n).
The problem with my code is that the loop does not want to rerun the list end for any value I take from the beginning of the list...
I would appreciate help :)
Thanks for the helpers!

def closest(lst, x):
    max_num = 0
    cur = lst[0]
    final = 0
    my_tup = ()
    for num in lst[::-1]:
        max_num = cur + num
        if max_num <= x:
            if max_num > final:
                final = max_num
                my_tup = (cur, num)
            else:
                cur = lst[1]

    return my_tup

print(closest([10,22,28,29,30,40], 54))  ---> return: (22,29)

Body:
Since you require tuples of exactly 2 elements this can be done with numpy to find the pair of points that are closest to x. Do the outer addition of the list with itself, find the closest absolute distance to x.

import numpy as np

def closest(lst, x):
    arr = np.array(lst)
    mat = np.abs(x - (arr[:, None] + arr)).astype(float)
    mat[np.diag_indices_from(mat)] = np.NaN # Exclude tuples of same point with itself
    i,j = np.unravel_index(np.nanargmin(mat), mat.shape)

    return arr[i], arr[j]

closest([10,22,28,29,30,40], 54)
(22, 30)

closest([10,27,28,29,30,40], 54)
(27, 28)


问:
How to put axios data into v-select by v-for?
I used axios to get multiple lines of data,
and then I wanted to put the data in v-select so that others could choose,
I thought of using v-for to make him print out line by line.
But the result shows no data available.

my code

```<code><template>
  <div>
     <v-select :item="desserts.name"></v-select>
  </div>
</template>

<script>
export default {
  data: () => ({
    desserts: [
      {
        id: "",
        name: ""
      }
    ]
  }),
  created() {
    this.getprotifile();
  },
  methods: {
    getprotifile() {
      this.axios
        .get("/api/admin/categories")
        .then(res => {
          //console.table(res.data);
          this.desserts = res.data;
          //console.log(this.desserts);
        })
        .catch(error => {
          console.error(error);
        })
        .finally(() => {});
    }
  }
};
</script>
</code>```

答:
If this is for the vuetify v-select component for :items="deserts" (notice items plural) you would need to have an array of objects like

```<code>deserts: [
    {text: "The name", value:"the ID"},
    ...
]
</code>```

or you can use the directives

```<code>item-text="name"
item-value="id"
</code>```

and then your :items object can look like

```<code>[{"id": 1,"name": "aaa"}, {"id": 4,"name": "bbb"}, {"id": 5,"name": "ccc"}, {"id": 9,"name": "ddd"}]
</code>```

You can use the map method if you need to map the data from the server in to the correct format

```<code>this.selectOptions = resp.data.options.map(options => ({value: option.id, text: option.name}));
</code>```

Body:
I used axios to get multiple lines of data,
and then I wanted to put the data in v-select so that others could choose,
I thought of using v-for to make him print out line by line.
But the result shows no data available.

my code

<template>

     <v-select :item="desserts.name"></v-select>

</template>

Body:
If this is for the vuetify v-select component for :items="deserts" (notice items plural) you would need to have an array of objects like

deserts: [
    {text: "The name", value:"the ID"},
    ...
]

or you can use the directives

item-text="name"
item-value="id"

and then your :items object can look like

[{"id": 1,"name": "aaa"}, {"id": 4,"name": "bbb"}, {"id": 5,"name": "ccc"}, {"id": 9,"name": "ddd"}]

You can use the map method if you need to map the data from the server in to the correct format

this.selectOptions = resp.data.options.map(options => ({value: option.id, text: option.name}));


问:
Laravel while empty collection add new parameters in filters to get notEmpty collection
I have this query who return an empty collection with the filter param categorie_compet_id with value 1.

while the collection is empty i need to update this id in order to get a notEmpty collection.

The categorie_compet_id can go from 1 to 10.

How could I do this properly?

$arbitres = Licencies::getArbitres();
    $arbitres->load('rencontreOfficiels');
    $arbitres->load('divisions');

$arbitres = $arbitres->reject(function ($arbitre) use ($rencontre) {
    return $arbitre->rencontreOfficiels->contains(function ($rencontreOfficiels) use ($rencontre) {
        return $rencontreOfficiels->rencontre_id === $rencontre->id;
    });
})->filter(function ($arbitre) {
    return $arbitre->divisions->contains('categorie_compet_id', 1);
})->filter(function($arbitre) {
    return $arbitre->level >= 3;
});
```

<h2>UPDATE</h2>

<pre class="lang-php prettyprint-override"><code>$arbitres->load('rencontreOfficiels');
$arbitres->load('divisions');

$arbitres = $arbitres->reject(function ($arbitre) use ($rencontre) {
    return $arbitre->rencontreOfficiels->contains(function ($rencontreOfficiels) use ($rencontre) {
        return $rencontreOfficiels->rencontre_id === $rencontre->id;
    });
})->filter(function ($arbitre) {
    return $arbitre->divisions->contains('categorie_compet_id', 1);
})->filter(function($arbitre) use ($rencontre) {
    return $arbitre->doesnthave('rencontreOfficiels')->where('rencontreOfficiels.dt_rencontre' , $rencontre->dt_rencontre);
});

//on génére les meilleurs arbitres
for ($i = 1; $i < 7; $i++) {
    $filtered = $arbitres->filter(function ($arbitre) use ($i) {
        return $arbitre->level <= $i;
    });

    if ($filtered->isNotEmpty()) {
        $arbitres = $filtered;
        break;
    }
}
</code>```

Here's my getArbitres method in model:

public static function getArbitres(){
    $all_licences = Licencies::whereIn('activite_licencie_id' , [24,25,50,80])
        ->where('valid_licence_id' , 3)
        ->where('saison_id' , self::getSaison()->id)
        ->where('dispo' , 1)
        ->get();

    return $licences;
}
```

答:
You could use a for loop.

$arbitres = $arbitres->reject(function ($arbitre) use ($rencontre) {
    return $arbitre->rencontreOfficiels->contains(function ($rencontreOfficiels) use ($rencontre) {
        return $rencontreOfficiels->rencontre_id === $rencontre->id;
    });

for ($i = 3; $i < 10; $i++) {
    $filtered = $arbitres->filter(function ($arbitre) use ($i) {
        return $arbitre->level >= $i;
    });

    if ($filtered->isNotEmpty()) {
        $arbitres = $filtered;
        break;
    }
}
```

<p>Simply replace <code>10</code> by your max level.</p>

<h2>Update</h2>

<p>You should be filtering your <code>$arbitres</code> collection from the database when retrieving instead of filtering them after.</p>

<pre class="lang-php prettyprint-override"><code>$arbitres = App\Arbitres::whereHas('rencontreOfficiels', function ($query) use ($rencontre) {
    $query->where('rencontre_id', $rencontre->id);
})->whereDoesntHave('rencontreOfficiels', function ($query) use ($rencontre) {
    $query->where('dt_rencontre', $rencontre->dt_rencontre);
})whereHas('divisions', function ($query) {
    $query->where('categorie_complet_id', 1);
})->get();
</code>```

Update 2

Since you cannot filter the $arbitres upon retrieval, you can filter them like this:

$arbitres = $arbitres->reject(function ($arbitre) use ($rencontre) {
    return $arbitre->rencontreOfficiels->contains(function ($rencontreOfficiels) use ($rencontre) {
        return $rencontreOfficiels->rencontre_id === $rencontre->id;
    });
})->filter(function ($arbitre){
    return $arbitre->divisions->contains('categorie_compet_id', 1);
})->filter(function($arbitre) use ($rencontre){
    return ! $arbitre->rencontreOfficiels->contains('dt_rencontre' , $rencontre->dt_rencontre);
});
```

Body:
I have this query who return an empty collection with the filter param categorie_compet_id with value 1.

while the collection is empty i need to update this id in order to get a notEmpty collection.

The categorie_compet_id can go from 1 to 10.

How could I do this properly?

$arbitres = Licencies::getArbitres();
    $arbitres->load('rencontreOfficiels');
    $arbitres->load('divisions');

$arbitres = $arbitres->reject(function ($arbitre) use ($rencontre) {
    return $arbitre->rencontreOfficiels->contains(function ($rencontreOfficiels) use ($rencontre) {
        return $rencontreOfficiels->rencontre_id === $rencontre->id;
    });
})->filter(function ($arbitre) {
    return $arbitre->divisions->contains('categorie_compet_id', 1);
})->filter(function($arbitre) {
    return $arbitre->level >= 3;
});

UPDATE

$arbitres->load('rencontreOfficiels');
$arbitres->load('divisions');

$arbitres = $arbitres->reject(function ($arbitre) use ($rencontre) {
    return $arbitre->rencontreOfficiels->contains(function ($rencontreOfficiels) use ($rencontre) {
        return $rencontreOfficiels->rencontre_id === $rencontre->id;
    });
})->filter(function ($arbitre) {
    return $arbitre->divisions->contains('categorie_compet_id', 1);
})->filter(function($arbitre) use ($rencontre) {
    return $arbitre->doesnthave('rencontreOfficiels')->where('rencontreOfficiels.dt_rencontre' , $rencontre->dt_rencontre);
});

//on génére les meilleurs arbitres
for ($i = 1; $i < 7; $i++) {
    $filtered = $arbitres->filter(function ($arbitre) use ($i) {
        return $arbitre->level <= $i;
    });

    if ($filtered->isNotEmpty()) {
        $arbitres = $filtered;
        break;
    }
}

Here's my getArbitres method in model:

public static function getArbitres(){
    $all_licences = Licencies::whereIn('activite_licencie_id' , [24,25,50,80])
        ->where('valid_licence_id' , 3)
        ->where('saison_id' , self::getSaison()->id)
        ->where('dispo' , 1)
        ->get();

    return $licences;
}

Body:
You could use a for loop.

$arbitres = $arbitres->reject(function ($arbitre) use ($rencontre) {
    return $arbitre->rencontreOfficiels->contains(function ($rencontreOfficiels) use ($rencontre) {
        return $rencontreOfficiels->rencontre_id === $rencontre->id;
    });

for ($i = 3; $i < 10; $i++) {
    $filtered = $arbitres->filter(function ($arbitre) use ($i) {
        return $arbitre->level >= $i;
    });

    if ($filtered->isNotEmpty()) {
        $arbitres = $filtered;
        break;
    }
}

Simply replace 10 by your max level.

Update

You should be filtering your $arbitres collection from the database when retrieving instead of filtering them after.

$arbitres = App\Arbitres::whereHas('rencontreOfficiels', function ($query) use ($rencontre) {
    $query->where('rencontre_id', $rencontre->id);
})->whereDoesntHave('rencontreOfficiels', function ($query) use ($rencontre) {
    $query->where('dt_rencontre', $rencontre->dt_rencontre);
})whereHas('divisions', function ($query) {
    $query->where('categorie_complet_id', 1);
})->get();

Update 2

Since you cannot filter the $arbitres upon retrieval, you can filter them like this:

$arbitres = $arbitres->reject(function ($arbitre) use ($rencontre) {
    return $arbitre->rencontreOfficiels->contains(function ($rencontreOfficiels) use ($rencontre) {
        return $rencontreOfficiels->rencontre_id === $rencontre->id;
    });
})->filter(function ($arbitre){
    return $arbitre->divisions->contains('categorie_compet_id', 1);
})->filter(function($arbitre) use ($rencontre){
    return ! $arbitre->rencontreOfficiels->contains('dt_rencontre' , $rencontre->dt_rencontre);
});