问:
Multiple gganimate plots both stacked and side by side
I have four animated plots with the same number of frames, of which I want three stacked and the fourth to the right of the three stacked animations. Normally I would use something like grid.arrange, but that does not seem to work with gganimate.

I got the following piece of code based on the code from here: https://github.com/thomasp85/gganimate/wiki/Animation-Composition

```<code>a_mgif <- image_read(a_gif)
b_mgif <- image_read(b_gif)
c_mgif <- image_read(c_gif)
d_mgif <- image_read(d_gif)

new_gif <- image_append(c(a_mgif[1], b_mgif[1], c_mgif[1], d_mgif[1]), stack = TRUE)

for(i in 2:100){
  combined <- image_append(c(a_mgif[i], b_mgif[i], c_mgif[i], d_mgif[i]), stack = TRUE)
  new_gif <- c(new_gif, combined)
}

magick::image_write(new_gif, path="animation.1.gif")
</code>```

This works fine and produces the four stacked animated plots. I tried to modify it to have the fourth plot to the right of the first three stacked plots as follows:

```<code>new_gif.1 <- image_append(c(a_mgif[1], b_mgif[1], c_mgif[1]), stack = TRUE)
new_gif.2 <- image_append(c(new_gif.1, d_mgif[1]), stack = FALSE)

for(i in 2:100){
  combined.1 <- image_append(c(a_mgif[i], b_mgif[i], c_mgif[i]), stack = TRUE)
  combined.2 <- image_append(c(combined.1, d_mgif[i]), stack = FALSE)
  new_gif.2 <- c(new_gif.2,combined.2)
}

magick::image_write(new_gif.2, path="animation.2.gif")
</code>```

This seems to work, up to the point of writing the file. It takes forever to write the file, I let it run for hours and it still didn't finish, while the first version where they are all stacked is written within a minute, so clearly something is wrong. It's exactly the same data/plots in both examples. Any ideas on what goes wrong here?

答:
What worked for me was to wrap the image_append calls into image_flatten. I also first combined img1 and img4 horizontally and then stacked this with img2 and img3.

Here I only recycled the two animations from the example, but this solution should also work with four independent animations - at least for me, on R4.0 with ImageMagick 6.9.10.23 and magick_2.3, although it takes about 3 minutes and maybe 630 MB of temp storage:

library(dplyr)
library(ggplot2)
library(magick)
library(gganimate)

A <- rnorm(100,50,10)
B <- rnorm(100,50,10)
DV <- c(A,B)
IV <- rep(c("A","B"), each=100)
sims <- rep(rep(1:10, each=10), 2)
df <- data.frame(sims, IV, DV)

means_df <- df %>%
    group_by(sims,IV) %>%
    summarize(means=mean(DV),
              sem = sd(DV)/sqrt(length(DV)))

stats_df <- df %>%
    group_by(sims) %>%
    summarize(ts = t.test(DV~IV,var.equal=TRUE)$statistic)

a <- ggplot(means_df, aes(x = IV,y = means, fill = IV)) +
    geom_bar(stat = "identity") +
    geom_point(aes(x = IV, y = DV), data = df, alpha = .25) +
    geom_errorbar(aes(ymin = means - sem, ymax = means + sem), width = .2) +
    theme_classic() +
    transition_states(
        states = sims,
        transition_length = 2,
        state_length = 1
    ) +
    enter_fade() +
    exit_shrink() +
    ease_aes('sine-in-out')

a_gif <- animate(a, width = 240, height = 240, renderer = magick_renderer())

b <- ggplot(stats_df, aes(x = ts))+
    geom_vline(aes(xintercept = ts, frame = sims))+
    geom_line(aes(x=x,y=y),
              data = data.frame(x = seq(-5,5, .1),
                                y = dt(seq(-5,5, .1), df = 18))) +
    theme_classic() +
    ylab("density") +
    xlab("t value") +
    transition_states(
        states = sims,
        transition_length = 2,
        state_length = 1
    ) +
    enter_fade() +
    exit_shrink() +
    ease_aes('sine-in-out')

b_gif <- animate(b, width = 240, height = 240, renderer = magick_renderer())

c_gif <- animate(b, width = 240, height = 240, renderer = magick_renderer())
d_gif <- animate(a, width = 240, height = 240, renderer = magick_renderer())

i=1
combined <- image_append(c(a_gif[i], d_gif[i]))
new_gif <- image_append(c(image_flatten(combined),
                          b_gif[i], c_gif[i]), stack=TRUE)

for(i in 2:100){
    combined <- image_append(c(a_gif[i], d_gif[i]))
    fullcombined <- image_append(c(image_flatten(combined),
                                   b_gif[i], c_gif[i]), stack=TRUE)
    new_gif <- c(new_gif, fullcombined)
}

image_write(new_gif, format="gif", path="animation.2.gif")

```
<p><strong>Edit: Alternative</strong>
Alternatively, you could use <code>cowplot</code> to arrange the plots and generate the individual frames in a loop and then use <code>gifski</code> to make the animation; that is even more flexible in terms of image placement, since you can add coordinates to <code>draw_image</code> (see corresponding <code>cowplot</code> examples). Below is a simple grid example:</p>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
library(ggplot2)
library(magick)
library(gganimate)
library(cowplot)
library(gifski)

A <- rnorm(100,50,10)
B <- rnorm(100,50,10)
DV <- c(A,B)
IV <- rep(c("A","B"), each=100)
sims <- rep(rep(1:10, each=10), 2)
df <- data.frame(sims, IV, DV)

means_df <- df %>%
    group_by(sims,IV) %>%
    summarize(means=mean(DV),
              sem = sd(DV)/sqrt(length(DV)))

stats_df <- df %>%
    group_by(sims) %>%
    summarize(ts = t.test(DV~IV,var.equal=TRUE)$statistic)

a <- ggplot(means_df, aes(x = IV,y = means, fill = IV)) +
    geom_bar(stat = "identity") +
    geom_point(aes(x = IV, y = DV), data = df, alpha = .25) +
    geom_errorbar(aes(ymin = means - sem, ymax = means + sem), width = .2) +
    theme_classic() +
    transition_states(
        states = sims,
        transition_length = 2,
        state_length = 1
    ) +
    enter_fade() +
    exit_shrink() +
    ease_aes('sine-in-out')

a_gif <- animate(a, width = 240, height = 240, renderer = magick_renderer())

b <- ggplot(stats_df, aes(x = ts))+
    geom_vline(aes(xintercept = ts, frame = sims))+
    geom_line(aes(x=x,y=y),
              data = data.frame(x = seq(-5,5, .1),
                                y = dt(seq(-5,5, .1), df = 18))) +
    theme_classic() +
    ylab("density") +
    xlab("t value") +
    transition_states(
        states = sims,
        transition_length = 2,
        state_length = 1
    ) +
    enter_fade() +
    exit_shrink() +
    ease_aes('sine-in-out')

b_gif <- animate(b, width = 240, height = 240, renderer = magick_renderer())

c_gif <- animate(b, width = 240, height = 240, renderer = magick_renderer())
d_gif <- animate(a, width = 240, height = 240, renderer = magick_renderer())

tdir <- tempdir()
for(i in 1:100){
    new_gif <- plot_grid(ggdraw() + draw_image(a_gif[i], scale = 0.9),
                         ggdraw() + draw_image(d_gif[i], scale = 0.9),
                         ggdraw() + draw_image(b_gif[i], scale = 0.9),
                         ggdraw(),
                         ggdraw() + draw_image(c_gif[i], scale = 0.9),
                         ncol=2)
    ggsave(
        filename = file.path(tdir, paste0("out_", sprintf("%03d", i), ".png")),
        plot = new_gif, width = 2.4, height = 3.6, device = "png")
}

png_files <- sort(list.files(path = tdir, pattern = "out_", full.names = TRUE))
gifski(png_files, gif_file = "out.gif", width = 480, height = 720, delay = .1,
       progress = TRUE)

</code>```

Edit #2 (May 2021):

Something changed since my initial answer, and, as @agbarnett pointed out, the renderer now has to be set explicitly to renderer = magick_renderer() in all the animate commands.

Body:
I have four animated plots with the same number of frames, of which I want three stacked and the fourth to the right of the three stacked animations. Normally I would use something like grid.arrange, but that does not seem to work with gganimate.

I got the following piece of code based on the code from here: https://github.com/thomasp85/gganimate/wiki/Animation-Composition

a_mgif <- image_read(a_gif)
b_mgif <- image_read(b_gif)
c_mgif <- image_read(c_gif)
d_mgif <- image_read(d_gif)

new_gif <- image_append(c(a_mgif[1], b_mgif[1], c_mgif[1], d_mgif[1]), stack = TRUE)

for(i in 2:100){
  combined <- image_append(c(a_mgif[i], b_mgif[i], c_mgif[i], d_mgif[i]), stack = TRUE)
  new_gif <- c(new_gif, combined)
}

magick::image_write(new_gif, path="animation.1.gif")

This works fine and produces the four stacked animated plots. I tried to modify it to have the fourth plot to the right of the first three stacked plots as follows:

new_gif.1 <- image_append(c(a_mgif[1], b_mgif[1], c_mgif[1]), stack = TRUE)
new_gif.2 <- image_append(c(new_gif.1, d_mgif[1]), stack = FALSE)

for(i in 2:100){
  combined.1 <- image_append(c(a_mgif[i], b_mgif[i], c_mgif[i]), stack = TRUE)
  combined.2 <- image_append(c(combined.1, d_mgif[i]), stack = FALSE)
  new_gif.2 <- c(new_gif.2,combined.2)
}

magick::image_write(new_gif.2, path="animation.2.gif")

This seems to work, up to the point of writing the file. It takes forever to write the file, I let it run for hours and it still didn't finish, while the first version where they are all stacked is written within a minute, so clearly something is wrong. It's exactly the same data/plots in both examples. Any ideas on what goes wrong here?

Body:
What worked for me was to wrap the image_append calls into image_flatten. I also first combined img1 and img4 horizontally and then stacked this with img2 and img3.

Here I only recycled the two animations from the example, but this solution should also work with four independent animations - at least for me, on R4.0 with ImageMagick 6.9.10.23 and magick_2.3, although it takes about 3 minutes and maybe 630 MB of temp storage:

library(dplyr)
library(ggplot2)
library(magick)
library(gganimate)

A <- rnorm(100,50,10)
B <- rnorm(100,50,10)
DV <- c(A,B)
IV <- rep(c("A","B"), each=100)
sims <- rep(rep(1:10, each=10), 2)
df <- data.frame(sims, IV, DV)

means_df <- df %>%
    group_by(sims,IV) %>%
    summarize(means=mean(DV),
              sem = sd(DV)/sqrt(length(DV)))

stats_df <- df %>%
    group_by(sims) %>%
    summarize(ts = t.test(DV~IV,var.equal=TRUE)$statistic)

a <- ggplot(means_df, aes(x = IV,y = means, fill = IV)) +
    geom_bar(stat = "identity") +
    geom_point(aes(x = IV, y = DV), data = df, alpha = .25) +
    geom_errorbar(aes(ymin = means - sem, ymax = means + sem), width = .2) +
    theme_classic() +
    transition_states(
        states = sims,
        transition_length = 2,
        state_length = 1
    ) +
    enter_fade() +
    exit_shrink() +
    ease_aes('sine-in-out')

a_gif <- animate(a, width = 240, height = 240, renderer = magick_renderer())

b <- ggplot(stats_df, aes(x = ts))+
    geom_vline(aes(xintercept = ts, frame = sims))+
    geom_line(aes(x=x,y=y),
              data = data.frame(x = seq(-5,5, .1),
                                y = dt(seq(-5,5, .1), df = 18))) +
    theme_classic() +
    ylab("density") +
    xlab("t value") +
    transition_states(
        states = sims,
        transition_length = 2,
        state_length = 1
    ) +
    enter_fade() +
    exit_shrink() +
    ease_aes('sine-in-out')

b_gif <- animate(b, width = 240, height = 240, renderer = magick_renderer())

c_gif <- animate(b, width = 240, height = 240, renderer = magick_renderer())
d_gif <- animate(a, width = 240, height = 240, renderer = magick_renderer())

i=1
combined <- image_append(c(a_gif[i], d_gif[i]))
new_gif <- image_append(c(image_flatten(combined),
                          b_gif[i], c_gif[i]), stack=TRUE)

