text:
Q: HTML div doesn't wrap  tag I am trying to make my div wrap the  tag however it doesn't wrap, the height is always higher of my div, and my  tag has no padding or margin, i tried many things but doesn't work, i am adding my style and the html code, i am also going to add some screenshots
CSS

HTML

                    menu

SCREENSHOTS
 tag

 wrapper tag

Thanks in advance for your help.

A: Maybe this is what you looking for:

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: inherit;
  display: block!important;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
  -moz-osx-font-smoothing: grayscale;
  font-feature-settings: 'liga';
  color: #ffffff;
}
.button-content-ic {
  background-color: #555555;
  display: inline-block;
  margin: auto;
}
body,
section,
div,
i {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

menu


text:
Q: Laravel list music genres with sub model popularity I have 4 tables:

*

*MusicGenre

*Artist

*Song

*SongInfo
weekly_hit is a column on the SongInfo table.
MusicGenre is connected to Artist like this:
public function artists()
{
    return $this->hasMany('App\Models\Artist\ArtistInfo','genre_id','id');
}

Artist is connected to Song like this:
public function songs()
{
    return $this->hasMany('App\Models\Song\Songs','artist_id');
}

And Song is connected to SongInfo like this:
public function info()
{
    return $this->hasOne('App\Models\Song\SongsInfo','song_id','id');
}

There is a no problem querying the table.
My problem is that I want to get the best music genres using weekly_hit in SongInfo table.
Edit:
I resolved that problem with raw code
"select music_genres.*,
sum(distinct song_info.weekly_hit) as song_popularity

from `music_genres`

left join `artist_info` on
`music_genres`.`id` = `artist_info`.`genre_id`

left join songs on
artist_info.artist_id = songs.artist_id

left join songs_info on
songs.id = songs_info.song_id

group by music_genres.name

order by song_popularity DESC

limit 5

But, I can't get songs. I want to get 5 song ordered by weekly_hit in songs_info  table from all returned music genres.
Guys i still searching a solution?
Can somebody help me?

A: You'll want to use Eloquent's hasManyThrough() relation to reach that deep in the relationship chain.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ubuntu Server 17.10 watchdog: BUG: soft lockup - CPU#5 stuck for 22s! I am having a soft lookup issue with both of my new machine, each configured identical..  Tomahawk B350 Motherboard, AMD Rizen 1800x, 64GB Corsair Velocity RAM, Samsung EVO pro 960 1TB M.2 (with another Samsung 1TB SSD drive on SATA).  GOLD 650w Power supplies, GeForce GTX 1050..
I had to use Artful because of a fix for the B350 MB's
Distributor ID: Ubuntu
Description:    Ubuntu 17.10
Release:        17.10
Codename:       artful

Syslog:
Feb 22 17:09:06 srv1 kernel: [50911.454881] watchdog: BUG: soft lockup - CPU#5 stuck for 22s! [kworker/5:1:4253]
Feb 22 17:09:06 srv1 kernel: [50911.454945] Modules linked in: ipt_MASQUERADE nf_nat_masquerade_ipv4 nf_conntrack_netlink nfnetlink xfrm_user xfrm_algo iptable_nat nf_conntrack_ipv4 nf_defrag_ipv4 nf_nat_ipv4 xt_addrtype iptable_filter xt_conntrack nf_nat nf_conntrack br_netfilter bridge stp llc aufs snd_hda_codec_hdmi snd_hda_codec_realtek snd_hda_codec_generic edac_mce_amd kvm snd_hda_intel irqbypass snd_hda_codec wmi_bmof snd_hda_core snd_hwdep snd_pcm i2c_piix4 snd_timer ccp snd soundcore shpchp tpm_infineon 8250_dw mac_hid ib_iser rdma_cm iw_cm ib_cm ib_core iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi ip_tables x_tables autofs4 btrfs raid10 raid456 async_raid6_recov async_memcpy async_pq async_xor async_tx xor raid6_pq libcrc32c raid1 raid0 multipath linear nouveau mxm_wmi video crct10dif_pclmul i2c_algo_bit crc32_pclmul
Feb 22 17:09:06 srv1 kernel: [50911.454982]  ttm ghash_clmulni_intel pcbc drm_kms_helper syscopyarea sysfillrect sysimgblt aesni_intel fb_sys_fops aes_x86_64 crypto_simd glue_helper cryptd drm r8169 nvme ahci mii libahci nvme_core wmi gpio_amdpt gpio_generic
Feb 22 17:09:06 srv1 kernel: [50911.454994] CPU: 5 PID: 4253 Comm: kworker/5:1 Not tainted 4.13.0-32-generic #35-Ubuntu
Feb 22 17:09:06 srv1 kernel: [50911.454995] Hardware name: Gigabyte Technology Co., Ltd. AB350-Gaming 3/AB350-Gaming 3-CF, BIOS F7 06/16/2017
Feb 22 17:09:06 srv1 kernel: [50911.455000] Workqueue: events netstamp_clear
Feb 22 17:09:06 srv1 kernel: [50911.455002] task: ffff934bca600000 task.stack: ffffa624916c8000
Feb 22 17:09:06 srv1 kernel: [50911.455005] RIP: 0010:smp_call_function_many+0x24a/0x270
Feb 22 17:09:06 srv1 kernel: [50911.455006] RSP: 0018:ffffa624916cbcc0 EFLAGS: 00000202 ORIG_RAX: ffffffffffffff10
Feb 22 17:09:06 srv1 kernel: [50911.455008] RAX: ffff934c1ee272d0 RBX: ffff934c1ed63a00 RCX: 0000000000000008
Feb 22 17:09:06 srv1 kernel: [50911.455009] RDX: 0000000000000001 RSI: 0000000000000000 RDI: ffff934c1e828128
Feb 22 17:09:06 srv1 kernel: [50911.455010] RBP: ffffa624916cbcf8 R08: ffffffffffffff00 R09: 000000000000ffdf
Feb 22 17:09:06 srv1 kernel: [50911.455011] R10: ffffd1f47f5e5b80 R11: 0000000000000000 R12: 0000000000000010
Feb 22 17:09:06 srv1 kernel: [50911.455011] R13: 0000000000000010 R14: ffffffffb6e33210 R15: 0000000000000000
Feb 22 17:09:06 srv1 kernel: [50911.455013] FS:  0000000000000000(0000) GS:ffff934c1ed40000(0000) knlGS:0000000000000000
Feb 22 17:09:06 srv1 kernel: [50911.455014] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
Feb 22 17:09:06 srv1 kernel: [50911.455014] CR2: 00007ff67c010b88 CR3: 0000000fd6002000 CR4: 00000000003406e0
Feb 22 17:09:06 srv1 kernel: [50911.455015] Call Trace:
Feb 22 17:09:06 srv1 kernel: [50911.455020]  ? netif_receive_skb_internal+0x28/0x3f0
Feb 22 17:09:06 srv1 kernel: [50911.455022]  ? arch_unregister_cpu+0x30/0x30
Feb 22 17:09:06 srv1 kernel: [50911.455024]  ? netif_receive_skb_internal+0x29/0x3f0
Feb 22 17:09:06 srv1 kernel: [50911.455025]  on_each_cpu+0x2d/0x60
Feb 22 17:09:06 srv1 kernel: [50911.455027]  ? netif_receive_skb_internal+0x28/0x3f0
Feb 22 17:09:06 srv1 kernel: [50911.455028]  text_poke_bp+0x6a/0xf0
Feb 22 17:09:06 srv1 kernel: [50911.455030]  __jump_label_transform.isra.0+0x10b/0x120
Feb 22 17:09:06 srv1 kernel: [50911.455032]  arch_jump_label_transform+0x32/0x50
Feb 22 17:09:06 srv1 kernel: [50911.455034]  __jump_label_update+0x68/0x80
Feb 22 17:09:06 srv1 kernel: [50911.455036]  jump_label_update+0xae/0xc0
Feb 22 17:09:06 srv1 kernel: [50911.455038]  __static_key_slow_dec+0x4e/0xa0
Feb 22 17:09:06 srv1 kernel: [50911.455040]  static_key_slow_dec+0x22/0x50
Feb 22 17:09:06 srv1 kernel: [50911.455041]  static_key_disable+0x21/0x30
Feb 22 17:09:06 srv1 kernel: [50911.455042]  netstamp_clear+0x34/0x40
Feb 22 17:09:06 srv1 kernel: [50911.455045]  process_one_work+0x1e7/0x410
Feb 22 17:09:06 srv1 kernel: [50911.455047]  worker_thread+0x4b/0x420
Feb 22 17:09:06 srv1 kernel: [50911.455049]  kthread+0x125/0x140
Feb 22 17:09:06 srv1 kernel: [50911.455050]  ? process_one_work+0x410/0x410
Feb 22 17:09:06 srv1 kernel: [50911.455052]  ? kthread_create_on_node+0x70/0x70
Feb 22 17:09:06 srv1 kernel: [50911.455054]  ret_from_fork+0x1f/0x30
Feb 22 17:09:06 srv1 kernel: [50911.455056] Code: 77 35 00 39 05 bc ad 34 01 89 c1 0f 8e 3d fe ff ff 48 98 48 8b 13 48 03 14 c5 e0 e3 f6 b7 48 89 d0 8b 52 18 83 e2 01 74 0a f3 90 <8b> 50 18 83 e2 01 75 f6 eb b9 48 c7 c2 20 08 26 b8 4c 89 e6 89

Originally I thought if I rebooted every morning at 3:00AM it would stop the freeze ups because they would lockup every week after being idle..  But that did not help..
Anything I can do to troubleshoot this further?


text:
Q: How to arrive at $\int x^2 \phi(x) \, \mathrm{dx} = \Phi(x) - x\phi(x) + C$ I found the following result in Wikipedia

$\int x^2 \phi(x) \, \mathrm{dx}  = \Phi(x) - x\phi(x) + C$

where $$\phi(x) = \frac{1}{(2\pi)^{1/2}} \mathrm{e}^{-\frac{1}{2}x^2}~\mathrm{and}~\Phi(x) = \int_{-\infty}^{x} \phi(\mathrm{t}) \mathrm{dt}\,.$$
I tried some partial integration so far but somehow I don't get it. Can someone tell me how to arrive at the equality?

A: If we let $f(x) := \Phi(x) - x\phi(x)$, we have - using that $\phi'(x) = -x\phi(x)$ -
\begin{align*}
  f'(x) &= \Phi'(x) - \phi(x) - x\phi'(x)\\
        &= -x\phi'(x)\\
        &= x^2 \phi(x)
\end{align*}
That is
$$ \int x^2\phi(x) \, dx = f(x) = \Phi(x) - x\phi(x) $$
by the fundamental theorem of calculus.


text:
Q: VQmod on new VPS not writing vqcache files or log files I am just moving an opencart site to a staging server and have vqmod installed in the site however I can't get vqmod to create the vqcache files and it isn't even logging any errors in the vqmod/log folder. I've basically set the directory structure to 777 to get it to work from a permissions point of view and everything is ownership user:www-data but still no joy.

A: Just in case anyone has a similar issue, it was a user groups issue, the ownership settings for the vqmod.php file were user:user rather than the required user:www-data

A: You should actually set the permissions for your vqmod.php to be the same as your index.phpin your main OpenCart folder, not alter the owner of the file. You should also set the permissions of the following be the same as your /system/cache/ folder
/vqmod/
/vqmod/vqcache/
/vqmod/logs/


text:
Q: Perturbation theory in Quantum Field Theory Let the Euclidean Lagrangian be $L_e(\phi,\dot{\phi})=\frac{1}{2}\dot{\phi}^2+\frac{1}{2}m^2{\phi}^2+\frac{\lambda}{4!}{\phi}^4$,for interacting case.Then,
$T\langle0\vert\hat{\phi}(t_a)\hat{\phi}(t_b)...\vert0\rangle$
$=\frac{\int D\phi e^{-\int_{-\infty}^{+\infty}dt L_e}\phi(t_a)\phi(t_b)....}{\int D\phi e^{-\int_{-\infty}^{+\infty}dt L_e}}$
$=\frac{\int D\phi e^{-\int_{-\infty}^{+\infty}dt {L^0}_e}\phi(t_a)\phi(t_b)....\sum_{n=0}^{\infty}(-\frac{\lambda}{4!})^{n}\frac{1}{n!}[\int_{-\infty}^{+\infty}dt {\phi}^4]^n}{\int D\phi e^{-\int_{-\infty}^{+\infty}dt {L^0}_e}\sum_{n=0}^{\infty}(-\frac{\lambda}{4!})^{n}\frac{1}{n!}[\int_{-\infty}^{+\infty}dt {\phi}^4]^n}$
$=\frac{[\int D\phi e^{-\int_{-\infty}^{+\infty}dt {L^0}_e}(\phi strings)]/[\int D\phi e^{-\int_{-\infty}^{+\infty}dt {L^0}_e}]}{[\int D\phi e^{-\int_{-\infty}^{+\infty}dt {L^0}_e}differentstrings of \phi]/[\int D\phi e^{-\int_{-\infty}^{+\infty}dt {L^0}_e}]}$
Then,we apply Wick's Theorem to the numerator and Denominator.This is what is normally done.My question is: We know that this is not a free theory,i.e. $\hat{\phi}$ can not be decomposed into creation,anhiliation operators.These are purely interacting fields.Although from the second step only functions appear and no operators appear,these functions are different from that of the free case.Can we apply Wick's theorem in such case to the numerator and denominator?

A: In order to apply Wick's theorem to interacting QFT in operator formalism you have to pass to the interaction picture of quantum mechanics. In this formalism, the Hamiltonian is split in two (unphysical) parts. The free part is responsible for the Heisenberg evolution of field operators (to which Wick's theorem is perfectly applicable), and the interaction part is responsible for the Schroedinger-like evolution of quantum states.
Take a look at this question and at my notes on interaction picture and deriving Feynman rules.
I hope this answers your question.


