问:
How many processors should be used with multiprocessing.Pool?
I am trying to use multiprocessing.Pool to run my code in parallel. To instantiate Pool, you have to set the number of processes. I am trying to figure out how many I should set for this. I understand this number shouldn't be more than the number of cores you have but I've seen different ways to determine what your system has available.

2 Methods:

multiprocessing.cpu_count()

len(os.sched_getaffinity(0))

I'm a little confused; what is the difference between the two and which should be implemented with Pool? I am working on a remote cluster, with the first, it outputs that there are 128 cpu, but the second gives 10.

答:
Just a couple of clarifications:

If you are submitting tasks that are 100% CPU, that is, there is no I/O or network waiting involved, then not only should the number of processes in the pool not exceed the number of cores available to you, there is no reason for it to exceed the number of tasks you will be submitting at any one time. For instance, if you were using the multiprocessing.pool.Pool.map method with an iterable containing N elements, the size of the pool should be min(N, available_cores), where the number of available cores would be given by len(os.sched_getaffinity(0)) (see the answer given by Marco Bonelli, but note that the os.sched.getaffinity method is not implemented on Windows).

However, if there is I/O and/or network waiting involved in your worker function in addition to CPU-intensive processing, you may certainly benefit by having a processing pool whose size is greater than the number of cores available to you since processes will be in a wait state at various points in processing. Depending on the mix of CPU and I/O and how the logic is arranged, the optimal solution might be to have a multithreading pool and and multiprocessing pool (whose size is based on the available cores and number of tasks) where the worker function is used with multithreading but is passed the multithreading pool to which submit calls are made for the CPU-intensive calculations.

Update

The following program show four methods of descending through a directory reading in every file ending in .py and computing some value from the retrieved text and building a list of these values. Processing has been neatly divided into functions that are I/O processing and CPU processing.

If you call function serial, then all the processing will be done serially with no multiprocessing. If you call function do_multiprocessing then multiprocessing alone will be used to complete the work using the default pool size. But that also means that all the file reading will also have a parallelization (or should I say "attempt at parallelization"?) based on that pool size, which may be a less than ideal situation, especially if you do not have a solid state drive. If you call function multithreading_and_multiprocessing, then a multithreading pool size of your choice will be used for doing the file reading processing and the multiprocessing pool for the CPU-intensive calculations. Finally there is version multiprocessing_cpu_only that when called only uses a multiprocessing pool for the CPU-intensive processing and the main process iterates through the directory submitting all the tasks to the pool. This would be somewhat equivalent to the mixed multithreading pool and multiprocessing pool example if the multithreading pool size were 1 except it is more efficient since it does not have the extra layer of submitting tasks to a multithreading queue first.

from multiprocessing.pool import ThreadPool, Pool
from pathlib import Path
import time
from functools import partial

def cpu_processing(text, increment):
    total = len(text)
    for _ in range(2_000_000):
        total += increment
    return total

def serial():
    """
    Call serial() for serial processing.
    """

    t = time.time_ns()
    results = []
    for path in Path('.').glob('**/*.py'):
        text = path.read_text(encoding='utf-8')
        results.append(cpu_processing(text, 1))
    print(f'Elapsed time = {(time.time_ns() - t) / 1_000_000_000.0} sec., #results = {len(results)}')

def process_path(path):
    text = path.read_text(encoding='utf-8')
    return cpu_processing(text, 1)

def do_multiprocessing():
    """
    Call do_multiprocessing for doing all processing with just
    a multiprocessing pool.
    """
    t = time.time_ns()
    mp_pool = Pool()
    results = mp_pool.map(process_path, Path('.').glob('**/*.py'))
    mp_pool.close()
    mp_pool.join()
    print(f'Elapsed time = {(time.time_ns() - t) / 1_000_000_000.0} sec., #results = {len(results)}')

def io_processing_parallel(mp_pool, path):
    text = path.read_text(encoding='utf-8')
    # Returns an AsyncResult instance:
    return mp_pool.apply_async(cpu_processing, args=(text, 1))

def multithreading_and_multiprocessing():
    """
    Call multithreading_and_multiprocessing to use a combination of
    multithreading and multiprocessing to have finer control over I/O concurrency.
    """
    t = time.time_ns()
    mp_pool = Pool()
    tp_pool = ThreadPool(2)
    worker = partial(io_processing_parallel, mp_pool)
    results = [async_result.get() for async_result in
               tp_pool.imap(worker, Path('.').glob('**/*.py'))]
    tp_pool.close()
    tp_pool.join()
    mp_pool.close()
    mp_pool.join()
    print(f'Elapsed time = {(time.time_ns() - t) / 1_000_000_000.0} sec., #results = {len(results)}')

def multiprocessing_cpu_only():
    """
    Call multiprocessing_cpu_only to use multiprocessing only for the
    CPU-intensive processing.
    """
    def get_texts():
        for path in Path('.').glob('**/*.py'):
            yield path.read_text(encoding='utf-8')

    t = time.time_ns()
    mp_pool = Pool()
    worker = partial(cpu_processing, increment=1)
    results = list(mp_pool.imap(worker, get_texts()))
    mp_pool.close()
    mp_pool.join()
    print(f'Elapsed time = {(time.time_ns() - t) / 1_000_000_000.0} sec., #results = {len(results)}')

if __name__ == '__main__':
    multithreading_and_multiprocessing()
```


来源: stackexchange

问:
How to show/hide @foreach statement
I have a Vuejs 3 dropdown reusable component. My problem is that the @foreach statement runs before the component loads so it causes a flash of the foreach results which is very ugly upon refresh or when the page is loading.

To demonstrate please check this gif:

My component in blade:

<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">

    <Dropdowncontent>

        <Dropdownitems href="/">
            All
        </Dropdownitems>

            @foreach ($categories as $category)
                <Dropdownitems
                    href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
                    class="{{ isset($currentCategory) && $currentCategory->is($category) ? ' selectedCategoryItem' : '' }}">
                    {{ $category->name }}
                </Dropdownitems>
            @endforeach

    </Dropdowncontent>

</Dropdown>

```
<p>I added a div to contain the @foreach statement but i don't know what to do from here. I don't want to use alpineJS as it will defeat the purpose of using Vue (I guess?).</p>
<p>I just need a way to only display this div or the @foreach statement if the component is fully loaded or if the button is pressed or something like that. Any ideas?</p>
<p>-- EDIT --</p>
<p>I tried to hide the links in my 'dropdownitems' vue component and set the default value to false. The links are now hidden but still the blade @foreach statement echoing out the results as text before the component is loaded:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>

        <slot />

</template>

<script>
export default {
    name: "Dropdownitems",
    setup() {
        const showLinks = false;

        return {
            showLinks,
        };
    },
};
</script>

<style></style></code>```

Here is a gif to show the result of that:

-- EDIT --

Here is my dropdown component:

<template>

        <slot name="toggler">
            <button
                class="flex max-h-52 w-full overflow-auto py-2 pl-3 pr-9 text-sm font-semibold lg:inline-flex lg:w-32"
            >
                {{ title }}
            </button>
        </slot>

        <slot />

</template>

```

答:
As your question, I think you have to add if condition on your dropdown component.

Your dropdown component should be like this

```<code>#dropdown.vue
<template>
    <div class="dropdown">
        <div @click="show = !show">{{title}}</div>

        <div v-if="show">
            <slot />
        </div>
    </div>
</template>
<script>
import { ref } from "vue";
export default {
  props: ["title"],
  setup(props) {
    const show = ref(false);
    return {
      show,
    };
  },
};
</script>
</code>```

Demo

---- EDIT ----

```<code>#dropdown.vue
<template>
    <div
        class="relative"
        v-click-outside="sharedState = false"
    >
        <slot name="toggler">
            <button
                class="flex max-h-52 w-full overflow-auto py-2 pl-3 pr-9 text-sm font-semibold lg:inline-flex lg:w-32"
                @click="sharedState = !sharedState"
            >
                {{ title }}
            </button>
        </slot>
        <div v-if="sharedState">
            <slot />
        </div>
    </div>
</template>

<script>
import vClickOutside from "click-outside-vue3";
import { ref, onMounted, provide } from "vue";
export default {
    name: "Dropdown",
    props: ["title"],
    directives: {
        clickOutside: vClickOutside.directive,
    },
    setup() {
        const sharedState = ref(false);

        // const showCategories = () => {
        //     sharedState.value = !sharedState.value;
        // };

        // const onClickOutside = (event) => {
        //     sharedState.value = false;
        // };

        provide("sharedState", sharedState);

        return {
            sharedState,
            //showCategories,
            //onClickOutside,
        };
    },
};
</script>

<style></style>
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to show/hide @foreach statement

Body:
I have a Vuejs 3 dropdown reusable component. My problem is that the @foreach statement runs before the component loads so it causes a flash of the foreach results which is very ugly upon refresh or when the page is loading.

To demonstrate please check this gif:

My component in blade:

<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">

    <Dropdowncontent>

        <Dropdownitems href="/">
            All
        </Dropdownitems>

            @foreach ($categories as $category)
                <Dropdownitems
                    href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
                    class="{{ isset($currentCategory) && $currentCategory->is($category) ? ' selectedCategoryItem' : '' }}">
                    {{ $category->name }}
                </Dropdownitems>
            @endforeach

    </Dropdowncontent>

</Dropdown>

I added a div to contain the @foreach statement but i don't know what to do from here. I don't want to use alpineJS as it will defeat the purpose of using Vue (I guess?).

I just need a way to only display this div or the @foreach statement if the component is fully loaded or if the button is pressed or something like that. Any ideas?

-- EDIT --

I tried to hide the links in my 'dropdownitems' vue component and set the default value to false. The links are now hidden but still the blade @foreach statement echoing out the results as text before the component is loaded:

<template>

        <slot />

</template>

Here is a gif to show the result of that:

-- EDIT --

Here is my dropdown component:

<template>

        <slot name="toggler">
            <button
                class="flex max-h-52 w-full overflow-auto py-2 pl-3 pr-9 text-sm font-semibold lg:inline-flex lg:w-32"
            >
                {{ title }}
            </button>
        </slot>

        <slot />

</template>

Body:
As your question, I think you have to add if condition on your dropdown component.

Your dropdown component should be like this

#dropdown.vue
<template>
    <div class="dropdown">
        <div @click="show = !show">{{title}}</div>

        <div v-if="show">
            <slot />
        </div>
    </div>
</template>
<script>
import { ref } from "vue";
export default {
  props: ["title"],
  setup(props) {
    const show = ref(false);
    return {
      show,
    };
  },
};
</script>

Demo

---- EDIT ----

#dropdown.vue
<template>
    <div
        class="relative"
        v-click-outside="sharedState = false"
    >
        <slot name="toggler">
            <button
                class="flex max-h-52 w-full overflow-auto py-2 pl-3 pr-9 text-sm font-semibold lg:inline-flex lg:w-32"
                @click="sharedState = !sharedState"
            >
                {{ title }}
            </button>
        </slot>
        <div v-if="sharedState">
            <slot />
        </div>
    </div>
</template>

<script>
import vClickOutside from "click-outside-vue3";
import { ref, onMounted, provide } from "vue";
export default {
    name: "Dropdown",
    props: ["title"],
    directives: {
        clickOutside: vClickOutside.directive,
    },
    setup() {
        const sharedState = ref(false);

        // const showCategories = () => {
        //     sharedState.value = !sharedState.value;
        // };

        // const onClickOutside = (event) => {
        //     sharedState.value = false;
        // };

        provide("sharedState", sharedState);

        return {
            sharedState,
            //showCategories,
            //onClickOutside,
        };
    },
};
</script>

<style></style>


问:
SpringBoot GraphQL mutation giving error No Root resolvers for query type 'Query' found
Am getting the error No Root resolvers for query type 'Query' found when using mutation in SpringBoot with GraphQL. The queries are working fine , but on adding the GraphQLMutationResolver, it is giving the error on Spring Boot startup.

Kindly advise.

.graphqls file

```<code>type Query {
    allBooks: [Book]
    getBookByIsn(isn: Int): Book
    allPublishers: [Publisher]
}