for(i in 2:100){
    combined <- image_append(c(a_gif[i], d_gif[i]))
    fullcombined <- image_append(c(image_flatten(combined),
                                   b_gif[i], c_gif[i]), stack=TRUE)
    new_gif <- c(new_gif, fullcombined)
}

image_write(new_gif, format="gif", path="animation.2.gif")

Edit: Alternative
Alternatively, you could use cowplot to arrange the plots and generate the individual frames in a loop and then use gifski to make the animation; that is even more flexible in terms of image placement, since you can add coordinates to draw_image (see corresponding cowplot examples). Below is a simple grid example:

library(dplyr)
library(ggplot2)
library(magick)
library(gganimate)
library(cowplot)
library(gifski)

A <- rnorm(100,50,10)
B <- rnorm(100,50,10)
DV <- c(A,B)
IV <- rep(c("A","B"), each=100)
sims <- rep(rep(1:10, each=10), 2)
df <- data.frame(sims, IV, DV)

means_df <- df %>%
    group_by(sims,IV) %>%
    summarize(means=mean(DV),
              sem = sd(DV)/sqrt(length(DV)))

stats_df <- df %>%
    group_by(sims) %>%
    summarize(ts = t.test(DV~IV,var.equal=TRUE)$statistic)

a <- ggplot(means_df, aes(x = IV,y = means, fill = IV)) +
    geom_bar(stat = "identity") +
    geom_point(aes(x = IV, y = DV), data = df, alpha = .25) +
    geom_errorbar(aes(ymin = means - sem, ymax = means + sem), width = .2) +
    theme_classic() +
    transition_states(
        states = sims,
        transition_length = 2,
        state_length = 1
    ) +
    enter_fade() +
    exit_shrink() +
    ease_aes('sine-in-out')

a_gif <- animate(a, width = 240, height = 240, renderer = magick_renderer())

b <- ggplot(stats_df, aes(x = ts))+
    geom_vline(aes(xintercept = ts, frame = sims))+
    geom_line(aes(x=x,y=y),
              data = data.frame(x = seq(-5,5, .1),
                                y = dt(seq(-5,5, .1), df = 18))) +
    theme_classic() +
    ylab("density") +
    xlab("t value") +
    transition_states(
        states = sims,
        transition_length = 2,
        state_length = 1
    ) +
    enter_fade() +
    exit_shrink() +
    ease_aes('sine-in-out')

b_gif <- animate(b, width = 240, height = 240, renderer = magick_renderer())

c_gif <- animate(b, width = 240, height = 240, renderer = magick_renderer())
d_gif <- animate(a, width = 240, height = 240, renderer = magick_renderer())

tdir <- tempdir()
for(i in 1:100){
    new_gif <- plot_grid(ggdraw() + draw_image(a_gif[i], scale = 0.9),
                         ggdraw() + draw_image(d_gif[i], scale = 0.9),
                         ggdraw() + draw_image(b_gif[i], scale = 0.9),
                         ggdraw(),
                         ggdraw() + draw_image(c_gif[i], scale = 0.9),
                         ncol=2)
    ggsave(
        filename = file.path(tdir, paste0("out_", sprintf("%03d", i), ".png")),
        plot = new_gif, width = 2.4, height = 3.6, device = "png")
}

png_files <- sort(list.files(path = tdir, pattern = "out_", full.names = TRUE))
gifski(png_files, gif_file = "out.gif", width = 480, height = 720, delay = .1,
       progress = TRUE)

Edit #2 (May 2021):

Something changed since my initial answer, and, as @agbarnett pointed out, the renderer now has to be set explicitly to renderer = magick_renderer() in all the animate commands.


来源: stackexchange

问:
2018 13" MacBook Pro (macOS 10.15.5) kernel panics when uploading binaries via Xcode or Transporter
I am having an issue with my MacBook Pro. Whenever I export an update for my apps via Xcode or Transporter to the App Store, the whole computer freezes and then restarts (kernel panic). I have been experiencing this since 10.15.4 and I thought macOS 10.15.5 update would help but no luck. The computers behaves fine, until I try to upload a binary to the App Store (At least let's say that's the only know way for me to trigger the bug). I did a clean install today, wiping all my data, reinstalling a fresh copy of macOS 10.15.5 and Xcode from the App Store. But  it always occurs after uploading for like 10 minutes. I am disgusted, as a developer, I have to use my wife's 2015 MacBook to upload my binaries, her computer has no issue. Am I the only one ? I would definitely hug that somebody who can help me fix it.

CRASH LOGS:

```<code>panic(cpu 2 caller 0xffffff7f985a1ad5): userspace watchdog timeout: remoted connection watchdog expired, no updates from remoted monitoring thread in 60 seconds, 423 checkins from thread since monitoring enabled 8500 seconds ago after wakeservice: com.apple.logd, total successful checkins since wake (8500 seconds ago): 850, last successful checkin: 10 seconds ago
service: com.apple.WindowServer, total successful checkins since wake (8500 seconds ago): 850, last successful checkin: 10 seconds ago

Backtrace (CPU 2), Frame : Return Address
0xffffff914a6db720 : 0xffffff8017b1f5cd
0xffffff914a6db770 : 0xffffff8017c58b05
0xffffff914a6db7b0 : 0xffffff8017c4a68e
0xffffff914a6db800 : 0xffffff8017ac5a40
0xffffff914a6db820 : 0xffffff8017b1ec97
0xffffff914a6db920 : 0xffffff8017b1f087
0xffffff914a6db970 : 0xffffff80182c2858
0xffffff914a6db9e0 : 0xffffff7f985a1ad5
0xffffff914a6db9f0 : 0xffffff7f985a17fa
0xffffff914a6dba10 : 0xffffff8018254aae
0xffffff914a6dba60 : 0xffffff7f985a0cfe
0xffffff914a6dbb60 : 0xffffff801825dcd3
0xffffff914a6dbca0 : 0xffffff8017c082b2
0xffffff914a6dbdb0 : 0xffffff8017b25328
0xffffff914a6dbe10 : 0xffffff8017afbcc5
0xffffff914a6dbe70 : 0xffffff8017b12aa2
0xffffff914a6dbf00 : 0xffffff8017c30d05
0xffffff914a6dbfa0 : 0xffffff8017ac6226
      Kernel Extensions in backtrace:
         com.apple.driver.watchdog(1.0)[B435C72B-B311-3C67-8AA1-1D5CE0FAD429]@0xffffff7f985a0000->0xffffff7f985a8fff

BSD process name corresponding to current thread: watchdogd
Boot args: chunklist-security-epoch=0 -chunklist-no-rev2-dev

Mac OS version:
19F96

Kernel version:
Darwin Kernel Version 19.5.0: Thu Apr 30 18:25:59 PDT 2020; root:xnu-6153.121.1~7/RELEASE_X86_64
Kernel UUID: 7B7F06EE-1B75-345E-B898-2FD4FEC20F0D
Kernel slide:     0x0000000017800000
Kernel text base: 0xffffff8017a00000
__HIB  text base: 0xffffff8017900000
System model name: MacBookPro15,2 (Mac-827FB448E656EC26)
System shutdown begun: NO

System uptime in nanoseconds: 25648972761027
last loaded kext at 20989527404840: >usb.cdc.acm    5.0.0 (addr 0xffffff7f9bc1f000, size 32768)
last unloaded kext at 21273759140481: >!UMergeNub   900.4.2 (addr 0xffffff7f9b7a2000, size 12288)
loaded kexts:
@nke.rvi    2.0.0
>!AGraphicsDevicePolicy 5.2.4
@fileutil   20.036.15
@AGDCPluginDisplayMetrics   5.2.4
>!AHV   1
|IOUserEthernet 1.0.1
|IO!BSerialManager  7.0.5f6
>AGPM   111.4.4
>!APlatformEnabler  2.7.0d0
>X86PlatformShim    1.0.0
>!AUpstreamUserClient   3.6.8
>pmtelemetry    1
>!A!IKBLGraphics    14.0.6
@Dont_Steal_Mac_OS_X    7.0.0
>BridgeAudioCommunication   6.70.7
>!ABacklight    180.3
>!AThunderboltIP    3.1.4
>!AAVEBridge    6.1
>!AMCCSControl  1.14
>!ABridgeAudio!C    6.70.7
>!AGFXHDA   100.1.428
>!ATopCaseHIDEventDriver    3430.1
>!AHIDALSService    1
>!A!ICFLGraphicsFramebuffer 14.0.6
>!A!ISlowAdaptiveClocking   4.0.0
>!A!IPCHPMC 2.0.1
@filesystems.autofs 3.0
@filesystems.apfs   1412.120.2
>BCMWLANFirmware4355.Hashstore  1
>BCMWLANFirmware4364.Hashstore  1
>BCMWLANFirmware4377.Hashstore  1
@filesystems.hfs.kext   522.100.5
@BootCache  40
@!AFSCompression.!AFSCompressionTypeDataless    1.0.0d1
@!AFSCompression.!AFSCompressionTypeZlib    1.0.0
>!AVirtIO   1.0
>!ABCMWLANBusInterfacePCIe  1
@private.KextAudit  1.0
>!ASmartBatteryManager  161.0.0
>!AACPIButtons  6.1
>!ASMBIOS   2.1
>!AACPIEC   6.1
>!AAPIC 1.7
$!AImage4   1
@nke.applicationfirewall    303
$TMSafetyNet    8
@!ASystemPolicy 2.0.0
|EndpointSecurity   1
>usb.!UHub  1.2
>!AGraphicsControl  5.2.4
|IOAVB!F    850.1
>!ASSE  1.0
>!ABacklightExpert  1.1.0
@!AGPUWrangler  5.2.4
>X86PlatformPlugin  1.0.0
>!ASMBus!C  1.0.18d1
>!AActuatorDriver   3440.1
|IONDRVSupport  576.1
>!AHIDKeyboard  209
>!AHS!BDriver   3430.1
>IO!BHIDDriver  7.0.5f6
>!AMultitouchDriver 3440.1
>!AInputDeviceSupport   3440.8
|IO!BHost!CUARTTransport    7.0.5f6
|IO!BHost!CTransport    7.0.5f6
>!A!ILpssUARTv1 3.0.60
>!A!ILpssUARTCommon 3.0.60
>!AOnboardSerial    1.0
@!AGraphicsDeviceControl    5.2.4
|IOAccelerator!F2   438.5.4
|IOGraphics!F   576.1
|IOSlowAdaptiveClocking!F   1.0.0
>IOPlatformPlugin!F 6.0.0d8
@plugin.IOgPTPPlugin    840.3
|IOEthernetAVB!C    1.1.0
@kext.triggers  1.0
>usb.cdc.ncm    5.0.0
>usb.cdc    5.0.0
>usb.networking 5.0.0
>usb.!UHostCompositeDevice  1.2
>usb.!UVHCIBCE  1.2
>usb.!UVHCI 1.2
>usb.!UVHCICommonBCE    1.0
>usb.!UVHCICommon   1.0
>!AEffaceableNOR    1.0
|IOBufferCopy!C 1.1.0
|IOBufferCopyEngine!F   1
|IONVMe!F   2.1.0
>!AThunderboltPCIDownAdapter    2.5.4
>!AThunderboltDPInAdapter   6.2.6
>!AThunderboltDPAdapter!F   6.2.6
>!AHPM  3.4.4
>!A!ILpssI2C!C  3.0.60
>!A!ILpssDmac   3.0.60
|IOSurface  269.11
@filesystems.hfs.encodings.kext 1
|IOAudio!F  300.2
@vecLib.kext    1.2.0
>!AThunderboltNHI   5.8.6
|IOThunderbolt!F    7.6.1
>!ABCMWLANCore  1.0.0
>mDNSOffloadUserClient  1.0.1b8
>IOImageLoader  1.0.0
|IOSerial!F 11
|IO80211!FV2    1200.12.2b1
>corecapture    1.0.4
|IOSkywalk!F    1
|IOUSB!F    900.4.2
>!A!ILpssI2C    3.0.60
>usb.!UXHCIPCI  1.2
>usb.!UXHCI 1.2
>!AEFINVRAM 2.1
>!AEFIRuntime   2.1
>!ASMCRTC   1.0
|IOSMBus!F  1.1
|IOHID!F    2.0.0
$quarantine 4
$sandbox    300.0
@kext.!AMatch   1.0.0d1
>!AKeyStore 2
>!UTDM  489.120.1
|IOSCSIBlockCommandsDevice  422.120.3
>!ACredentialManager    1.0
>KernelRelayHost    1
>!ASEPManager   1.0.1
>IOSlaveProcessor   1
>!AFDEKeyStore  28.30
>!AEffaceable!S 1.0
>!AMobileFileIntegrity  1.0.5
@kext.CoreTrust 1
|CoreAnalytics!F    1
|IOTimeSync!F   840.3
|IONetworking!F 3.4
>DiskImages 493.0.0
|IO!B!F 7.0.5f6
|IO!BPacketLogger   7.0.5f6
|IOUSBMass!SDriver  157.121.1
|IOSCSIArchitectureModel!F  422.120.3
|IO!S!F 2.1
|IOUSBHost!F    1.2
>usb.!UCommon   1.0
>!UHostMergeProperties  1.2
>!ABusPower!C   1.0
|IOReport!F 47
>!AACPIPlatform 6.1
>!ASMC  3.1.9
>watchdog   1
|IOPCI!F    2.9
|IOACPI!F   1.4
@kec.pthread    1
@kec.corecrypto 1.0
@kec.Libm   1
</code>```