text:
Q: dplyr::inner_join -- how to include certain observations even if they don't appear in both dataframes I have two dataframes that I want to merge by a common variable. Some observations appear in one data but not in the other, and vice verse. When merging, I want to keep only the observations that appear in both dataframes, and therefore dplyr::inner_join() is appropriate.
However, there's an exclusion. There are some observations that I'd like to include in the merged data no matter what. That is, even if they don't appear in both original dataframes. The indication to which ones are those "special" observations to keep is given as certain values in certain columns.
Example
I want to merge the following dataframes (df_population and df_gdp)
1. df_population
library(tibble)
library(dplyr)

## helper function
myFun <- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

set.seed(2021)

df_population <-
  tribble(~country, ~population,
        "australia", 24.99,
        "united_kingdom", 66.65,
        "france", 66.99,
        "spain", 46.94,
        "canada", 37.59,
        "brazil", 209.5) %>%
  mutate(col_of_strings = c(myFun(5), "dont_leave_me_behind"))

## # A tibble: 6 x 3
##   country        population col_of_strings
##   <chr>               <dbl> <chr>
## 1 australia            25.0 GLNWN9968R
## 2 united_kingdom       66.6 FTELH3426F
## 3 france               67.0 NFOSZ6335V
## 4 spain                46.9 ZFGRD8875F
## 5 canada               37.6 GFICE2875O
## 6 brazil              210.  dont_leave_me_behind

2. df_gdp
df_gdp <-
  tribble(~country, ~gdp_growth,
        "australia", 2.9,
        "united_kingdom", 1.4,
        "france", 1.7,
        "spain", 2.4,
        "canada", 1.9,
        "greece", 1.9) %>%
  mutate(col_of_strings = sample(c(myFun(5), "dont_leave_me_behind")))

## # A tibble: 6 x 3
##   country        gdp_growth col_of_strings
##   <chr>               <dbl> <chr>
## 1 australia             2.9 dont_leave_me_behind
## 2 united_kingdom        1.4 RQHHI9679V
## 3 france                1.7 PFSZX1552L
## 4 spain                 2.4 BQTBY7537E
## 5 canada                1.9 OECIK9698V
## 6 greece                1.9 VXDQQ4718J

 My Problem
Normally I'd go with
dplyr::inner_join(df_population, df_gdp, by = "country")

But:
Although I want only the countries that are common to both dataframes, I still want to include any country that has col_of_strings == dont_leave_me_behind
I hope there's a simple solution to this. Thanks!

A: Three ways come to mind.

*

*Per @M.Viking's suggestion, full_join first and then filter.
dplyr::full_join(df_population, df_gdp, by = "country") %>%
  dplyr::filter(
    col_of_strings.y == "dont_leave_me_behind" | !is.na(col_of_strings.x),
    col_of_strings.x == "dont_leave_me_behind" | !is.na(col_of_strings.y)
  )
# # A tibble: 6 x 5
#   country        population col_of_strings.x     gdp_growth col_of_strings.y
#   <chr>               <dbl> <chr>                     <dbl> <chr>
# 1 australia            25.0 LQMPB3662R                  2.9 VKBCE2969H
# 2 united_kingdom       66.6 WDXVX4684T                  1.4 FMAKF4470M
# 3 france               67.0 VJHBH0078U                  1.7 dont_leave_me_behind
# 4 spain                46.9 XFJPD7687T                  2.4 RMPYK2467U
# 5 canada               37.6 AQRCR0724P                  1.9 JXMMZ3736X
# 6 brazil              210.  dont_leave_me_behind       NA   <NA>

*Do the inner join, extract missing rows from each frame, and bind_rows them back in. This steps requires some renaming because of the .x/.y names post-join.
tmp1 <- dplyr::inner_join(df_population, df_gdp, by = "country")

missing_pop <- df_population %>%
  dplyr::filter(
    col_of_strings == "dont_leave_me_behind",
    !country %in% tmp1$country
  ) %>%
  dplyr::rename(col_of_strings.x = col_of_strings)
missing_pop
# # A tibble: 1 x 3
#   country population col_of_strings.x
#   <chr>        <dbl> <chr>
# 1 brazil        210. dont_leave_me_behind

missing_gdp <- df_gdp %>%
  dplyr::filter(
    col_of_strings == "dont_leave_me_behind",
    !country %in% tmp1$country
  ) %>%
  dplyr::rename(col_of_strings.y = col_of_strings)
missing_gdp
# # A tibble: 0 x 3
# # ... with 3 variables: country <chr>, gdp_growth <dbl>, col_of_strings.y <chr>

out <- dplyr::bind_rows(tmp1, missing_pop, missing_gdp)
out
# # A tibble: 6 x 5
#   country        population col_of_strings.x     gdp_growth col_of_strings.y
#   <chr>               <dbl> <chr>                     <dbl> <chr>
# 1 australia            25.0 LQMPB3662R                  2.9 VKBCE2969H
# 2 united_kingdom       66.6 WDXVX4684T                  1.4 FMAKF4470M
# 3 france               67.0 VJHBH0078U                  1.7 dont_leave_me_behind
# 4 spain                46.9 XFJPD7687T                  2.4 RMPYK2467U
# 5 canada               37.6 AQRCR0724P                  1.9 JXMMZ3736X
# 6 brazil              210.  dont_leave_me_behind       NA   <NA>

*Similar to 2, but using anti_join:
tmp1 <- dplyr::inner_join(df_population, df_gdp, by = "country")
out <- dplyr::bind_rows(
  tmp1,
  dplyr::filter(df_population, col_of_strings == "dont_leave_me_behind") %>%
    dplyr::anti_join(., tmp1, by = "country") %>%
    dplyr::rename(col_of_strings.x = col_of_strings),
  dplyr::filter(df_gdp, col_of_strings == "dont_leave_me_behind") %>%
    anti_join(., tmp1, by = "country") %>%
    dplyr::rename(col_of_strings.y = col_of_strings)
)

The latter two perform about the same with benchmarking:
bench::mark(full1=..., inner2=..., inner3=...)
# # A tibble: 3 x 13
#   expression     min  median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result memory
#   <bch:expr> <bch:t> <bch:t>     <dbl> <bch:byt>    <dbl> <int> <dbl>   <bch:tm> <list> <list>
# 1 full1       5.83ms  7.72ms     127.     1.36KB     4.32    59     2      463ms <tibb~ <Rpro~
# 2 inner2      9.54ms 11.46ms      84.9   11.28KB     2.07    41     1      483ms <tibb~ <Rpro~
# 3 inner3     13.95ms 14.92ms      62.9   11.28KB     4.49    28     2      445ms <tibb~ <Rpro~
# # ... with 2 more variables: time <list>, gc <list>

where the full_join works much better in this case. Larger data may perform significantly differently, I haven't tested it yet.


text:
Q: What is topology of feedback for circuit?
I am confused between Voltage Shunt and Current Shunt Also mention why R2 shouldn't be considered as feedback as it is emitter degeneration resistance
Consider the above circuit why can't I consider the current being one sampled the only problem I see in doing that is that there is no load but if I consider the amplifier to of type series series that should not be a problem as current is going to considered as output quantity and why will I need to  worry about load for its measurement.

A: This looks like a Series-Shunt circuit topology. The way I learned it was that after you identify the feedback circuit, trace the path from the input to that circuit. If you passed through an active device, it is series, otherwise it is shunt. Repeat that process for the output. Then if it is input series, and output shunt it is called "series-shunt."
Feedback is literally the "feeding" of the output "back" into the input. R2 is not in the path of the output signal to the input, thus it is not part of the feedback circuit (beta circuit).