type Book {
    isn: Int
    title: String
    author: String
    publishedDate: String
    publisher: Publisher!
}

type Publisher {
    pId : Int
    publisherName: String
    address: String
}

input CreatePublisher {
    pId : Int
    publisherName: String
    address: String
}

type Mutation {
    addPublisher(input: CreatePublisher!): Publisher
}

</code>```

Mutation Resolver

```<code>@Component
public class PublisherMutation implements GraphQLMutationResolver{

    @Autowired
    private PublisherRepository publisherRepository;

    @Transactional
    public Publisher addPublisher(CreatePublisher createPublisher ) {
        Publisher publisher = new Publisher(createPublisher.getPId(), createPublisher.getPublisherName(), createPublisher.getAddress());
        publisherRepository.save(publisher);
        return publisher;

    }

}

</code>```

答: Done, solved by adding a newTypeWiring of type Mutation for Create

Body:
Am getting the error No Root resolvers for query type 'Query' found when using mutation in SpringBoot with GraphQL. The queries are working fine , but on adding the GraphQLMutationResolver, it is giving the error on Spring Boot startup.

Kindly advise.

.graphqls file

type Query {
    allBooks: [Book]
    getBookByIsn(isn: Int): Book
    allPublishers: [Publisher]
}

type Book {
    isn: Int
    title: String
    author: String
    publishedDate: String
    publisher: Publisher!
}

type Publisher {
    pId : Int
    publisherName: String
    address: String
}

input CreatePublisher {
    pId : Int
    publisherName: String
    address: String
}

type Mutation {
    addPublisher(input: CreatePublisher!): Publisher
}

Mutation Resolver

@Component
public class PublisherMutation implements GraphQLMutationResolver{

    @Autowired
    private PublisherRepository publisherRepository;

    @Transactional
    public Publisher addPublisher(CreatePublisher createPublisher ) {
        Publisher publisher = new Publisher(createPublisher.getPId(), createPublisher.getPublisherName(), createPublisher.getAddress());
        publisherRepository.save(publisher);
        return publisher;

    }

}


问:
Archunit check method calls
I have a class that has three methods that shouldn't be called from certain classes.

How can I check this with Archunit?

So for example

```<code>public class Foo {

   public void method1() {
   }

   public void method2() {
   }

   public void method3() {
   }
}
</code>```

method1 and method2 should only be called by classes Bar1 and Bar2.

答:
I have a very similar requirement and came up with this:

```<code>@ArchTest
    public static final ArchRule rule = noClasses()
            .that(not(name(Bar1.class.getName()))
                          .and(not(name(Bar2.class.getName()))))
            .should().callMethodWhere(target(nameMatching("method1"))
                                              .and(target(owner(assignableTo(Foo.class)))))
            .orShould().callMethodWhere(target(nameMatching("method2"))
                                              .and(target(owner(assignableTo(Foo.class)))));