答:
Turns out my 2 months old struggle all came from the fact I had my iPhone connected to the Mac during submissions to App Store. Somebody read my logs on Apple Community and told me:

usb.cdc.acm appears to be something that interfaces with a USB
  cellular modems. Since it was the last loaded kext, that might have
  something to do with it

I unplugged the iPhone during Xcode upload, and it worked fine, so I managed to share my solution with you. Obviously there is a conflict with the iPhone cellular sharing, even though both devices were on Wifi.

Cheers

ContentLicense: CC BY-SA 4.0

Body:
I am having an issue with my MacBook Pro. Whenever I export an update for my apps via Xcode or Transporter to the App Store, the whole computer freezes and then restarts (kernel panic). I have been experiencing this since 10.15.4 and I thought macOS 10.15.5 update would help but no luck. The computers behaves fine, until I try to upload a binary to the App Store (At least let's say that's the only know way for me to trigger the bug). I did a clean install today, wiping all my data, reinstalling a fresh copy of macOS 10.15.5 and Xcode from the App Store. But  it always occurs after uploading for like 10 minutes. I am disgusted, as a developer, I have to use my wife's 2015 MacBook to upload my binaries, her computer has no issue. Am I the only one ? I would definitely hug that somebody who can help me fix it.

CRASH LOGS:

panic(cpu 2 caller 0xffffff7f985a1ad5): userspace watchdog timeout: remoted connection watchdog expired, no updates from remoted monitoring thread in 60 seconds, 423 checkins from thread since monitoring enabled 8500 seconds ago after wakeservice: com.apple.logd, total successful checkins since wake (8500 seconds ago): 850, last successful checkin: 10 seconds ago
service: com.apple.WindowServer, total successful checkins since wake (8500 seconds ago): 850, last successful checkin: 10 seconds ago

Backtrace (CPU 2), Frame : Return Address
0xffffff914a6db720 : 0xffffff8017b1f5cd
0xffffff914a6db770 : 0xffffff8017c58b05
0xffffff914a6db7b0 : 0xffffff8017c4a68e
0xffffff914a6db800 : 0xffffff8017ac5a40
0xffffff914a6db820 : 0xffffff8017b1ec97
0xffffff914a6db920 : 0xffffff8017b1f087
0xffffff914a6db970 : 0xffffff80182c2858
0xffffff914a6db9e0 : 0xffffff7f985a1ad5
0xffffff914a6db9f0 : 0xffffff7f985a17fa
0xffffff914a6dba10 : 0xffffff8018254aae
0xffffff914a6dba60 : 0xffffff7f985a0cfe
0xffffff914a6dbb60 : 0xffffff801825dcd3
0xffffff914a6dbca0 : 0xffffff8017c082b2
0xffffff914a6dbdb0 : 0xffffff8017b25328
0xffffff914a6dbe10 : 0xffffff8017afbcc5
0xffffff914a6dbe70 : 0xffffff8017b12aa2
0xffffff914a6dbf00 : 0xffffff8017c30d05
0xffffff914a6dbfa0 : 0xffffff8017ac6226
      Kernel Extensions in backtrace:
         com.apple.driver.watchdog(1.0)[B435C72B-B311-3C67-8AA1-1D5CE0FAD429]@0xffffff7f985a0000->0xffffff7f985a8fff

BSD process name corresponding to current thread: watchdogd
Boot args: chunklist-security-epoch=0 -chunklist-no-rev2-dev

Mac OS version:
19F96

Kernel version:
Darwin Kernel Version 19.5.0: Thu Apr 30 18:25:59 PDT 2020; root:xnu-6153.121.1~7/RELEASE_X86_64
Kernel UUID: 7B7F06EE-1B75-345E-B898-2FD4FEC20F0D
Kernel slide:     0x0000000017800000
Kernel text base: 0xffffff8017a00000
__HIB  text base: 0xffffff8017900000
System model name: MacBookPro15,2 (Mac-827FB448E656EC26)
System shutdown begun: NO

System uptime in nanoseconds: 25648972761027
last loaded kext at 20989527404840: >usb.cdc.acm    5.0.0 (addr 0xffffff7f9bc1f000, size 32768)
last unloaded kext at 21273759140481: >!UMergeNub   900.4.2 (addr 0xffffff7f9b7a2000, size 12288)
loaded kexts:
@nke.rvi    2.0.0
>!AGraphicsDevicePolicy 5.2.4
@fileutil   20.036.15
@AGDCPluginDisplayMetrics   5.2.4
>!AHV   1
|IOUserEthernet 1.0.1
|IO!BSerialManager  7.0.5f6
>AGPM   111.4.4
>!APlatformEnabler  2.7.0d0
>X86PlatformShim    1.0.0
>!AUpstreamUserClient   3.6.8
>pmtelemetry    1
>!A!IKBLGraphics    14.0.6
@Dont_Steal_Mac_OS_X    7.0.0
>BridgeAudioCommunication   6.70.7
>!ABacklight    180.3
>!AThunderboltIP    3.1.4
>!AAVEBridge    6.1
>!AMCCSControl  1.14
>!ABridgeAudio!C    6.70.7
>!AGFXHDA   100.1.428
>!ATopCaseHIDEventDriver    3430.1
>!AHIDALSService    1
>!A!ICFLGraphicsFramebuffer 14.0.6
>!A!ISlowAdaptiveClocking   4.0.0
>!A!IPCHPMC 2.0.1
@filesystems.autofs 3.0
@filesystems.apfs   1412.120.2
>BCMWLANFirmware4355.Hashstore  1
>BCMWLANFirmware4364.Hashstore  1
>BCMWLANFirmware4377.Hashstore  1
@filesystems.hfs.kext   522.100.5
@BootCache  40
@!AFSCompression.!AFSCompressionTypeDataless    1.0.0d1
@!AFSCompression.!AFSCompressionTypeZlib    1.0.0
>!AVirtIO   1.0
>!ABCMWLANBusInterfacePCIe  1
@private.KextAudit  1.0
>!ASmartBatteryManager  161.0.0
>!AACPIButtons  6.1
>!ASMBIOS   2.1
>!AACPIEC   6.1
>!AAPIC 1.7
$!AImage4   1
@nke.applicationfirewall    303
$TMSafetyNet    8
@!ASystemPolicy 2.0.0
|EndpointSecurity   1
>usb.!UHub  1.2
>!AGraphicsControl  5.2.4
|IOAVB!F    850.1
>!ASSE  1.0
>!ABacklightExpert  1.1.0
@!AGPUWrangler  5.2.4
>X86PlatformPlugin  1.0.0
>!ASMBus!C  1.0.18d1
>!AActuatorDriver   3440.1
|IONDRVSupport  576.1
>!AHIDKeyboard  209
>!AHS!BDriver   3430.1
>IO!BHIDDriver  7.0.5f6
>!AMultitouchDriver 3440.1
>!AInputDeviceSupport   3440.8
|IO!BHost!CUARTTransport    7.0.5f6
|IO!BHost!CTransport    7.0.5f6
>!A!ILpssUARTv1 3.0.60
>!A!ILpssUARTCommon 3.0.60
>!AOnboardSerial    1.0
@!AGraphicsDeviceControl    5.2.4
|IOAccelerator!F2   438.5.4
|IOGraphics!F   576.1
|IOSlowAdaptiveClocking!F   1.0.0
>IOPlatformPlugin!F 6.0.0d8
@plugin.IOgPTPPlugin    840.3
|IOEthernetAVB!C    1.1.0
@kext.triggers  1.0
>usb.cdc.ncm    5.0.0
>usb.cdc    5.0.0
>usb.networking 5.0.0
>usb.!UHostCompositeDevice  1.2
>usb.!UVHCIBCE  1.2
>usb.!UVHCI 1.2
>usb.!UVHCICommonBCE    1.0
>usb.!UVHCICommon   1.0
>!AEffaceableNOR    1.0
|IOBufferCopy!C 1.1.0
|IOBufferCopyEngine!F   1
|IONVMe!F   2.1.0
>!AThunderboltPCIDownAdapter    2.5.4
>!AThunderboltDPInAdapter   6.2.6
>!AThunderboltDPAdapter!F   6.2.6
>!AHPM  3.4.4
>!A!ILpssI2C!C  3.0.60
>!A!ILpssDmac   3.0.60
|IOSurface  269.11
@filesystems.hfs.encodings.kext 1
|IOAudio!F  300.2
@vecLib.kext    1.2.0
>!AThunderboltNHI   5.8.6
|IOThunderbolt!F    7.6.1
>!ABCMWLANCore  1.0.0
>mDNSOffloadUserClient  1.0.1b8
>IOImageLoader  1.0.0
|IOSerial!F 11
|IO80211!FV2    1200.12.2b1
>corecapture    1.0.4
|IOSkywalk!F    1
|IOUSB!F    900.4.2
>!A!ILpssI2C    3.0.60
>usb.!UXHCIPCI  1.2
>usb.!UXHCI 1.2
>!AEFINVRAM 2.1
>!AEFIRuntime   2.1
>!ASMCRTC   1.0
|IOSMBus!F  1.1
|IOHID!F    2.0.0
$quarantine 4
$sandbox    300.0
@kext.!AMatch   1.0.0d1
>!AKeyStore 2
>!UTDM  489.120.1
|IOSCSIBlockCommandsDevice  422.120.3
>!ACredentialManager    1.0
>KernelRelayHost    1
>!ASEPManager   1.0.1
>IOSlaveProcessor   1
>!AFDEKeyStore  28.30
>!AEffaceable!S 1.0
>!AMobileFileIntegrity  1.0.5
@kext.CoreTrust 1
|CoreAnalytics!F    1
|IOTimeSync!F   840.3
|IONetworking!F 3.4
>DiskImages 493.0.0
|IO!B!F 7.0.5f6
|IO!BPacketLogger   7.0.5f6
|IOUSBMass!SDriver  157.121.1
|IOSCSIArchitectureModel!F  422.120.3
|IO!S!F 2.1
|IOUSBHost!F    1.2
>usb.!UCommon   1.0
>!UHostMergeProperties  1.2
>!ABusPower!C   1.0
|IOReport!F 47
>!AACPIPlatform 6.1
>!ASMC  3.1.9
>watchdog   1
|IOPCI!F    2.9
|IOACPI!F   1.4
@kec.pthread    1
@kec.corecrypto 1.0
@kec.Libm   1


问:
How can i print a page in asp.net without master page and to change color schemes of the page?
i have made a page in asp.net, i have a costing calculator which has more than 50 fields, dependent on each other, one is the result of previous two and like that, i want my page to be printed in a well manner, and the header of the page which is in master page should not be in print, also the color schemes i want to adjust, let me know the best solution for this which .net provides</p>

答:
Put the content inside
YOUR CONTENT NEEDS TO BE PRINTED

Then call the javascript function on button click which will  print  the selected area or only html of div. pass the id of div on calling javascript function.

```<code>function CallPrint(var strid)
{

var prtContent = document.getElementById(strid);
var WinPrint = window.open('','','letf=10,top=10,width="450",height="250",toolbar=1,scrollbars=1,status=0');

WinPrint.document.write("<html><head><LINK rel=\"stylesheet\" type\"text/css\" href=\"css/print.css\" media=\"print\"><LINK rel=\"stylesheet\" type\"text/css\" href=\"css/print.css\" media=\"screen\"></head><body>");

WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.write("</body></html>");
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();

return false;
}
</code>```