text:
Q: How to create try-error class in R I need to return "try-error" class or same class which inherits from it. Is it possible in R?
So, is it possible to create function like this:
Foo <- function(x)
{
    if (x != 2) { res <- 1 }
    else { res <- # create object with class type "try-error" and message "I hate 2!"/ }

    return(res);
}

A: Classes are a pretty loose concept in R; you can just assign any class(es) you desire as character strings in the class attribute of an object. For example, using the structure function:
Foo <- function(x) {
    if (x != 2) {
        res <- 1
    } else {
        res <- structure(
            "message",
            class = c("try-error", "character")
        )
    }
    res
}

Foo(1)
# [1] 1

Foo(2)
# [1] "message"
# attr(,"class")
# [1] "try-error" "character"

class(Foo(2))
# [1] "try-error" "character"

Alternatively, you could use
res <- "message"
class(res) <- c("try-error", class(res))

in place of structure.
It's usually a good idea to add new classes rather than completely overwrite the old classes so that method dispatch works reasonably, but depending on your use case this may not be needed or desired.

A: Why don't you use try?
Foo <- function(x)
{ res <- try({
    if (x == 2L) stop("I hate 2!", call. = FALSE)
    1
  })
  res
}

Foo(2)
#Error : I hate 2!
#[1] "Error : I hate 2!\n"
#attr(,"class")
#[1] "try-error"
#attr(,"condition")
#<simpleError: I hate 2!>

I can't see a good reason why you'd create an object of class "try-error" manually.


text:
Q: Sqlite-net hanging call on Windows 10 So I've been working on a desktop application that utilizes SQLite for storage of some per-execution data. We're working in C#, .NET 4.5, Visual Studio 2012, using the following nuget packages to support out SQLite needs:

*

*sqlite-net

*System.Data.SQLite (x86/x64)

*System.Data.SQLite Core (x86/x64)

*System.Data.SQLite EF6

*System.Data.SQLite LINQ

These packages install two files: SQLite.cs and SQLiteAsync.cs into the project, managed code. However we needed to go seek out sqlite3.dll in order to support these files' calls to unmanaged code. This file is included at the root level of the project and is copied to the bin on build.
Now, we began development on Windows 8.1 and were able to successfully use SQLite to create/update .sqlite DB files. Then came the switch to Windows 10 (it's free, this is now the most important platform to support) and now any call to the unmanaged code (sqlite3.dll) HANGS. Hanging is the worst, no exceptions, no clues, unmanaged code = no debugging. Can I get an amen?
The hang happens on SQLite3.Open, here is the call stack (that I had to piece together, I hate hangs...)
**HANGS AT THIS CALL: SQLite3.Open**
var r = SQLite3.Open(databasePathAsBytes, out handle, (int) openFlags, IntPtr.Zero) in SQLite.cs
: base(SQLiteConnectionString.DatabasePath, SQLIteOpenFlags, SQLiteConnectionString.StoreDateTimeAsTicks) in SQLite.cs
Connection = new SQLiteConnectionWithLock(SQLiteConnectionString, SQLIteOpenFlags) in SQLiteAsync.cs
entry = new Entry(SQLiteConnectionString, SQLIteOpenFlags) in SQLiteAsync.cs
return SQLiteConnectionPool.Shared.GetConnection(SQLiteConnectionString, SQLIteOpenFlags) in SQLiteAsync.cs
var conn = this.GetConnection() in SQLiteAsync.cs (their code)
Task initTask = db.RunInTransactionAsync(...) in SQLFacade.cs (our code)

I hope that isn't too difficult to read.
Anyways, I'm hoping that somebody out there has some insight into why this is happening suddenly. I've tried reinstalling all of the nuget packages and getting the latest sqlite3.dll to no avail. In the meantime I will be checking with Windows Defender and Bitdefender (my chosen antivirus) to see if perhaps they're blocking access to sqlite3.dll for some reason.
If anyone has contact with a member of the SQLite team please reference to them this post, this snag is a HUGE roadblock for our team's progress.
Thanks SO!

A: BIG, BIG SIGH
I was on the wrong build configs. We're building a 64-bit app, somehow my project build configs were x86 across the board. sqlite3.dll is a 64 bit library. If it were the other way around I would have seen a BadImageFormatException, in this case I got a hang.
Ah the programmer's life.
I hope this post helps SOMEBODY, otherwise it will forever live on my wall of shame.


text:
Q: I can't get field to display an existing date from my database This is bugging me. In my application I am updating a datetime value. I am doing so by first splitting the datetime into seperate date and time fields, and then upon updating I tell the program to merge the date back into the datetime value again.
I can enter new values just fine. They get saved correctly.
The only problem I am facing is that I cannot get the existing seperated values to display in my fields. I want the users to be able to see what values they already have before changing them.
I am allowed to display the full datetime value without any problems, but not the seperate values for date and time.

        <b-form-row>
          <b-col lg="6">
            <b-form-group :label="$t('Move in date')">
              <b-date-picker  v-model="tenancy.dateForMovingIn"/>
            </b-form-group>
          </b-col>
        </b-form-row>

        <script>
        export default {
        data() {
      return {
        tenancy: {
          moveInDateTime: null,
          dateForMovingIn: null,
        }
    },
    methods: {
      show(tenancy) {

        tenancy = JSON.parse(JSON.stringify(tenancy));

        tenancy.moveInDateTime = tenancy.moveInDateTime ? new Date(tenancy.moveInDateTime) : tenancy.moveInDateTime;
        tenancy.dateForMovingIn = moment(this.tenancy.moveInDateTime).format('YYYY-MM-DD')
        tenancy.timeForMovingIn = moment(this.tenancy.moveInDateTime).format('HH:mm')

        this.tenancy = tenancy
      },

      submit() {
        this.tenancy.moveInDateTime  = moment(this.tenancy.dateForMovingIn + ' ' + this.tenancy.timeForMovingIn, 'YYYY-MM-DD HH:mm')
        this.tenancy.moveOutDateTime = moment(this.tenancy.dateForMovingOut + ' ' + this.tenancy.timeForMovingOut, 'YYYY-MM-DD HH:mm')
        }
      }
    }
        </script>


text:
Q: How can I create a flat dictionary from a nested dictionary whose keys are a subset of a reference dictionary? I am creating a nested reference dictionary to record all possible keys a data dictionary could have with corresponding values which are all the keys to be used in the flat dictionary.
The data dictionary's keys will always be a subset of the keys of the reference dictionary.  The flat dictionary's keys will always be a subset of the set of values of the reference dictionary.
In other words, given a reference dictionary with assignments like this:
reference['agent']['address'] = 'agentaddress'
reference['agent']['zone']['id'] = 'agentzoneid'
reference['eventid'] = 'eventid'
reference['file']['hash'] = 'filehash'
reference['file']['name'] = 'filename'

and a data dictionary with assignments like this:
nested['agent']['address'] = '172.16.16.16'
nested['eventid'] = '1234566778'
nested['file']['name'] = 'reallybadfile.exe'

code should produce a dictionary which could have been assigned like this:
flat['agentaddress'] = '172.16.16.16'
flat['eventid'] = '1234566778'
flat['filename'] = 'reallybadfile.exe'

I can never know which fields in the nested dictionary will be populated and which will not, but I can know the mappings in the reference dictionary.
I expect I will need to use recursion to traverse dictionaries into child dictionaries and potentially some sort of indirection to create the flat dictionary keys and values from the reference dictionary values and the nested dictionary keys respectively.
However, I have not yet been able to generate code that makes any sense.
Perhaps from a very high level, it may look something like this:
def this(ref, nest, flat, *args):
    for (k,v) in reference:
        if type(v) is dict:
            this(?, ?, ?, ?)
        elif nested[path][to][k]:
            flat[reference[path][to][k]] = nested[path][to][k]

where [path][to][k] represents some way to do indirection, and *args is something I'd pass to the recursive function so that I would have a way to have context enough to reach through the nestedness of the dictionaries for the reference to the keys and values I need.

A: Using a generator, this is fairly straight forward:
Code:
def make_flat_tuples(data, ref):
    for k, v in data.items():
        if isinstance(v, dict):
            for x in make_flat_tuples(v, ref[k]):
                yield x
        else:
            yield ref[k], v

flat = dict(make_flat_tuples(nested, reference))

Test Code:
from collections import defaultdict

reference = defaultdict(dict)
reference['agent'] = defaultdict(dict)

reference['agent']['address'] = 'agentaddress'
reference['agent']['zone']['id'] = 'agentzoneid'
reference['eventid'] = 'eventid'
reference['file']['hash'] = 'filehash'
reference['file']['name'] = 'filename'

nested = defaultdict(dict)

nested['agent']['address'] = '172.16.16.16'
nested['eventid'] = '1234566778'
nested['file']['name'] = 'reallybadfile.exe'

print(dict(make_flat_tuples(nested, reference)))

Results:
{
    'agentaddress': '172.16.16.16',
    'eventid': '1234566778',
    'filename': 'reallybadfile.exe'
}

A: @StephenRauch answer is good, if you do not want to use generators simply reformat as follows:
# r=reference, n=nested, f=final
def buildDict(r, n, f):
    for key in n.keys():
        if isinstance(n[key], dict):
            buildDict(r.get(key), n[key], f)
        else:
            if r.get(key):
                f[r.get(key)] = n[key]


text:
Q: Product of correlated random variables Suppose $X_1,...,X_n$ is a sequence of stationary correlated random variables in $\{-1,+1\}$ such that :
$\mathbb{P}[X_i = +1] = p$,
$\mathbb{P}[X_i = -1] = 1-p$ with $p\in (0,1)$,
and with a correlation $\rho_{j}$ is defined by:
$$ \rho_{j}:= \frac{\mathbb{E}[X_iX_{i+j}] - \mathbb{E}[X_i]\mathbb{E}[X_{i+j}]}{\mathbb{E}[X_i]\mathbb{E}[X_{i+j}]}\text{ (independent of }i\text{ by stationarity)}$$
My question concerns the expectation of the product:
$$P_n:=\mathbb{E}\left[\prod_{i=1}^n X_i\right]$$
Clearly, if the $X_i$ are independent, then $P_n = (2p-1)^n$ .
My question is the following:

If $\rho_j =O(e^{-\kappa j})$ when $j\to\infty$ for some $\kappa>0$, what can we say about $P_n$? Can we compute it explicitly ? Can we obtain an asymptotic formula in the limit $n\to \infty$?

Thanks for your help !
Edit:
A more specific question (proof or counter-example):
Is it true that one can find a sequence $c_n = O(e^{-\lambda n})$ for some $\lambda>0$ such that
$$P_n = \prod_{i=1}^n (2p-1+c_i)$$


text:
Q: Show custom message in Error List C# vsix extension I am creating a VSIX extension. Here I have added errors in Error List but, the issue bar (just upside to the error list) is still showing No issues found followed by a green mark (follow the attached image):

These 7 Errors must be shown on the issue bar as the VS IDE usually do, as the following image:

Now, I want my project to work/show errors like 2nd Image. Following is my code for adding these custom errors :
internal static class ErrorListManager
{
    public static ErrorListProvider errorListProvider;

    public static void Initialize(IServiceProvider serviceProvider)
    {
        errorListProvider = new ErrorListProvider(serviceProvider);
    }

    public static void AddError(string errorMsg) {
        AddTask(errorMsg, TaskErrorCategory.Error);
    }

    private static void AddTask(string errorMsg, TaskErrorCategory category)
    {
        errorListProvider.Tasks.Add(new ErrorTask
        {
            Category = TaskCategory.User,
            ErrorCategory = category,
            Text = errorMsg
        });
    }
}

private void CreateVisualsCall(List<string> templist2, int markCountLoc)
{
    //if (this.checkCountIfMarked <= markCountLoc)
    if (markCountLoc > 0)
    {
        //this.markthis.Clear();
        //CreateVisuals(templist2[templist2.Count - this.checkCountIfMarked],markCountLoc,templist2);
        CreateVisuals(templist2[templist2.Count - markCountLoc], markCountLoc, templist2);
    }
    else
    {
            foreach (Image img in this.drawingImageList) {

            // Align the image with the top of the bounds of the text geometry
            //Canvas.SetLeft(img, this.geometry.Bounds.Left);
            //Canvas.SetTop(img, this.geometry.Bounds.Top);

            this.layer.AddAdornment(AdornmentPositioningBehavior.OwnerControlled, span, null, img, null);
        }

        -------
        ErrorListManager.AddError("Test  Message");//only this line is calling and creating custom error!
        -------
    }
}

My  question is: How can I remove "No issues found (as in img 1)" and place the errors over that (like img 2)

I followed this tutorial for creating up to this.


text:
Q: How to convert rows into columns and vice versa using browser side scripting of html page? Is there any jquery method revert row into columns and vice versa?
Page tag draws an a4 sized sheet using css.
This table is generated via PHP code but we cannot print column first and add them to same row so I have to do all of this using browser side scripting.
<page size="A4" class="flex-container">

1

101

2

102

3

103

4

104

5

105

6

106

7

107

8

108

9

109

10

110

11

111

12

112

13

113

14

114

15

115

16

116

17

117

18

118

19

119

20

120

21

</page>

I have found below code on SO but i cannot understand how to apply this on div. I am not a professional developer yet so please help me

Here is my css
body {
padding-top: 50px;
}
page {
background: white;
display: block;
margin: 0 auto;
margin-bottom: 0.5cm;
box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
page[size="A4"] {
width: 29.7cm;
height: 21cm;
align-content: center;
}
.divTableCell{
border: 1px solid #999999;
display: table-cell;
width: 200px;
align-content: center;
align-items: center;
text-align: center;
height: 40px;
}
.divTableRow {
display: table-row;
width: inherit;
}
.flex-container{
display: -webkit-box;  /* OLD - iOS 6-, Safari 3.1-6, BB7 */
display: -ms-flexbox;  /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */

justify-content: center;
align-items: center;
background-color: #ffffff;
}
@media print {
body, page {
margin: 0;
box-shadow: 0;
}
}

A: There is no CSS to work on but I just checked the function and it works great.
Use this to build your code.

$("a").click(function(){
$(".divTableBody").each(function() {
    var $this = $(this);
    var newrows = [];
    $this.find(".divTableRow").each(function(){
        var i = 0;
        $(this).find(".divTableCell").each(function(){
            i++;
            if(newrows[i] === undefined) { newrows[i] = $("

"); }
            newrows[i].append($(this));
        });
    });
    $this.find(".divTableRow").remove();
    $.each(newrows, function(){
        $this.append(this);
    });
});
return false;
});
body {
padding-top: 50px;
}
page {
background: white;
display: block;
margin: 0 auto;
margin-bottom: 0.5cm;
box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
page[size="A4"] {
width: 29.7cm;
height: 21cm;
align-content: center;
}
.divTableCell{
border: 1px solid #999999;
display: table-cell;
width: 200px;
align-content: center;
align-items: center;
text-align: center;
height: 40px;
}
.divTableRow {
display: table-row;
width: inherit;
}
.flex-container{
display: -webkit-box;  /* OLD - iOS 6-, Safari 3.1-6, BB7 */
display: -ms-flexbox;  /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
display: flex;         /* NEW, Spec - Firefox, Chrome, Opera */

justify-content: center;
align-items: center;
background-color: #ffffff;
}
@media print {
body, page {
margin: 0;
box-shadow: 0;
}
}

test
<page size="A4" class="flex-container">

1

101

2

102

3

103

4

104

5

105

6

106

7

107

8

108

9

109

10

110

11

111

12

112

13

113

14

114

15

115

16

116

17

117

18

118

19

119

20

120

21

</page>


text:
Q: How to replace every 2nd line sed How to replace every 2nd line of a text file with another text file list of lines.
Example:
cat filea.txt
I love Pink
I love Blue
I love Dogs
I love MOMO

cat bileb.txt
I hate yello
I hate white
I hate rats
I hate pigs

Now I need the output as
I love Pink
I hate yello
I love Dogs
I hate rats

textbile b should replace the every 2nd line of text filea without appending it. How can we do that using -i with sed or awk.

I tried to do that using paste comand that dosen't replace it appends.

A: With GNU sed, you can use the R command:

   R filename
          Append  a line read from filename.  Each invocation of the command
          reads a line from the file.  This is a GNU extension.

So
$ sed 'R fileb.txt' filea.txt
I love Pink
I hate yello
I love Blue
I hate white
I love Dogs
I hate rats
I love MOMO
I hate pigs

Combined with d to delete the original line:
$ sed -e '2~2{R fileb.txt' -e 'd;}' filea.txt
I love Pink
I hate yello
I love Dogs
I hate white

If you want to replace every 2nd line of filea.txt with every 2nd line of fileb.txt, then:
$ sed '2~2d' fileb.txt | sed -e '2~2{R /dev/stdin' -e 'd;}' filea.txt
I love Pink
I hate yello
I love Dogs
I hate rats

Alternatively, use paste to join lines of the files side-by-side, then pipe to sed to change the default tab delimiters to newlines on only the odd lines:
$ paste filea.txt fileb.txt | sed -n '1~2s/\t/\n/p'
I love Pink
I hate yello
I love Dogs
I hate rats

Obviously this won't work if the original filea.txt may contain tab characters.
Since you also tagged your question awk, you could also consider something like
awk '{getline x < "fileb.txt"} NR%2 {print; print x}' filea.txt


text:
Q: boxed text and underline within the gb4e environment I would like to ask about boxed text and underline within the gb4e environment. I would like to box the text to indicate that this word is important. At the same time, I would like to draw an underline from the boxed text to the end of the sentence, which is emphasized with boldface.
I would like to this within the gb4e environment because the text boxed and underlined is not English. However, as you can see, the gloss is not properly assigned to the underlined text. Also, there is a space between the box and the underline as in (2) in the picture in the bottom of this post.
What I would like to make is the attached one, which is created by MS Word.

Could you tell me how to write the code for this type of expression?
The following is the code I wrote.
\documentclass{article}
\usepackage{times}
\usepackage[utf8]{inputenc}
\usepackage[margin=2cm]{geometry}
\usepackage{gb4e}
\noautomath

\begin{document}
\begin{exe}
\ex[]{\gll Naoya-wa Mari-ga Nani-o Non-da ka Yumi-ni it-ta no? \\
      Naoya-\textsc{Top} Mari-\textsc{Nom} what-\textsc{Acc} drink-\textsc{Past} Q Yumi-\textsc{Dat} it-\textsc{Past} Q?  \\
      \trans `(Lit.) For which $x$, $x$ a thing, Naoya said to Yumi whether Mari drink $x$.'
}

\ex[]{\gll Naoya-wa Mari-ga \underline{\framebox{\textbf{Nani}}-o Non-da ka Yumi-ni it-ta \textbf{no}}? \\
      Naoya-\textsc{Top} Mari-\textsc{Nom} what-\textsc{Acc} drink-\textsc{Past} Q Yumi-\textsc{Dat} it-\textsc{Past} Q?  \\
      \trans `(Lit.) For which $x$, $x$ a thing, Naoya said to Yumi whether Mari drink $x$.'
}

\ex[]{\gll Naoya-wa Mari-ga \underline{\textbf{Nani}-o Non-da ka Yumi-ni it-ta \textbf{no}}? \\
      Naoya-\textsc{Top} Mari-\textsc{Nom} what-\textsc{Acc} drink-\textsc{Past} Q Yumi-\textsc{Dat} it-\textsc{Past} Q?  \\
      \trans `(Lit.) For which $x$, $x$ a thing, Naoya said to Yumi whether Mari drink $x$.'
}

\ex[]{\gll Naoya-wa Mari-ga \framebox{\textbf{Nani}}-o Non-da ka Yumi-ni it-ta \textbf{no}? \\
      Naoya-\textsc{Top} Mari-\textsc{Nom} what-\textsc{Acc} drink-\textsc{Past} Q Yumi-\textsc{Dat} it-\textsc{Past} Q?  \\
      \trans `(Lit.) For which $x$, $x$ a thing, Naoya said to Yumi whether Mari drink $x$.'
}

\end{exe}
\end{document}

The following is the result of the code.

A: Because of the way the glossing is done each individual word/gloss pair in the gloss lines must be separated. This is why you can't use \underline around groups of words: the entire underlined group will be considered a single word for the glossing macro, which is not what you want.
Here's a solution using TikZ.  I've defined two commands \UL and \LU to denote the beginning and end of the underlining.  Then I've made a \gluline command which underlines everything between those two markers.  This can be used with or without the \framebox.
Some things to understand about this solution:

*

*you need to compile the document twice to get the underlining to show up

*if the \UL ... \LU words break over a line, the underlining will fail.

If you need underlining to work across broken lines of the gloss, you will need to mark subsequent stretches of underlining manually, (i.e., not using the wrapper macros).  I've added an example to show how to do this.
\documentclass{article}
%\usepackage{times} % don't use this use newtxtext instead
\usepackage{newtxtext}
\usepackage[utf8]{inputenc}
\usepackage[margin=2cm]{geometry}
\usepackage{tikz}
\newcommand*{\tkzmk}[1]{\tikz[remember picture,overlay] \node (#1) {};}
\newcommand*{\tkzuline}[2]{\tikz[overlay,remember picture]{ \draw (#1.south) -- (#2.south);}}
\newcommand*{\UL}{\tkzmk{1}}
\newcommand*{\LU}{\tkzmk{2}}
\newcommand*{\gluline}{\tkzuline{1}{2}}
\usepackage{gb4e}
\noautomath

\begin{document}
\begin{exe}

\ex[]{\gll Naoya-wa Mari-ga \UL\framebox{\textbf{Nani}}-o Non-da ka Yumi-ni it-ta \textbf{no}\LU? \\
      Naoya-\textsc{Top} Mari-\textsc{Nom} what-\textsc{Acc} drink-\textsc{Past} Q Yumi-\textsc{Dat} it-\textsc{Past} Q?  \\
      \trans `(Lit.) For which $x$, $x$ a thing, Naoya said to Yumi whether Mari drink $x$.' }
\gluline

\ex[]{\gll Naoya-wa Mari-ga \UL\textbf{Nani}-o Non-da ka Yumi-ni it-ta \textbf{no}\LU? \\
      Naoya-\textsc{Top} Mari-\textsc{Nom} what-\textsc{Acc} drink-\textsc{Past} Q Yumi-\textsc{Dat} it-\textsc{Past} Q?  \\
      \trans `(Lit.) For which $x$, $x$ a thing, Naoya said to Yumi whether Mari drink $x$.'
}
\gluline

\end{exe}
\begin{minipage}{.5\linewidth}
\begin{exe}
\ex[]{\gll Naoya-wa Mari-ga \UL\framebox{\textbf{Nani}}-o Non-da ka\LU{} \tkzmk{3}Yumi-ni it-ta \textbf{no}\tkzmk{4}? \\
      Naoya-\textsc{Top} Mari-\textsc{Nom} what-\textsc{Acc} drink-\textsc{Past} Q Yumi-\textsc{Dat} it-\textsc{Past} Q?  \\
      \trans `(Lit.) For which $x$, $x$ a thing, Naoya said to Yumi whether Mari drink $x$.' }
\gluline
\tkzuline{3}{4}
\end{exe}
\end{minipage}
\end{document}


text:
Q: Existence of joint optimal coupling Given probability distributions $(\mu_1, \mu_2,\dots,\mu_n)$ on a sufficiently nice space $X$, does there always exist a random vector $(X_1,X_2\dots,X_n)$ such that any pair $(X_i,X_j)$ is an optimal coupling of $\mu_i$ and $\mu_j$?
This is possible if we only require that $(X_k,X_{k+1})$ are optimal couplings of $\mu_k$ and $\mu_{k+1}$ for $k\in\{1,\dots,n-1\}$, this is a result of the gluing lemma. If any restrictions are required on the measures or the space, I am very interested nonetheless.

A: Consider a graph $G$ on $\{1,\ldots,n\}$ where $\mu_i$ is assigned to node $i$, and an edge $\{i,j\}$ in $G$ indicates that the coupling 0f $\mu_i$ and $\mu_j$ is required to be optimal. If $G$   has no cycles (i.e., it is a forest) then the proof of the gluing lemma (see, e.g., [1]), applied separately to each tree of the forest, extends to show that a global coupling can be arranged to be optimal on all edges of $G$. Conversely, we next verify that if $G$ contains a cycle, then there is a choice of the measures $\mu_i$ where such a global optimal coupling does not exist.
Let us first show this for a cycle of length 3:
Suppose the variable $X$ is uniform in $\{1,2,3\}$, the variable $Y$ is uniform in $\{2,3,4\}$ and $Z$ is uniform in $\{1,3,4\}$.
Under the optimal coupling $P_1$ of $(X,Y)$, we have $P_1(Y=4|X=1)=1$.
Under the optimal coupling $P_2$ of $(Y,Z)$, we have $P_2(Z=4|Y=4)=1$.
Under the optimal coupling $P_3$ of $(X,Z)$, we have $P_3(Z=4|X=1)=0$.
This shows that there is no coupling of $(X,Y,Z)$ that projects to the optimal couplings $P_1, P_2, P_3$.
For a cycle of length $k>3$, simply assign two adjacent nodes of the cycle the laws of $X$ and $Y$, and assign all other nodes the law of $Z$.
[1]  Villani, Cedric. Optimal transport: old and new. Vol. 338. Berlin: springer, 2009.


text:
Q: How to include an sql file within another sql file in MS SQL? We have several SQL scripts which are generated from an Entity Model. They need to be run in a specific order. Additionally there are several filling scripts which insert test data into the database.
Currently I need to open each script in Visual Studio and execute them in the correct order by clicking Execute (ctrl shift E).
Is there a way to create a script like Master.sql that contains includes like this:
BEGIN TRANSACTION

ImportOrInclude myDB1.sql
ImportOrInclude myDB2.sql
...

COMMIT

This is only required to run from Visual Studio and will not be part of the application itself.
How can this be done?
EDIT 1
I've found that there is something called SQLCMD Scripts which can import SQL files:
http://msdn.microsoft.com/en-us/library/aa833281%28v=vs.80%29.aspx
But my question is then how to get the directory path of the current solution  into the :r command.
EDIT 2
So I figured out how to do it, not perfectly, but it works. The downside is that the $(SolutionDir) is not loaded from the Visual Studio variables, so you need to set it up manually. This code is meant to be run in Visual Studio:
-- turn on in menu: Data -> Transact SQL editor -> SQL CMD mode
-- set this to path where the .sln file is.
:setvar SolutionDir C:\_work\projectname\

:!! echo $(SolutionDir)Maa.EntityModel.All\DbWEntityModel.edmx.sql
:r $(SolutionDir)Maa.EntityModel.All\DbWEntityModel.edmx.sql
go

:!! echo $(SolutionDir)Maa.EntityModel.All\DblQEntityModel.edmx.sql
:r $(SolutionDir)Maa.EntityModel.All\DbQEntityModel.edmx.sql
go

A: Use the Business Intelligence Development Studio that comes with SQL Server to do this. Create a new SSIS Package. Inside this package create several Execute SQL Tasks in the Control Flow for each file you have and set SQLSourceType to FileConnection and choose your file.

A: Use sqlcmd utility.
Extract you might find interesting:
-i input_file[,input_file2...]

Identifies the file that contains a batch of SQL statements or stored procedures. Multiple files may be specified that will be read and processed in order. Do not use any spaces between file names. sqlcmd will first check to see whether all the specified files exist. If one or more files do not exist, sqlcmd will exit.
Example:
sqlcmd -dDataBaseName -E -Stcp:ServerName\instancename -imaster.sql

Master.Sql:
:r file1.sql
:r file2.sql


text:
Q: Looping with Multiple Parameters without the for loop Below is a micro-version of my data set. I would like to loop through the three variables without using the 'for' function.
Reproducible Version of the Subject Data Set
cat1 <- rep(c("A","S"),each=40)# First variable
cat2 <- rep(c("C","M","Y","K"), each=10, times=2) # Second variable
num1 <- rep(c(0,10,20,30,40,45,65,80,90,100),8) # Third variable
rspns <-structure(list(dataSet = c(0.2484375, 0.3959375, 0.4875, 0.57875, 0.6696875, 0.694375,
    0.816875, 0.879375, 0.9121875, 0.93125, 0.25125, 0.3796875, 0.4609375, 0.5396875, 0.6159375,
    0.6515625, 0.7696875, 0.8384375, 0.864375, 0.8865625, 0.271875, 0.39875, 0.4821875,
    0.5628125, 0.6284375, 0.650625, 0.7553125, 0.8003125, 0.8103125, 0.8125, 0.251875, 0.3775,
    0.4703125, 0.5725, 0.6996875, 0.7378125, 0.945, 1.055625, 1.1021875, 1.1140625, 0.25125,
    0.4203125, 0.5215625, 0.615625, 0.71, 0.74, 0.865625, 0.9246875, 0.9603125, 0.9734375,
    0.256875, 0.3953125, 0.4775, 0.5528125, 0.62875, 0.65875, 0.78375, 0.8384375, 0.8653125,
    0.8740625, 0.2790625, 0.4215625, 0.515, 0.6009375, 0.6665625, 0.693125, 0.7959375, 0.83875,
    0.8490625, 0.8575, 0.2571875, 0.3759375, 0.4665625, 0.56375, 0.68875, 0.725, 0.9259375,
    1.0328125, 1.085625, 1.1096875)), .Names = "rspns",
  class = "data.frame", row.names = c(NA, -80L))
gain <- data.frame(cat1,cat2,num1, rspns=rspns)

tint <-  function(x,y,z) gain[cat1 == x & cat2 == y & num1 == z, 4]
dgain <- function(x,y,z){(100* (1-10^-(tint(x,y,z) - tint(x,y,0))) / (1-10^-(tint(x,y,100)- tint(x,y,0)))) - z}

How can I get the dgain function, which takes three parameters, to loop through cat1, cat2 and num1 variables without using for loops?
Your help and technical expertise is greatly appreciated.

A: Here's the basic idea of what I was getting at with my comments:
#With a basic for loop for reference
out1 <- rep(NA,80)
for (i in 1:80){
    out1[i] <- dgain(cat1[i],cat2[i],num1[i])
}

out2 <- mapply(dgain,x = cat1,y = cat2,z = num1)

out3 <- dgain(cat1,cat2,num1)

all.equal(out1,unname(out2))
[1] TRUE
> all.equal(out1,out3)
[1] "Mean relative difference: 0.2579067"

It's probably possible to refactor your code such that the final idiom (dgain(cat1,cat2,num1)) would return the correct result, but it would take more tinkering than I have time for. The issue is that you're subsetting a data frame from your global environment inside one of your functions using ==, which won't return what you want if you pass is vector arguments.
Nothing special is going on with mapply. It's almost literally doing the same thing as the for loop, only perhaps slightly more efficiently and perhaps in a more aesthetically pleasing manner.


text:
Q: Google One tap sign-in UI not displayed after clicking the close button I am trying to make the new google one tap sign in work following this guide:
https://developers.google.com/identity/one-tap/web
google.accounts.id.initialize({
            client_id: '123123123123123123.apps.googleusercontent.com',
            cancel_on_tap_outside: false,
            callback: handleCredentialResponse
        });

        //google.accounts.id.prompt(true);

        google.accounts.id.prompt((notification) => {
            if (notification.isNotDisplayed() || notification.isSkippedMoment()) {

                // continue with another identity provider.
            }
    });

I am using the One Tap JavaScript API to display One Tap. And it perfectly does what it needs to do.
Client side verification and all works well but I've got one problem. After I close the UI by clicking the close button at the top right corner of the window, the UI is not displayed anymore and when I examine the notification status it shows me this error;
opt_out_or_no_session
What do I need to do to keep the UI displayed even if it's closed by the user?
I appreciate any help.

A: google.accounts.id.prompt((notification) => {
            if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
                document.cookie =  `g_state=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT`;
                google.accounts.id.prompt()
            }
        });

this worked for me to delete the cookie and try again

A: This is the so-called "Exponential Cool Down" feature. More details at https://developers.google.com/identity/one-tap/web/guides/features#exponential_cool_down.
Google One Tap is an optimized UX for users to sign-in or sign-up with just one tap. If a user doesn't want to sign-in/sign-up (by closing the One Tap), it should not be displayed again and again on each page reloading or navigation. To most users, it's an annoying UX.
With the cool down feature, users won't feel to be pushed to sign-in/sign-up.

A: In development, I was able to reset the exponential cool down by removing the g_state cookie.
One method for this might be to add a development-only "Clear Google One Tap Cookie" link that run an server-side action to remove the g_state cookie and then redirect back to the previous page.

A: Individual user accounts may globally opt-out of using One Tap from their Google Account settings page.
In this case opt_out_or_no_session will be returned.
You'll not be able to force users to use One Tap if they've opt out globally or if the exponential cooldown is active.
During development, on your account, you can follow the suggestions in the Answers to reset the cooldown.


text:
Q: R: How to transform set-membership indicator line item data into single summary row of all set combinations? I have line items indicating which groups my customers are members of.
cols <- c("CustomerName", "Magazines", "Books", "Emails")
df <- data.frame(matrix(ncol = length(cols), nrow=0))
colnames(df) <- cols

df[nrow(df) + 1,] <- c("Alice", 1, 0, 1)
df[nrow(df) + 1,] <- c("Bob", 0, 1, 1)
df[nrow(df) + 1,] <- c("Chris", 1, 1, 1)
df[nrow(df) + 1,] <- c("Darcy", 0, 1, 1)

How do I summarize data of this shape into a single summary row with columns & counts for each possible group-combination?
Desired output:
df_DesiredOutput <- c("Books" = 0, "Magazines" = 0, "Emails" = 0, "BooksMagazines" = 0, "BooksEmails" = 1, "MagazinesEmails" = 2, "BooksMagazinesEmails" = 1)

The transformation should be agnostic to the number of products as well as their actual product names.


text:
Q: Estimating a true mean
A sample average is 54 while a sample size is 159. If a population deviation is 19 estimate a true mean that should be accurate with a probability of 99%.

So I started with $(1-0.99)/2 = 1/200$ then I started to look in the Z-Table for the Z-Score. I came up with the value of 0.1841 which I am not sure is correct. After that I substracted $54-0.1841=53.8159$ and added $54+0.1841=54.1841$ to get that CI is (53.8159,54.1841). Is this correct, or am I missing the complete idea of the task?

A: Overlooking awkward terminology: A 99% confidence interval for the
population mean $\mu$ is $\bar X \pm 2.576\frac{\sigma}{\sqrt{n}}.$
I got the interval $(51.9571, 56.0429),$ but you should check my
arithmetic.


text:
Q: insert values to database after looping through a form Briefly, my script includes form ask how many images to enter ,,the entered value will be in a while loop that will display a form with inputs equally to image value entered . okey , I made the submit button outside the loop ,I want now to add them to database ,,I used again a while loop with the query as I did in the form ,,but it only inserts the last item ..What could the problem be ? This is part of the script :
if (isset($_POST["chooseimagen"])) {
    $i=0;
    $imgvl = $_POST["imgvl"];
    $cid = $_POST["cid"];
    while($i<$imgvl){

       echo '<form name="finalform" method="post" action="">
        id of content :<input type="text" name="idcontent" value="'.$cid.'"/>

       Enter id of image :<input type="text" name="imgid" value=""/>

       Enter name of image : <input type="text" name="imgname" value=""/>

       -----------------------------------------------------------------------

       ';
       $i++;
    }

  echo  "

<input type='hidden' name='imgvl' value='".$imgvl."'/><input type='submit' name='addto' value='insert images'/></form";
}

    ?>
<?php
 if(isset($_POST["addto"])){
  $imgvl = $_POST["imgvl"];
     $i=0;
     while ($i < $imgvl){
     $idcontent = $_POST["idcontent"];
     $imgid = $_POST["imgid"];
     $imgname = $_POST["imgname"];
     $queryin = "insert into content_images values ('$imgid','$idcontent','$imgname','ok')";
     mysqli_query($con,$queryin);
         $i++;
     }

 }

?>

A: Still new to development, but I think I know..
A few things, you are creating a new form with every loop, but only closing it once. Also you are missing a >, so technically you are not closing the forms at all.
while($i<$imgvl){

   echo '<form name="finalform" method="post" action="">

...
$i++;
}

echo  "

<input type='hidden' name='imgvl' value='".$imgvl."'/>
<inputtype='submit' name='addto' value='insert images'/></form";

But I think the reason you are getting this problem is each form you create has the same names for the inputs. That's why you are only getting the last item, because every item you are inserting is just the last input set.
Because you have no action on the form, every form is essentially combined. This means there is no way to distinguish which input name you are reffering to and therefore it takes the last value that was assigned.
Hope this helps


text:
Q: Heroku clock process keeps crashing I'm trying to utilize APScheduler to periodically check a database and send an email if needed. Unfortunately, whenever I deploy to Heroku I keep obtaining this same error. The code ran perfectly fine when I ran it locally.
This is my code:
from flask_apscheduler import APScheduler, scheduler
#from pytz import timezone
#from sendgrid import SendGridAPIClient
#from sendgrid.helpers.mail import Mail
#from models import db, User, Applications, Tasks, Contact
#from datetime import datetime, timedelta
#from flask import current_app as app

sched = APScheduler()

def send_email():
    print("Hello")

sched.add_job(id='Sending Email', func=send_email, trigger='interval', minutes = 1)
sched.start()
print("HelloTest")

I commented out most of imports it just to test the clock process without the interference of other modules.
I keep getting this error:
2021-12-04T07:37:14.422436+00:00 heroku[clock.1]: Starting process with command `python /app/backend/clock.py`
2021-12-04T07:37:15.106399+00:00 heroku[clock.1]: State changed from starting to u
2021-12-04T07:37:16.801846+00:00 heroku[clock.1]: Process exited with status 0
2021-12-04T07:37:16.877624+00:00 heroku[clock.1]: State changed from up to crashed
2021-12-04T07:37:16.601432+00:00 app[clock.1]: /app/.heroku/python/lib/python3.9/site-packages/apscheduler/util.py:95: PytzUsageWarning: The zone attribute is specific to pytz's interface; please migrate to a new time zone provider. For more details on how to do so, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html
2021-12-04T07:37:16.601448+00:00 app[clock.1]:   if obj.zone == 'local':
2021-12-04T07:37:16.604340+00:00 app[clock.1]: /app/.heroku/python/lib/python3.9/site-packages/apscheduler/triggers/interval.py:66: PytzUsageWarning: The normalize method is no longer necessary, as this time zone supports the fold attribute (PEP 495). For more details on migrating to a PEP 495-compliant implementation, see https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html
2021-12-04T07:37:16.604342+00:00 app[clock.1]:   return self.timezone.normalize(next_fire_time)
2021-12-04T07:37:16.610777+00:00 app[clock.1]: HelloTest

A: You need to set SCHEDULER_TIMEZONE in the app Config, I think the default is being passed to APScheduler which is the library having the problem
app.config['SCHEDULER_TIMEZONE'] = "Europe/Berlin"


text:
Q: How to store document vectors in a database for a search engine? I have implemented a search engine in Java. It has a database that stores the inverted index ie mapping from terms to list of documents the term appears in. There is a feature that allows a user to upload a document which can be added to document for indexing. The problem that i'm facing is that , everytime a new document is added , the index is reconstructed in memory instead of being updated . To update , i would need a database that stores document vectors that are essentially tf-idf's(term frequency* inverse document frequency) of each and every term in the index. I'm not able to work out database structure for it as in what rows and columns or multiple tables would be needed for storing such a structure.
I need to store
1. Document ID
2. Document Title
3. N dimensional Document vector where N is the number of unique terms
4. N terms
5. IDF of each term
6. TF of each term for every document.

I need it so that at the time of query matching i can extract this vector and calculate its similarity with the query vector.If you want any additional information, please let me know.
Thank you very much , I'm sure i would get some help here.

A: Are you sure you wanna use a Database to implement a search engine?
You may take a look at this Java framework which does an excellent job and very simple to learn .
Lucene Tutorial in 5 mins
It uses the Vector Space Model and there's no need for you to worry about all the above fields you mentioned in your post, since Lucene stores them along with much more advanced ranking factors.
I am sorry that my reply doesn't help you if you are intentionally using the Databases.


text:
Q: PrettyFaces, transient view and named path parameters give a warning I have a weird problem with PrettyFaces:
When combining a transient view (<f:view transient="true" />), named parameters in my pretty-config.xml (<pattern value="/document/#{id}" />), I get the following warning in my <h:messages />:
@ViewScoped beans are not supported on stateless views

The warning disappears as soon as I remove the #{id} from my pattern. I think that, somehow, PrettyFaces stores some state in the viewscope when using named parameters and JSF does not like it inside a transient view.
Is it a bug?

A: The problem seems to come from a bug in the JSF implementation.
See those 2 links:

*

*https://github.com/ocpsoft/rewrite/issues/208

*https://java.net/jira/browse/JAVASERVERFACES-3939


text:
Q: Child-element in inline-block div changes the parents siblings position I have a couple of divs with some content (another div inside). I want the parent divs to be positioned in a nice line and I want the child div to be relative to its parent.
I've made a JSFiddle To illustrate. Right now the divs are all nicely placed, but if you remove the '.btn' div in the last one, everything gets messed up.
To see what I mean, change the HTML in the JSFiddle to:

>>

>>

What's going on here? How can I get the desired result?

A: You should use floats for a better layout:

.expand{
  border:1px solid black;
  width:400px;
  height:400px;
  display:inline-block;
  float: left;
}

.btn{
  cursor:pointer;
  position:relative;
  top:150px;
  left: 150px;
  border: 1px solid black;
  width:40px;
  height:40px;
  vertical-align:middle;
  text-align:center;
  line-height:40px;
}

>>

>>

A:

.expand {
  border: 1px solid black;
  width: 400px;
  height: 400px;
  display: inline-block;
  vertical-align: top;
}

.btn{
  margin: -20px 0 0 -20px;
  cursor: pointer;
  position: relative;
  top: 50%;
  left: 50%;
  border: 1px solid black;
  width: 40px;
  height: 40px;
  vertical-align: middle;
  text-align: center;
  line-height: 40px;
}

>>

>>

A: You can simply play with the position property to get the desired result.
just add position:relative to your .expand class
.expand {
        position:relative;
        border: 1px solid black;
        width: 400px;
        height: 400px;
        display: inline-block;
    }

and update the position to absolute to your .btn class
.btn {
        cursor: pointer;
        position: absolute;
        top: 150px;
        left: 150px;
        border: 1px solid black;
        width: 40px;
        height: 40px;
        vertical-align: middle;
        text-align: center;
        line-height: 40px;
    }


text:
Q: i am trying to extract date from text using regular expression I am trying to extract the date from this '2025-03-21T12:54:41Z' text using python regular expression.
date=re.match('(\d{4})[/.-](\d{2})[/.-](\d{2})$', date[0])
print(date)

This give output as None
also, I tried this code
date_reg_exp = re.compile('\d{4}(?P<sep>[-/])\d{2}(?P=sep)\d{2}')
matches_list=date_reg_exp.findall(date[0])
for match in matches_list:
  print match

This gives output as - only
Please help

A: Your regular expression is wrong because it has a $ at the end. $ asserts that this is the end of the string.
The regex engine matches your string with the regex and after matching the last two digits, expects a $ - end of the string. However, your string still has T12:54:41Z before the end, so the regex does not match.
To fix this, remove $:
>>> re.match('(\d{4})[/.-](\d{2})[/.-](\d{2})', '2025-03-21T12:54:41Z')
<_sre.SRE_Match object; span=(0, 10), match='2025-03-21'>

A: Instead of  using $ sigil at the end of your regexp, which is matching end-of-line character, try using ^ at the beginning:
import re
date='2025-03-21T12:54:41Z'
date=re.match('^(\d{4})[/.-](\d{2})[/.-](\d{2})', date)
print(date)

Output in python3:
<_sre.SRE_Match object; span=(0, 10), match='2025-03-21'>

Python2:
<_sre.SRE_Match object at 0x7fd191ac1ae0>


text:
Q: Solving P(TRUE) of finding counterpart pairs in 2 sets with constraints involving the Universal Genetic Code Alright, I posted this same question over at MSE, https://math.stackexchange.com/questions/2395394/solving-ptrue-of-finding-counterpart-pairs-in-2-sets-with-constraints-involvin,
I had a bounty on it for 100 and a user named Vincent told me he had solved it, and that it would just take a day or two to write out.  During that day or two, the bounty expired...and he mysteriously disappeared with the solution...and
I havn't heard from him at all .  I do not know if those events were causally correlated or just correlated.  It's been over ~11 days now...so I'm concluding my question over there is dead and gone.  Hence, why I've gone all out with 200 bounty on this one.
Regardless, given his questions over there in the comments I tried to be very specific about what I'm asking here (hence the very long subscripts, heh).
I actually need to try to figure out a means of doing this without generating simulations...and/or then using those generated simulations as a sample for the larger population...and then just extrapolate via a few tests to make sure I can "safety make those assumptions."
It's more about understanding the relationship and patterns of ALOT of questions like this one (there are many varieties) and correlating them to any biological reasoning or mechanism.  That's why I want to know how to do it, if its possible.
I apologize for the lack or incorrect usage of formal notation.  Did my best.
Regardless, here is my question.
( My use of "|" ANYWHERE means OR )
$$D = D\_EitherUnlessInitialSpecificed = (D\_Initial | D_CounterpartToInitial)$$ $$B = B\_EitherUnlessInitialSpecificed = (B\_Initial | B\_CounterpartToInitial)$$
Yes, I wrote that redundantly, but hopefully clearly.I hope I wrote that correctly.
Definition of counterparts:
a, c, g, and t do not represent anything quantifiable.  They only represent a quality.
As stated more generally above, and more specifically down below:
$$D\; can\; only = a\;  or \; c\; ; \; a < -- > c$$
$$if\;  D = a,\; then \;D_c = c$$$$if\;  D = c,\; then \;D_c = a$$
$$B\; can\; only = t\;  or \; g\; ; \; t < -- > g$$
$$if\;  B = t,\; then \;B_c = g$$$$if\;  B = g,\; then \;D_c = t$$
In the end, everything comes down to the placement of $a$, $c$, $g$, and $t$ within constraints I'll define shortly.
$$W = (D\;|B)$$
and we'll be using 2 instances of
$W$, $W_1$ & $W_2$ which are not exclusive of each other in any context, nor are they exclusive/equal when the same instance is repeated in the same or a different set/array/etc.
They are more like placeholders for a position which you're trying to find the counterpart to.
If I use $W_2$ or $W_1$ and then use it again multiple times, each time it takes on a value which is assigned actually only by you.
Now,
$$W_1 = (D | B)$$$$W_2 = (D | B)$$
$$Wa\; =\; an\; instance\; of\; the
\;set \;or\; what\; I\; am\; going \;to \;begin \;calling\; an\;"array"\; \{W_1,W_2\}$$
We'll make 8 individual instances of these paired arrays and then store them into an array, $ArrayTop$ aka $ArrT$
$$ArrT\;=\;\{Wa_1,Wa_2,Wa_3,Wa_4,Wa_5,Wa_6,Wa_7,Wa_8\}$$
You can also reference the items in the array from their order via
$ArrT_1,ArrT_2...etc.$ if needed.
Now, we'll make 16 more individual instances of these paired arrays and then store them into another array, $ArrayBottom$ aka $ArrB$. However, we'll start $Wa_x$ at 9.
$$ArrB\;=\;\{Wa_9,Wa_{10},Wa_{11},Wa_{12},Wa_{13},Wa_{14},Wa_{15},Wa_{16},Wa_{17},Wa_{18},Wa_{19},Wa_{20},Wa_{21},Wa_{22},Wa_{23},Wa_{24}\}$$
or
$$ArrB_1, ArrB_2...ArrB_{16}$$
If, given $ArrT$ & $ArrB$ and these constraints,
$$Each$$
$$ a, c, g,\ and\ t$$
$$has \;a \;required \;"point\; usage" \;of \;exactly \;16\; for\; W_1 \;collectively\; and\; W_2\; collectively.$$
Every time one of these 4 letters is used in:

$ArrT$, it acquires 4 points.
$ArrB1$ or $ArrB2$, then it acquires 3 points.
$ArrB3$ through to $ArrB14$, then it acquires 2 points.
$ArrB15$ or $ArrB16$, then it acquires 1 point.

To clarify further, a letter acquires points for it's $W_1$ and separately for its $W_2$.

Find the number of all possible scenarios for the placements of
$$a,t,g,\; and\; c$$
where, for each item in $ArrT$, two items in $ArrB$ contain the respective counterparts of $W_1$ and $W_2$ from that item in $ArrT = TRUE$.
Also, the total # of possible scenarios if you want, although that's somewhat easy to figure out.
To Summarize: My question is
1) What is the answer you come up with.
2) How did you do it?
Any questions, let me know.

I have included a picture to provide the context for what this is for and where it comes from to hopefully help resolve any confusion.
One very important thing I need to stress here and which can cause confusion with this picture is the fact that there are actually a few symmetries with very low probabilities to occur especially in tandem between the two halves (pending you're looking for them).  I will say that this is our genetic code for everything on earth...so that's kind of cool but the question I'm asking has absolutely nothing to do with symmetry and only the presence of things in the top group that then have their counterparts in the bottom regardless of their location in the "horizontal" plane of the group.  The mathematical explanation should hopefully communicate that though.
Ignore the upper left part of the picture and any row that is the "3rd row" in either of the groups. (Contains R, Y, H, N, and 2 instances of G)

A: I'm back... I posted the answer to the original question at https://math.stackexchange.com/a/2419479/101420
Now that we are at stats.stackexchange I can say a bit more about the first line of that answer, namely that it is more of a counting problem than a probability question. Probabilities are sometimes defined as a ratio: the number of 'interesting' or 'relevant' cases divided by the 'total' number of cases.
In the other answer I computed the first of these numbers (which is also what you are asking here in the body of the question - probabilities show up only in the title) but if you want to turn the answer into a probability, you also need the second number, i.e. the total number of things that COULD have happened (with equal probability) under a simpler model of the underlying biology. The question is: what is the simpler model? If you consider 'all cases' to be all ways of placing a, c, t, g into the 48 slots then there are $4^{48}$ possibilities, but from the wording of the question I get the impression that you have a more subtle idea about what is going on here: the 'total' number of cases is the number of placements of a, c, g, t that obey  some but not all of the conditions from the question, and within that you consider the interesting cases the ones that satisfy all.
I computed the number of interesting cases over at MSE, but if you want a probability you need to be more specific about what subset of conditions define the 'total' number of cases.


text:
Q: Double sum with binomial coefficients $\sum_{1\le i
Find a closed form formula for this sum:
  $$\sum_{1\le i<j\le m} \sum_{\substack{1\le k,l\le n \\  k+l\le n}}{n\choose k} {n-k\choose l} (j-i-1)^{n-k-l}$$
It's quite likely that it can be done with standard techniques, but I haven't tried to do it completely, because it was very tedious. I think combinatorial interpretation can be a nice way here, although tricky. It's easy to prove that inner sum is equal to $n(n-1)(j-i+1)^{n-2}$ but then I really doubt sum $\sum_{1\le i<j\le m}n(n-1)(j-i+1)^{n-2}$ can be easily computed. Can anybody help?


text:
Q: Why the optimal value that minimizes a function does not satisfy condition? I have found a solved example of A Stochastic Two-Period Model with No Setup Cost that has a lot of complicated calculations to arrive to the solution.
In the following example, $c=$cost of ordering, $h=$cost of holding and $p=$shortage cost.

The part where things start to complicate, is when making the substitution of $y_1^0$ into $C_1(x_1)$.
Clearly will not be an easy calculation by hand since $C_1$ has this function $L$, that it's evaluated with diferent arguments, which are two integrals.
I am not sure what form the argument of $\displaystyle \min_{y_1\ge x_1}\{\dots\}$ will have, nor what would be best to do next.  My book mentions this OR Courseware but since I have the pdf file book I don't have the disk? is refering to.
And my question is what can I do here in order to find the optimal $y_1^0$ without having to deal with lots and lots of calculations by hand?
Any suggestions are very appreciated.

The $C_1(x_1):$

The $L(z):$

edit.
Following the comment of Larry, I substitute $y_1^0$ in the equation equal to zero (below the $C_1(x_1)$ definition in the image).
I assumed $y_1^0=5$ to be the optimal and this is what I got
$$-15+(15+10)\frac{5}{10}+(10-15)\Phi(5-2)+(15+10)\int_0^{3}\Phi(5-\xi)\phi_D(\xi)d\xi $$ $$=more\ calculations$$ $$=-\frac {11}{8}$$ This is different than $0$, which I don't understand why, the equation should have had the value $0$ because the book mentioned the optimal was $y_1^0=5$ and not $y_1^0=6$. Also the optimal should satisfy the equation equal to zero, but does not.
I really don't see what am I doing wrong? I did check twice the calculations of the expression and found no errors.

A: I don't fully understand/ know about this topic but I have some ideas about the possible answer or how to disentangle the problems.
The optimal value of $y_1^0$ is $5.42$, as they compute in the example. However, they don't use the general equation:

But, the equation for the case of a uniform distribution:

In fact you can use the first equation (I did it) and obtain the same result. I give you some middle steps:
$$-15 + \frac{25y_1^0}{10} - 5 \frac{y_1^0-y_2^0}{10} + 25 \int_0^{y_1^0-y_2^0} \frac{y_1^0-\xi}{10}\frac{1}{10}d\xi = 0.$$
After substituting $y_2^0=2$ and some computations you reach:
$$-\frac{29}{2} + 2 y_1^0 + \frac{{y_1^0}^2}{8}=0,$$
with the only positive solution being $y_1^0 = 5.4164$. However, I imagine $y_1^0$ needs to be an integer, so he substitutes $C_1(x_1)$ for either $y_1^0=5$ and $y_1^0=6$ (the nearest points) to find which of them is the one that gives a smaller value. You can try to see if you can get this.
I computed $L(z)$ and I get:
$$L(z)=p\int_z^{10}  \frac{\xi-z}{10} d\xi + h \int_0^z \frac{z-\xi}{10}d\xi = \dots = \frac{p}{20} \left(10^2 - 20z\right) + \frac{z^2}{20} (p+h) = 5 (15-3z + \frac{z^2}{4}),$$
in case it is useful for you.


text:
Q: Struct and functions with templates I just started using templates and want to implement it in this fashion within my header file, but I am getting various errors and don't really understand why.
Header File:
#ifndef EXAM3_H_
#define EXAM3_H_

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

const int maxInt = 2147483647;

template <typename T>

struct nodeType {
    T data;
    nodeType *next;
};

bool search(nodeType *head, const T &searchItem);
void deleteNode(nodeType *&head, nodeType *&tail, int &count, const T &deleteItem);
void initializeList(nodeType *&head, nodeType *&tail, int &count);
bool isEmptyList(const nodeType *head);
void printList(nodeType *head);
int lengthList(nodeType *head);
void destroyList(nodeType *&head, nodeType *&tail, int &count);
void insert(const T &newItem, nodeType *&head, nodeType *&tail, int &count);

#endif

Errors:

A: I think you forgot to put class list or something like that
#ifndef EXAM3_H_
#define EXAM3_H_

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

const int maxInt = 2147483647;

template <typename T>
class list{
public:
    struct nodeType {
        T data;
        nodeType *next;
    };

    bool search(nodeType *head, const T &searchItem);
    void deleteNode(nodeType *&head, nodeType *&tail, int &count, const T &deleteItem);
    void initializeList(nodeType *&head, nodeType *&tail, int &count);
    bool isEmptyList(const nodeType *head);
    void printList(nodeType *head);
    int lengthList(nodeType *head);
    void destroyList(nodeType *&head, nodeType *&tail, int &count);
    void insert(const T &newItem, nodeType *&head, nodeType *&tail, int &count);
};
#endif

But If the functions are not member functions, you are wrong, so write them, as follows
template<typename T>
bool search(nodeType <T> *head, const T &searchItem);
template<typename T>
void deleteNode(nodeType <T> *&head, nodeType <T> *&tail, int &count, const T &deleteItem);
template<typename T>
void initializeList(nodeType <T> *&head, nodeType <T> *&tail, int &count);
template<typename T>
bool isEmptyList(const nodeType <T> *head);
template<typename T>
void printList(nodeType <T> *head);
template<typename T>
int lengthList(nodeType <T> *head);
template<typename T>
void destroyList(nodeType <T> *&head, nodeType <T> *&tail, int &count);
template<typename T>
void insert(const T &newItem, nodeType <T> *&head, nodeType <T> *&tail, int &count);


text:
Q: Access: Updating multiple records with the same number I have a table of products, each of which have a serial numbers. There is also another field labelled SOP.
Basically when the product sells the SOP number (order number) will go in the field next to each serial number.
Before I continue, when I say scan this is because everything is barcoded.
I want to be able to create a form where I can scan in the SOP number and then for it to tab down where I can scan in all the serial numbers within that SOP.
It will then need to update each of the scanned in serial numbers with the relevant SOP number.
Any ideas?

A: the steps you need to do to achieve this are
1) Create an Orders table with a field for the SOP number
2) Create an Order Details table with field for the SOP number
3) Create a form with a data source of the Orders table
4) Add a subform to the Orders form relating/linking the two forms on the SOP number
5) On the Orders form, disable "Tab Stop" for all fields except the SOP number field.
6) On the Orders form make sure that the "Enter Key Behavior" for the SOP number field     is "Default". If you don't do this, when the SOP number is canned, any subsequent scans will go into the same field.
7) On the Orders form add an "After Update" Event Procedure to
  i) Test if a value has been entered in the SOP number field
    and if so
  ii)Set focus on the SOP number on the Order Detail subform
    otherwise set focus to the SOP number field on the Orders form
8) On the Order Details subform, disable "tab Stop" for all fields except the serial number field.
9) On the Order Details subform make sure that the "Enter Key Behavior" for the serial number field is "Default".
10) Make sure the scanner is programmed to emulate an enter key press (CR/LF) after each scan, this is the default for most scanners I believe.

After scanning the SOP number, if an entry is found, the focus will shift to the serial number field on the subform, and you can then begin scanning serial numbers.
Example AfterUpdate event for SOP number field
Private Sub OrderSopNumber_AfterUpdate()
  If Me.OrderSopNumber > "" Then
    Me.sfmOrderDetail.Form.OrderDetailSerialNumber.SetFocus
  Else
    Me.OrderSopNumber.SetFocus
  End If
End Sub


text:
Q: Convert Objective-C method to Swift I am using a custom UISwitch Control called DVSwitch which is written in Objective-C for a Swift/ Xcode6 project. I need to call its -setPressedHandler: Method and having a hard time converting it to Swift. Can anyone please show me how to write the code block below in Swift.
[switcher setPressedHandler: ^(NSUInteger index) {
    NSLog(@"Did switch to index: %lu", (unsigned long)index);
}];

A: It would be:
switcher.setPressedHandler() { index in
    println("Did switch to index: \(index)")
}

Obviously, you must include the appropriate DVSwitch header in the project's bridging header.


text:
Q: Localization-induced homomorphism Currently, I am trying to follow the proof of Proposition 2.5 in this paper. The proposition and proof are shown below, where $S$ is a multiplicatively closed subset of the commutative ring $R$.

I just have one question about this proof. It is the third sentence of the proof. Why does there exist such a $t$? Is $t$ just another name for $1/s$? If this is the case, how we know that $s$ is invertible? From my knowledge, it's not necessary that every element of the multiplicatively closed subset $S$ is invertible.
Thank you!

A: The fraction $f_2(a_2)/s=0/1$ in the localization $S^{-1}A_3$.
Now recall when two fractions are same in a localization. This mean that there exists $t\in S$ such that $t(f_2(a_2)\cdot 1-0\cdot s)=0$ in $A_3$. There you go!


text:
Q: Finding an endomorphism with given characteristics. I have been trying the following, but can't get my head around how to go on. I need to find an endomorphism $f$ in $\mathbb{R}^3$ (in the canonical basis) such that:

*

*Its rank is 2.

*Its trace is 4.

*$(2,1,1)$ is one of its eigenvectors.

*$U = \{ (x,y,z) \in \mathbb{R}^3 : x+y-z = 0\}$ is an eigenspace.

I can derive some information from this facts, but I can't come close to actually defining an endomorphism. So far I know:

*

*If the rank of $f$ is 2, then $\dim(f(\mathbb{R}^3))=2$ and by the rank-nullity theorem, the nullity of $f$ must be 1.

*If its trace is four, the sum of its eigenvalues is also four: $\lambda_1 + \lambda_2 + \lambda_3 = 4$
I don't know how to use the rest of the information provided. Could anyone guide me in the right direction?

A: Consider the vectors $v_1=(2,1,1)$, $v_2=(1,0,1)$, and $v_3=(0,1,1)$. Clearly, $\bigl\langle\{v_2,v_3\}\bigr\rangle=U$. So, take $f$ such that:

*

*$f(v_1)=0$;

*$f(v_2)=2v_2$;

*$f(v_3)=2v_3$
and you're done. Note that if $f$ is constructed this way, then$$f(x,y,z)=(-2y+2z,-x+y+z,-x-y+3z).$$


text:
Q: What is the upper speed limit for wind powered Blackbird? Background
Imagine you have wind powered car "Blackbird". The objective is simple make the fastest wind powered car.
So I was watching Veritasium and learned that "Blackbird" can go counterintuitively faster than the windspeed! In fact the claim is at one point it was going $2.8$ times the windspeed (3:12).
Question
Assuming parameters such as mass, etc is there a theoretical upper limit at what percentage of the windspeed such a vehicle can go at?

A: I expect that the vehicle speed that they attained is very close to the limit for that type of design.
The blackbird vehicle is very flimsy, they are desperately trying to keep the weight down.

The blackbird vehicle is harvesting energy from the difference in velocity between air and ground. That means that it is all about traction.
For going downwind the wheels need to have good traction; when going downwind the wheels are driving the propellor.
A wheel - being in contact with the solid ground - is capable of 100% traction; you just need to make sure the wheel will not slip.
The traction of a propellor, however, is inherently poor, because a propellor is churning air.
Imagine trying to propel an engine driven vehicle with a propellor. For a given engine output a propeller will give you far less propulsion than using the engine to drive the wheels.
For comparison:
In a follow-up video Derek demonstrated a device that I will call 'difference cart'

The difference cart has wheel traction both against the ground and the wooden beam above it.
By making the difference in diameter between the wheels more extreme (or by adding gearing) the difference cart can achieve a higher ratio.
For even more traction you could use toothed belts and gears.

A: While there are practical limits of course to top speeds (involving propeller supersonic tip speed impacts, etc.) there is no theoretical upper limit to the multiple of windspeed.  In other words, achieving say 50x the speed of the wind in a 1mph involves only drive train efficiency questions and not those pesky top speed issues involved if one were attempting 50x in a 20mph wind.
What is the practical limit on multiples?  Well, the design point for the hand carved propeller on the Blackbird was 2x the speed of the wind.  After construction and success at the design point, a variable pitch hub was installed which extended the design point by a bit.  Even with this handicap and cobbled together bike and go-kart parts (and an original budget of $5k), the vehicle has been recorded still accelerating above 3x the speed of the wind (to a 3.3x max as I recall).
That the Blackbird record could be smacked around pretty good given any reasonable budget is a foregone conclusion to those of us in the know.  Given a really good budget, multiples of 5-7x should be achievable.  Speeds of 140+ could be doable on the top end.
Don't think we haven't thought about it. :)


text:
Q: Allocating non-default hugepages with mmap or shmget on linux x86-64 UPDATE: I switched the default hugepagesize to 2MB and rebooted to confirm that it was always the non-default size that failed, and now I can allocate from both pools. I am confused, but possibly making progress.
I have been trying to get shmget and mmap to allocate from the non-default hugepage pool without success on kernel 4.13.0-32-generic. I have configured both 2M and 1G hugepages. With the 1G page as the default size this call will succeed:
addr = mmap(0, byteAmount, PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_HUGETLB|MAP_ANONYMOUS|MAP_HUGE_1GB, -1, 0);
but this will fail with Cannot allocate memory:
addr = mmap(0, byteAmount, PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_HUGETLB|MAP_ANONYMOUS|MAP_HUGE_2MB, -1, 0);
hugeadm --explain output:
Total System Memory: 32004 MB

Mount Point          Options
/dev/hugepages       rw,relatime,pagesize=1024M
/dev/hugepages2MB    rw,relatime,pagesize=2M

Huge page pools:
      Size  Minimum  Current  Maximum  Default
   2097152     1024     1024     1024
1073741824        1        1        1        *

Huge page sizes with configured pools:
2097152
1073741824

The /proc/sys/vm/min_free_kbytes of 67584 is too small. To maximiuse efficiency
of fragmentation avoidance, there should be at least one huge page free per zone
in the system which minimally requires a min_free_kbytes value of 57671680

A /proc/sys/kernel/shmmax value of 6442450944 bytes may be sub-optimal. To maximise
shared memory usage, this should be set to the size of the largest shared memory
segment size you want to be able to use. Alternatively, set it to a size matching
the maximum possible allocation size of all huge pages. This can be done
automatically, using the --set-recommended-shmmax option.

The recommended shmmax for your currently allocated huge pages is 3221225472 bytes.
To make shmmax settings persistent, add the following line to /etc/sysctl.conf:
  kernel.shmmax = 3221225472
hugeadm:WARNING: There is no swap space configured, resizing hugepage pool may fail
hugeadm:WARNING: Use --add-temp-swap option to temporarily add swap during the resize

To make your hugetlb_shm_group settings persistent, add the following line to /etc/sysctl.conf:
  vm.hugetlb_shm_group = 0

Note: Permanent swap space should be preferred when dynamic huge page pools are used.

The objective is to be able to use a combination of both 2MB and 1GB pages to maximise TLB hitrates. Any help greatly appreciated!

A: OK, I confirmed that both the mmap and shmget calls are now working to allocate memory from both the 2M and 1G hugepage pools. It looks like the hugepage system had somehow got into a bad state and a reboot was needed to fix it. Possibly this was caused by me changing the size of the 1G pool dynamically by writing to /sys/kernel/mm/hugepages/hugepages-1048576kB/nr_hugepages
Sorry for the noise!


text:
Q: jq filter: ok if item not in list (jq newbie here, sorry if this question has an obvious answer :) )
I'd like to filter json based on whether a value is not in a list.
Here's a concrete example:
Input
[
    {
        "n": "A",
        "a": 659533330984,
        "vals": {
            "n2": "B",
            "b": 5193941030
        }
     },
    {
        "n": "A",
        "a": 659533330984,
        "vals": {
            "n2": "C",
            "b": 4872891707
        }
    },
    {
        "n": "B",
        "a": 659533330984,
        "vals": {
            "n2": "C",
            "b": 4872891707
        }
    }
]

Filter
[.n, .vals.n2] not in  (["A", "B"], ["B", "C"])
Hence, in jq, I tried the following commands (also based on this related question)
jq '[ .[] | select([.n, .vals.n2] as $i | (["A", "B"], ["B", "C"]) | index($i) | not )]'

and
jq '[ .[] | select([.n, .vals.n2] != (["A", "B"], ["B", "C"]))]'

However, the both commands give the output
[
  {
    "n": "A",
    "a": 659533330984,
    "vals": {
      "n2": "B",
      "b": 5193941030
    }
  },
  {
    "n": "A",
    "a": 659533330984,
    "vals": {
      "n2": "C",
      "b": 4872891707
    }
  },
  {
    "n": "A",
    "a": 659533330984,
    "vals": {
      "n2": "C",
      "b": 4872891707
    }
  },
  {
    "n": "B",
    "a": 659533330984,
    "vals": {
      "n2": "C",
      "b": 4872891707
    }
  }
]

whereas this would be the desired output -- without duplicates and with logical AND of all "blacklisted" values:
[
  {
    "n": "A",
    "a": 659533330984,
    "vals": {
      "n2": "C",
      "b": 4872891707
    }
  }
]

It makes sense that the second command does not work, since if I understood correctly, the comma operator basically means that jq evaluates the expression once for every listed element - hence the duplicates. However simply piping through unique does not help since the output should not contain any of the filter pairs.
The only other idea I have at the moment is to pipe select through select through select... for each item in the "blacklist". However, I'd like to read the blacklist as an input -- I could dynamically create the command, but I was wondering whether there is a more beautiful solution? It feels like as if there must be...
I'd be very happy to hear your input on how to approach this best.
I'm using jq version jq-1.5-1-a5b5cbe.

A: The expression:
([.n, .vals.n2]) not in (["A", "B"], ["B", "C"])

would be equivalent to:
([.n, .vals.n2]) != ["A", "B"] and ([.n, .vals.n2]) != ["B", "C"]

As you have it here:
select([.n, .vals.n2] != (["A", "B"], ["B", "C"]))

it's not quite the same as the comma effectively makes it an or.
You'll need to do something more like this:
select([.n, .vals.n2] as $v | $v != ["A", "B"] and $v != ["B", "C"])

or
select([.n, .vals.n2] as $v | all(["A", "B"], ["B", "C"]; $v != .))

Also if you wanted to stick with your first approach, you would have to put the values in an array and not just separated by a comma.
select([.n, .vals.n2] as $i | [["A", "B"], ["B", "C"]] | index($i) | not)

A: When using index to find the index of an array (say $x), you have to write:
index([$x])

(This has to do with the fact that index is designed to work in a uniform way on both JSON strings and arrays.)
An efficient solution
[["A", "B"], ["B", "C"]] as $blacklist
| map( [.n, .vals.n2] as $i
       | select( $blacklist | index([$i]) | not) )

From the jq FAQ

: Given an array, A, containing an item, X, how can I find the least index of X in A? Why does [1] | index(1) return null rather than 0? Why does [1,2] | index([1,2]) return 0 rather than null?
A: The simplest uniform method for finding the least index of X in an array is to query for [X] rather than X itself, that is: index([X]).
By contrast, the filter index([1,2]) attempts to find [1,2] as a subsequence of contiguous items in the input array. This is for uniformity with the behavior of t | index(s) where s and t are strings.
If X is not an array, then index([X]) may be abbreviated to index(X).


text:
Q: Create a multi column array using for loop So as the question states, im trying to create an array using a for loop, this seems as though its a simple question, but i cant find the asnwer on SO or googling. Heres what im doing:
$twelve=array("user","day");

for($i=0; $i<$value; $i++)
{
    $total=$anarray[$i][value]; //get a value

    $twelve[$i]=($i,$total);  //insert values into array
}

this doesn't work, how should i go about getting this to work?

A: I think it should be $twelve[$i] = array($i, $total);
Also, on this line;
$total=$anarray[$i][value]; //get a value

Unless value is defined as a constant, I think you want to do $anarray[$i][$value];.
PHP might not recognize value as a set variable or a constant, therefore crashes and never sets $twelve to any value.

A: You may end up in a never-ending loop if $total=$anarray[$i][value];  is an increasing value. Regardless of the loop, you'll want to do as the other answerer mentioned, namely:
$twelve[$i] = array($i, $total);

A: I have found a solution that does work
in each loop simply do:
$twelve[$i]["user"]=$i;
$twelve[$i]["day"]=$total;

It would be nice if there is a way to do that in one line, but that is working.


text:
Q: AJAX don't wait for response I have a webpage that has a simple AJAX request on page load:
$(document).ready(function() {
    $.get("ajax.php?do=something", function(response) {
        alert('response');
    });
});

This request takes about 15 seconds on my local test machine. The ajax.php does use session_start(), but calls session_write_close() straight after (almost straight after - it is called before any of the intensive processing is done):
<?php
session_start();

if(empty($_GET['do']))
    die("!Invalid request.");

$do = $_GET['do'];

if($do=="something-else")
{
}
else if($do=="something")
{
    session_write_close();

    $customerId = $_SESSION['customerId'];

    //processing done here
}
?>

The problem is the once this page loads, the AJAX is fired, but then if the user clicks on a link to go to another page, the browser waits for 15 seconds and then redirects.
I want to let the user go to other pages without having to wait, or if they stay, i want them to see the response.
EDIT Just to clarify it a bit more. Every page has a session_start() at the top, including the one that the user is trying to go to.
I am using the session in the ajax.php, and have edited the original question to reflect this.

A: Where is the link that is being clicked? Where does the link point to and how does it tie in with the AJAX you have posted? From what I see the AJAX worked as expected. You are not doing anything with sessions so you might as well not have any session start or close.
I would post this as a comment but it wont let me therefore I am giving this as an answer until you can give more details.


text:
Q: Bash script "read" not pausing for user input when executed from SSH shell I'm new to Bash scripting, so please be gentle.
I'm connected to a Ubuntu server via SSH (PuTTY) and when I run this command, I expect the bash script that downloads and executes to allow user input and then echo that input.  It seems to just write out the echo label for the input request and terminate.
wget -O - https://raw.github.com/aaronhancock/pub/master/bash/readtest.sh | bash

Any clue what I might be doing wrong?
UPDATE: This bash command does exactly what I wanted
bash <(wget -q -O - https://raw.github.com/aaronhancock/pub/master/bash/readtest.sh)

A: Jonathan already mentioned: bash takes its stdin from the pipe.
And therefore you cannot pipe the script into bash when you want to interactively input something. But you could use the process substitution feature of bash (assumed your login shell is a bash):
bash <(wget -O - https://raw.github.com/aaronhancock/pub/master/bash/readtest.sh)

A: Bash is taking stdin from the pipe, not from the terminal.  So you can't pipe a script to bash and still use the "read" command for user input.
Notice that you have the same problem if you save the script to a local file and pipe it to bash:
less readtest.sh | bash

A: I found this also works and helps keep the data in the current scope.
eval "wget -q -O - https://raw.github.com/aaronhancock/pub/master/bash/readtest.sh"


text:
Q: .bat Find and Rename I have outputted some text files all in the same directory. Each .txt file has within a group number, this number always starts with RXC and can go upwards of 5 characters afterwards, giving us RXCXXXXX i need the script to find this RXC number and rename the file to its corresponding group number, then do the same for all files in the same directory.
Thanks in advance,
Joe

A: using System.IO;
foreach(var file in Directory.GetFiles("."))
{
    var content = File.ReadAllText(file);
    var startIndex = content.IndexOf("RXC");
    var id = content.Substring(startIndex, 8);
    File.Move(file, id);
}

A: Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="c:\test"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
    If objFS.GetExtensionName(strFile) = "txt" Then
        strFileName = strFile.Name
        Set objFile = objFS.OpenTextFile(strFileName)
        Do Until objFile.AtEndOfStream
            strLine=objFile.ReadLine
            If InStr(strLine,"RXC" ) > 0 Then
                number=Mid(strLine,4)
                objFile.Close
                strFile.Name = Trim(number)&".txt"
                Exit Do
            End If
        Loop
    End If
Next