</code>```

I have not tested it, but should be close I think.

EDIT: imports are:

```<code>import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.base.DescribedPredicate.not;
import static com.tngtech.archunit.core.domain.JavaCall.Predicates.target;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.assignableTo;
import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.name;
import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.nameMatching;
import static com.tngtech.archunit.core.domain.properties.HasOwner.Predicates.With.owner;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
</code>```

Title: Archunit check method calls

Body:
I have a class that has three methods that shouldn't be called from certain classes.

How can I check this with Archunit?

So for example

public class Foo {

   public void method1() {
   }

   public void method2() {
   }

   public void method3() {
   }
}

method1 and method2 should only be called by classes Bar1 and Bar2.

Body:
I have a very similar requirement and came up with this:

@ArchTest
    public static final ArchRule rule = noClasses()
            .that(not(name(Bar1.class.getName()))
                          .and(not(name(Bar2.class.getName()))))
            .should().callMethodWhere(target(nameMatching("method1"))
                                              .and(target(owner(assignableTo(Foo.class)))))
            .orShould().callMethodWhere(target(nameMatching("method2"))
                                              .and(target(owner(assignableTo(Foo.class)))));

I have not tested it, but should be close I think.

EDIT: imports are:

import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.base.DescribedPredicate.not;
import static com.tngtech.archunit.core.domain.JavaCall.Predicates.target;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.assignableTo;
import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.name;
import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.nameMatching;
import static com.tngtech.archunit.core.domain.properties.HasOwner.Predicates.With.owner;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;


问:
How can I reinstall a system PL/SQL package in Oracle?
I have noticed that if someone overwrites or deletes a system package you cannot recover the initial code.  In my case, I have lost DBMS_OUTPUT package. Does anyone knows how to reinstall it ?</p>

答: The package is created with the scripts dbmsotpt.sql (package spec) and then prvtotpt.plb (package body), though I have never executed these scripts directly. The scripts can be found under /rdbms/admin.</p>


问:
Error installing specific python packages in jupyter notebook?
i've been trying to import specfic python packages in jupyter, so far
!pip install
has worked for both numpy and sklearn, however when doing the same for pandas and matplotlib it raises the following exception

```<code>> Building wheel for pillow (setup.py) ... error   ERROR: Complete
> output from command /snap/jupyter/6/bin/python -u -c 'import
> setuptools,
> tokenize;__file__='"'"'/tmp/pip-install-jprnodmm/pillow/setup.py'"'"';f=getattr(tokenize,
> '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"',
> '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))'
> bdist_wheel -d /tmp/pip-wheel-lfpgysu2 --python-tag cp37:   ERROR:
> running bdist_wheel   running build   running build_py   creating
> build   creating build/lib.linux-x86_64-3.7   creating
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImageWin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImtImagePlugin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImageFilter.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/FliImagePlugin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImageGrab.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImagePath.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/IcoImagePlugin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/BufrStubImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/MicImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageShow.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageFont.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PdfImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageTk.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/XbmImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/Hdf5StubImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageQt.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/IcnsImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/_util.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/XVThumbImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageColor.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/FontFile.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/EpsImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/__main__.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/FpxImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/CurImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PdfParser.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/McIdasImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageTransform.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/SunImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PsdImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/XpmImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/_version.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/TarIO.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PcdImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/WebPImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/DcxImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/WmfImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImageFile.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/TiffImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PyAccess.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/WalImageFile.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImageMorph.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PaletteFile.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImagePalette.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/MpegImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PcxImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/GimpPaletteFile.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/MpoImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PalmImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImageChops.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/DdsImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/FtexImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/features.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/Image.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImageMode.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PixarImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/MspImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/BdfFontFile.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/GimpGradientFile.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PpmImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/__init__.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageEnhance.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/JpegPresets.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageMath.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ExifTags.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/TgaImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageCms.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/IptcImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/FitsStubImagePlugin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/_binary.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ContainerIO.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImageOps.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/_tkinter_finder.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/PcfFontFile.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImageSequence.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/BmpImagePlugin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/GribStubImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/GdImageFile.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageDraw.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/BlpImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageStat.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/TiffTags.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/JpegImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/SpiderImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageDraw2.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/SgiImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PngImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PSDraw.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/Jpeg2KImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/GbrImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/GifImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> running egg_info   writing src/Pillow.egg-info/PKG-INFO   writing
> dependency_links to src/Pillow.egg-info/dependency_links.txt   writing
> top-level names to src/Pillow.egg-info/top_level.txt   reading
> manifest file 'src/Pillow.egg-info/SOURCES.txt'   reading manifest
> template 'MANIFEST.in'   warning: no files found matching '*.c'
> warning: no files found matching '*.h'   warning: no files found
> matching '*.sh'   warning: no previously-included files found matching
> '.appveyor.yml'   warning: no previously-included files found matching
> '.clang-format'   warning: no previously-included files found matching
> '.coveragerc'   warning: no previously-included files found matching
> '.editorconfig'   warning: no previously-included files found matching
> '.readthedocs.yml'   warning: no previously-included files found
> matching 'codecov.yml'   warning: no previously-included files
> matching '.git*' found anywhere in distribution   warning: no
> previously-included files matching '*.pyc' found anywhere in
> distribution   warning: no previously-included files matching '*.so'
> found anywhere in distribution   no previously-included directories
> found matching '.ci'   writing manifest file
> 'src/Pillow.egg-info/SOURCES.txt'   running build_ext
>
>      The headers or library files could not be found for jpeg,   a required dependency when compiling Pillow from source.
>      Please see the install instructions at:
>      https://pillow.readthedocs.io/en/latest/installation.html
>      Traceback (most recent call last):
>     File "/tmp/pip-install-jprnodmm/pillow/setup.py", line 996, in <module>
>       zip_safe=not (debug_build() or PLATFORM_MINGW),
>     File "/snap/jupyter/6/lib/python3.7/site-packages/setuptools/__init__.py",
> line 145, in setup
>       return distutils.core.setup(**attrs)
>     File "/snap/jupyter/6/lib/python3.7/distutils/core.py", line 148, in setup
>       dist.run_commands()
>     File "/snap/jupyter/6/lib/python3.7/distutils/dist.py", line 966, in run_commands
>       self.run_command(cmd)
>     File "/snap/jupyter/6/lib/python3.7/distutils/dist.py", line 985, in run_command
>       cmd_obj.run()
>     File "/snap/jupyter/6/lib/python3.7/site-packages/wheel/bdist_wheel.py",
> line 192, in run
>       self.run_command('build')
>     File "/snap/jupyter/6/lib/python3.7/distutils/cmd.py", line 313, in run_command
>       self.distribution.run_command(command)
>     File "/snap/jupyter/6/lib/python3.7/distutils/dist.py", line 985, in run_command
>       cmd_obj.run()
>     File "/snap/jupyter/6/lib/python3.7/distutils/command/build.py", line 135, in run
>       self.run_command(cmd_name)
>     File "/snap/jupyter/6/lib/python3.7/distutils/cmd.py", line 313, in run_command
>       self.distribution.run_command(command)
>     File "/snap/jupyter/6/lib/python3.7/distutils/dist.py", line 985, in run_command
>       cmd_obj.run()
>     File "/snap/jupyter/6/lib/python3.7/site-packages/setuptools/command/build_ext.py",
> line 78, in run
>       _build_ext.run(self)
>     File "/snap/jupyter/6/lib/python3.7/distutils/command/build_ext.py", line
> 340, in run
>       self.build_extensions()
>     File "/tmp/pip-install-jprnodmm/pillow/setup.py", line 804, in build_extensions
>       raise RequiredDependencyException(f)   __main__.RequiredDependencyException: jpeg
>      During handling of the above exception, another exception occurred:
>      Traceback (most recent call last):
>     File "<string>", line 1, in <module>
>     File "/tmp/pip-install-jprnodmm/pillow/setup.py", line 1009, in <module>
>       raise RequiredDependencyException(msg)   __main__.RequiredDependencyException:
>      The headers or library files could not be found for jpeg,   a required dependency when compiling Pillow from source.
>      Please see the install instructions at:
>      https://pillow.readthedocs.io/en/latest/installation.html
>
>      ----------------------------------------   ERROR: Failed building wheel for pillow   Running setup.py clean for pillow
</code>```

any idea why these two specific packages aren't installing properly with pip? im on ubuntu linux.

答:
Those packages have specific build dependencies that are not currently available on your system:

The headers or library files could not be found for jpeg,   a required dependency when compiling Pillow from source.

From the errors, it looks like you need to install at least the libjpeg-dev package:

```<code># apt update
# apt install libjpeg-dev
</code>```

You may discover additional dependencies you'll need to satisfy before the binary components of the package will compile successfully.

Body:
i've been trying to import specfic python packages in jupyter, so far
!pip install
has worked for both numpy and sklearn, however when doing the same for pandas and matplotlib it raises the following exception

> Building wheel for pillow (setup.py) ... error   ERROR: Complete
> output from command /snap/jupyter/6/bin/python -u -c 'import
> setuptools,
> tokenize;__file__='"'"'/tmp/pip-install-jprnodmm/pillow/setup.py'"'"';f=getattr(tokenize,
> '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"',
> '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))'
> bdist_wheel -d /tmp/pip-wheel-lfpgysu2 --python-tag cp37:   ERROR:
> running bdist_wheel   running build   running build_py   creating
> build   creating build/lib.linux-x86_64-3.7   creating
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImageWin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImtImagePlugin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImageFilter.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/FliImagePlugin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImageGrab.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImagePath.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/IcoImagePlugin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/BufrStubImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/MicImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageShow.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageFont.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PdfImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageTk.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/XbmImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/Hdf5StubImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageQt.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/IcnsImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/_util.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/XVThumbImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageColor.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/FontFile.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/EpsImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/__main__.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/FpxImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/CurImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PdfParser.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/McIdasImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageTransform.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/SunImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PsdImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/XpmImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/_version.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/TarIO.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PcdImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/WebPImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/DcxImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/WmfImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImageFile.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/TiffImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PyAccess.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/WalImageFile.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImageMorph.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PaletteFile.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImagePalette.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/MpegImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PcxImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/GimpPaletteFile.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/MpoImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PalmImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImageChops.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/DdsImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/FtexImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/features.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/Image.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/ImageMode.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/PixarImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/MspImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/BdfFontFile.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/GimpGradientFile.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PpmImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/__init__.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageEnhance.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/JpegPresets.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageMath.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ExifTags.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/TgaImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageCms.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/IptcImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/FitsStubImagePlugin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/_binary.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ContainerIO.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImageOps.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/_tkinter_finder.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/PcfFontFile.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/ImageSequence.py ->
> build/lib.linux-x86_64-3.7/PIL   copying src/PIL/BmpImagePlugin.py ->
> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/GribStubImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/GdImageFile.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageDraw.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/BlpImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageStat.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/TiffTags.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/JpegImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/SpiderImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/ImageDraw2.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/SgiImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PngImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/PSDraw.py -> build/lib.linux-x86_64-3.7/PIL   copying
> src/PIL/Jpeg2KImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/GbrImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> copying src/PIL/GifImagePlugin.py -> build/lib.linux-x86_64-3.7/PIL
> running egg_info   writing src/Pillow.egg-info/PKG-INFO   writing
> dependency_links to src/Pillow.egg-info/dependency_links.txt   writing
> top-level names to src/Pillow.egg-info/top_level.txt   reading
> manifest file 'src/Pillow.egg-info/SOURCES.txt'   reading manifest
> template 'MANIFEST.in'   warning: no files found matching '*.c'
> warning: no files found matching '*.h'   warning: no files found
> matching '*.sh'   warning: no previously-included files found matching
> '.appveyor.yml'   warning: no previously-included files found matching
> '.clang-format'   warning: no previously-included files found matching
> '.coveragerc'   warning: no previously-included files found matching
> '.editorconfig'   warning: no previously-included files found matching
> '.readthedocs.yml'   warning: no previously-included files found
> matching 'codecov.yml'   warning: no previously-included files
> matching '.git*' found anywhere in distribution   warning: no
> previously-included files matching '*.pyc' found anywhere in
> distribution   warning: no previously-included files matching '*.so'
> found anywhere in distribution   no previously-included directories
> found matching '.ci'   writing manifest file
> 'src/Pillow.egg-info/SOURCES.txt'   running build_ext
>
>      The headers or library files could not be found for jpeg,   a required dependency when compiling Pillow from source.
>      Please see the install instructions at:
>      https://pillow.readthedocs.io/en/latest/installation.html
>      Traceback (most recent call last):
>     File "/tmp/pip-install-jprnodmm/pillow/setup.py", line 996, in <module>
>       zip_safe=not (debug_build() or PLATFORM_MINGW),
>     File "/snap/jupyter/6/lib/python3.7/site-packages/setuptools/__init__.py",
> line 145, in setup
>       return distutils.core.setup(**attrs)
>     File "/snap/jupyter/6/lib/python3.7/distutils/core.py", line 148, in setup
>       dist.run_commands()
>     File "/snap/jupyter/6/lib/python3.7/distutils/dist.py", line 966, in run_commands
>       self.run_command(cmd)
>     File "/snap/jupyter/6/lib/python3.7/distutils/dist.py", line 985, in run_command
>       cmd_obj.run()
>     File "/snap/jupyter/6/lib/python3.7/site-packages/wheel/bdist_wheel.py",
> line 192, in run
>       self.run_command('build')
>     File "/snap/jupyter/6/lib/python3.7/distutils/cmd.py", line 313, in run_command
>       self.distribution.run_command(command)
>     File "/snap/jupyter/6/lib/python3.7/distutils/dist.py", line 985, in run_command
>       cmd_obj.run()
>     File "/snap/jupyter/6/lib/python3.7/distutils/command/build.py", line 135, in run
>       self.run_command(cmd_name)
>     File "/snap/jupyter/6/lib/python3.7/distutils/cmd.py", line 313, in run_command
>       self.distribution.run_command(command)
>     File "/snap/jupyter/6/lib/python3.7/distutils/dist.py", line 985, in run_command
>       cmd_obj.run()
>     File "/snap/jupyter/6/lib/python3.7/site-packages/setuptools/command/build_ext.py",
> line 78, in run
>       _build_ext.run(self)
>     File "/snap/jupyter/6/lib/python3.7/distutils/command/build_ext.py", line
> 340, in run
>       self.build_extensions()
>     File "/tmp/pip-install-jprnodmm/pillow/setup.py", line 804, in build_extensions
>       raise RequiredDependencyException(f)   __main__.RequiredDependencyException: jpeg
>      During handling of the above exception, another exception occurred:
>      Traceback (most recent call last):
>     File "<string>", line 1, in <module>
>     File "/tmp/pip-install-jprnodmm/pillow/setup.py", line 1009, in <module>
>       raise RequiredDependencyException(msg)   __main__.RequiredDependencyException:
>      The headers or library files could not be found for jpeg,   a required dependency when compiling Pillow from source.
>      Please see the install instructions at:
>      https://pillow.readthedocs.io/en/latest/installation.html
>
>      ----------------------------------------   ERROR: Failed building wheel for pillow   Running setup.py clean for pillow

any idea why these two specific packages aren't installing properly with pip? im on ubuntu linux.

Body:
Those packages have specific build dependencies that are not currently available on your system:

The headers or library files could not be found for jpeg,   a required dependency when compiling Pillow from source.

From the errors, it looks like you need to install at least the libjpeg-dev package:

# apt update
# apt install libjpeg-dev

You may discover additional dependencies you'll need to satisfy before the binary components of the package will compile successfully.


问:
Multi job pipeline always checks out same commit?
I have defined a multi job azure pipeline where every job needs to clone and checkout the source git repository. Some of these jobs can take a while so I am wondering if every job always clones and checks out the momentary HEAD version/commit of the Git branch or the pipeline trigger commit is remembered by the pipeline and then used for every job in order to have a consistent pipeline run.

I am pretty sure resp. can only hope the 2nd to be the case (and never saw anything else) but I am wondering if someone can point me to some Azure docs that officially confirm it.

答:
When a pipeline is queued the ref is set. All jobs in the pipeline will checkout that reference. It's one of the reasons why the agent checks out the ref specifically and leaves the repo in detached HEAD state.

I can't find a doc that explicitly explains this, but that's how it works.


问:
javascript toggle to show/hide div
I have a javascript toggle function:

```<code><script type="text/javascript">
    function toggle(layer) {
    var d = document.getElementById(layer);
    d.style.display = (d.style.display == 'none') ? '' : 'none';
    }
    </script>
</code>```

What this does is:

I have a few links on page and on click of these links it shows / hides the respective DIV section associated with it..

In the following two links it opens and closes div section named stusearch & facsearch

```<code><a href="javascript:toggle('stusearch')" ><b>Student Manager</b></a>
<a href="javascript:toggle('facsearch')" ><b>Faculty Manager</b></a>
</code>```

This works well except that, i would like to hide the previous shown toggle when a new toggle link is clicked, at the moment the previous one remains open, and the new one opens up below it.

答:
Here is a jQuery solution in case you ever decide to implement a library:

the JavaScript:

```<code>function toggle(layer) {
    $('.toggleableSearch').hide();
    $(layer).show();
}
</code>```

the html:

```<code><a href="javascript:toggle('stusearch')" ><b>Student Manager</b></a>
<a href="javascript:toggle('facsearch')" ><b>Faculty Manager</b></a>

<div id="stusearch" class="toggleableSearch"></div>
<div id="facsearch" class="toggleableSearch"></div>
</code>```

ContentLicense: CC BY-SA 3.0

Title: javascript toggle to show/hide div

Body:
I have a javascript toggle function:

What this does is:

I have a few links on page and on click of these links it shows / hides the respective DIV section associated with it..

In the following two links it opens and closes div section named stusearch & facsearch

Student Manager
Faculty Manager

This works well except that, i would like to hide the previous shown toggle when a new toggle link is clicked, at the moment the previous one remains open, and the new one opens up below it.

Body:
Here is a jQuery solution in case you ever decide to implement a library:

the JavaScript:

function toggle(layer) {
    $('.toggleableSearch').hide();
    $(layer).show();
}

the html:

<a href="javascript:toggle('stusearch')" ><b>Student Manager</b></a>
<a href="javascript:toggle('facsearch')" ><b>Faculty Manager</b></a>

<div id="stusearch" class="toggleableSearch"></div>
<div id="facsearch" class="toggleableSearch"></div>


问:
NUnit async task fails "Method has non-void return value, but no result is expected"
I'm running unit tests in ReSharper with NUnit 3.10.

I'm getting this error when doing a simple async test:

Method has non-void return value, but no result is expected

My test is literally:

```<code>[Test]
public async Task Nothing()
{
    await Task.Delay(100);
}
</code>```

It says in the documentation that this is in fact the correct way to run async tests.

答: For me the issues was that instead of using a NuGet package, the references were to a DLL that's compiled targeting .NET Framework 3.5. Using a NuGet package of NUnit fixed it.</p>

Body:
I'm running unit tests in ReSharper with NUnit 3.10.

I'm getting this error when doing a simple async test:

Method has non-void return value, but no result is expected

My test is literally:

[Test]
public async Task Nothing()
{
    await Task.Delay(100);
}

It says in the documentation that this is in fact the correct way to run async tests.


问:
How to check if a Storyboard exists in a specific NSBundle
I'm making an app that makes use of a framework that I'm creating.

The framework contains storyboards but in some cases the project making use of the framework will need to override the storyboard by providing a new one.

So my goal is to check if a storyboard with a given name exists in [NSBundle mainBundle], if not then I will get the base version from my framework.

I have tried getting the storyboard from the main bundle and checking for the result being nil but it throws an exception if it can't find it. So I then tried to catch the exception and then load the storyboard from the framework. This does work but it feels dirty and it could well hit the performance of my app.

I have also tried pathForResource in the bundle:

```<code>if([[NSBundle mainBundle] pathForResource:name ofType:@"storyboard"] != nil) {

}
</code>```

But this never finds the storyboard.

Does anyone know of any other way that I can check if a storyboard exists in a specific bundle?

答:
Swift:

```<code>if Bundle.main.path(forResource: storyboardName, ofType: "storyboardc") != nil
{
   //The storyboard exists
}
</code>```

Body:
I'm making an app that makes use of a framework that I'm creating.

The framework contains storyboards but in some cases the project making use of the framework will need to override the storyboard by providing a new one.

So my goal is to check if a storyboard with a given name exists in [NSBundle mainBundle], if not then I will get the base version from my framework.

I have tried getting the storyboard from the main bundle and checking for the result being nil but it throws an exception if it can't find it. So I then tried to catch the exception and then load the storyboard from the framework. This does work but it feels dirty and it could well hit the performance of my app.

I have also tried pathForResource in the bundle:

if([[NSBundle mainBundle] pathForResource:name ofType:@"storyboard"] != nil) {

}

But this never finds the storyboard.

Does anyone know of any other way that I can check if a storyboard exists in a specific bundle?

Body:
Swift:

if Bundle.main.path(forResource: storyboardName, ofType: "storyboardc") != nil
{
   //The storyboard exists
}


问:
Handle PostgreSQL transaction errors in GDALVectorTranslate
In c++ I'm using the GDAL library for importing geo-spatial files into Postgres/PostGIS.

The GDAL library will create a table in the Postgres database and insert the data. But I can't figure out how to handle errors during the inserting of data.

I'm using GDALVectorTranslate https://gdal.org/api/gdal_utils.html#gdal__utils_8h_1aa176ae667bc857ab9c6016dbe62166eb

If an Postgres error occurs the error text will be outputted and the program continues to run. I would like to handle these Postgres errors.

An error could be:

```<code>ERROR 1: INSERT command for new feature failed.
ERROR:  invalid byte sequence for encoding "UTF8": 0xe5 0x20 0x46
</code>```

For now I let my program count the rows in the destination table and if zero then assume error. But that doesn't work if appending to an existing table.

    auto *dst = (GDALDataset *) GDALVectorTranslate(nullptr, pgDs, 1, &sourceDs, opt, &bUsageError);

    if (dst == nullptr) {
        std::cout << "ERROR! Couldn't create table" << std::endl;
        return FALSE;
    } else {
        OGRLayer *layer = dst->GetLayerByName(altName);
        // Here the rows are counted
        if (layer->GetFeatureCount() == 0) {
            std::cout << "ERROR! Insert failed" << std::endl;
            return FALSE;
        }
        std::cout << "   Imported";
        return TRUE;
    }
```

答:
You can register your own error handler to log and count the underlying errors:</p>
```<code>struct {/*members for handling errors*/} ctx;
static void myErrorHandler(CPLErr e, CPLErrorNum n, const char* msg) {
   ctx *myctx = (ctx*)CPLGetErrorHandlerUserData();
   /* do something with ctx to log and increment error count */
}

int myTranslateFunc() {
   ctx myctx; //+initialization
   CPLPushErrorHandlerEx(&myErrorHandler,&myctx);
   auto *dst = (GDALDataset *) GDALVectorTranslate(nullptr, pgDs, 1, &sourceDs, opt, &bUsageError);
   CPLPopErrorHandler();
   //inspect myctx for potential errors
}

</code>```

Body:
In c++ I'm using the GDAL library for importing geo-spatial files into Postgres/PostGIS.

The GDAL library will create a table in the Postgres database and insert the data. But I can't figure out how to handle errors during the inserting of data.

I'm using GDALVectorTranslate https://gdal.org/api/gdal_utils.html#gdal__utils_8h_1aa176ae667bc857ab9c6016dbe62166eb

If an Postgres error occurs the error text will be outputted and the program continues to run. I would like to handle these Postgres errors.

An error could be:

ERROR 1: INSERT command for new feature failed.
ERROR:  invalid byte sequence for encoding "UTF8": 0xe5 0x20 0x46

For now I let my program count the rows in the destination table and if zero then assume error. But that doesn't work if appending to an existing table.

    auto *dst = (GDALDataset *) GDALVectorTranslate(nullptr, pgDs, 1, &sourceDs, opt, &bUsageError);

    if (dst == nullptr) {
        std::cout << "ERROR! Couldn't create table" << std::endl;
        return FALSE;
    } else {
        OGRLayer *layer = dst->GetLayerByName(altName);
        // Here the rows are counted
        if (layer->GetFeatureCount() == 0) {
            std::cout << "ERROR! Insert failed" << std::endl;
            return FALSE;
        }
        std::cout << "   Imported";
        return TRUE;
    }

Body:
You can register your own error handler to log and count the underlying errors:

struct {/*members for handling errors*/} ctx;
static void myErrorHandler(CPLErr e, CPLErrorNum n, const char* msg) {
   ctx *myctx = (ctx*)CPLGetErrorHandlerUserData();
   /* do something with ctx to log and increment error count */
}

int myTranslateFunc() {
   ctx myctx; //+initialization
   CPLPushErrorHandlerEx(&myErrorHandler,&myctx);
   auto *dst = (GDALDataset *) GDALVectorTranslate(nullptr, pgDs, 1, &sourceDs, opt, &bUsageError);
   CPLPopErrorHandler();
   //inspect myctx for potential errors
}


问:
Why is SUM() and COUNT() returning different values?
I have two near identical queries and I'm trying to understand why they're returning different results. I would like to produce a table with a user_id and a food_orders column showing how many items each user has ordered. These queries produce this table but calculate different results in the food_orders column in some rows.

My questions are why is this and which should I use?

A simplified version of my queries are below.

Query 1 (using COUNT):

```<code>WITH order_made AS (
    SELECT restaurant_id,
           count(
                   CASE
                       WHEN item LIKE '%_angus' then 1
                       WHEN item LIKE '%_organic' then 1
                       WHEN item LIKE '%_lean' then 1
                       ELSE 0
                       END)
               AS burgers
    FROM mcdonalds.specialist_orders
    GROUP BY mcdonalds.specialist_orders.user_id
    UNION ALL
    SELECT restaurant_id,
           COUNT(
                   CASE
                       WHEN item LIKE 'salad%' THEN 1
                       WHEN item LIKE 'tomato%' THEN 1
                       WHEN item LIKE 'potatoes%' THEN 1
                       ELSE 0
                       END)
               AS vegetables
    FROM public.bulk_orders
    GROUP BY public.bulk_orders.user_id),
</code>```

Query 2 (using SUM):

```<code>WITH orders_made AS (
    SELECT user_id, SUM(food_orders) AS food_orders
    FROM (SELECT user_id,
                   CASE
                       WHEN item LIKE '%_angus' then 1
                       WHEN item LIKE '%_organic' then 1
                       WHEN item LIKE '%_lean' then 1
                       ELSE 0
                       END
               AS food_orders
    FROM mcdonalds.specialist_orders
    UNION ALL
    SELECT user_id,
                   CASE
                       WHEN item LIKE 'salad%' THEN 1
                       WHEN item LIKE 'tomato%' THEN 1
                       WHEN item LIKE 'potatoes%' THEN 1
                       ELSE 0
                       END
               AS food_orders
    FROM public.bulk_orders
    GROUP BY user_id)
</code>```

答:
Because COUNT function count when the value isn't NULL (include 0) if you don't want to count, need to let CASE WHEN return NULL

so if you remove ELSE 0 from your CASE WHEN or use ELSE NULL to instead, that result would be as same as SUM

```<code>WITH order_made AS (
    SELECT restaurant_id,
           count(
                   CASE
                       WHEN item LIKE '%_angus' then 1
                       WHEN item LIKE '%_organic' then 1
                       WHEN item LIKE '%_lean' then 1
                       END)
               AS burgers
    FROM mcdonalds.specialist_orders
    GROUP BY mcdonalds.specialist_orders.user_id
    UNION ALL
    SELECT restaurant_id,
           COUNT(
                   CASE
                       WHEN item LIKE 'salad%' THEN 1
                       WHEN item LIKE 'tomato%' THEN 1
                       WHEN item LIKE 'potatoes%' THEN 1
                       END)
               AS vegetables
    FROM public.bulk_orders
    GROUP BY public.bulk_orders.user_id),
</code>```

Body:
I have two near identical queries and I'm trying to understand why they're returning different results. I would like to produce a table with a user_id and a food_orders column showing how many items each user has ordered. These queries produce this table but calculate different results in the food_orders column in some rows.

My questions are why is this and which should I use?

A simplified version of my queries are below.

Query 1 (using COUNT):

WITH order_made AS (
    SELECT restaurant_id,
           count(
                   CASE
                       WHEN item LIKE '%_angus' then 1
                       WHEN item LIKE '%_organic' then 1
                       WHEN item LIKE '%_lean' then 1
                       ELSE 0
                       END)
               AS burgers
    FROM mcdonalds.specialist_orders
    GROUP BY mcdonalds.specialist_orders.user_id
    UNION ALL
    SELECT restaurant_id,
           COUNT(
                   CASE
                       WHEN item LIKE 'salad%' THEN 1
                       WHEN item LIKE 'tomato%' THEN 1
                       WHEN item LIKE 'potatoes%' THEN 1
                       ELSE 0
                       END)
               AS vegetables
    FROM public.bulk_orders
    GROUP BY public.bulk_orders.user_id),

Query 2 (using SUM):

WITH orders_made AS (
    SELECT user_id, SUM(food_orders) AS food_orders
    FROM (SELECT user_id,
                   CASE
                       WHEN item LIKE '%_angus' then 1
                       WHEN item LIKE '%_organic' then 1
                       WHEN item LIKE '%_lean' then 1
                       ELSE 0
                       END
               AS food_orders
    FROM mcdonalds.specialist_orders
    UNION ALL
    SELECT user_id,
                   CASE
                       WHEN item LIKE 'salad%' THEN 1
                       WHEN item LIKE 'tomato%' THEN 1
                       WHEN item LIKE 'potatoes%' THEN 1
                       ELSE 0
                       END
               AS food_orders
    FROM public.bulk_orders
    GROUP BY user_id)

Body:
Because COUNT function count when the value isn't NULL (include 0) if you don't want to count, need to let CASE WHEN return NULL

so if you remove ELSE 0 from your CASE WHEN or use ELSE NULL to instead, that result would be as same as SUM

WITH order_made AS (
    SELECT restaurant_id,
           count(
                   CASE
                       WHEN item LIKE '%_angus' then 1
                       WHEN item LIKE '%_organic' then 1
                       WHEN item LIKE '%_lean' then 1
                       END)
               AS burgers
    FROM mcdonalds.specialist_orders
    GROUP BY mcdonalds.specialist_orders.user_id
    UNION ALL
    SELECT restaurant_id,
           COUNT(
                   CASE
                       WHEN item LIKE 'salad%' THEN 1
                       WHEN item LIKE 'tomato%' THEN 1
                       WHEN item LIKE 'potatoes%' THEN 1
                       END)
               AS vegetables
    FROM public.bulk_orders
    GROUP BY public.bulk_orders.user_id),


问:
Microsoft.CppCommon.targets: The specified task executable "cmd.exe" could not be run. Because the file contains a virus
Suddenly my project has stopped to build. I don't even know where should I look to resolve the error?
What I've done I scanned my PC on viruses, added exception in Windows Defender for cmd.exe.

C:\Program Files (x86)\Microsoft Visual
Studio\2019\Enterprise\MSBuild\Microsoft\VC\v160\Microsoft.CppCommon.targets(241,5):
error MSB6003: The specified task executable "cmd.exe" could not be
run. System.ComponentModel.Win32Exception (0x80004005): Operation did
not complete successfully because the file contains a virus or
potentially unwanted software

答: In event log I found a suspicious message from RAV antivirus. The problem was in RAV Antivirus. Somehow(?) it got installed on my machine and it was blocking cmd.exe from running.


问:
Image polar transformation in R
I have a picture like this, taken with Google Street View app and cropped to the top half:

I use Gimp polar coordinates filter to obtain this new image:

I would like to do the same within R, keeping all the pixel values information.

Here I found a similar question but the results is not exactly what I need (the center of the transformation is a corner). The adjusted code (there was an issue with radians) is:

```<code># Load the image
library(png)
library(RCurl)
d <- readPNG( getBinaryURL( "http://i.stack.imgur.com/rMR3C.png" ) )
image(d)

x0 = as.vector(col(d))
y0 = as.vector(row(d))

r = sqrt( (x0^2) + (y0^2)  ) #x
a = atan(y0/x0) * 215 / (pi/2) #y
m = as.matrix(data.frame(y=a, x=r))

m = round(m)
m[m>215] = NA
m[m==0] = NA

xn = d[m]
xn = matrix(xn, 215, 215)

image(xn)
</code>```

The answer to that question expands on the issue and show a code to do a polar to cartesian transformation but I cannot do the reverse.

答:
The magick package does the job.

```<code>library(magick)

# load sample image
z <- image_read("https://i.stack.imgur.com/MYIeg.jpg")

# do polar distortion
zp <- image_distort(z, # source image
                    "Polar", # type, check availability at distort_types()
                    c(0), # coordinates, I could not understand fully but this work
                    bestfit=T # crop to the image to a square
)

plot(zp)
</code>```

Title: Image polar transformation in R

Body:
I have a picture like this, taken with Google Street View app and cropped to the top half:

I use Gimp polar coordinates filter to obtain this new image:

I would like to do the same within R, keeping all the pixel values information.

Here I found a similar question but the results is not exactly what I need (the center of the transformation is a corner). The adjusted code (there was an issue with radians) is:

# Load the image
library(png)
library(RCurl)
d <- readPNG( getBinaryURL( "http://i.stack.imgur.com/rMR3C.png" ) )
image(d)

x0 = as.vector(col(d))
y0 = as.vector(row(d))

r = sqrt( (x0^2) + (y0^2)  ) #x
a = atan(y0/x0) * 215 / (pi/2) #y
m = as.matrix(data.frame(y=a, x=r))

m = round(m)
m[m>215] = NA
m[m==0] = NA

xn = d[m]
xn = matrix(xn, 215, 215)

image(xn)

The answer to that question expands on the issue and show a code to do a polar to cartesian transformation but I cannot do the reverse.

Body:
The magick package does the job.

library(magick)

# load sample image
z <- image_read("https://i.stack.imgur.com/MYIeg.jpg")

# do polar distortion
zp <- image_distort(z, # source image
                    "Polar", # type, check availability at distort_types()
                    c(0), # coordinates, I could not understand fully but this work
                    bestfit=T # crop to the image to a square
)

plot(zp)


问:
Working with multiple processes in Ruby
Is there a module for Ruby that makes it easy to share objects between multiple processes?  I'm looking for something similar to Python's multiprocessing, which supports process-safe queues and pipes that can be shared between processes.</p>

答:
Combining DRb, which provides simple inter-process communication, with Queue or SizedQueue, which are both threadsafe queues, should give you what you need.

You may also want to check out beanstalkd which is also hosted on github

OwnerDisplayName: Readonly

ContentLicense: CC BY-SA 2.5

Title: Working with multiple processes in Ruby

OwnerDisplayName: John Douthat


问:
Why this image is not opening?
Hello there I am using the code below. The image is saved but its not opening. Can some one guide please.</p>
```<code>import librosa
import librosa.display
path='E:/Python_On_All_Dataset/testing_plot/15a02Ea.wav'
y,sr=librosa.load(path,16000)

plt.figure(figsize=(15,8))
librosa.display.waveplot(y,sr=16000)

plt.show()
plt.savefig('sample_wav.png',dpi=300)
</code>```

答: The code is correct only plt.show() should be after save command, as plt.show() flush the plot.</p>

Title: Why this image is not opening?

Body:
Hello there I am using the code below. The image is saved but its not opening. Can some one guide please.

import librosa
import librosa.display
path='E:/Python_On_All_Dataset/testing_plot/15a02Ea.wav'
y,sr=librosa.load(path,16000)

plt.figure(figsize=(15,8))
librosa.display.waveplot(y,sr=16000)

plt.show()
plt.savefig('sample_wav.png',dpi=300)


问:
Button onlick show alert box
I have a modal and after pressing the password update button, the modal should close and an alert box should appear on my homepage. however, the alert box will not appear when the page is first opened. how can I do it? Do you have any examples you can share?</p>

答:
If you are using the alerts provided by the browser, you have to add a EventListener to your button like:

yourCloseButton.addEventListener("click", () => {
  alert("The modal has been closed!");
});
```

Title: Button onlick show alert box


问:
Because app requires SDK version >=2.15.1 <3.0.0, version solving failed
Can anyone tell me why am I getting this error?

```<code>The current Dart SDK version is 2.12.0.

Because app requires SDK version >=2.15.1 <3.0.0, version solving failed.
pub get failed (1; Because app requires SDK version >=2.15.1 <3.0.0, version solving failed.)
</code>```

here is my flutter --version

```<code>Flutter 2.10.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision db747aa133 (2 days ago) • 2022-02-09 13:57:35 -0600
Engine • revision ab46186b24
Tools • Dart 2.16.1 • DevTools 2.9.2

</code>```

答: I think you should update dart version, can upgrade dart version this link</p>

Body:
Can anyone tell me why am I getting this error?

The current Dart SDK version is 2.12.0.

Because app requires SDK version >=2.15.1 <3.0.0, version solving failed.
pub get failed (1; Because app requires SDK version >=2.15.1 <3.0.0, version solving failed.)

here is my flutter --version

Flutter 2.10.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision db747aa133 (2 days ago) • 2022-02-09 13:57:35 -0600
Engine • revision ab46186b24
Tools • Dart 2.16.1 • DevTools 2.9.2


问:
Add a custom header per rule on Kubernetes Ingress with Istio
I have created a Kubernetes ingress on my cluster where it uses Istio as an ingress controller. I don't want to use the gateway and virtual service provided by Istio and would like to set this up with the good old Kubernetes ingress.

What I am having a hard time with is configuring a custom header to this ingress. I know with:

Nginx ingress controller, I can use nginx.ingress.kubernetes.io/configuration-snippet: 'more_set_input_headers "foo: bar";'

Traefik, I can use ingress.kubernetes.io/custom-request-headers: "foo: bar"

What is the corresponding annotation while using Istio? or is that even possible while using Istio this way?

答:
Not really possible. To add a custom header to the request, you have to add

headers:
  request:
    add:
      custom-header: value
```

block to a VirtualService.

There are no Resource Annotations in Istio that control this behaviour, like with nginx or Traefik.

Body:
Not really possible. To add a custom header to the request, you have to add

headers:
  request:
    add:
      custom-header: value

block to a VirtualService.

There are no Resource Annotations in Istio that control this behaviour, like with nginx or Traefik.


问:
IE: Choose a digital certificate from a blank, empty list
I've created a web application that I've hosted with IIS 7 on a Windows Server 2008 machine.  I've loaded a security certificate for secure.xxxxx.com.

IIS 7 Server Certificates http://img401.imageshack.us/img401/324/certxx6.gif

When I browse to the web site with Microsoft Internet Explorer, I get this prompt:

Choose a digital certificate

  Identification

  The website you want to view requests identification.

  Please choose a certificate.

There are no certificates.  It's an empty, blank list.

If I click either OK or Cancel, then the page loads just fine.  There's no warning or other indication from Internet Explorer that there is a security issue.

Microsoft Internet Explorer SSL Security Certificate Website Identification http://img207.imageshack.us/img207/8265/ie2yr5.gif

The Apple Safari browser won't display the page at all.

Safari can't open the page.

  Safari can't open the page xxxxx because
  it couldn't establish a secure connection
  to the server xxxxx.

Apple Safari can't open the page http://img80.imageshack.us/img80/2899/safka3.gif

Both Mozilla Firefox and Google Chrome load the web site perfectly with no hassles.

Mozilla Firefox SSL Security Certificate http://img158.imageshack.us/img158/6833/foxsk4.gif

Google Chrome SSL Security Certificate http://img367.imageshack.us/img367/7928/chrsx2.gif

Why might Microsoft Internet Explorer and Apple Safari fail to load my web site properly?

答: A SSL connection where the server presents a certificate and the user is required to present a certificate is considered 2-way SSL. Governments and businesses are the ones who usually use it the most.</p>

OwnerDisplayName: Zack


问:
How to play audio through earpiece in android 12?
I am developing a voice call app for android using PeerJS and WebView. And I want the audio to play through the earpiece. Here is my code,

```<code>private fun initAudio(){
  am = getSystemService(AUDIO_SERVICE) as AudioManager
  volumeControlStream = AudioManager.STREAM_VOICE_CALL
  am.mode = AudioManager.MODE_IN_COMMUNICATION
  am.isSpeakerphoneOn = false//<= not working in android 12
}

private fun toggleSpeakerMode(){
  am.isSpeakerphoneOn = !am.isSpeakerphoneOn // <= final value is always true in android 12
}
</code>```

The above code works fine on older versions of android, but not in android 12 (emulator).
am.isSpeakerphoneOn is always true in android 12. Am I doing something wrong here? Or is it a bug in the emulator?

答:
there is a new API call in Android 12/S/API 31, setCommunicationDevice(AudioDeviceInfo). for switching between speaker an built-in earpiece now we can use:

```<code>ArrayList<Integer> targetTypes = new ArrayList<>();
if (earpieceMode) {
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE);
} else { // play out loud
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
}
// more targetTypes may be added in some cases
// set up will pick and first available, so order matters

List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
outer:
for (Integer targetType : targetTypes) {
    for (AudioDeviceInfo device : devices) {
        if (device.getType() == targetType) {
            boolean result = audioManager.setCommunicationDevice(device);
            Log.i("AUDIO_MANAGER", "setCommunicationDevice type:" + targetType + " result:" + result);
            if (result) break outer;
        }
    }
}
</code>```

mode change isn't needed (but for voip calls is strongly suggested) and my streams are AudioManager.STREAM_VOICE_CALL type (where applicable)

Body:
I am developing a voice call app for android using PeerJS and WebView. And I want the audio to play through the earpiece. Here is my code,

private fun initAudio(){
  am = getSystemService(AUDIO_SERVICE) as AudioManager
  volumeControlStream = AudioManager.STREAM_VOICE_CALL
  am.mode = AudioManager.MODE_IN_COMMUNICATION
  am.isSpeakerphoneOn = false//<= not working in android 12
}

private fun toggleSpeakerMode(){
  am.isSpeakerphoneOn = !am.isSpeakerphoneOn // <= final value is always true in android 12
}

The above code works fine on older versions of android, but not in android 12 (emulator).
am.isSpeakerphoneOn is always true in android 12. Am I doing something wrong here? Or is it a bug in the emulator?

Body:
there is a new API call in Android 12/S/API 31, setCommunicationDevice(AudioDeviceInfo). for switching between speaker an built-in earpiece now we can use:

ArrayList<Integer> targetTypes = new ArrayList<>();
if (earpieceMode) {
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE);
} else { // play out loud
    targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
}
// more targetTypes may be added in some cases
// set up will pick and first available, so order matters

List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
outer:
for (Integer targetType : targetTypes) {
    for (AudioDeviceInfo device : devices) {
        if (device.getType() == targetType) {
            boolean result = audioManager.setCommunicationDevice(device);
            Log.i("AUDIO_MANAGER", "setCommunicationDevice type:" + targetType + " result:" + result);
            if (result) break outer;
        }
    }
}

mode change isn't needed (but for voip calls is strongly suggested) and my streams are AudioManager.STREAM_VOICE_CALL type (where applicable)


问:
How to propagate context via Kleisli?
Just trying to propagate my tracing context inside Kleisli as it was done originally in the next tutorial.

```<code>  object TraceLogger {
    def log(msg: String): Kleisli[IO, UUID, Unit] = Kleisli { traceId => IO(println(s"[$traceId] $msg")) }
  }

  trait ServiceStub {
    def request(arg: String): Kleisli[IO, UUID, _]
  }

  trait ClientStub {
    def get(arg: String): Kleisli[IO, UUID, _]
  }

  case class FirstServiceExample(clientStub: ClientStub) extends ServiceStub {
    override def request(arg: String): Kleisli[IO, UUID, _] = Kleisli { (context: UUID) =>
      val requestComputation = clientStub.get("calling second service!")
      TraceLogger.log(arg)
      requestComputation(context)
    }
  }

  case class FirstClientExample(service: FirstServiceExample) {
    def request(): IO[_] = {
      val traceId = UUID.randomUUID()
      service.request("root!").run(traceId)
    }
  }
</code>```

And now I need to run execution:

```<code> val exampleClientStub = new ClientStub() {
      override def get(arg: String): Kleisli[IO, UUID, _] = Kleisli.ask
 }

val exampleClientService = FirstServiceExample(exampleClientStub)
FirstClientExample(exampleClientService).request().unsafeRunSync()
</code>```

But, unfortunately, I don't see any logs here. Would you kindly help me to find an issue?

答:
TraceLogger.log(arg) This returns an IO which is just a description of computation; it is doing nothing.

And since you just leave that value alone it is equivalent to just having a 1 in the middle of your code, it is simply discarded.

You need to chain your IOs together to create new IOs that represent "do this and then do that", that is basically what the flatMap method does.

Kleisli { (context: UUID) =>
  val requestComputation = clientStub.get("calling second service!")
  TraceLogger.log(arg)(context) >> // >> is equivalent to flatMap(_ => )
  requestComputation(context)
}
```

(There is probably a better way to write this, I am not used to Kliesli)

Fabio's series on "Programas as Values" may be very useful: https://systemfw.org/archive.html

Title: How to propagate context via Kleisli?

Body:
Just trying to propagate my tracing context inside Kleisli as it was done originally in the next tutorial.

  object TraceLogger {
    def log(msg: String): Kleisli[IO, UUID, Unit] = Kleisli { traceId => IO(println(s"[$traceId] $msg")) }
  }

  trait ServiceStub {
    def request(arg: String): Kleisli[IO, UUID, _]
  }

  trait ClientStub {
    def get(arg: String): Kleisli[IO, UUID, _]
  }

  case class FirstServiceExample(clientStub: ClientStub) extends ServiceStub {
    override def request(arg: String): Kleisli[IO, UUID, _] = Kleisli { (context: UUID) =>
      val requestComputation = clientStub.get("calling second service!")
      TraceLogger.log(arg)
      requestComputation(context)
    }
  }

  case class FirstClientExample(service: FirstServiceExample) {
    def request(): IO[_] = {
      val traceId = UUID.randomUUID()
      service.request("root!").run(traceId)
    }
  }

And now I need to run execution:

 val exampleClientStub = new ClientStub() {
      override def get(arg: String): Kleisli[IO, UUID, _] = Kleisli.ask
 }

val exampleClientService = FirstServiceExample(exampleClientStub)
FirstClientExample(exampleClientService).request().unsafeRunSync()

But, unfortunately, I don't see any logs here. Would you kindly help me to find an issue?

Body:
TraceLogger.log(arg) This returns an IO which is just a description of computation; it is doing nothing.

And since you just leave that value alone it is equivalent to just having a 1 in the middle of your code, it is simply discarded.

You need to chain your IOs together to create new IOs that represent "do this and then do that", that is basically what the flatMap method does.

Kleisli { (context: UUID) =>
  val requestComputation = clientStub.get("calling second service!")
  TraceLogger.log(arg)(context) >> // >> is equivalent to flatMap(_ => )
  requestComputation(context)
}

(There is probably a better way to write this, I am not used to Kliesli)

Fabio's series on "Programas as Values" may be very useful: https://systemfw.org/archive.html


问:
How to know if two arrays have the same values
I have these two arrays: one is filled with information from an ajax request and another stores the buttons the user clicks on. I use this code (I filled with sample numbers):

```<code>var array1 = [2, 4];
var array2 = [4, 2]; //It cames from the user button clicks, so it might be disordered.
array1.sort(); //Sorts both Ajax and user info.
array2.sort();
if (array1==array2) {
    doSomething();
}else{
    doAnotherThing();
}
</code>```

But it always gives false, even if the two arrays are the same, but with different name. (I checked this in Chrome's JS Console). So, is there any way I could know if these two arrays contain the same? Why is it giving false? How can I know which values in the first array are not in the second?

答:
For ES6</p>
```<code>var array1 = [2, 4];
var array2 = [4, 2];

let difference = array1.filter(x => !array2.includes(x));

console.log("equals", difference?.length != 0 ? false : true)
</code>```

Body:
I have these two arrays: one is filled with information from an ajax request and another stores the buttons the user clicks on. I use this code (I filled with sample numbers):

var array1 = [2, 4];
var array2 = [4, 2]; //It cames from the user button clicks, so it might be disordered.
array1.sort(); //Sorts both Ajax and user info.
array2.sort();
if (array1==array2) {
    doSomething();
}else{
    doAnotherThing();
}

But it always gives false, even if the two arrays are the same, but with different name. (I checked this in Chrome's JS Console). So, is there any way I could know if these two arrays contain the same? Why is it giving false? How can I know which values in the first array are not in the second?

Body:
For ES6

var array1 = [2, 4];
var array2 = [4, 2];

let difference = array1.filter(x => !array2.includes(x));

console.log("equals", difference?.length != 0 ? false : true)


问:
multiply column values by a different constant per row
```<code>vars   x        y         z
a     0.00045   0.00065   0.0076
b     1.0       1.0       1.0
c     0.0000067 0.0000043  0.00067
</code>```

I need to multiply certain variables with a particular constant, for example a*100 and b*1000, but keep c as constant, so that it will be easier to compare the variables. How to do it?

答:
You can multiply by a dictionary after setting "vars" as the index:

```<code>df.set_index('vars').mul({'a': 100, 'b': 1000, 'c': 1}, axis=0)
</code>```

output:

```<code>                x            y           z
vars
a        0.045000     0.065000     0.76000
b     1000.000000  1000.000000  1000.00000
c        0.000007     0.000004     0.00067
</code>```

If you have many columns an only want to multiply a few you can use a Series and combine_first:

```<code>df = df.set_index('vars')

df.mul(pd.Series({'a': 100, 'b': 1000}), axis=0).combine_first(df)
</code>```

Body:
vars   x        y         z
a     0.00045   0.00065   0.0076
b     1.0       1.0       1.0
c     0.0000067 0.0000043  0.00067

I need to multiply certain variables with a particular constant, for example a*100 and b*1000, but keep c as constant, so that it will be easier to compare the variables. How to do it?

Body:
You can multiply by a dictionary after setting "vars" as the index:

df.set_index('vars').mul({'a': 100, 'b': 1000, 'c': 1}, axis=0)

output:

                x            y           z
vars
a        0.045000     0.065000     0.76000
b     1000.000000  1000.000000  1000.00000
c        0.000007     0.000004     0.00067

If you have many columns an only want to multiply a few you can use a Series and combine_first:

df = df.set_index('vars')

df.mul(pd.Series({'a': 100, 'b': 1000}), axis=0).combine_first(df)


问:
VSCode display hex values for variables in debug mode
Is VSCode able to display hex values for local variables in debug mode ? I have been searching for a way to make this happen but with no success.</p>

答:
This answer applies to GDB debugging.

For an active debug session, type the following in the debug console:

```<code>-exec set output-radix 16
</code>```

To apply this every time the debugger runs, add text "set output-radix 16" in the "setupCommands" section of launch.json

"setupCommands": [
    {
        "description": "Enable pretty-printing for gdb",
        "text": "-enable-pretty-printing",
        "ignoreFailures": true
    },
    { "text": "set output-radix 16" }
]
```

Body:
This answer applies to GDB debugging.

For an active debug session, type the following in the debug console:

-exec set output-radix 16

To apply this every time the debugger runs, add text "set output-radix 16" in the "setupCommands" section of launch.json

"setupCommands": [
    {
        "description": "Enable pretty-printing for gdb",
        "text": "-enable-pretty-printing",
        "ignoreFailures": true
    },
    { "text": "set output-radix 16" }
]


问:
Referring to columns by name in for loop
I have a loop in R that loops over columns in a dataframe las_ref for those columns where the name matches a value in a vector las_names.
As the original las_ref dataframe has rows with duplicated incidentid values, I am aiming to extract the most common value in each of the columns in las_names for each incidentid, produce a new column and use a join to produce a dataframe las_ref3 with the most common values in every row.

Structure of las_ref

```<code>incidentid incident var1
001             abc   45
002             abc   NA
002              NA   78
003             def   12
004             xyz   NA
004             xyz   10
004             abc   10
</code>```

Intended structure of las_ref3

```<code>incidentid incident var1 incident-new var1-new
001             abc   45          abc       45
002             abc   NA          abc       78
002              NA   78          abc       78
003             def   12          def       12
004             xyz   NA          xyz       10
004             xyz   10          xyz       10
004             abs   10          xyz       10
</code>```

Below is the loop I am trying to use.

```<code>las_names <- c("incident","var1")
for(i in las_names) {
  las_ref2 <- las_ref %>%
    group_by(across(c(incidentid, paste(i)))) %>%
    tally() %>%
    filter(!is.na(paste(i))) %>%
    arrange(incidentid, desc(n)) %>%
    summarize(paste(i,"-new") = first(paste(i)))
  las_ref3 <- las_ref %>%
    left_join(select(las_ref2, incidentid, paste(i,"-new")), by = c("incidentid"))
}
</code>```

Currently there seem to be two issues that I think revolve around the use of i to refer to the columns incident and var in the examples above.

The first is that the !is.na() function is not removing the NA values in the columns referred to by i, although this does not produce an error.
The second, which does produce an error, is the summarise line. I get an  unexpected '=' in error when this line is run.

Neither issue occurs when I run the code outside of the loop, specifying column names individually - the result comes out as expected. As the dataset is fairly large, I was hoping to use the loop to avoid doing each column individually.

答:
We could write your loop in the following way to make it work:

library(tidyverse)

las_ref <- tribble(~incidentid , ~incident, ~var1,
    "001",             "abc",   45,
    "002",             "abc",   NA,
    "002",              NA,     78,
    "003",             "def",   12,
    "004",             "xyz",   NA,
    "004",             "xyz",   10,
    "004",             "abc",   10
)

las_names <- c("incident","var1")

las_ref3 <- las_ref

for(i in las_names) {
  las_ref2 <- las_ref %>%
    group_by(across(c(incidentid, paste(i)))) %>%
    tally() %>%
    filter(!is.na(!! sym(paste(i)))) %>%
    arrange(incidentid, desc(n)) %>%
    summarize("{i}-new" := first(!! sym(paste(i))))
  las_ref3 <- las_ref3 %>%
    left_join(select(las_ref2, incidentid, !! sym(paste0(i,"-new"))), by = c("incidentid"))
}

las_ref3
#> # A tibble: 7 x 5
#>   incidentid incident  var1 `incident-new` `var1-new`
#>   <chr>      <chr>    <dbl> <chr>               <dbl>
#> 1 001        abc         45 abc                    45
#> 2 002        abc         NA abc                    78
#> 3 002        <NA>        78 abc                    78
#> 4 003        def         12 def                    12
#> 5 004        xyz         NA xyz                    10
#> 6 004        xyz         10 xyz                    10
#> 7 004        abc         10 xyz                    10
```
<hr />
<p>We can also use <code>purrr::map_dfc</code> within <code>mutate</code> together with <code>purrr:set_names</code>:</p>
<pre class="lang-r prettyprint-override"><code>las_ref %>%
  group_by(incidentid) %>%
  mutate(map_dfc(set_names(las_names, paste0(las_names, "-new")),
              ~ count(cur_data_all(), "{.x}" := eval(sym(.x))) %>%
                arrange(desc(n)) %>%
                slice_head() %>%
                pull(eval(sym(.x)))
  )
  )

#> # A tibble: 7 x 5
#> # Groups:   incidentid [4]
#>   incidentid incident  var1 `incident-new` `var1-new`
#>   <chr>      <chr>    <dbl> <chr>               <dbl>
#> 1 001        abc         45 abc                    45
#> 2 002        abc         NA abc                    78
#> 3 002        <NA>        78 abc                    78
#> 4 003        def         12 def                    12
#> 5 004        xyz         NA xyz                    10
#> 6 004        xyz         10 xyz                    10
#> 7 004        abc         10 xyz                    10
</code>```

I have a package on github, {dplyover}, which makes the approach above a bit simpler by using over and its .names argument:

library(dplyover) # https://github.com/TimTeaFan/dplyover

las_ref %>%
  group_by(incidentid) %>%
  mutate(over(las_names,
              ~ count(cur_data_all(), "{.x}" := eval(sym(.x))) %>%
                arrange(desc(n)) %>%
                slice_head() %>%
                pull(eval(sym(.x))),
              .names = "{x}-new")
  )

#> # A tibble: 7 x 5
#> # Groups:   incidentid [4]
#>   incidentid incident  var1 `incident-new` `var1-new`
#>   <chr>      <chr>    <dbl> <chr>               <dbl>
#> 1 001        abc         45 abc                    45
#> 2 002        abc         NA abc                    78
#> 3 002        <NA>        78 abc                    78
#> 4 003        def         12 def                    12
#> 5 004        xyz         NA xyz                    10
#> 6 004        xyz         10 xyz                    10
#> 7 004        abc         10 xyz                    10
```

Created on 2022-02-11 by the reprex package (v2.0.1)

Body:
I have a loop in R that loops over columns in a dataframe las_ref for those columns where the name matches a value in a vector las_names.
As the original las_ref dataframe has rows with duplicated incidentid values, I am aiming to extract the most common value in each of the columns in las_names for each incidentid, produce a new column and use a join to produce a dataframe las_ref3 with the most common values in every row.

Structure of las_ref

incidentid incident var1
001             abc   45
002             abc   NA
002              NA   78
003             def   12
004             xyz   NA
004             xyz   10
004             abc   10

Intended structure of las_ref3

incidentid incident var1 incident-new var1-new
001             abc   45          abc       45
002             abc   NA          abc       78
002              NA   78          abc       78
003             def   12          def       12
004             xyz   NA          xyz       10
004             xyz   10          xyz       10
004             abs   10          xyz       10

Below is the loop I am trying to use.

las_names <- c("incident","var1")
for(i in las_names) {
  las_ref2 <- las_ref %>%
    group_by(across(c(incidentid, paste(i)))) %>%
    tally() %>%
    filter(!is.na(paste(i))) %>%
    arrange(incidentid, desc(n)) %>%
    summarize(paste(i,"-new") = first(paste(i)))
  las_ref3 <- las_ref %>%
    left_join(select(las_ref2, incidentid, paste(i,"-new")), by = c("incidentid"))
}

Currently there seem to be two issues that I think revolve around the use of i to refer to the columns incident and var in the examples above.

The first is that the !is.na() function is not removing the NA values in the columns referred to by i, although this does not produce an error.
The second, which does produce an error, is the summarise line. I get an  unexpected '=' in error when this line is run.

Neither issue occurs when I run the code outside of the loop, specifying column names individually - the result comes out as expected. As the dataset is fairly large, I was hoping to use the loop to avoid doing each column individually.

Body:
We could write your loop in the following way to make it work:

library(tidyverse)

las_ref <- tribble(~incidentid , ~incident, ~var1,
    "001",             "abc",   45,
    "002",             "abc",   NA,
    "002",              NA,     78,
    "003",             "def",   12,
    "004",             "xyz",   NA,
    "004",             "xyz",   10,
    "004",             "abc",   10
)

las_names <- c("incident","var1")

las_ref3 <- las_ref

for(i in las_names) {
  las_ref2 <- las_ref %>%
    group_by(across(c(incidentid, paste(i)))) %>%
    tally() %>%
    filter(!is.na(!! sym(paste(i)))) %>%
    arrange(incidentid, desc(n)) %>%
    summarize("{i}-new" := first(!! sym(paste(i))))
  las_ref3 <- las_ref3 %>%
    left_join(select(las_ref2, incidentid, !! sym(paste0(i,"-new"))), by = c("incidentid"))
}

las_ref3
#> # A tibble: 7 x 5
#>   incidentid incident  var1 `incident-new` `var1-new`
#>   <chr>      <chr>    <dbl> <chr>               <dbl>
#> 1 001        abc         45 abc                    45
#> 2 002        abc         NA abc                    78
#> 3 002        <NA>        78 abc                    78
#> 4 003        def         12 def                    12
#> 5 004        xyz         NA xyz                    10
#> 6 004        xyz         10 xyz                    10
#> 7 004        abc         10 xyz                    10

We can also use purrr::map_dfc within mutate together with purrr:set_names:

las_ref %>%
  group_by(incidentid) %>%
  mutate(map_dfc(set_names(las_names, paste0(las_names, "-new")),
              ~ count(cur_data_all(), "{.x}" := eval(sym(.x))) %>%
                arrange(desc(n)) %>%
                slice_head() %>%
                pull(eval(sym(.x)))
  )
  )

#> # A tibble: 7 x 5
#> # Groups:   incidentid [4]
#>   incidentid incident  var1 `incident-new` `var1-new`
#>   <chr>      <chr>    <dbl> <chr>               <dbl>
#> 1 001        abc         45 abc                    45
#> 2 002        abc         NA abc                    78
#> 3 002        <NA>        78 abc                    78
#> 4 003        def         12 def                    12
#> 5 004        xyz         NA xyz                    10
#> 6 004        xyz         10 xyz                    10
#> 7 004        abc         10 xyz                    10

I have a package on github, {dplyover}, which makes the approach above a bit simpler by using over and its .names argument:

library(dplyover) # https://github.com/TimTeaFan/dplyover

las_ref %>%
  group_by(incidentid) %>%
  mutate(over(las_names,
              ~ count(cur_data_all(), "{.x}" := eval(sym(.x))) %>%
                arrange(desc(n)) %>%
                slice_head() %>%
                pull(eval(sym(.x))),
              .names = "{x}-new")
  )

#> # A tibble: 7 x 5
#> # Groups:   incidentid [4]
#>   incidentid incident  var1 `incident-new` `var1-new`
#>   <chr>      <chr>    <dbl> <chr>               <dbl>
#> 1 001        abc         45 abc                    45
#> 2 002        abc         NA abc                    78
#> 3 002        <NA>        78 abc                    78
#> 4 003        def         12 def                    12
#> 5 004        xyz         NA xyz                    10
#> 6 004        xyz         10 xyz                    10
#> 7 004        abc         10 xyz                    10

Created on 2022-02-11 by the reprex package (v2.0.1)


问:
How can I align a column heading and contact info in same row?
This might be silly question but yet I am stucked here.

There is A4 size paper in which I want Company Name at the center of the page and in the same row I want WhatsApp and contact number right aligned one after another. Below is my code attached.

Thanks in advance.

.invoice-title {
  font-size: 25px;
  text-align: center;
  font-weight: bold;
  color: #CD1818;
  padding-top: 10px;
}

.invoice-title small {
  font-size: 12px;
  text-align: right;
  padding-top: 10px;
  color: #262a2e;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="invoice-title"><span>COMPANY NAME</span>
  <small class="float-right"><i class="fab fa-whatsapp"></i> : 99887766655 \nCall : 5544332211</small>
</p></code>```

答:
It's easy with flexbox. Try this

.invoice-title{
    font-size: 25px;
    font-weight: bold;
    color: #CD1818;
    padding-top: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.invoice-title span {
    margin-left: auto;
}

.invoice-title small{
    font-size: 12px;
    text-align: right;
    color: #262a2e;
    margin-left: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<p class="invoice-title">
    <span>COMPANY NAME</span>
    <small>
        <i class="fab fa-whatsapp"></i> :
        99887766655 <br>Call : 5544332211
    </small>
</p></code>```

Body:
This might be silly question but yet I am stucked here.

There is A4 size paper in which I want Company Name at the center of the page and in the same row I want WhatsApp and contact number right aligned one after another. Below is my code attached.

Thanks in advance.

.invoice-title {
  font-size: 25px;
  text-align: center;
  font-weight: bold;
  color: #CD1818;
  padding-top: 10px;
}

.invoice-title small {
  font-size: 12px;
  text-align: right;
  padding-top: 10px;
  color: #262a2e;
}

COMPANY NAME
   : 99887766655 \nCall : 5544332211

Body:
It's easy with flexbox. Try this

.invoice-title{
    font-size: 25px;
    font-weight: bold;
    color: #CD1818;
    padding-top: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.invoice-title span {
    margin-left: auto;
}

.invoice-title small{
    font-size: 12px;
    text-align: right;
    color: #262a2e;
    margin-left: auto;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<p class="invoice-title">
    <span>COMPANY NAME</span>
    <small>
        <i class="fab fa-whatsapp"></i> :
        99887766655 <br>Call : 5544332211
    </small>
</p>