Call CallPrint('DivGrid');" on onclick() of button or use below: but.Attributes.Add("OnClick", "return CallPrint('DivGrid');");

ContentLicense: CC BY-SA 3.0

Body:
Put the content inside <div id="divid">YOUR CONTENT NEEDS TO BE PRINTED</div>

Then call the javascript function on button click which will  print  the selected area or only html of div. pass the id of div on calling javascript function.

function CallPrint(var strid)
{

var prtContent = document.getElementById(strid);
var WinPrint = window.open('','','letf=10,top=10,width="450",height="250",toolbar=1,scrollbars=1,status=0');

WinPrint.document.write("<html><head><LINK rel=\"stylesheet\" type\"text/css\" href=\"css/print.css\" media=\"print\"><LINK rel=\"stylesheet\" type\"text/css\" href=\"css/print.css\" media=\"screen\"></head><body>");

WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.write("</body></html>");
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();

return false;
}

Call CallPrint('DivGrid');" on onclick() of button or use below: but.Attributes.Add("OnClick", "return CallPrint('DivGrid');");


问:
There is a way to use ngx-translate in angular library and in root project at the same time?
I have angular library with a component that uses ngx-translate for translation:

```<code>@NgModule({
    imports: [
       TranslateModule.forRoot({
            loader: {
              provide: TranslateLoader,
              useClass: WebpackTranslateLoader,
              deps: [HttpClient],
            },
            isolate: true
          }),
    ],
    ...
})
export class LibraryModule {
    ...
}
</code>```

If I use this library in a simple project - it works as expected.
But if I use it in a project with its own ngx-translate configuration:

```<code>@NgModule({
  imports: [
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useClass: WebpackTranslateLoader,
        deps: [HttpClient],

       },
        }),
      ],
...
</code>```

Then project translations don't work. Translations are taken from the shared library.
If I don't use the library, it works as expected.

I have tried to use TranslateModule.forChild in library module and obtained this error:
AppComponent.html:1 ERROR NullInjectorError: StaticInjectorError(AppModule)[TranslateService -> TranslateStore]:

I use:

```<code>"@angular/core": "^9.1.4",
"@ngx-translate/core": "^12.1.2",
"@ngx-translate/http-loader": "^4.0.0",
</code>```

答:
Force assignment in component root constructor solve this problem.

```<code>this._translateService.currentLoader = new WebpackTranslateLoader();
</code>```

But child library translation is missing. It's problem solved by merging translations manually:

```<code>getTranslation(lang: string): Observable<any> {
    const result = forkJoin(
      [
        from(<rootTranslation>),
        new ChildLibraryTranslateLoader().getTranslation(lang)]
      ).pipe(map(translations => {
        return { ...translations[0], ...translations[1] };
    }));

    return result;
</code>```

Body:
I have angular library with a component that uses ngx-translate for translation:

@NgModule({
    imports: [
       TranslateModule.forRoot({
            loader: {
              provide: TranslateLoader,
              useClass: WebpackTranslateLoader,
              deps: [HttpClient],
            },
            isolate: true
          }),
    ],
    ...
})
export class LibraryModule {
    ...
}

If I use this library in a simple project - it works as expected.
But if I use it in a project with its own ngx-translate configuration:

@NgModule({
  imports: [
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useClass: WebpackTranslateLoader,
        deps: [HttpClient],

       },
        }),
      ],
...

Then project translations don't work. Translations are taken from the shared library.
If I don't use the library, it works as expected.

I have tried to use TranslateModule.forChild in library module and obtained this error:
AppComponent.html:1 ERROR NullInjectorError: StaticInjectorError(AppModule)[TranslateService -> TranslateStore]:

I use:

"@angular/core": "^9.1.4",
"@ngx-translate/core": "^12.1.2",
"@ngx-translate/http-loader": "^4.0.0",

Body:
Force assignment in component root constructor solve this problem.

this._translateService.currentLoader = new WebpackTranslateLoader();

But child library translation is missing. It's problem solved by merging translations manually:

getTranslation(lang: string): Observable<any> {
    const result = forkJoin(
      [
        from(<rootTranslation>),
        new ChildLibraryTranslateLoader().getTranslation(lang)]
      ).pipe(map(translations => {
        return { ...translations[0], ...translations[1] };
    }));

    return result;


问:
CGContext antialiasing works not as expected when drawing on transparent background
Example was taken from https://medium.com/@s1ddok/combine-the-power-of-coregraphics-and-metal-by-sharing-resource-memory-eabb4c1be615. Just changed color space from r8unorm to rgba8unorm.

```<code>// CGContext created with aligned data, which shared with MTLTexture
let cgContext = textureContext.cgContext
        let clearRect = CGRect(
                origin: .zero,
                size: CGSize(width: cgContext.width, height: cgContext.height)
        )
        cgContext.setAllowsAntialiasing(true)
        cgContext.setShouldAntialias(true)
        cgContext.clear(clearRect)

        cgContext.addPath(path)
        cgContext.setFillColor(fillColor ?? UIColor.clear.cgColor)
        cgContext.fillPath(using: fillRule.cgFillRuleValue())
</code>```

Rendered path on shared data chunk then used as texture for quad primitive that rendered on MTKView's texture. But there is problem - antialiasing will mix path fill color with clear(black) color on edges like this(hope if difference between this pics is noticeable) -

This is normal overlap, when I prefill context area with red color

If antialiasing is switched off for context - edges will clearly white, but sharpened

Is there are way to overlap two textures with clear and smooth edges without rendering an appropriate chunk of overlapped texture to overlapping texture before drawing path?

UPD:
How context is created

```<code>func createCGMTLContext(withSize size: CGSize) -> CGMTLContext? {
        let width = Int(size.width)
        let height = Int(size.height)

        let pixelRowAlignment = device.minimumTextureBufferAlignment(for: .rgba8Unorm)
        let bytesPerRow = alignUp(size: width, align: pixelRowAlignment) * 4

        let pagesize = Int(getpagesize())
        let allocationSize = alignUp(size: bytesPerRow * height, align: pagesize)
        var data: UnsafeMutableRawPointer? = nil
        let result = posix_memalign(&data, pagesize, allocationSize)
        if result != noErr {
            fatalError("Error during memory allocation")
        }

        let context = CGContext(data: data,
                width: width,
                height: height,
                bitsPerComponent: 8,
                bytesPerRow: bytesPerRow,
                space: CGColorSpaceCreateDeviceRGB(),
                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!

        context.scaleBy(x: 1.0, y: -1.0)
        context.translateBy(x: 0, y: -CGFloat(context.height))

        let buffer = device.makeBuffer(
                bytesNoCopy: context.data!,
                length: allocationSize,
                options: .storageModeShared,
                deallocator: { pointer, length in free(data) }
        )!

        let textureDescriptor = MTLTextureDescriptor()
        textureDescriptor.pixelFormat = .rgba8Unorm
        textureDescriptor.width = context.width
        textureDescriptor.height = context.height
        textureDescriptor.storageMode = buffer.storageMode
        textureDescriptor.usage = .shaderRead

        let texture = buffer.makeTexture(descriptor: textureDescriptor,
                offset: 0,
                bytesPerRow: context.bytesPerRow)

        guard let requiredTexture = texture else {
            return nil
        }

        let cgmtlContext = CGMTLContext(
                cgContext: context,
                buffer: buffer,
                texture: requiredTexture
        )

        return cgmtlContext
    }
</code>```

There is how metal blending setted up

```<code>pipelineDescriptor.colorAttachments[0].rgbBlendOperation = .add
            pipelineDescriptor.colorAttachments[0].alphaBlendOperation = .add
            pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = .sourceAlpha
            pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = .sourceAlpha
            pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
            pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha
</code>```

答:
After reading https://metalbyexample.com/translucency-and-transparency/ I noticed a comment from Warren Moore:

Since you’re loading your textures with CoreGraphics, you’re getting premultiplied alpha (i.e., the color channels are already multiplied by their respective alpha values). The consequence of using premultiplied alpha with the SourceAlpha, OneMinusSourceAlpha blend factors is that the source alpha value is redundantly multiplied, causing areas with a < 1.0 to become unnaturally dark. If instead you use the One, OneMinusSourceAlpha blend factors, you get a much more pleasing result.Incidentally, this is the main reason I used an opaque texture and translucent vertex colors when demonstrating blending in the article.

Changing sourceAlpha to One helped. Unfortunately, alpha premultiplying in CGContext can't be turned off

Body:
Example was taken from https://medium.com/@s1ddok/combine-the-power-of-coregraphics-and-metal-by-sharing-resource-memory-eabb4c1be615. Just changed color space from r8unorm to rgba8unorm.

// CGContext created with aligned data, which shared with MTLTexture
let cgContext = textureContext.cgContext
        let clearRect = CGRect(
                origin: .zero,
                size: CGSize(width: cgContext.width, height: cgContext.height)
        )
        cgContext.setAllowsAntialiasing(true)
        cgContext.setShouldAntialias(true)
        cgContext.clear(clearRect)

        cgContext.addPath(path)
        cgContext.setFillColor(fillColor ?? UIColor.clear.cgColor)
        cgContext.fillPath(using: fillRule.cgFillRuleValue())

Rendered path on shared data chunk then used as texture for quad primitive that rendered on MTKView's texture. But there is problem - antialiasing will mix path fill color with clear(black) color on edges like this(hope if difference between this pics is noticeable) -

This is normal overlap, when I prefill context area with red color

If antialiasing is switched off for context - edges will clearly white, but sharpened

Is there are way to overlap two textures with clear and smooth edges without rendering an appropriate chunk of overlapped texture to overlapping texture before drawing path?

UPD:
How context is created

func createCGMTLContext(withSize size: CGSize) -> CGMTLContext? {
        let width = Int(size.width)
        let height = Int(size.height)

        let pixelRowAlignment = device.minimumTextureBufferAlignment(for: .rgba8Unorm)
        let bytesPerRow = alignUp(size: width, align: pixelRowAlignment) * 4

        let pagesize = Int(getpagesize())
        let allocationSize = alignUp(size: bytesPerRow * height, align: pagesize)
        var data: UnsafeMutableRawPointer? = nil
        let result = posix_memalign(&data, pagesize, allocationSize)
        if result != noErr {
            fatalError("Error during memory allocation")
        }

        let context = CGContext(data: data,
                width: width,
                height: height,
                bitsPerComponent: 8,
                bytesPerRow: bytesPerRow,
                space: CGColorSpaceCreateDeviceRGB(),
                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!

        context.scaleBy(x: 1.0, y: -1.0)
        context.translateBy(x: 0, y: -CGFloat(context.height))

        let buffer = device.makeBuffer(
                bytesNoCopy: context.data!,
                length: allocationSize,
                options: .storageModeShared,
                deallocator: { pointer, length in free(data) }
        )!

        let textureDescriptor = MTLTextureDescriptor()
        textureDescriptor.pixelFormat = .rgba8Unorm
        textureDescriptor.width = context.width
        textureDescriptor.height = context.height
        textureDescriptor.storageMode = buffer.storageMode
        textureDescriptor.usage = .shaderRead

        let texture = buffer.makeTexture(descriptor: textureDescriptor,
                offset: 0,
                bytesPerRow: context.bytesPerRow)

        guard let requiredTexture = texture else {
            return nil
        }

        let cgmtlContext = CGMTLContext(
                cgContext: context,
                buffer: buffer,
                texture: requiredTexture
        )

        return cgmtlContext
    }

There is how metal blending setted up

pipelineDescriptor.colorAttachments[0].rgbBlendOperation = .add
            pipelineDescriptor.colorAttachments[0].alphaBlendOperation = .add
            pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = .sourceAlpha
            pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = .sourceAlpha
            pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
            pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha


问:
React form upload auto submitting, depending on the order
can anyone please help me, with my upload form code, for some reason my onChange function on the other inputs prevent you from adding images first before filling in the other fields, if you do it automatically submits the form. This is not a working version, but it is the full code: https://codesandbox.io/s/reverent-hugle-rsqqx

I'm not referring to the splitURL message it shows, if you fill out each of the text fields and then add the images, it's fine.

It doesn't submit, which allows the user to click the submit button.

If you add images first and then fill out just one of the text fields the form submits automatically.

I do not want this, I am designing a page where I would like to have the option to add the images for upload before filling out the rest of the form.

The only thing I can pinpoint it down to is the onChange function, if i remove that from one of the inputs I can fill out the input after adding images.

答:
found the problem, the library "react-filepond" main element "FilePond" is specting an array of objects in the "files" property, so to fix the problem you just do the following:

```<code>// Add the spread operator in the items array too.
setPosterCollection([...posterCollection, ...items]);
</code>```

This will fix the error and allow the user to fill the form in any order as he/she wish to.

Body:
found the problem, the library "react-filepond" main element "FilePond" is specting an array of objects in the "files" property, so to fix the problem you just do the following:

// Add the spread operator in the items array too.
setPosterCollection([...posterCollection, ...items]);

This will fix the error and allow the user to fill the form in any order as he/she wish to.


问:
AWS Amplify Console shows weird xml instead of 404
I´ve deployed a vanilla js app via the AWS amplify console and got a subdomain from amplifyapp.com. When I call source files directly, f.e. master.myappid.amplifyapp.com/js/index.js, the content is being shown like it should. Also, when calling the domain without any specific file, it will show the index.html as expected. But, when calling non-existant folders or just a sub-folder, not a specific file in it, it will not throw a 404, but instead show a weird xml response, something like this:

```<code><Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>X</RequestId><HostId>X</HostId></Error>
</code>```

Also, when calling non-existant files, f.e. /abc.html, it will also show this message. How can I setup a rule to make AWS Amplify Console show a 404 when sub-directories with no index.html, non-existant directorys or non-existant files are being called?

答: The AWS Amplify documentation has further detail on using Redirects to handle this situation. For my case, I created a SPA app (React) and you must set up a Redirect for direct URL navigation to work with Amplify.</p>

Body:
I´ve deployed a vanilla js app via the AWS amplify console and got a subdomain from amplifyapp.com. When I call source files directly, f.e. master.myappid.amplifyapp.com/js/index.js, the content is being shown like it should. Also, when calling the domain without any specific file, it will show the index.html as expected. But, when calling non-existant folders or just a sub-folder, not a specific file in it, it will not throw a 404, but instead show a weird xml response, something like this:

<Error>AccessDenied<Message>Access Denied</Message><RequestId>X</RequestId><HostId>X</HostId></Error>

Also, when calling non-existant files, f.e. /abc.html, it will also show this message. How can I setup a rule to make AWS Amplify Console show a 404 when sub-directories with no index.html, non-existant directorys or non-existant files are being called?


问:
Why is there a curled bracket on the List?
Recently stumped upon this line in a program, and I have no idea what the bracket for (List<Level>) is for . Anybody got any idea ?

List<Level> levelList = (List<Level>)dao.getAllLevels();

答: It's called a cast. It's used to enforce the type of the following variable, in this case, to be sure that dao.getAllLevels() returns an object of type List.</p>


问:
Google Sheets DGET function not matching on a case where data exists
In the following sheet

https://docs.google.com/spreadsheets/d/1xFtZJOQ1JbnyKTBrFx-P9H10XqAmYE8zEiP7aaFAVe4/edit?usp=sharing

in tab Sheet1 cell AB3 I am trying to link DGET to pull the timestamp from tab Pre-Installation matching on the complaint number column W. It shows no results despite the row having the value

Is there some aspect I am missing here. The function being used is

=DGET('Pre-Installation'!A:I,"Timestamp",{"Complaint Number"; W3})

答:
Updated answer (following OP's sharing the sheet)

The formula does work as expected.

Please make sure the headings match exactly.

The problem lies in the fact that in your imported data, the heading is

Complaint Number +1ExtraSpace .

Notice the extra empty space in the end.

What you have in your DGET function is

Complaint Number +NoExtraSpace.

Since the data is imported, by changing the heading to Complaint Number without any extra space in the end, the formula works as expected.

BEST PRACTICE

When writing the formula, always Copy+Paste the headers, thus avoiding any mistakes

Original answer

The formula does work as expected.

```<code>=DGET('Pre-Installation'!A:I,"Timestamp",{"Complaint Number"; W3})
</code>```

You do need though to format it as Date time from the menu.

Body:
Updated answer (following OP's sharing the sheet)

The formula does work as expected.

Please make sure the headings match exactly.

The problem lies in the fact that in your imported data, the heading is

Complaint Number +1ExtraSpace .

Notice the extra empty space in the end.

What you have in your DGET function is

Complaint Number +NoExtraSpace.

Since the data is imported, by changing the heading to Complaint Number without any extra space in the end, the formula works as expected.

BEST PRACTICE

When writing the formula, always Copy+Paste the headers, thus avoiding any mistakes

Original answer

The formula does work as expected.

=DGET('Pre-Installation'!A:I,"Timestamp",{"Complaint Number"; W3})

You do need though to format it as Date time from the menu.


问:
iOS: centering CAShapeLayer inside a constrained subview
I'm trying to render a shape in the center of Circle, a custom subclass of UIView (first snippet). Then I'm adding the Circle as a subview in my VC and adding constraints (second snippet).

When height and width is constrained, the rendered shape has its center (undesirably) in the top left corner of the Circle view (picture bellow). When only X and Y of the Circle view are constrained, the shape is in center as expected.

Why does this happen and what do I do to be able to constrain Circle as I please but still have the shape render in the center of Circle ? Thanks.

Circle:

```<code>class Circle: UIView {

func render(){
    let shapeLayer = CAShapeLayer()
    let center = self.center
    let endAngle = 2 * CGFloat.pi
    let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: 0, endAngle: endAngle, clockwise: true)

    shapeLayer.path = circularPath.cgPath
    self.layer.addSublayer(shapeLayer)
  }
}
</code>```

VC:

```<code>class VC: UIViewController {
let circle = Circle()

override func viewDidLoad() {
    super.viewDidLoad()
    configure()
    circle.render()
}

func configure(){
    view.backgroundColor = .white
    view.addSubview(progressCircle)
    progressCircle.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        progressCircle.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        progressCircle.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        progressCircle.heightAnchor.constraint(equalToConstant: 200),
        progressCircle.widthAnchor.constraint(equalToConstant: 200)
    ])
  }
}
</code>```

Result:

答:
Here is fixed view (tested with Xcode 11.4 / Playground)</p>

```<code>class Circle: UIView {
    let shapeLayer = CAShapeLayer()

override func layoutSubviews() {
    super.layoutSubviews()
    shapeLayer.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
}

func render(){
    let center = self.center
    let endAngle = 2 * CGFloat.pi
    let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: 0, endAngle: endAngle, clockwise: true)

    shapeLayer.path = circularPath.cgPath
    self.layer.addSublayer(shapeLayer)
  }
}
</code>```

Body:
I'm trying to render a shape in the center of Circle, a custom subclass of UIView (first snippet). Then I'm adding the Circle as a subview in my VC and adding constraints (second snippet).

When height and width is constrained, the rendered shape has its center (undesirably) in the top left corner of the Circle view (picture bellow). When only X and Y of the Circle view are constrained, the shape is in center as expected.

Why does this happen and what do I do to be able to constrain Circle as I please but still have the shape render in the center of Circle ? Thanks.

Circle:

class Circle: UIView {

func render(){
    let shapeLayer = CAShapeLayer()
    let center = self.center
    let endAngle = 2 * CGFloat.pi
    let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: 0, endAngle: endAngle, clockwise: true)

    shapeLayer.path = circularPath.cgPath
    self.layer.addSublayer(shapeLayer)
  }
}

VC:

class VC: UIViewController {
let circle = Circle()

override func viewDidLoad() {
    super.viewDidLoad()
    configure()
    circle.render()
}

func configure(){
    view.backgroundColor = .white
    view.addSubview(progressCircle)
    progressCircle.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        progressCircle.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        progressCircle.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        progressCircle.heightAnchor.constraint(equalToConstant: 200),
        progressCircle.widthAnchor.constraint(equalToConstant: 200)
    ])
  }
}

Result:

Body:
Here is fixed view (tested with Xcode 11.4 / Playground)

class Circle: UIView {
    let shapeLayer = CAShapeLayer()

override func layoutSubviews() {
    super.layoutSubviews()
    shapeLayer.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
}

func render(){
    let center = self.center
    let endAngle = 2 * CGFloat.pi
    let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: 0, endAngle: endAngle, clockwise: true)

    shapeLayer.path = circularPath.cgPath
    self.layer.addSublayer(shapeLayer)
  }
}


问:
Contact form 7 not show success message?
I have copied code about contact form 7 wordpress, currently the data has been successfully sent to the database external, but the messages success are almost not displayed as well as I have moved to the thank you page. Thank you

```<code>function wpcf7_send_to_external ( $cf7 ) {

//external db details
$username = 'username';
$password = 'pass';
$database = 'database';
$host = 'myip';

//create new wpdb instance
$mydb = new wpdb($username, $password, $database, $host);

        $cf7 = WPCF7_ContactForm::get_current();
        $submission = WPCF7_Submission::get_instance();
        $data = $submission->get_posted_data();

        $field1 = $data["name"];
        $field2 = $data["semail"];
        $field3 = $data["phone"];
        $field4 = $data["nhu"];

        //insert into external db
        $mydb->insert(

            'customer',

            array(
                'name' => $field1,
                'email' => $field2,
                'phone' => $field3,
                'content' => $field4
            ),

            array(
                '%s','%s','%s','%s'
            )
        );
</code>```

}

add_action("wpcf7_before_send_mail", "wpcf7_send_to_external");

答:
This looks like it's called from a JavaScript file you could just do a console.log there.

```<code>console.log("Success message!");
</code>```

If you need data from the PHP file you can send it back with an echo. (Which can be accessed as the response to the HTTP request.

```<code>echo "some data: $variable";
</code>```

Body:
I have copied code about contact form 7 wordpress, currently the data has been successfully sent to the database external, but the messages success are almost not displayed as well as I have moved to the thank you page. Thank you

function wpcf7_send_to_external ( $cf7 ) {

//external db details
$username = 'username';
$password = 'pass';
$database = 'database';
$host = 'myip';

//create new wpdb instance
$mydb = new wpdb($username, $password, $database, $host);

        $cf7 = WPCF7_ContactForm::get_current();
        $submission = WPCF7_Submission::get_instance();
        $data = $submission->get_posted_data();

        $field1 = $data["name"];
        $field2 = $data["semail"];
        $field3 = $data["phone"];
        $field4 = $data["nhu"];

        //insert into external db
        $mydb->insert(

            'customer',

            array(
                'name' => $field1,
                'email' => $field2,
                'phone' => $field3,
                'content' => $field4
            ),

            array(
                '%s','%s','%s','%s'
            )
        );

}

add_action("wpcf7_before_send_mail", "wpcf7_send_to_external");

Body:
This looks like it's called from a JavaScript file you could just do a console.log there.

console.log("Success message!");

If you need data from the PHP file you can send it back with an echo. (Which can be accessed as the response to the HTTP request.

echo "some data: $variable";


问:
Can you compare values across probes in a multi-CPU safe way in DTrace?
I'm trying to write a DTrace script which does the following:

Whenever a new thread is started, increment a count.

Whenever one of these threads exits, decrement the count, and exit the script if the count is now zero.

I have something like this:

```<code>BEGIN {
  threads_alive = 0;
}

proc:::lwp-start /execname == $$1/ {
  self->started = timestamp;
  threads_alive += 1;
}

proc:::lwp-exit /self->started/ {
  threads_alive -= 1;
  if (threads_alive == 0) {
    exit(0);
  }
}
</code>```

However, this doesn't work, because threads_alive is a scalar variable and thus it is not multi-cpu safe. As a result, multiple threads will overwrite each other's changes to the variable.

I have also tried using an aggregate variable instead:

```<code>@thread_count = sum(1)
//or
@threads_entered = count();
@threads_exitted = count();
</code>```

Unfortunately, I haven't found syntax to be able to do something like @thread_count == 0 or @threads_started == @threads_stopped.

答:
DTrace doesn't have facilities for doing the kind of thread-safe data sharing you're proposing, but you have a few options depending on precisely what you're trying to do.

If the executable name is unique, you can use the proc:::start and proc:::exit probes for the start of the first thread and the exit of the last thread respectively:

```<code>proc:::start
/execname == $$1/
{
        my_pid = pid;
}

proc:::exit
/pid == my_pid/
{
        exit(0);
}
</code>```

If you're using the -c option to dtrace, the BEGIN probe fires very shortly after the corresponding proc:::start. Internally, dtrace -c starts the specified forks the specified command and then starts tracing at one of four points: exec (before the first instruction of the new program), preinit (after ld has loaded all libraries), postinit (after each library's _init has run), or main (right before the first instruction of the program's main function, though this is not supported in macOS).

If you use dtrace -x evaltime=exec -c <program> BEGIN will fire right before the first instruction of the program executes:

```<code># dtrace -xevaltime=exec -c /usr/bin/true -n 'BEGIN{ts = timestamp}' -n 'pid$target:::entry{printf("%dus", (timestamp - ts)/1000); exit(0); }'
dtrace: description 'BEGIN' matched 1 probe
dtrace: description 'pid$target:::entry' matched 1767 probes
dtrace: pid 1848 has exited
CPU     ID                    FUNCTION:NAME
 10  16757                _dyld_start:entry 285us
</code>```

The 285us is due to the time it takes dtrace to resume the process via /proc or ptrace(2) on macOS. Rather than proc:::start or proc:::lwp-start you may be able to use BEGIN, pid$target::_dyld_start:entry, or pid$target::main:entry.

Body:
I'm trying to write a DTrace script which does the following:

Whenever a new thread is started, increment a count.

Whenever one of these threads exits, decrement the count, and exit the script if the count is now zero.

I have something like this:

BEGIN {
  threads_alive = 0;
}

proc:::lwp-start /execname == $$1/ {
  self->started = timestamp;
  threads_alive += 1;
}

proc:::lwp-exit /self->started/ {
  threads_alive -= 1;
  if (threads_alive == 0) {
    exit(0);
  }
}

However, this doesn't work, because threads_alive is a scalar variable and thus it is not multi-cpu safe. As a result, multiple threads will overwrite each other's changes to the variable.

I have also tried using an aggregate variable instead:

@thread_count = sum(1)
//or
@threads_entered = count();
@threads_exitted = count();

Unfortunately, I haven't found syntax to be able to do something like @thread_count == 0 or @threads_started == @threads_stopped.

Body:
DTrace doesn't have facilities for doing the kind of thread-safe data sharing you're proposing, but you have a few options depending on precisely what you're trying to do.

If the executable name is unique, you can use the proc:::start and proc:::exit probes for the start of the first thread and the exit of the last thread respectively:

proc:::start
/execname == $$1/
{
        my_pid = pid;
}

proc:::exit
/pid == my_pid/
{
        exit(0);
}

If you're using the -c option to dtrace, the BEGIN probe fires very shortly after the corresponding proc:::start. Internally, dtrace -c starts the specified forks the specified command and then starts tracing at one of four points: exec (before the first instruction of the new program), preinit (after ld has loaded all libraries), postinit (after each library's _init has run), or main (right before the first instruction of the program's main function, though this is not supported in macOS).

If you use dtrace -x evaltime=exec -c <program> BEGIN will fire right before the first instruction of the program executes:

# dtrace -xevaltime=exec -c /usr/bin/true -n 'BEGIN{ts = timestamp}' -n 'pid$target:::entry{printf("%dus", (timestamp - ts)/1000); exit(0); }'
dtrace: description 'BEGIN' matched 1 probe
dtrace: description 'pid$target:::entry' matched 1767 probes
dtrace: pid 1848 has exited
CPU     ID                    FUNCTION:NAME
 10  16757                _dyld_start:entry 285us

The 285us is due to the time it takes dtrace to resume the process via /proc or ptrace(2) on macOS. Rather than proc:::start or proc:::lwp-start you may be able to use BEGIN, pid$target::_dyld_start:entry, or pid$target::main:entry.


问:
cosine similarity = 1.0 even when source/input string has extra tokens not seen in the corpus?
I am using TfidfVectorizer and cosine_similarity from scikit-learn.  When I have a new string and I try to find the cosine similarity to the strings in the original training corpus, I notice that the cosine similarity is 1.0 even when the string is an exact match plus additional novel tokens in the new string, no matter how many such additional tokens there are.

For example a new string of the form "a b x y z" will have cosine similarity 1.0 to an original string "a b" if x, y, and z are not in the original corpus at all.

I understand how this happens, because the novel tokens are ignored when vectorizing the new string according to the features established by the training corpus, but I want to be able to detect that "a b x y z" is NOT really a "perfect" match to "a b".

Any ideas on how I could incorporate something into the matching that would be sensitive to this type of difference (presence of novel tokens)?

Edit: here is an illustration based on the comments of @Arash:

The scenario I am describing tries to match novel input to the trained corpus:

```<code>corpus = (
        "The sky is blue",
        "The sun is bright",
        "The sun in the sky is bright",
        "We can see the shining sun, the bright sun"
        )
input = ("The sky is blue",
        "They say the sky is blue you know",
        )
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer()
tfidf_corpus = tfidf_vectorizer.fit_transform(corpus)
print(tfidf_corpus.shape)

tfidf_input = tfidf_vectorizer.transform(input)
print(tfidf_input.shape)

from sklearn.metrics.pairwise import cosine_similarity
cosine_similarity(tfidf_input, tfidf_corpus)
</code>```

The output is

```<code>(4, 11)
(2, 11)
array([[1.        , 0.36651513, 0.52305744, 0.13448867],
       [1.        , 0.36651513, 0.52305744, 0.13448867]])
</code>```

So you can see that both input strings/documents get a perfect similarity of 1.0 to the corpus's "The sky is blue" even though the second input ("They say the sky is blue you know") has several non-matching words (which happen not to appear in the corpus).

I would have expected that the cosine similarity for my second input item could be computed on an extended vector that adds elements for the novel words (each of which has a document frequency of 0 and so maximal IDF), so that the similarity would come out lower.

Simply including the new input data in the corpus is not a good general solution since we might receive new inputs one at a time in the future and we don't want to have to re-train the entire corpus every time we want to match one new input document/string.

答:
I can't replicate what you are describing. Try this:

    documents = (
    "The sky is blue",
    "The sky is blue you know",
    "The sun is bright",
    "The sun in the sky is bright",
    "We can see the shining sun, the bright sun"
    )

    from sklearn.feature_extraction.text import TfidfVectorizer
    tfidf_vectorizer = TfidfVectorizer()
    tfidf_matrix = tfidf_vectorizer.fit_transform(documents)
    print(tfidf_matrix.shape)

    from sklearn.metrics.pairwise import cosine_similarity
    cosine_similarity(tfidf_matrix[0:1], tfidf_matrix)
```

<p>Your output will be </p>

<pre class="lang-py prettyprint-override"><code>    array([[1.        , 0.67166626, 0.35369001, 0.50353381, 0.13245011]])
</code>```

This indicates that the similarity between the first and second sentences is 0.67, not 1.0

EDITED
The issue that you are describing is that the vectors are identical. You want the TF-IDF to take the new words and the frequency of the new words into account.
So, you can just do this:

    # refit tfidf_vectorizer to the corpus and new documents
    tfidf_vectorizer.fit(input + corpus)
    # transform using the new model
    tfidf_input = tfidf_vectorizer.transform(input)
```

Body:
I am using TfidfVectorizer and cosine_similarity from scikit-learn.  When I have a new string and I try to find the cosine similarity to the strings in the original training corpus, I notice that the cosine similarity is 1.0 even when the string is an exact match plus additional novel tokens in the new string, no matter how many such additional tokens there are.

For example a new string of the form "a b x y z" will have cosine similarity 1.0 to an original string "a b" if x, y, and z are not in the original corpus at all.

I understand how this happens, because the novel tokens are ignored when vectorizing the new string according to the features established by the training corpus, but I want to be able to detect that "a b x y z" is NOT really a "perfect" match to "a b".

Any ideas on how I could incorporate something into the matching that would be sensitive to this type of difference (presence of novel tokens)?

Edit: here is an illustration based on the comments of @Arash:

The scenario I am describing tries to match novel input to the trained corpus:

corpus = (
        "The sky is blue",
        "The sun is bright",
        "The sun in the sky is bright",
        "We can see the shining sun, the bright sun"
        )
input = ("The sky is blue",
        "They say the sky is blue you know",
        )
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer()
tfidf_corpus = tfidf_vectorizer.fit_transform(corpus)
print(tfidf_corpus.shape)

tfidf_input = tfidf_vectorizer.transform(input)
print(tfidf_input.shape)

from sklearn.metrics.pairwise import cosine_similarity
cosine_similarity(tfidf_input, tfidf_corpus)

The output is

(4, 11)
(2, 11)
array([[1.        , 0.36651513, 0.52305744, 0.13448867],
       [1.        , 0.36651513, 0.52305744, 0.13448867]])

So you can see that both input strings/documents get a perfect similarity of 1.0 to the corpus's "The sky is blue" even though the second input ("They say the sky is blue you know") has several non-matching words (which happen not to appear in the corpus).

I would have expected that the cosine similarity for my second input item could be computed on an extended vector that adds elements for the novel words (each of which has a document frequency of 0 and so maximal IDF), so that the similarity would come out lower.

Simply including the new input data in the corpus is not a good general solution since we might receive new inputs one at a time in the future and we don't want to have to re-train the entire corpus every time we want to match one new input document/string.

Body:
I can't replicate what you are describing. Try this:

    documents = (
    "The sky is blue",
    "The sky is blue you know",
    "The sun is bright",
    "The sun in the sky is bright",
    "We can see the shining sun, the bright sun"
    )

    from sklearn.feature_extraction.text import TfidfVectorizer
    tfidf_vectorizer = TfidfVectorizer()
    tfidf_matrix = tfidf_vectorizer.fit_transform(documents)
    print(tfidf_matrix.shape)

    from sklearn.metrics.pairwise import cosine_similarity
    cosine_similarity(tfidf_matrix[0:1], tfidf_matrix)

Your output will be

    array([[1.        , 0.67166626, 0.35369001, 0.50353381, 0.13245011]])

This indicates that the similarity between the first and second sentences is 0.67, not 1.0

EDITED
The issue that you are describing is that the vectors are identical. You want the TF-IDF to take the new words and the frequency of the new words into account.
So, you can just do this:

    # refit tfidf_vectorizer to the corpus and new documents
    tfidf_vectorizer.fit(input + corpus)
    # transform using the new model
    tfidf_input = tfidf_vectorizer.transform(input)


问:
Can I run Scrapy on Windows with Python 3?
Seems like Scrapy 1.1.0rc3 isn't working on Windows with Python 3.

When I run scrapy crawl dmoz command specified on Scrapy tutorial I get following exception:

```<code>D:\Copy From 2\Python Project\ZhihuPlan\tutorial\tutorial>scrapy crawl dmoz
2016-04-26 14:40:36 [scrapy] INFO: Scrapy 1.1.0rc3 started (bot: tutorial)
2016-04-26 14:40:36 [scrapy] INFO: Overridden settings: {'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['tutorial.spiders'], 'BOT_NAME': 'tutorial', 'NEWSPIDER_MODULE': 'tutorial.spiders'}
2016-04-26 14:40:36 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.logstats.LogStats']
Unhandled error in Deferred:
2016-04-26 14:40:36 [twisted] CRITICAL: Unhandled error in Deferred:

Traceback (most recent call last):
File "D:\Anaconda\Lib\site-packages\scrapy\commands\crawl.py", line 57, in run self.crawler_process.crawl(spname, **opts.spargs)
File "D:\Anaconda\Lib\site-packages\scrapy\crawler.py", line 163, in crawl return self._crawl(crawler, *args, **kwargs)
File "D:\Anaconda\Lib\site-packages\scrapy\crawler.py", line 167, in _crawl
    d = crawler.crawl(*args, **kwargs)
File "D:\Anaconda\Lib\site-packages\twisted\internet\defer.py", line 1274, in unwindGenerator
    return _inlineCallbacks(None, gen, Deferred())
--- <exception caught here> ---
  File "D:\Anaconda\Lib\site-packages\twisted\internet\defer.py", line 1128, in _inlineCallbacks
    result = g.send(result)
  File "D:\Anaconda\Lib\site-packages\scrapy\crawler.py", line 72, in crawl
    self.engine = self._create_engine()
  File "D:\Anaconda\Lib\site-packages\scrapy\crawler.py", line 97, in _create_engine
    return ExecutionEngine(self, lambda _: self.stop())
  File "D:\Anaconda\Lib\site-packages\scrapy\core\engine.py", line 68, in __init__
    self.downloader = downloader_cls(crawler)
  File "D:\Anaconda\Lib\site-packages\scrapy\core\downloader\__init__.py", line 88, in __init__
    self.middleware = DownloaderMiddlewareManager.from_crawler(crawler)
  File "D:\Anaconda\Lib\site-packages\scrapy\middleware.py", line 58, in from_crawler
    return cls.from_settings(crawler.settings, crawler)
  File "D:\Anaconda\Lib\site-packages\scrapy\middleware.py", line 34, in from_settings
    mwcls = load_object(clspath)
  File "D:\Anaconda\Lib\site-packages\scrapy\utils\misc.py", line 44, in load_object
    mod = import_module(module)
  File "d:\anaconda\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import

 File "<frozen importlib._bootstrap>", line 969, in _find_and_load

  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked

  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked

  File "<frozen importlib._bootstrap_external>", line 662, in exec_module

  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed

  File "D:\Anaconda\Lib\site-packages\scrapy\downloadermiddlewares\retry.py", line 23, in <module>
    from scrapy.xlib.tx import ResponseFailed
  File "D:\Anaconda\Lib\site-packages\scrapy\xlib\tx\__init__.py", line 3, in <module>
    from twisted.web import client
  File "D:\Anaconda\Lib\site-packages\twisted\web\client.py", line 41, in <module>
    from twisted.internet.endpoints import TCP4ClientEndpoint, SSL4ClientEndpoint
  File "D:\Anaconda\Lib\site-packages\twisted\internet\endpoints.py", line 34, in <module>
    from twisted.internet.stdio import StandardIO, PipeAddress
  File "D:\Anaconda\Lib\site-packages\twisted\internet\stdio.py", line 30, in <module>
    from twisted.internet import _win32stdio
builtins.ImportError: cannot import name '_win32stdio'
2016-04-26 14:40:36 [twisted] CRITICAL:
</code>```

Is there any way to fix this error? Can I run Scrapy on Windows with Python 3?

答:
Scrapy now works for on Windows 10 with Python 3. I tried it just now through conda prompt.

First, open conda and activate the environment to which you added scrapy.

```<code>conda activate <your environment>
</code>```

Then run scrapy

```<code>scrapy runspider <path.to.file.py>
</code>```

...and scrapy should run.

Body:
Seems like Scrapy 1.1.0rc3 isn't working on Windows with Python 3.

When I run scrapy crawl dmoz command specified on Scrapy tutorial I get following exception:

D:\Copy From 2\Python Project\ZhihuPlan\tutorial\tutorial>scrapy crawl dmoz
2016-04-26 14:40:36 [scrapy] INFO: Scrapy 1.1.0rc3 started (bot: tutorial)
2016-04-26 14:40:36 [scrapy] INFO: Overridden settings: {'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['tutorial.spiders'], 'BOT_NAME': 'tutorial', 'NEWSPIDER_MODULE': 'tutorial.spiders'}
2016-04-26 14:40:36 [scrapy] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.logstats.LogStats']
Unhandled error in Deferred:
2016-04-26 14:40:36 [twisted] CRITICAL: Unhandled error in Deferred:

Traceback (most recent call last):
File "D:\Anaconda\Lib\site-packages\scrapy\commands\crawl.py", line 57, in run self.crawler_process.crawl(spname, **opts.spargs)
File "D:\Anaconda\Lib\site-packages\scrapy\crawler.py", line 163, in crawl return self._crawl(crawler, *args, **kwargs)
File "D:\Anaconda\Lib\site-packages\scrapy\crawler.py", line 167, in _crawl
    d = crawler.crawl(*args, **kwargs)
File "D:\Anaconda\Lib\site-packages\twisted\internet\defer.py", line 1274, in unwindGenerator
    return _inlineCallbacks(None, gen, Deferred())
--- <exception caught here> ---
  File "D:\Anaconda\Lib\site-packages\twisted\internet\defer.py", line 1128, in _inlineCallbacks
    result = g.send(result)
  File "D:\Anaconda\Lib\site-packages\scrapy\crawler.py", line 72, in crawl
    self.engine = self._create_engine()
  File "D:\Anaconda\Lib\site-packages\scrapy\crawler.py", line 97, in _create_engine
    return ExecutionEngine(self, lambda _: self.stop())
  File "D:\Anaconda\Lib\site-packages\scrapy\core\engine.py", line 68, in __init__
    self.downloader = downloader_cls(crawler)
  File "D:\Anaconda\Lib\site-packages\scrapy\core\downloader\__init__.py", line 88, in __init__
    self.middleware = DownloaderMiddlewareManager.from_crawler(crawler)
  File "D:\Anaconda\Lib\site-packages\scrapy\middleware.py", line 58, in from_crawler
    return cls.from_settings(crawler.settings, crawler)
  File "D:\Anaconda\Lib\site-packages\scrapy\middleware.py", line 34, in from_settings
    mwcls = load_object(clspath)
  File "D:\Anaconda\Lib\site-packages\scrapy\utils\misc.py", line 44, in load_object
    mod = import_module(module)
  File "d:\anaconda\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import

 File "<frozen importlib._bootstrap>", line 969, in _find_and_load

  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked

  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked

  File "<frozen importlib._bootstrap_external>", line 662, in exec_module

  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed

  File "D:\Anaconda\Lib\site-packages\scrapy\downloadermiddlewares\retry.py", line 23, in <module>
    from scrapy.xlib.tx import ResponseFailed
  File "D:\Anaconda\Lib\site-packages\scrapy\xlib\tx\__init__.py", line 3, in <module>
    from twisted.web import client
  File "D:\Anaconda\Lib\site-packages\twisted\web\client.py", line 41, in <module>
    from twisted.internet.endpoints import TCP4ClientEndpoint, SSL4ClientEndpoint
  File "D:\Anaconda\Lib\site-packages\twisted\internet\endpoints.py", line 34, in <module>
    from twisted.internet.stdio import StandardIO, PipeAddress
  File "D:\Anaconda\Lib\site-packages\twisted\internet\stdio.py", line 30, in <module>
    from twisted.internet import _win32stdio
builtins.ImportError: cannot import name '_win32stdio'
2016-04-26 14:40:36 [twisted] CRITICAL:

Is there any way to fix this error? Can I run Scrapy on Windows with Python 3?

Body:
Scrapy now works for on Windows 10 with Python 3. I tried it just now through conda prompt.

First, open conda and activate the environment to which you added scrapy.

conda activate <your environment>

Then run scrapy

scrapy runspider <path.to.file.py>

...and scrapy should run.


问:
Flutter http headers
The post request is throwing an error while setting the header map.

Here is my code

```<code>Future<GenericResponse> makePostCall(
  GenericRequest genericRequest) {String URL = "$BASE_URL/api/";

Map data = {
  "name": "name",
  "email": "email",
  "mobile": "mobile",
  "transportationRequired": false,
  "userId": 5,
};

Map userHeader = {"Content-type": "application/json", "Accept": "application/json"};

return _netUtil.post(URL, body: data, headers:userHeader).then((dynamic res) {
  print(res);
  if (res["code"] != 200) throw new Exception(res["message"][0]);
  return GenericResponse.fromJson(res);
});

}
</code>```

but I'm getting this exception with headers.

```<code>══╡ EXCEPTION CAUGHT BY GESTURE ╞═
flutter: The following assertion was thrown while handling a gesture:
flutter: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      NetworkUtil.post1 (package:saranam/network/network_util.dart:50:41)
flutter: #1      RestDatasource.bookPandit (package:saranam/network/rest_data_source.dart:204:21)
</code>```

Anybody facing this issue? I didn't find any clue with the above log.

答:
```<code> void getApi() async {
SharedPreferences prefsss = await SharedPreferences.getInstance();
String tokennn = prefsss.get("k_token");
String url = 'http://yourhost.com/services/Default/Places/List';
Map<String, String> mainheader = {
  "Content-type": "application/json",
  "Cookie": tokennn
};
String requestBody =
    '{"Take":100,"IncludeColumns":["Id","Name","Address","PhoneNumber","WebSite","Username","ImagePath","ServiceName","ZoneID","GalleryImages","Distance","ServiceTypeID"],"EqualityFilter":{"ServiceID":${_radioValue2 != null ? _radioValue2 : '""'},"ZoneID":"","Latitude":"${fav_lat != null ? fav_lat : 0.0}","Longitude":"${fav_long != null ? fav_long : 0.0}","SearchDistance":"${distanceZone}"},"ContainsText":"${_txtSearch}"}';

Response response = await post(url , headers: mainheader ,body:requestBody);
String parsedata = response.body;
var data = jsonDecode(parsedata);
var getval = data['Entities'] as List;
setState(() {
  list = getval.map<Entities>((json) => Entities.fromJson(json)).toList();
});
}
</code>```

Title: Flutter http headers

Body:
The post request is throwing an error while setting the header map.

Here is my code

Future<GenericResponse> makePostCall(
  GenericRequest genericRequest) {String URL = "$BASE_URL/api/";

Map data = {
  "name": "name",
  "email": "email",
  "mobile": "mobile",
  "transportationRequired": false,
  "userId": 5,
};

Map userHeader = {"Content-type": "application/json", "Accept": "application/json"};

return _netUtil.post(URL, body: data, headers:userHeader).then((dynamic res) {
  print(res);
  if (res["code"] != 200) throw new Exception(res["message"][0]);
  return GenericResponse.fromJson(res);
});

}

but I'm getting this exception with headers.

══╡ EXCEPTION CAUGHT BY GESTURE ╞═
flutter: The following assertion was thrown while handling a gesture:
flutter: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      NetworkUtil.post1 (package:saranam/network/network_util.dart:50:41)
flutter: #1      RestDatasource.bookPandit (package:saranam/network/rest_data_source.dart:204:21)

Anybody facing this issue? I didn't find any clue with the above log.


问:
Using HtmlHelper in a Controller
Is it possible to use HtmlHelper in a controller, for-example to get the TextBox(...) method? not that I can't write the html that it generates myself, but I just want to understand how this works so I can create the best solution.</p>

答:
Here's an example adapted from this:

```<code>var h = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView("omg"), new ViewDataDictionary(), new TempDataDictionary()), new ViewPage());
h.TextBox("myname");
</code>```

Note that this is a hack, it can be done but I don't think there's any good reason to do this...

OwnerDisplayName: Gil

Title: Using HtmlHelper in a Controller

Body:
Here's an example adapted from this:

var h = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView("omg"), new ViewDataDictionary(), new TempDataDictionary()), new ViewPage());
h.TextBox("myname");

Note that this is a hack, it can be done but I don't think there's any good reason to do this...

OwnerDisplayName: mausch

ContentLicense: CC BY-SA 2.5


问:
How to select values from a CSV file depending on the value of a specific column
Take this csv as an example:

```<code>Col1, Col2
1,3,
0,5,
1,4
0,7
</code>```

Say that I have a list, and I want to append the values of Col2 to the list only if the value of Col1 in the same row is 1. The resulting list should be [3,4].

How can I do this with pandas without using iterrows()?

答:
```<code>import pandas as pd

lst_result=[]
for ind, row in df.iterrows():
    if df.at[ind,'Col1'] == 1:
        lst_result.append(df.at(ind,['Col2']))
print(lst_result)
</code>```

Body:
Take this csv as an example:

Col1, Col2
1,3,
0,5,
1,4
0,7

Say that I have a list, and I want to append the values of Col2 to the list only if the value of Col1 in the same row is 1. The resulting list should be [3,4].

How can I do this with pandas without using iterrows()?


问:
Inside the console.log dollar symbol isn't working
This is the code for greet.js where we pass 2 parameters via command line. But it isn't printing the proper results.</p>

```<code>const firstname = process.argv[2];
const lastname = process.argv[3];
console.log('hello ${firstname} ${lastname}');
</code>```

答:
const firstname = process.argv[2];
const lastname = process.argv[3];

console.log(hello ${firstname} ${lastname});

use backTicks not normal ' ';

Body:
This is the code for greet.js where we pass 2 parameters via command line. But it isn't printing the proper results.

const firstname = process.argv[2];
const lastname = process.argv[3];
console.log('hello ${firstname} ${lastname}');


问:
KeyboardExtension adjustTextPosition issues with emojis
I'm helping build a keyboardextension and I've recently run into an issue with Swift 4 and emojis. The new UTF-16 emoji support for Swift 4 is really nice but there is an issue with adjustTextPosition in UIInputViewController.

If we call adjustTextPosition to step over an emoji it will simply not step far enough, it seems like the characteroffset used by UIInputViewController doesn't match the character count used by the system.

To test simply write a text with emojis and whenever some key is clicked call:

```<code>super.textDocumentProxy.adjustTextPosition(byCharacterOffset: 1)
</code>```

What can be observed is that we have to click it more than what is to be expected.

答:
Adjusting caret position measured in grapheme clusters (Swift Characters):

```<code>func adjustCaretPosition(offset: Int) {
    guard let textAfterCaret = textDocumentProxy.documentContextAfterInput else { return }

    if let offsetIndex = offset > 0 ?  textAfterCaret.index(textAfterCaret.startIndex, offsetBy: offset, limitedBy: textAfterCaret.endIndex) : textBeforeCaret.index(textBeforeCaret.endIndex, offsetBy: offset, limitedBy: textAfterCaret.startIndex),
        let offsetIndex_utf16 = offsetIndex.samePosition(in: offset > 0 ? textAfterCaret.utf16 : textBeforeCaret.utf16)
    {
        let offset = offset > 0 ? textAfterCaret.utf16.distance(from: textAfterCaret.utf16.startIndex, to: offsetIndex_utf16) : textBeforeCaret.utf16.distance(from: textBeforeCaret.utf16.endIndex, to: offsetIndex_utf16)
        textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)
    }
    else {
        textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)
    }
}
</code>```

UPD: A messy hack, to try and fix Safari inconsistency. Since there's no way to discriminate between safari and not safari, to act based on result looks like the only solution.

```<code>func adjustCaretPosition(offset: Int) {
    // for convenience
    let textAfterCaret = textDocumentProxy.documentContextAfterInput ?? ""
    let textBeforeCaret = textDocumentProxy.documentContextBeforeInput ?? ""

    if let offsetIndex = offset > 0 ?  textAfterCaret.index(textAfterCaret.startIndex, offsetBy: offset, limitedBy: textAfterCaret.endIndex) : textBeforeCaret.index(textBeforeCaret.endIndex, offsetBy: offset, limitedBy: textAfterCaret.startIndex),
        let offsetIndex_utf16 = offsetIndex.samePosition(in: offset > 0 ? textAfterCaret.utf16 : textBeforeCaret.utf16)
    {
        // part of context before caret adjustment
        let previousText = offset > 0 ? textAfterCaret : textBeforeCaret

        // what we expect after adjustment
        let expectedText = offset > 0 ? String(textAfterCaret[offsetIndex..<textAfterCaret.endIndex]) : String(textBeforeCaret[textBeforeCaret.startIndex..<offsetIndex])

        // offset in UTF-16 characters
        let offset_utf16 = offset > 0 ? textAfterCaret.utf16.distance(from: textAfterCaret.utf16.startIndex, to: offsetIndex_utf16) : textBeforeCaret.utf16.distance(from: textBeforeCaret.utf16.endIndex, to: offsetIndex_utf16)

        // making adjustment
        textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)

        // part of context after caret adjustment
        let compareText = offset > 0 ? textAfterCaret : textBeforeCaret

        // rollback if got unwanted results
        // then adjust by grapheme clusters offset
        if compareText != "", expectedText != compareText, compareText != previousText {
            textDocumentProxy.adjustTextPosition(byCharacterOffset: -offset_utf16)
            textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)
        }
    }
    else {
        // we probably stumbled upon a textDocumentProxy inconsistency, i.e. context got divided by an emoji
        // adjust by grapheme clusters offset
        textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)
    }
}
</code>```

Body:
I'm helping build a keyboardextension and I've recently run into an issue with Swift 4 and emojis. The new UTF-16 emoji support for Swift 4 is really nice but there is an issue with adjustTextPosition in UIInputViewController.

If we call adjustTextPosition to step over an emoji it will simply not step far enough, it seems like the characteroffset used by UIInputViewController doesn't match the character count used by the system.

To test simply write a text with emojis and whenever some key is clicked call:

super.textDocumentProxy.adjustTextPosition(byCharacterOffset: 1)

What can be observed is that we have to click it more than what is to be expected.

Body:
Adjusting caret position measured in grapheme clusters (Swift Characters):

func adjustCaretPosition(offset: Int) {
    guard let textAfterCaret = textDocumentProxy.documentContextAfterInput else { return }

    if let offsetIndex = offset > 0 ?  textAfterCaret.index(textAfterCaret.startIndex, offsetBy: offset, limitedBy: textAfterCaret.endIndex) : textBeforeCaret.index(textBeforeCaret.endIndex, offsetBy: offset, limitedBy: textAfterCaret.startIndex),
        let offsetIndex_utf16 = offsetIndex.samePosition(in: offset > 0 ? textAfterCaret.utf16 : textBeforeCaret.utf16)
    {
        let offset = offset > 0 ? textAfterCaret.utf16.distance(from: textAfterCaret.utf16.startIndex, to: offsetIndex_utf16) : textBeforeCaret.utf16.distance(from: textBeforeCaret.utf16.endIndex, to: offsetIndex_utf16)
        textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)
    }
    else {
        textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)
    }
}

UPD: A messy hack, to try and fix Safari inconsistency. Since there's no way to discriminate between safari and not safari, to act based on result looks like the only solution.

func adjustCaretPosition(offset: Int) {
    // for convenience
    let textAfterCaret = textDocumentProxy.documentContextAfterInput ?? ""
    let textBeforeCaret = textDocumentProxy.documentContextBeforeInput ?? ""

    if let offsetIndex = offset > 0 ?  textAfterCaret.index(textAfterCaret.startIndex, offsetBy: offset, limitedBy: textAfterCaret.endIndex) : textBeforeCaret.index(textBeforeCaret.endIndex, offsetBy: offset, limitedBy: textAfterCaret.startIndex),
        let offsetIndex_utf16 = offsetIndex.samePosition(in: offset > 0 ? textAfterCaret.utf16 : textBeforeCaret.utf16)
    {
        // part of context before caret adjustment
        let previousText = offset > 0 ? textAfterCaret : textBeforeCaret

        // what we expect after adjustment
        let expectedText = offset > 0 ? String(textAfterCaret[offsetIndex..<textAfterCaret.endIndex]) : String(textBeforeCaret[textBeforeCaret.startIndex..<offsetIndex])

        // offset in UTF-16 characters
        let offset_utf16 = offset > 0 ? textAfterCaret.utf16.distance(from: textAfterCaret.utf16.startIndex, to: offsetIndex_utf16) : textBeforeCaret.utf16.distance(from: textBeforeCaret.utf16.endIndex, to: offsetIndex_utf16)

        // making adjustment
        textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)

        // part of context after caret adjustment
        let compareText = offset > 0 ? textAfterCaret : textBeforeCaret

        // rollback if got unwanted results
        // then adjust by grapheme clusters offset
        if compareText != "", expectedText != compareText, compareText != previousText {
            textDocumentProxy.adjustTextPosition(byCharacterOffset: -offset_utf16)
            textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)
        }
    }
    else {
        // we probably stumbled upon a textDocumentProxy inconsistency, i.e. context got divided by an emoji
        // adjust by grapheme clusters offset
        textDocumentProxy.adjustTextPosition(byCharacterOffset: offset)
    }
}


问:
Returning smart pointer from raw pointer
This is the way i am returning smart pointer from a raw pointer.

```<code>std::shared_ptr<Geometry> Clone() const
{
    Circle *sc = new Circle(*this);
    return std::shared_ptr< Geometry >(sc);
}
</code>```

Is it the correct way to return Smart pointer from raw pointer ?

答:
The correct way to do it is to return the following

```<code>return std::make_shared<Geometry>(new Circle(*this));
</code>```

If you create the shared pointer like this

```<code>std::shared_ptr<Geometry> Clone() const
{
  Circle *sc = new Circle(*this);
  return std::shared_ptr< Geometry >(sc);
}
</code>```

You end up with two allocations in memory which is not what you want.

Explanation:

A shared pointer has a wrapper with information around the pointer to keep tabs on the reference counts. When you call make_shared, those two pieces (wrapper plus the raw pointer) are guaranteed to be in the same memory block.

Otherwise it looks like this

```<code>+--+      +---------+-------------+--------------
|sp| ---> | raw ptr | strong refs | weak refs ...
+--+      +---------+-------------+--------------
                 \
               +---------+
               |  Circle |
               +---------+
</code>```

But by using make_shared instead, it looks like this in memory

```<code>+--+      +---------+-------------+--------------
|sp| ---> | Circle  | strong refs | weak refs ...
+--+      +---------+-------------+--------------
</code>```

That is much more effective.

Body:
This is the way i am returning smart pointer from a raw pointer.

std::shared_ptr<Geometry> Clone() const
{
    Circle *sc = new Circle(*this);
    return std::shared_ptr< Geometry >(sc);
}

Is it the correct way to return Smart pointer from raw pointer ?

Body:
The correct way to do it is to return the following

return std::make_shared<Geometry>(new Circle(*this));

If you create the shared pointer like this

std::shared_ptr<Geometry> Clone() const
{
  Circle *sc = new Circle(*this);
  return std::shared_ptr< Geometry >(sc);
}

You end up with two allocations in memory which is not what you want.

Explanation:

A shared pointer has a wrapper with information around the pointer to keep tabs on the reference counts. When you call make_shared, those two pieces (wrapper plus the raw pointer) are guaranteed to be in the same memory block.

Otherwise it looks like this

+--+      +---------+-------------+--------------
|sp| ---> | raw ptr | strong refs | weak refs ...
+--+      +---------+-------------+--------------
                 \
               +---------+
               |  Circle |
               +---------+

But by using make_shared instead, it looks like this in memory

+--+      +---------+-------------+--------------
|sp| ---> | Circle  | strong refs | weak refs ...
+--+      +---------+-------------+--------------

That is much more effective.


问:
How to send a Get request in iOS?
I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as

```<code>[requestObject setHTTPMethod:@"GET"];
</code>```

Tell me what could be the problem. Also provide me the code if you have.

答:
```<code>NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
            URLWithString:serverAddress]
            cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                   timeoutInterval:10
 ];

[request setHTTPMethod: @"GET"];

NSError *requestError = nil;
NSURLResponse *urlResponse = nil;

NSData *response1 =
        [NSURLConnection sendSynchronousRequest:request
                         returningResponse:&urlResponse error:&requestError];
</code>```

Title: How to send a Get request in iOS?

Body:
I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:]
I am setting it as

[requestObject setHTTPMethod:@"GET"];

Tell me what could be the problem. Also provide me the code if you have.


问:
Create partitioned table with date suffix in bigquery using SQL or web UI
I want to create such table:

```<code>CREATE TABLE sometable
(SELECT columns, columns, date_col)
PARTITIONED BY date_col
</code>```

And I want it to be date partitioned with the date in table suffix: sometable$date_partition

I read the docs, but can't complete this neither with web UI nor with SQL.

The web UI shows such error "Missing argument for parameter DATE."

```<code>My table name is "daily_export_${DATE}"
My partitioning column isn't blank, it's date_col.
</code>```

Can I have a simple example, please?

答:
PARTITION BY goes earlier

The query needs to parse the table suffix into a DATE type.

For example:

CREATE OR REPLACE TABLE temp.so
PARTITION BY date_from_table_name
AS
SELECT PARSE_DATE('%Y%m%d', _table_suffix) date_from_table_name, event_timestamp, event_name, items
FROM `bingo-blast-174dd.analytics_151321511.events_*`
WHERE _table_suffix BETWEEN '20200530' AND '20200531'
LIMIT 10
```

Body:
I want to create such table:

CREATE TABLE sometable
(SELECT columns, columns, date_col)
PARTITIONED BY date_col

And I want it to be date partitioned with the date in table suffix: sometable$date_partition

I read the docs, but can't complete this neither with web UI nor with SQL.

The web UI shows such error "Missing argument for parameter DATE."

My table name is "daily_export_${DATE}"
My partitioning column isn't blank, it's date_col.

Can I have a simple example, please?