text:
Q: Why does my Intel Skylake / Kaby Lake CPU incur a mysterious factor 3 slowdown in a simple hash table implementation? In short:
I have implemented a simple (multi-key) hash table with buckets (containing several elements) that exactly fit a cacheline.
Inserting into a cacheline bucket is very simple, and the critical part of the main loop.
I have implemented three versions that produce the same outcome and should behave the same.
The mystery
However, I'm seeing wild performance differences by a surprisingly large factor 3, despite all versions having the exact same cacheline access pattern and resulting in identical hash table data.
The best implementation insert_ok suffers around a factor 3 slow down compared to insert_bad & insert_alt on my CPU (i7-7700HQ).
One variant insert_bad is a simple modification of insert_ok that adds an extra unnecessary linear search within the cacheline to find the position to write to (which it already knows) and does not suffer this x3 slow down.
The exact same executable shows insert_ok a factor 1.6 faster compared to insert_bad & insert_alt on other CPUs (AMD 5950X (Zen 3), Intel i7-11800H (Tiger Lake)).
# see https://github.com/cr-marcstevens/hashtable_mystery
$ ./test.sh
model name      : Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
==============================
CXX=g++    CXXFLAGS=-std=c++11 -O2 -march=native -falign-functions=64
tablesize: 117440512 elements: 67108864 loadfactor=0.571429
- test insert_ok : 11200ms
- test insert_bad: 3164ms
  (outcome identical to insert_ok: true)
- test insert_alt: 3366ms
  (outcome identical to insert_ok: true)

tablesize: 117440813 elements: 67108864 loadfactor=0.571427
- test insert_ok : 10840ms
- test insert_bad: 3301ms
  (outcome identical to insert_ok: true)
- test insert_alt: 3579ms
  (outcome identical to insert_ok: true)

The Code
// insert element in hash_table
inline void insert_ok(uint64_t k)
{
    // compute target bucket
    uint64_t b = mod(k);
    // bounded linear search for first non-full bucket
    for (size_t c = 0; c < 1024; ++c)
    {
        bucket_t& B = table_ok[b];
        // if bucket non-full then store element and return
        if (B.size != bucket_size)
        {
            B.keys[B.size] = k;
            B.values[B.size] = 1;
            ++B.size;
            ++table_count;
            return;
        }
        // increase b w/ wrap around
        if (++b == table_size)
            b = 0;
    }
}
// equivalent to insert_ok
// but uses a stupid linear search to store the element at the target position
inline void insert_bad(uint64_t k)
{
    // compute target bucket
    uint64_t b = mod(k);
    // bounded linear search for first non-full bucket
    for (size_t c = 0; c < 1024; ++c)
    {
        bucket_t& B = table_bad[b];
        // if bucket non-full then store element and return
        if (B.size != bucket_size)
        {
            for (size_t i = 0; i < bucket_size; ++i)
            {
                if (i == B.size)
                {
                    B.keys[i] = k;
                    B.values[i] = 1;
                    ++B.size;
                    ++table_count;
                    return;
                }
            }
        }
        // increase b w/ wrap around
        if (++b == table_size)
            b = 0;
    }
}
// instead of using bucket_t.size, empty elements are marked by special empty_key value
// a bucket is filled first to last, so bucket is full if last element key != empty_key
uint64_t empty_key = ~uint64_t(0);
inline void insert_alt(uint64_t k)
{
    // compute target bucket
    uint64_t b = mod(k);
    // bounded linear search for first non-full bucket
    for (size_t c = 0; c < 1024; ++c)
    {
        bucket_t& B = table_alt[b];
        // if bucket non-full then store element and return
        if (B.keys[bucket_size-1] == empty_key)
        {
            for (size_t i = 0; i < bucket_size; ++i)
            {
                if (B.keys[i] == empty_key)
                {
                    B.keys[i] = k;
                    B.values[i] = 1;
                    ++table_count;
                    return;
                }
            }
        }
        // increase b w/ wrap around
        if (++b == table_size)
            b = 0;
    }
}

My analysis
I've tried various modifications to the loop C++, but inherently it's so simple, the compiler will produce the same assembly.
It's really not obvious from the resulting assembly what the factor 3 loss might cause.
I've tried measuring with perf, but I can't seem to pinpoint any meaningful difference.
Comparing the assembly of the 3 versions which are all just relatively small loops, there is nothing that suggests anything close that may cause a factor 3 loss between these versions.
Hence, I presume the 3x slow down is a weird effect of automatic prefetching, or branch prediction, or instruction/jump alignment or maybe a combination of those.
Does anybody have better insights or ways to measure what effects might actually be at play here?
Details
I've created a small working C++11 example that demonstrates the problem.
The code is available at https://github.com/cr-marcstevens/hashtable_mystery
This also includes my own static binaries that demonstrate this problem on my CPU, as different compilers may produce different code.
As well as dumped assembly code for all three hash table versions.
perf event measurements
Here are a lot of perf event measurements. I've focused on ones that include the word miss and stall.
Each event has two lines:

*

*the first line corresponds to insert_ok which has the slowdown

*the second line corresponds to insert_alt which has an additional loop and additional work, but ends up faster

=== L1-dcache-load-misses ===
insert_ok : 171411476
insert_alt: 244244027
=== L1-dcache-loads ===
insert_ok : 775468123
insert_alt: 1038574743
=== L1-dcache-stores ===
insert_ok : 621353009
insert_alt: 554244145
=== L1-icache-load-misses ===
insert_ok : 69666
insert_alt: 259102
=== LLC-load-misses ===
insert_ok : 70519701
insert_alt: 71399242
=== LLC-loads ===
insert_ok : 130909270
insert_alt: 134776189
=== LLC-store-misses ===
insert_ok : 16782747
insert_alt: 16851787
=== LLC-stores ===
insert_ok : 17072141
insert_alt: 17534866
=== arith.divider_active ===
insert_ok : 26810
insert_alt: 26611
=== baclears.any ===
insert_ok : 2038060
insert_alt: 7648128
=== br_inst_retired.all_branches ===
insert_ok : 546479449
insert_alt: 938434022
=== br_inst_retired.all_branches_pebs ===
insert_ok : 546480454
insert_alt: 938412921
=== br_inst_retired.cond_ntaken ===
insert_ok : 237470651
insert_alt: 433439086
=== br_inst_retired.conditional ===
insert_ok : 477604946
insert_alt: 802468807
=== br_inst_retired.far_branch ===
insert_ok : 1058138
insert_alt: 1052510
=== br_inst_retired.near_call ===
insert_ok : 227076
insert_alt: 227074
=== br_inst_retired.near_return ===
insert_ok : 227072
insert_alt: 227070
=== br_inst_retired.near_taken ===
insert_ok : 307946256
insert_alt: 503926433
=== br_inst_retired.not_taken ===
insert_ok : 237458763
insert_alt: 433429466
=== br_misp_retired.all_branches ===
insert_ok : 36443541
insert_alt: 90626754
=== br_misp_retired.all_branches_pebs ===
insert_ok : 36441027
insert_alt: 90622375
=== br_misp_retired.conditional ===
insert_ok : 36454196
insert_alt: 90591031
=== br_misp_retired.near_call ===
insert_ok : 173
insert_alt: 169
=== br_misp_retired.near_taken ===
insert_ok : 19032467
insert_alt: 40361420
=== branch-instructions ===
insert_ok : 546476228
insert_alt: 938447476
=== branch-load-misses ===
insert_ok : 36441314
insert_alt: 90611299
=== branch-loads ===
insert_ok : 546472151
insert_alt: 938435143
=== branch-misses ===
insert_ok : 36436325
insert_alt: 90597372
=== bus-cycles ===
insert_ok : 222283508
insert_alt: 88243938
=== cache-misses ===
insert_ok : 257067753
insert_alt: 475091979
=== cache-references ===
insert_ok : 445465943
insert_alt: 590770464
=== cpu-clock ===
insert_ok : 10333.94 msec cpu-clock:u # 1.000 CPUs utilized
insert_alt: 4766.53 msec cpu-clock:u # 1.000 CPUs utilized
=== cpu-cycles ===
insert_ok : 25273361574
insert_alt: 11675804743
=== cpu_clk_thread_unhalted.one_thread_active ===
insert_ok : 223196489
insert_alt: 88616919
=== cpu_clk_thread_unhalted.ref_xclk ===
insert_ok : 222719013
insert_alt: 88467292
=== cpu_clk_unhalted.one_thread_active ===
insert_ok : 223380608
insert_alt: 88212476
=== cpu_clk_unhalted.ref_tsc ===
insert_ok : 32663820508
insert_alt: 12901195392
=== cpu_clk_unhalted.ref_xclk ===
insert_ok : 221957996
insert_alt: 88390991
insert_alt: === cpu_clk_unhalted.ring0_trans ===
insert_ok : 374
insert_alt: 373
=== cpu_clk_unhalted.thread ===
insert_ok : 25286801620
insert_alt: 11714137483
=== cycle_activity.cycles_l1d_miss ===
insert_ok : 16278956219
insert_alt: 7417877493
=== cycle_activity.cycles_l2_miss ===
insert_ok : 15607833569
insert_alt: 7054717199
=== cycle_activity.cycles_l3_miss ===
insert_ok : 12987627072
insert_alt: 6745771672
=== cycle_activity.cycles_mem_any ===
insert_ok : 23440206343
insert_alt: 9027220495
=== cycle_activity.stalls_l1d_miss ===
insert_ok : 16194872307
insert_alt: 4718344050
=== cycle_activity.stalls_l2_miss ===
insert_ok : 15350067722
insert_alt: 4578933898
=== cycle_activity.stalls_l3_miss ===
insert_ok : 12697354271
insert_alt: 4457980047
=== cycle_activity.stalls_mem_any ===
insert_ok : 20930005455
insert_alt: 4555461595
=== cycle_activity.stalls_total ===
insert_ok : 22243173394
insert_alt: 6561416461
=== dTLB-load-misses ===
insert_ok : 67817362
insert_alt: 63603879
=== dTLB-loads ===
insert_ok : 775467642
insert_alt: 1038562488
=== dTLB-store-misses ===
insert_ok : 8823481
insert_alt: 13050341
=== dTLB-stores ===
insert_ok : 621353007
insert_alt: 554244145
=== dsb2mite_switches.count ===
insert_ok : 93894397
insert_alt: 315793354
=== dsb2mite_switches.penalty_cycles ===
insert_ok : 9216240937
insert_alt: 206393788
=== dtlb_load_misses.miss_causes_a_walk ===
insert_ok : 177266866
insert_alt: 101439773
=== dtlb_load_misses.stlb_hit ===
insert_ok : 2994329
insert_alt: 35601646
=== dtlb_load_misses.walk_active ===
insert_ok : 4747616986
insert_alt: 3893609232
=== dtlb_load_misses.walk_completed ===
insert_ok : 67817832
insert_alt: 63591832
=== dtlb_load_misses.walk_completed_4k ===
insert_ok : 67817841
insert_alt: 63596148
=== dtlb_load_misses.walk_pending ===
insert_ok : 6495600072
insert_alt: 5987182579
=== dtlb_store_misses.miss_causes_a_walk ===
insert_ok : 89895924
insert_alt: 21841494
=== dtlb_store_misses.stlb_hit ===
insert_ok : 4940907
insert_alt: 21970231
=== dtlb_store_misses.walk_active ===
insert_ok : 1784142210
insert_alt: 903334856
=== dtlb_store_misses.walk_completed ===
insert_ok : 8845884
insert_alt: 13071262
=== dtlb_store_misses.walk_completed_4k ===
insert_ok : 8822993
insert_alt: 12936414
=== dtlb_store_misses.walk_pending ===
insert_ok : 1842905733
insert_alt: 933039119
=== exe_activity.1_ports_util ===
insert_ok : 991400575
insert_alt: 1433908710
=== exe_activity.2_ports_util ===
insert_ok : 782270731
insert_alt: 1314443071
=== exe_activity.3_ports_util ===
insert_ok : 556847358
insert_alt: 1158115803
=== exe_activity.4_ports_util ===
insert_ok : 427323800
insert_alt: 783571280
=== exe_activity.bound_on_stores ===
insert_ok : 299732094
insert_alt: 303475333
=== exe_activity.exe_bound_0_ports ===
insert_ok : 227569792
insert_alt: 348959512
=== frontend_retired.dsb_miss ===
insert_ok : 6771584
insert_alt: 93700643
=== frontend_retired.itlb_miss ===
insert_ok : 1115
insert_alt: 1689
=== frontend_retired.l1i_miss ===
insert_ok : 3639
insert_alt: 3857
=== frontend_retired.l2_miss ===
insert_ok : 2826
insert_alt: 2830
=== frontend_retired.latency_ge_1 ===
insert_ok : 9206268
insert_alt: 178345368
=== frontend_retired.latency_ge_128 ===
insert_ok : 2708
insert_alt: 2703
=== frontend_retired.latency_ge_16 ===
insert_ok : 403492
insert_alt: 820950
=== frontend_retired.latency_ge_2 ===
insert_ok : 4981263
insert_alt: 85781924
=== frontend_retired.latency_ge_256 ===
insert_ok : 802
insert_alt: 970
=== frontend_retired.latency_ge_2_bubbles_ge_1 ===
insert_ok : 56936702
insert_alt: 225712704
=== frontend_retired.latency_ge_2_bubbles_ge_2 ===
insert_ok : 10312026
insert_alt: 163227996
=== frontend_retired.latency_ge_2_bubbles_ge_3 ===
insert_ok : 7599252
insert_alt: 122841752
=== frontend_retired.latency_ge_32 ===
insert_ok : 3599
insert_alt: 3317
=== frontend_retired.latency_ge_4 ===
insert_ok : 2627373
insert_alt: 42287077
=== frontend_retired.latency_ge_512 ===
insert_ok : 418
insert_alt: 241
=== frontend_retired.latency_ge_64 ===
insert_ok : 2474
insert_alt: 2802
=== frontend_retired.latency_ge_8 ===
insert_ok : 528748
insert_alt: 951836
=== frontend_retired.stlb_miss ===
insert_ok : 769
insert_alt: 562
=== hw_interrupts.received ===
insert_ok : 9330
insert_alt: 3738
=== iTLB-load-misses ===
insert_ok : 456094
insert_alt: 90739
=== iTLB-loads ===
insert_ok : 949
insert_alt: 1031
=== icache_16b.ifdata_stall ===
insert_ok : 1145821
insert_alt: 862403
=== icache_64b.iftag_hit ===
insert_ok : 1378406022
insert_alt: 4459469241
=== icache_64b.iftag_miss ===
insert_ok : 61812
insert_alt: 57204
=== icache_64b.iftag_stall ===
insert_ok : 56551468
insert_alt: 82354039
=== idq.all_dsb_cycles_4_uops ===
insert_ok : 896374829
insert_alt: 1610100578
=== idq.all_dsb_cycles_any_uops ===
insert_ok : 1217878089
insert_alt: 2739912727
=== idq.all_mite_cycles_4_uops ===
insert_ok : 315979501
insert_alt: 480165021
=== idq.all_mite_cycles_any_uops ===
insert_ok : 1053703958
insert_alt: 2251382760
=== idq.dsb_cycles ===
insert_ok : 1218891711
insert_alt: 2744099964
=== idq.dsb_uops ===
insert_ok : 5828442701
insert_alt: 10445095004
=== idq.mite_cycles ===
insert_ok : 470409312
insert_alt: 1664892371
=== idq.mite_uops ===
insert_ok : 1407396065
insert_alt: 4515396737
=== idq.ms_cycles ===
insert_ok : 583601361
insert_alt: 587996351
=== idq.ms_dsb_cycles ===
insert_ok : 218346
insert_alt: 74155
=== idq.ms_mite_uops ===
insert_ok : 1266443204
insert_alt: 1277980465
=== idq.ms_switches ===
insert_ok : 149106449
insert_alt: 150392336
=== idq.ms_uops ===
insert_ok : 1266950097
insert_alt: 1277330690
=== idq_uops_not_delivered.core ===
insert_ok : 1871959581
insert_alt: 6531069387
=== idq_uops_not_delivered.cycles_0_uops_deliv.core ===
insert_ok : 289301660
insert_alt: 946930713
=== idq_uops_not_delivered.cycles_fe_was_ok ===
insert_ok : 24668869613
insert_alt: 9335642949
=== idq_uops_not_delivered.cycles_le_1_uop_deliv.core ===
insert_ok : 393750384
insert_alt: 1344106460
=== idq_uops_not_delivered.cycles_le_2_uop_deliv.core ===
insert_ok : 506090534
insert_alt: 1824690188
=== idq_uops_not_delivered.cycles_le_3_uop_deliv.core ===
insert_ok : 688462029
insert_alt: 2416339045
=== ild_stall.lcp ===
insert_ok : 380
insert_alt: 480
=== inst_retired.any ===
insert_ok : 4760842560
insert_alt: 5470438932
=== inst_retired.any_p ===
insert_ok : 4760919037
insert_alt: 5470404264
=== inst_retired.prec_dist ===
insert_ok : 4760801654
insert_alt: 5470649220
=== inst_retired.total_cycles_ps ===
insert_ok : 25175372339
insert_alt: 11718929626
=== instructions ===
insert_ok : 4760805219
insert_alt: 5470497783
=== int_misc.clear_resteer_cycles ===
insert_ok : 199623562
insert_alt: 671083279
=== int_misc.recovery_cycles ===
insert_ok : 314434729
insert_alt: 704406698
=== itlb.itlb_flush ===
insert_ok : 303
insert_alt: 248
=== itlb_misses.miss_causes_a_walk ===
insert_ok : 19537
insert_alt: 116729
=== itlb_misses.stlb_hit ===
insert_ok : 11323
insert_alt: 5557
=== itlb_misses.walk_active ===
insert_ok : 2809766
insert_alt: 4070194
=== itlb_misses.walk_completed ===
insert_ok : 24298
insert_alt: 45251
=== itlb_misses.walk_completed_4k ===
insert_ok : 34084
insert_alt: 29759
=== itlb_misses.walk_pending ===
insert_ok : 853764
insert_alt: 2817933
=== l1d.replacement ===
insert_ok : 171135334
insert_alt: 244967326
=== l1d_pend_miss.fb_full ===
insert_ok : 354631656
insert_alt: 382309583
=== l1d_pend_miss.pending ===
insert_ok : 16792436441
insert_alt: 22979721104
=== l1d_pend_miss.pending_cycles ===
insert_ok : 16377420892
insert_alt: 7349245429
=== l1d_pend_miss.pending_cycles_any ===
insert_ok : insert_alt: === l2_lines_in.all ===
insert_ok : 303009088
insert_alt: 411750486
=== l2_lines_out.non_silent ===
insert_ok : 157208112
insert_alt: 309484666
=== l2_lines_out.silent ===
insert_ok : 127379047
insert_alt: 84169481
=== l2_lines_out.useless_hwpf ===
insert_ok : 70374658
insert_alt: 144359127
=== l2_lines_out.useless_pref ===
insert_ok : 70747103
insert_alt: 142931540
=== l2_rqsts.all_code_rd ===
insert_ok : 71254
insert_alt: 242327
=== l2_rqsts.all_demand_data_rd ===
insert_ok : 137366274
insert_alt: 143507049
=== l2_rqsts.all_demand_miss ===
insert_ok : 150071420
insert_alt: 150820168
=== l2_rqsts.all_demand_references ===
insert_ok : 154854022
insert_alt: 160487082
=== l2_rqsts.all_pf ===
insert_ok : 170261458
insert_alt: 282476184
=== l2_rqsts.all_rfo ===
insert_ok : 17575896
insert_alt: 16938897
=== l2_rqsts.code_rd_hit ===
insert_ok : 79800
insert_alt: 381566
=== l2_rqsts.code_rd_miss ===
insert_ok : 25800
insert_alt: 33755
=== l2_rqsts.demand_data_rd_hit ===
insert_ok : 5191029
insert_alt: 9831101
=== l2_rqsts.demand_data_rd_miss ===
insert_ok : 132253891
insert_alt: 133965310
=== l2_rqsts.miss ===
insert_ok : 305347974
insert_alt: 414758839
=== l2_rqsts.pf_hit ===
insert_ok : 14639778
insert_alt: 19484420
=== l2_rqsts.pf_miss ===
insert_ok : 156092998
insert_alt: 263293430
=== l2_rqsts.references ===
insert_ok : 326549998
insert_alt: 443460029
=== l2_rqsts.rfo_hit ===
insert_ok : 11650
insert_alt: 21474
=== l2_rqsts.rfo_miss ===
insert_ok : 17544467
insert_alt: 16835137
=== l2_trans.l2_wb ===
insert_ok : 157044674
insert_alt: 308107712
=== ld_blocks.no_sr ===
insert_ok : 14
insert_alt: 13
=== ld_blocks.store_forward ===
insert_ok : 158
insert_alt: 128
=== ld_blocks_partial.address_alias ===
insert_ok : 5155853
insert_alt: 17867414
=== load_hit_pre.sw_pf ===
insert_ok : 10840795
insert_alt: 11072297
=== longest_lat_cache.miss ===
insert_ok : 257061118
insert_alt: 471152073
=== longest_lat_cache.reference ===
insert_ok : 445701577
insert_alt: 583870610
=== machine_clears.count ===
insert_ok : 3926377
insert_alt: 4280080
=== machine_clears.memory_ordering ===
insert_ok : 97177
insert_alt: 25407
=== machine_clears.smc ===
insert_ok : 138579
insert_alt: 305423
=== mem-stores ===
insert_ok : 621353009
insert_alt: 554244143
=== mem_inst_retired.all_loads ===
insert_ok : 775473590
insert_alt: 1038559807
=== mem_inst_retired.all_stores ===
insert_ok : 621353013
insert_alt: 554244145
=== mem_inst_retired.lock_loads ===
insert_ok : 85
insert_alt: 85
=== mem_inst_retired.split_loads ===
insert_ok : 171
insert_alt: 174
=== mem_inst_retired.split_stores ===
insert_ok : 53
insert_alt: 49
=== mem_inst_retired.stlb_miss_loads ===
insert_ok : 68308539
insert_alt: 18088047
=== mem_inst_retired.stlb_miss_stores ===
insert_ok : 264054
insert_alt: 819551
=== mem_load_l3_hit_retired.xsnp_none ===
insert_ok : 231116
insert_alt: 175217
=== mem_load_retired.fb_hit ===
insert_ok : 6510722
insert_alt: 95952490
=== mem_load_retired.l1_hit ===
insert_ok : 698271530
insert_alt: 920982402
=== mem_load_retired.l1_miss ===
insert_ok : 69525335
insert_alt: 20089897
=== mem_load_retired.l2_hit ===
insert_ok : 1451905
insert_alt: 773356
=== mem_load_retired.l2_miss ===
insert_ok : 68085186
insert_alt: 19474303
=== mem_load_retired.l3_hit ===
insert_ok : 222829
insert_alt: 155958
=== mem_load_retired.l3_miss ===
insert_ok : 67879593
insert_alt: 19244746
=== memory_disambiguation.history_reset ===
insert_ok : 97621
insert_alt: 25831
=== minor-faults ===
insert_ok : 1048716
insert_alt: 1048718
=== node-loads ===
insert_ok : 71473780
insert_alt: 71377840
=== node-stores ===
insert_ok : 16781161
insert_alt: 16842666
=== offcore_requests.all_data_rd ===
insert_ok : 284186682
insert_alt: 392110677
=== offcore_requests.all_requests ===
insert_ok : 530876505
insert_alt: 777784382
=== offcore_requests.demand_code_rd ===
insert_ok : 34252
insert_alt: 45896
=== offcore_requests.demand_data_rd ===
insert_ok : 133468710
insert_alt: 134288893
=== offcore_requests.demand_rfo ===
insert_ok : 17612516
insert_alt: 17062276
=== offcore_requests.l3_miss_demand_data_rd ===
insert_ok : 71616594
insert_alt: 82917520
=== offcore_requests_buffer.sq_full ===
insert_ok : 2001445
insert_alt: 3113287
=== offcore_requests_outstanding.all_data_rd ===
insert_ok : 35577129549
insert_alt: 78698308135
=== offcore_requests_outstanding.cycles_with_data_rd ===
insert_ok : 17518017620
insert_alt: 7940272202
=== offcore_requests_outstanding.demand_code_rd ===
insert_ok : 11085819
insert_alt: 9390881
=== offcore_requests_outstanding.demand_data_rd ===
insert_ok : 15902243707
insert_alt: 21097348926
=== offcore_requests_outstanding.demand_data_rd_ge_6 ===
insert_ok : 1225437
insert_alt: 317436422
=== offcore_requests_outstanding.demand_rfo ===
insert_ok : 1074492442
insert_alt: 1157902315
=== offcore_response.demand_code_rd.any_response ===
insert_ok : 53675
insert_alt: 69683
=== offcore_response.demand_code_rd.l3_hit.any_snoop ===
insert_ok : 19407
insert_alt: 29704
=== offcore_response.demand_code_rd.l3_hit.snoop_none ===
insert_ok : 12675
insert_alt: 11951
=== offcore_response.demand_code_rd.l3_miss.any_snoop ===
insert_ok : 34617
insert_alt: 40868
=== offcore_response.demand_code_rd.l3_miss.spl_hit ===
insert_ok : 0
insert_alt: 753
=== offcore_response.demand_data_rd.any_response ===
insert_ok : 131014821
insert_alt: 134813171
=== offcore_response.demand_data_rd.l3_hit.any_snoop ===
insert_ok : 59713328
insert_alt: 50254543
=== offcore_response.demand_data_rd.l3_miss.any_snoop ===
insert_ok : 71431585
insert_alt: 83916030
=== offcore_response.demand_data_rd.l3_miss.spl_hit ===
insert_ok : 244837
insert_alt: 6441992
=== offcore_response.demand_rfo.any_response ===
insert_ok : 16876557
insert_alt: 17619450
=== offcore_response.demand_rfo.l3_hit.any_snoop ===
insert_ok : 907432
insert_alt: 45127
=== offcore_response.demand_rfo.l3_hit.snoop_none ===
insert_ok : 787567
insert_alt: 794579
=== offcore_response.demand_rfo.l3_hit_e.any_snoop ===
insert_ok : 496938
insert_alt: 173658
=== offcore_response.demand_rfo.l3_hit_e.snoop_none ===
insert_ok : 779919
insert_alt: 50575
=== offcore_response.demand_rfo.l3_hit_m.any_snoop ===
insert_ok : 128627
insert_alt: 25483
=== offcore_response.demand_rfo.l3_miss.any_snoop ===
insert_ok : 16782186
insert_alt: 16847970
=== offcore_response.demand_rfo.l3_miss.snoop_none ===
insert_ok : 16782647
insert_alt: 16850104
=== offcore_response.demand_rfo.l3_miss.spl_hit ===
insert_ok : 0
insert_alt: 1364
=== offcore_response.other.any_response ===
insert_ok : 137231000
insert_alt: 189526494
=== offcore_response.other.l3_hit.any_snoop ===
insert_ok : 62695084
insert_alt: 51005882
=== offcore_response.other.l3_hit.snoop_none ===
insert_ok : 62975018
insert_alt: 50217349
=== offcore_response.other.l3_hit_e.any_snoop ===
insert_ok : 62770215
insert_alt: 50691817
=== offcore_response.other.l3_hit_e.snoop_none ===
insert_ok : 62602591
insert_alt: 50642954
=== offcore_response.other.l3_miss.any_snoop ===
insert_ok : 74247236
insert_alt: 139212975
=== offcore_response.other.l3_miss.snoop_none ===
insert_ok : 75911794
insert_alt: 141076520
=== other_assists.any ===
insert_ok : 1
insert_alt: 3
=== page-faults ===
insert_ok : 1048719
insert_alt: 1048718
=== partial_rat_stalls.scoreboard ===
insert_ok : 530950991
insert_alt: 539869553
=== ref-cycles ===
insert_ok : 32546980212
insert_alt: 12930921138
=== resource_stalls.any ===
insert_ok : 21923576648
insert_alt: 5205690082
=== resource_stalls.sb ===
insert_ok : 397908667
insert_alt: 402738367
=== rs_events.empty_cycles ===
insert_ok : 1173721723
insert_alt: 1880165720
=== rs_events.empty_end ===
insert_ok : 87752182
insert_alt: 160792701
=== sw_prefetch_access.t0 ===
insert_ok : 20835202
insert_alt: 20599176
=== task-clock ===
insert_ok : 10416.86 msec task-clock:u # 1.000 CPUs utilized
insert_alt: 4767.78 msec task-clock:u # 1.000 CPUs utilized
=== tlb_flush.stlb_any ===
insert_ok : 1835393
insert_alt: 1835396
=== topdown-fetch-bubbles ===
insert_ok : 1904143421
insert_alt: 6543146396
=== topdown-slots-issued ===
insert_ok : 7538371393
insert_alt: 14449966516
=== topdown-slots-retired ===
insert_ok : 5267325162
insert_alt: 5849706597
=== uops_dispatched_port.port_0 ===
insert_ok : 1252121297
insert_alt: 1489605354
=== uops_dispatched_port.port_1 ===
insert_ok : 1379316967
insert_alt: 1585037107
=== uops_dispatched_port.port_2 ===
insert_ok : 1140861153
insert_alt: 1785053149
=== uops_dispatched_port.port_3 ===
insert_ok : 1187151423
insert_alt: 1828975838
=== uops_dispatched_port.port_4 ===
insert_ok : 1577171758
insert_alt: 1557761857
=== uops_dispatched_port.port_5 ===
insert_ok : 1341370655
insert_alt: 1653599117
=== uops_dispatched_port.port_6 ===
insert_ok : 1856735970
insert_alt: 4387464794
=== uops_dispatched_port.port_7 ===
insert_ok : 508351498
insert_alt: 603583315
=== uops_executed.core ===
insert_ok : 7225522677
insert_alt: 12716368190
=== uops_executed.core_cycles_ge_1 ===
insert_ok : 3041586797
insert_alt: 5168421550
=== uops_executed.core_cycles_ge_2 ===
insert_ok : 2017794537
insert_alt: 3653591208
=== uops_executed.core_cycles_ge_3 ===
insert_ok : 1225785335
insert_alt: 2316014066
=== uops_executed.core_cycles_ge_4 ===
insert_ok : 657121809
insert_alt: 1143390519
=== uops_executed.core_cycles_none ===
insert_ok : 22191507320
insert_alt: 6563722081
=== uops_executed.cycles_ge_1_uop_exec ===
insert_ok : 3040999757
insert_alt: 5175668459
=== uops_executed.cycles_ge_2_uops_exec ===
insert_ok : 2015520940
insert_alt: 3659989196
=== uops_executed.cycles_ge_3_uops_exec ===
insert_ok : 1224025952
insert_alt: 2319025110
=== uops_executed.cycles_ge_4_uops_exec ===
insert_ok : 657094113
insert_alt: 1141381027
=== uops_executed.stall_cycles ===
insert_ok : 22350754164
insert_alt: 6590978048
=== uops_executed.thread ===
insert_ok : 7214521925
insert_alt: 12697219901
=== uops_executed.x87 ===
insert_ok : 2992
insert_alt: 3337
=== uops_issued.any ===
insert_ok : 7531354736
insert_alt: 14462113169
=== uops_issued.slow_lea ===
insert_ok : 2136241
insert_alt: 2115308
=== uops_issued.stall_cycles ===
insert_ok : 23244177475
insert_alt: 7416801878
=== uops_retired.macro_fused ===
insert_ok : 410461916
insert_alt: 735050350
=== uops_retired.retire_slots ===
insert_ok : 5265023980
insert_alt: 5855259326
=== uops_retired.stall_cycles ===
insert_ok : 23513958928
insert_alt: 9630258867
=== uops_retired.total_cycles ===
insert_ok : 25266688635
insert_alt: 11703285605

Background
I'm implementing a cryptanalytic attack in C++11 and need to find many collisions between two large lists (both generated on the fly).
A crucial part of the attack thus just consists of two critical loops:

*

*first populating a hash table with one list

*then matching the other list against the hash table.

The hash table operations are thus performance critical, and a factor 3 slow down means the attack is 3x slower.
Regarding design:
Besides trying to minimize memory usage, I'm also trying to have a typical hash table operation operate on just a single cacheline. As I expect that will increase overall attack performance, especially when running the attack on all CPU cores.

A: Summary
The TLDR is that loads which miss all levels of the TLB (and so require a page walk) and which are separated by address unknown stores can't execute in parallel, i.e., the loads are serialized and the memory level parallelism (MLP) factor is capped at 1. Effectively, the stores fence the loads, much as lfence would.
The slow version of your insert function results in this scenario, while the other two don't (the store address is known). For large region sizes the memory access pattern dominates, and the performance is almost directly related to the MLP: the fast versions can overlap load misses and get an MLP of about 3, resulting in a 3x speedup (and the narrower reproduction case we discuss below can show more than a 10x difference on Skylake).
The underlying reason seems to be that the Skylake processor tries to maintain page-table coherence, which is not required by the specification but can work around bugs in software.
The Details
For those who are interested, we'll dig into the details of what's going on.
I could reproduce the problem immediately on my Skylake i7-6700HQ machine, and by stripping out extraneous parts we can reduce the original hash insert benchmark to this simple loop, which exhibits the same issue:
tlb_fencing:

    xor     eax, eax  ; the index pointer
    mov     r9 , [rsi + region.start]

    mov     r8 , [rsi + region.size]
    sub     r8 , 200                   ; pointer to end of region (plus a bit of buffer)

    mov     r10, [rsi + region.size]
    sub     r10, 1 ; mask

    mov     rsi, r9   ; region start

.top:
    mov     rcx, rax
    and     rcx, r10        ; remap the index into the region via masking
    add     rcx, r9         ; make pointer p into the region
    mov     rdx, [rcx]      ; load 8 bytes at p, always zero
    xor     rcx, rcx        ; no-op
    mov     DWORD [rsi + rdx + 160], 0 ; store zero at p + 160
    add     rax, (64 * 67)  ; advance a prime number of cache lines slightly larger than a page

    dec     rdi
    jnz     .top

    ret

This is roughly equivalent to the B.size access (the load) and the B.values[B.size] = 1 access (the store) of the innermost loop of insert_ok4.
Concentrating on the loop, we do a strided load and a fixed store. Then move the load location forward by a bit more than the size of a page (4 KiB). Critically, the store address depends on the result of the load: as the addressing expression [rsi + rdx + 160] includes rdx which is the register holding the loaded value1. The store always occurs to the same address, as none of the address components changes in the loop (so we expect an L1 cache hit always).
The original hash example did a lot more work, and accessed memory randomly, and had the store to the same line as the load, but this simple loop captures the same effect.
We use also one other version of the benchmark, which is identical except that the no-op xor rcx, rcx between the load and the store is replaced by xor rdx, rdx. This breaks the dependency between the load and the store address.
Naively, we don't expect this dependency to do much. The stores here are fire-and-forget: we don't read from the stored location again (at least not for many iterations) so they aren't part of any carried dependency chain. For small regions we expect the bottleneck to be just chewing through the ~8 uops and for large regions we expect the time to handle all the cache misses to dominate: critically, we expect many misses to be handled in parallel since the load addresses can be independently calculated from simple non-memory uops.
Find below the performance in cycles for region sizes from 4 KiB up to 256 MiB, with the following three variations:
2M dep: The loop shown above (with the store address dependent on load) with 2 MiB huge pages.
4K dep: The loop shown above (with the store address dependent on load) with standard 4 KiB pages.
4K indep: The variant of the above loop with but with xor rdx, rdx replacing xor rcx, rcx to break the dependency between the load result and store address, using 4 KiB pages.
The result:

The performance of all the variants is basically identical for small region sizes. Everything up to 256 KiB takes 2 cycles/iteration, limited simply by the 8 uops in the loop and the CPU width of 4 uops/cycle. A bit of math shows that we have decent MLP (memory level parallelism): an L2 cache hit has a latency of 12 cycles, but we are completing one every 2 cycles, so on average we must be overlapping the latency of 6 L1 misses to achieve that.
Between 256 KiB and 4096 KiB the performance degrades somewhat as L3 hits start happening, but performance is good and MLP high.
At 8196 KiB performance degrades catastrophically for only the 4K dep case, crossing over 150 cycles and eventually stabilizing at about 220 cycles. It is more than 10 times slower than the other two cases2.
We can already make some key observations:

*

*Both the 2M dep and the 4K indep cases are fast: so this is not just about the dependency between the stores, but also about paging behavior.

*The 2M dep case is fastest of all, so we know the dependency doesn't cause some fundamental problem even when you miss to memory.

*The performance of the slow 4K dep case is suspiciously similar to the memory latency of my machine.

I've mentioned MLP above and calculated a lower bound on the MLP based on the observed performance, but on Intel CPUs we can measure MLP directly using two performance counters:

l1d_pend_miss.pending
Counts duration of L1D miss outstanding, that is each cycle number of Fill Buffers (FB) outstanding required by Demand Reads.

l1d_pend_miss.pending_cycles
Cycles with L1D load Misses outstanding

The first counts, every cycle, how many requests are outstanding from the L1D. So if 3 misses are in progress, this counter increments by 3 every cycle. The second counter increments by 1 every cycle at least one miss is in progress. You can see it as a version of the first counter which saturates at 1 every cycle. The ratio l1d_pend_miss.pending / l1d_pend_miss.pending_cycles of these counters over a period of time is the average MLP factor while any miss is outstanding3.
Let's plot that MLP ratio for the dep and indep versions of the 4K benchmark:

The problem becomes very clear. Up to regions of 4096 KiB, performance is identical, and MLP is high (for very small region sizes there is "no" MLP since there are no L1D misses at all). Suddenly at 8192 KiB, the MLP for the dependent case drops to 1 and stays there, while in the independent case the MLP goes to almost 10. That alone basically explains the 10x performance difference: the dependent case is not able to overlap loads, at all.
Why? The problem seems to be TLB misses. What happens at 8192 KiB is that the benchmark starts missing the TLB. Specifically, each Skylake core has 1536 STLB (second-level TLB) entries which can cover 1536 × 4096 = 6 MiB of 4K pages. So right between the 4 and 8 MiB region sizes, TLB misses go to 1 per iteration based on dtlb_load_misses.walk_completed, leading to this almost-too-perfect-is-it-fake plot:

So that's what happens: when address-unknown stores are in the store buffer, loads that take STLB misses can't overlap: they go one-at-a-time. So you suffer the full memory latency for every access. This also explains why the 2MB page case was fast: 2 MB pages can cover 3 GiB of memory, so there are no STLB misses/page walks for these region sizes.
Why
This behavior seems to stem from the fact that Skylake and other earlier Intel processors implement page table coherence, even though the x86 platform does not require it. Page table coherence means that if a store which modifies an address mapping (for example) a subsequent load that uses a virtual address affected by the remapping will consistently see the new mapping without any explicit flushes.
This insight comes from Henry Wong who reports in his excellent article on page walk coherence that to do this, page walks are terminated if a conflicting or address-unknown store is encountered during the walk:

Unexpectedly, Intel Core 2 and newer systems behaved as though a pagewalk coherence misspeculation had occurred even though there were no page table modifications. These systems have memory dependence prediction, so the load should have speculatively executed much earlier than the store and broken the data dependence chain.
It turns out it is precisely the early-executing load that is responsible for the incorrectly-detected misspeculation. This gives a hint on how coherence violations may be detected: by comparing pagewalks to known older store addresses (in the store queue?), and assuming a coherence violation if there is an older store with a conflict or an unknown address.

So even though these stores are totally innocent in that they don't modify any page tables, they get caught up in the page table coherence mechanism. We can find further evidence of this theory by looking at the event dtlb_load_misses.miss_causes_a_walk. Unlike the walk_completed event, this counts all walks that started even if they don't complete successfully. That one looks like this (again, 2M isn't shown because it starts no page walks at all):

Huh! The 4K dependent shows two started walks, only one of which completes successfully. That's two walks for every load. This aligns with the theory that the page walk starts for the load in iteration N+1, but it finds the store from iteration N still sitting in the store buffer (since the load for iteration N provides its address, and it is still in progress). Since the address is unknown, the page walk is canceled as Henry describes. Further page walks are delayed until the store address is resolved. The upshot is all the loads complete in a serialized fashion because the page walk for load N+1 must wait for the result of load N.
Why the "bad" and "alt" methods are fast
Finally, there is one remaining mystery. The above explains why the original hash access was slow, but not why the other two were fast. The key is that both of the fast methods don't have address-unknown stores, because the data dependency with the load is replaced by a speculative control dependency.
Take a look at the inner loop for the insert_bad approach:
for (size_t i = 0; i < bucket_size; ++i)
{
    if (i == B.size)
    {
        B.keys[i] = k;
        B.values[i] = 1;
        ++B.size;
        ++table_count;
        return;
    }
}

Note that the stores use the loop index i. Unlike the insert_ok case, where the index [B.size] comes from a store, i is a simply a calculated value in a register. Now i is related to the loaded value B.size since its final value will be equal to it, but that is established via a comparison which is a speculated control dependency. It doesn't cause any problem with page walk cancellation. This scenario does have a lot of mis-predictons (since the loop exit is unpredictable) but for the large region case these aren't actually too harmful because the bad path usually makes the same memory accesses as the good path (specifically, the next value inserted is always the same) and memory access behavior dominates.
The same is true for the alt case: the index to write at is established by using a calculated value i to load a value, check if it is the special marker value and then writing at that location using index i. Again, no delayed store address, just a quickly calculated register value and a speculated control dependency.
What About Other Hardware
Like the question author, I found the effect on Skylake, but I also observed the same behavior on Haswell. On Ice Lake, I can't reproduce it: both the dep and indep have almost identical performance.
User Noah, however, reported he could reproduce on Tigerlake using the original benchmark for certain alignments. I believe the most likely cause is that TGL isn't subject to this page walk behavior, but rather at some alignments the memory disambiguation predictors collide causing a very similar effect: the loads can't execute ahead of earlier address-unknown stores because the processor thinks the stores might forward to the load.
Run It Yourself
You can run the benchmark I describe above yourself. It's part of uarch-bench. On Linux (or WSL, but performance counters aren't available) you can run the following command to collect the results:
for s in 2M-dep 4K-dep 4K-indep; do ./uarch-bench --timer=perf --test-name="studies/memory/tlb-fencing/*$s" --extra-events=dtlb_load_misses.miss_causes_a_walk#walk_s,dtlb_load_misses.walk_completed#walk_c,l1d_pend_miss.pending#l1d_p,l1d_pend_miss.pending_cycles#l1d_pc; done

Some systems may not have enough free performance counters available (if you have hyperthreading enabled), so you can do two runs using different sets of counters each time.

1 In this case, rdx is always zero (the region is entirely full of zeros) so the store address happens to be the same as if this register wasn't included in the addressing expression, but the CPU doesn't know that!
2 Here, the 2M dep case also starts to show better performance than the 4K indep case, although the gap is modest.
3 Note the "while any miss is outstanding" part: you could also calculate MLP as l1d_pend_miss.pending / cycles, which would be the average MLP over a period of time, regardless of whether any misses were outstanding. Each is useful in their own way, but in a case like this with misses constantly outstanding they give almost identical values.
4 Yes, there are many differences between this and the original example. We store to a single fixed location, whereas the original loop stored near the load location, which varies every iteration. We store 0 not 1. We don't check B.size to see if it is too large. In our test the loaded value is always 0. There is no search loop for when the bucket is full. We don't load a random value to address, but just do a linear stride. However, these are not material: the same effect occurs in both cases and you can incrementally modify the original example by removing complexity until you reach this simple case.


text:
Q: When selecting fields from XML column in SQL server I get no result and no error I have a table with an XML Typed column containing an XML structure with a namespace.
Table is named PersonX
It contains an XML typed column named customData
The customData column contains this structure:
<personX:CustomData xmlns:personX="http://www.provider.com/PersonX">
    <MailingStreet>123 First Street, APT 123</MailingStreet>
    <MailingCity>Dallas</MailingCity>
    <MailingState>TX</MailingState>
    <MailingZip>73425</MailingZip>
    <ResidenceCity>Dallas</ResidenceCity>
    <ResidenceCounty>Dallas</ResidenceCounty>
    <ExportDate>2021-05-19T00:00:00Z</ExportDate>
    <IssueDate>2021-05-18T00:00:00Z</IssueDate>
    <ExpireDate>2022-05-23T00:00:00Z</ExpireDate>
    <SubmissionDate>2021-05-03T00:00:00Z</SubmissionDate>
</personX:CustomData>

My query:
declare @xml xml
select @xml = customData from PersonX

;with xmlnamespaces('http://www.provider.com/PersonX' as ns, DEFAULT 'http://www.provider.com/PersonX')
select Person.x.value('MailingStreet[1]','varchar(max)') as street
from @xml.nodes('personX') as Person(x)

When I run, I get a blank value for street.  I think it has something to do with the colon in the root element <personX:CustomData ...
I think I've missed something simple?
Also as a bonus question, how do I just run the query on the table itself instead of selecting into a variable?

A: Please try the following solution.
Directly from the table, no temporary variables.
There is no need to define the same namespace twice.
SQL
-- DDL and sample data population, start
DECLARE @tbl table (ID INT IDENTITY PRIMARY KEY, customData XML);
INSERT INTO @tbl ( customData) VALUES
(N'<personX:CustomData xmlns:personX="http://www.provider.com/PersonX">
    <MailingStreet>123 First Street, APT 123</MailingStreet>
    <MailingCity>Dallas</MailingCity>
    <MailingState>TX</MailingState>
    <MailingZip>73425</MailingZip>
    <ResidenceCity>Dallas</ResidenceCity>
    <ResidenceCounty>Dallas</ResidenceCounty>
    <ExportDate>2021-05-19T00:00:00Z</ExportDate>
    <IssueDate>2021-05-18T00:00:00Z</IssueDate>
    <ExpireDate>2022-05-23T00:00:00Z</ExpireDate>
    <SubmissionDate>2021-05-03T00:00:00Z</SubmissionDate>
</personX:CustomData>');
-- DDL and sample data population, end

WITH XMLNAMESPACES ('http://www.provider.com/PersonX' AS personX)
SELECT ID
    , c.value('(MailingStreet/text())[1]', 'VARCHAR(50)') AS MailingStreet
    , c.value('(MailingCity/text())[1]', 'VARCHAR(50)') AS MailingCity
FROM @tbl
CROSS APPLY customData.nodes('/personX:CustomData') AS t(c);

-- if enforced by the XML Schema
WITH XMLNAMESPACES ('http://www.provider.com/PersonX' AS personX)
SELECT ID
    , c.value('(MailingStreet)[1]', 'VARCHAR(50)') AS MailingStreet
    , c.value('(MailingCity)[1]', 'VARCHAR(50)') AS MailingCity
FROM @tbl
CROSS APPLY customData.nodes('/personX:CustomData') AS t(c);

Output
+----+---------------------------+-------------+
| ID |       MailingStreet       | MailingCity |
+----+---------------------------+-------------+
|  1 | 123 First Street, APT 123 | Dallas      |
+----+---------------------------+-------------+

redpajama_set_name: RedPajamaStackExchange


text:
Q: Проверка всех TextBox'ов на пустоту На GroupBox расположены TextB и СомboB как проверить их разом на заполненость(пустоту) и изменить цвет пустых?
Хотя бы текстбоксы, комбо не принципиально.
Заранее спасибо!☺☻

A: bool allEmpty = true;
bool someEmpty = false;

foreach(TextBox textBox in groupBox.Controls.OfType<TextBox>())
{
  if (string.IsNullOrEmpty(textBox.Text))
  {
    someEmpty = true;
    textBox.BackColor = Color.Red;
  }
  else
    allEmpty = false;
}

if (!someEmpty)
{
  // ВСЕ боксы не пусты, выполнять код на добавление в БД
}

A: bool allEmpty = groupBox.Controls.OfType<TextBox>().All(tb => tb.Text == string.Empty);


text:
Q: jQuery data() in window.load and document.ready, got undefined? Need to store some data in window.load and retrieve in document.ready:
<script>
   $(window).load(function() { // Store here
      $('img.storable').each(function() {
         $(this).data("key", "value");
         console.log($(this).data("key")); // Output: value
      };
   };

   $(document).ready(function() { // Retrieve here
      $('img.storable').each(function() {
         console.log($(this).data("key")); // Output: undefined!
      };
   };
</script>

Output in document.ready is undefined. Am I missing something about DOM events?

A: $(document).ready() runs as soon as the DOM has loaded, but $(window).load() will not run until the DOM has loaded AND all dom resources have loaded (like images and CSS files and stuff). That means that $(document).ready() will run before you set the value.

A: I think document ready happens before window.load ...
So it should be exactly the other way around
Just do a simple test:
$(document).ready(function() {
   alert('document ready');
});
$(window).load(function() {
   alert('window load');
});


text:
Q: Fluent nHibernate and JoinSubClasses I am not sure if this a problem with my Fluent configuration or some logic in my thinking.
Basically I have a Person class from which I have two inherited classes, Author and Borrower (it's a library system). The mapping I have is.
public class PersonMap : ClassMap<Person>
{
    public PersonMap()
    {
        Id(x => x.Id, "id");
        Map(x => x.Name, "name");

        // Subclasses
        AddPart(new AuthorMap());
        AddPart(new BorrowerMap());
    }
}

public class AuthorMap : JoinedSubClassPart<Author>
{
    public AuthorMap() : base("person_id")
    {
        Map(x => x.Country, "country");
        HasMany(x => x.Books).Cascade.All().WithKeyColumn("book_id");
    }
}

public class BorrowerMap : JoinedSubClassPart<Borrower>
{
    public BorrowerMap() : base("person_id")
    {
        Map(x => x.UserName, "user_name");
        HasMany(x => x.Schedule).Cascade.SaveUpdate().WithKeyColumn("borrower_id");
    }
}

Now if I run the HQL "FROM Author a ORDER BY a.Name" it will return a list of all Author and Borrower entities where I obviously just want a list of authors. Please feel free to set me straight on this.

A: A few things to try:

*

*In each of the subclass maps, set the table name with WithTableName("Author")

*Is person_id the key column on each subclass table? If not, change base("person_id") to base("key column name")
For example, I just tested a very similar query with the following mappings:
public class DigitalFreeSubscriptionMap : JoinedSubClassPart<DigitalFreeSubscription>
{
    public DigitalFreeSubscriptionMap()
        : base("DigitalFreeSubscriptions")
    {
        WithTableName("DigitalFreeSubscriptions");
        ...

and
public class FreeSubscriptionMap : JoinedSubClassPart<FreeSubscription>
{
    public FreeSubscriptionMap()
        : base("FreeSubscriptions")
    {
        WithTableName("FreeSubscriptions");
        ...

Both are subclasses of Subscription. In the database I tested on there are 1700 DigitalFreeSubscriptions while there are over a million FreeSubscripions (and other kinds of subscriptions). The HQL query "FROM DigitalFreeSubscripion" returned 1700 results.
Per request, the top of the SubscriptionMap:
public class SubscriptionMap : AuditableClassMap<Subscription>
{
    public SubscriptionMap()
    {
        WithTable("Subscriptions");
        Id(x => x.Id, "Subscriptions");

        AddPart(new FreeSubscriptionMap());
        AddPart(new DigitalFreeSubscriptionMap());
        // More sublass mappings and then the field mappings


text:
Q: Why is my jQuery fadein failing with IE 10? Can someone tell me why this doesn't work in IE?
http://jsfiddle.net/GASxF/1/
$(function(){  // $(document).ready shorthand
  $('#tempoffline').fadeIn('slow');
});

A: You can read about issues with fadeIn in IE here - http://www.kevinleary.net/jquery-fadein-fadeout-problems-in-internet-explorer/ .
But won`t scroll do the work for you?
Another possible workaround that I saw is like that:
$("#divToHide").hide().fadeIn(6000);

A: Maybe you want that:
$(function(){  // $(document).ready shorthand
  $('#tempoffline').delay(40000).fadeIn();
});

Or that:
$(function(){  // $(document).ready shorthand
  $('#tempoffline').fadeIn(40000);
});

A: It appears Mooseman had it right -- but with jQuery 2.x. Thanks.


text:
Q: C#/Powerpoint add-in file select and "store" For one part of the add-in I am creating I would like to add a video file. I am not necessarily trying to show the video in powerpoint, but I need to place this file somewhere for later reference.
So a) can I store the file within the powerpoint file, or b) if I have a relatively positioned file (same folder) could I then access the file easily?
I will be getting the file name from file open dialog.

A: If you want to embed the you could use the following code to add a new shape containing the video and hide it.
Dim shape As shape
Set shape = Slide.Shapes.AddMediaObject(videofile, 0, 0, -1, -1)
shape.Visible = msoFalse

However, it can be tricky to retrieve the video file later. See How to export movie from Powerpoint 2010 and VBA Export embedded video from Powerpoint presentation.
Or you could read the video data and store it in a slide or shape tag which might be an overkill depending on what you are trying to achieve.
Surely, you could copy the video file to the same directory as the PPT file but it will be lost if you move the PPT file or send it by mail etc.


text:
Q: Objective C - Static and global variable? In my .m file for a class named Ad , I have 3 static strings
static NSString *AdStateDisabled = @"disable";
static NSString *AdStateExpired = @"expired";
static NSString *AdStateActive = @"active";

I can simply use these static variables in the current class, but i cannot call them from any other class, is there a way to make these static variables global?
So for example in my viewcontroller class i can do something like.
//HomeViewController.m
if ([self.ad.state isEqual:Ad.AdStateDisabled])
{
     //do something
}

A: You could add the following declarations to your HomeViewController.h header, which would then need to be imported anywhere you wanted access to the strings.
//HomeViewController.h
extern NSString *AdStateDisabled;
extern NSString *AdStateExpired;
extern NSString *AdStateActive;

Then alter your definitions to remove 'static'.
//HomeViewController.m
NSString *AdStateDisabled = @"disable";
NSString *AdStateExpired = @"expired";
NSString *AdStateActive = @"active";

If you don't want a user of the strings to have to import HomeViewController.h then you could also just define those strings in AdState.h and put the definitions into AdState.m (and remove them from HomeViewController.m) after which users of the string would just need to import AdState.h to use the strings.

A: First, remove the static. Static variables and functions in C and Objective-C mean that they're visible only to the current compilation unit (that is more or less: only the file that you've declared the statix variable in can see it).
Next, you also need to declare the variables in a public header file with "extern", like the one of the class associated with the class:
extern NSString *AdStateDisabled;

You can then use them in other files as well, but you would not access them as "Ad.AdStateDisabled" but just as "AdStateDisabled".

A: From the looks of it, it seems you're trying to create some kind of "string based enumerator" for your state types. Happy to report that Obj-C now provides means to do that nicely:
In your header file, add the following declarations:
typedef NSString *AdState NS_TYPED_ENUM;
extern AdState const AdStateDisabled;
extern AdState const AdStateExpired;
extern AdState const AdStateActive;

And in the .m file, add the following definitions:
AdState const AdStateDisabled = @"disable"
AdState const AdStateExpired = @"expired";
AdState const AdStateActive = @"active";

You can then use these constants and even enumerate over them using for loops and so on. You will need to import this header in every source you intend to use these constants in, so you may create some "common.h" header for infrastructure, and tell the target to use it as "precompiled header" or the like.


text:
Q: Difference between extend() and + in lists - python I want to know what is the exact difference between l1+l2 and l1.extend(l2) as it both concatenates the lists in python.
I have already went through the below post regarding the same question.
Concatenating two lists - difference between '+=' and extend()
I clearly understand that extend() involves a function call and hence can be a bit more expensive. And also l1+l2 option cannot be used for non-local variables.
But in my case, I had a recursive code which eventually returns concatenation of two lists. I used extend method l1.extend(l2). And i got the following errors.
nonetype' object is not iterable
object of type 'NoneType' has no len()
But note that the list is not None or of NoneType.
I even tried printing the type(l1) and len(l1) and the type is list only.
But one thing is that, if i replace extend method with l1 + l2, entire code works fine and i didn't get any error.
May I know why is this so? Any ideas/suggestions

A: >>> print(l1.extend(l2))
None

l1.extend(l2) returns none while l1 has been updated. The mistake (but without code we can't tell for sure) is probably that you need to assign l1.extend(l2) to a (new) variable again.


text:
Q: Помогите оптимизировать запрос db2 Помогите оптимизировать запрос. Выглядит он монстрообразно.
select distinct  PUBLSEQ from PUBLCOVER P
      WHERE EXISTS
      ( SELECT * FROM PUBLCOVER A, XCOVERAREA B, XPRODCODEDICT C
        WHERE A.PUBLSEQ = P.PUBLSEQ
        AND A.COVER_STATUS = 'Y'
        AND A.COVAREA = B.COVAREA
        AND B.COVAREA_PRODCODE IS NOT NULL
        AND B.COVAREA_PRODCODE = C.PRODCODE
        AND C.STATUS = 'A'
        AND A.COVAREA = 1823
        )
      AND NOT EXISTS
      ( SELECT * FROM PUBLCOVER A, XCOVERAREA B, XPRODCODEDICT C
        WHERE A.PUBLSEQ = P.PUBLSEQ
        AND A.COVER_STATUS = 'Y'
        AND A.COVAREA = B.COVAREA
        AND B.COVAREA_PRODCODE IS NOT NULL
        AND B.COVAREA_PRODCODE = C.PRODCODE
        AND C.STATUS = 'A'
        AND A.COVAREA NOT IN (1823, 34)
        )

Очень бы хотелось избавиться от EXISTS или NOT EXISTS, оставив один из них.

A: Давайте попробуем так:
WITH SEQAREA AS
  (
  SELECT DISTINCT A.PUBLSEQ, A.COVAREA
  FROM PUBLCOVER A
    JOIN XCOVERAREA B ON B.COVAREA = A.COVAREA
    JOIN XPRODCODEDICT C ON C.PRODCODE = B.COVAREA_PRODCODE
  WHERE
    A.COVER_STATUS = 'Y' AND
    B.COVAREA_PRODCODE IS NOT NULL AND
    C.STATUS = 'A'
  )
SELECT DISTINCT SA1.SEQ
FROM SEQAREA SA1
 LEFT JOIN SEQAREA SA2 ON SA1.SEQ = SA2.SEQ and SA2.AREA NOT IN (1823, 34)
WHERE SA2.SEQ IS NULL AND SA1.AREA = 1823

Сначала мы соединим все участвующие таблицы, чтобы получить одну широкую, виртуальную таблицу и выберем из нее все уникальные пары publseq и covarea. Сделаем это внутри cte (конструкция with).
Затем соединим получившиеся результаты сами с собой так, чтобы с одной стороны были все записи, а с другой только те, у которых area не равна 1823 или 34.
Тогда нужные нам записи будут иметь справа значения null. Используя это знание и применяя дополнительный фильтр, чтобы откинуть записи с area равной 34 мы получим то, что нам нужно.
Судя по документации db2 должен материализовать запрос в конструкции with так, что двойное обращение к этому запросу просканирует таблицы только один раз.

A: думаю будет так
 select distinct PUBLSEQ from PUBLCOVER P
  WHERE EXISTS
  (
   SELECT count(*) cou, A.COVAREA
      FROM PUBLCOVER A, XCOVERAREA B, XPRODCODEDICT C
     WHERE A.PUBLSEQ = P.PUBLSEQ
       AND A.COVER_STATUS = 'Y'
       AND A.COVAREA = B.COVAREA
       AND B.COVAREA_PRODCODE IS NOT NULL
       AND B.COVAREA_PRODCODE = C.PRODCODE
       AND C.STATUS = 'A'
       AND A.COVAREA IN (1823, 34)
     GROUP BY A.COVAREA
    HAVING (A.COVAREA = 1823 AND cou > 0)
       AND (A.COVAREA = 34   AND cou = 0)
    )


text:
Q: Copy, Cut and Paste text within a WYSIWYG I'm trying to build a WYSIWYG, and I've three buttons: copy, cut and paste.
I tried this script for each one of them, but it didn't worked.
This is my script :
//Copy
document.getElementById('copy').addEventListener('click', function(){
    document.execCommand('copy', false, null);
}, false);

//Cut
document.getElementById('cut').addEventListener('click', function(){
    document.execCommand('cut', false, null);
}, false);

//Paste
document.getElementById('paste').addEventListener('click', function(){
    document.execCommand('paste', false, null);
}, false);

In Google chrome, Internet Explorer 11, Safari and Opera no one of them has worked, and I don't get anything in the console.
In Mozilla Firefox I get this message :
Error: Permission denied for <file://> to get property Clipboard.cutcopy
document.execCommand('cut', false, null);

The same thing for copy and paste.
How can I solve this ?

A: You cannot do this with JavaScript alone. You you have to depend on flash for this. Checkout zeroclipboard. It might shed some hope :)


text:
Q: Make copy to my account I have a few shared Worksheet with a set of scripts. When the user finishes his/her work, I want them to click a button to execute the script.
The first step, is to make a backup copy of the w/s. Here is the problem, it copies to HIS/HER account.
That's wrong. I want it to my  account.
ss.copy(this+"bkp")
what do I have to do to make this copy be dumped on my account?

A: Make the script run as you, instead of the user. When up publish the app select the execute as me function.


text:
Q: Angular JS ng-show/ hide based on drop-down list selected value in the following code I have one drop-down list (serviceSmallId) for type of service.
It is populated using model info.
There is a second field check-box which should only be visible when drop-down has a selected value of 'Weekly'. I am trying to use ng-show/ hide of angular.
I tried to search for possible solutions but no luck.
Can anyone please guide me what I am doing wrong.

                <button class="btn btn-info" ng-click="vm.goBack()">Back</button>
                <button class="btn btn-info" ng-click="vm.cancel()" ng-disabled="!vm.canSave">Cancel</button>
                <button class="btn btn-info" ng-click="vm.save()" ng-disabled="!vm.canSave">Save</button>

                    <form class="form-horizontal">

                            Service

                                <select class="form-control" id="serviceSmallId" ng-model="vm.scrubber.serviceSmallId"
                                        ng-options="item.dataLookupId as item.description for item in vm.serviceSmalls | orderBy:['sortOrder','description']">
                                </select>

                            <input class="form-control" type="checkbox" id="fullyFlanged" value="Bar" />

 </form>

A: You don't need to get the value property because a ng-model don't hold the element but the value itself;

must be

EDIT: In your case vm.scrubber.serviceSmallId will contain the ID and not the description Weekly. I suggest you to use ng-change directive to call a function in your controller that will find the item based on ID and set in the controller to be visible for ng-show.
  <select class="form-control" id="serviceSmallId" ng-model="vm.scrubber.serviceSmallId"
            ng-options="item.dataLookupId as item.description for item in vm.serviceSmalls | orderBy:['sortOrder','description']"
            ng-change="vm.selectObj()">

vm.selectObj() will find and set the current selected object in the scope to an controller variable (ex.: vm.selectedItem) and:

A: There probably is a more elegant "angular way" solution,
but I updated you code to work here - http://jsbin.com/tupisoriho/1/edit?html,js,output
Explanation of changes

*

*Provided ng-show a value vm.checker

*added ng-change to the select element and gave it a function checkerGo which tested to see if dropdown == 'weekly', if yes change vm.checker
Update
there is a more "angular way" - using expressions!
As per @Omri Aharon fiddle/comment below.


text:
Q: python, while loop, at the start of each hour call method OK, I have a IRC bot that has been my on going project while I pickup python, and thanks to everyone here who has helped when I have hit a wall.
ok so I have a while loop, I want a way to find if a new hour has started and if so, to run a method to update any settings, and to make sure that it is still connected to channels.  I just have no idea how to go about, checking the time, and then to call a method.
there are many other things happening if this while loop, so doing a sleep for an hour isn't the best way to do this.
As I know questions with out code get marked down, here is some code.
while 1:
    if(newhour() == 1):
        run_Method()

A: To answer your question, you could do something like:
current_hour = datetime.now().hour

while 1:
    if(datetime.now().hour != current_hour):
        run_Method()
        current_hour = datetime.now().hour

WARNING: This is a very simplistic solution.

A: Don't use an infinite while loop, you'll  be wasting a processor core just to run a silly while loop. At least put a sleep() inside the while loop if you do use it anyway for a casual test code.
Cron service is already running in the system for this task. Place your script there (or create a script that calls your main script.)

$ cd /etc/cron.hourly/

Let's say proj_x.sh calls your main script. Create proj_x.sh:

$ vi proj_x.sh

Place the following code into proj_x.sh
#!/usr/bin/env python
/home/user/path_to_proj_x/cron_hourly.py

Make it executable:

$ chmod +744 proj_x.sh

Now, /home/user/path_to_proj_x/cron_hourly.py is the main script that carries your run_method()


text:
Q: Svn commit changes ip I've got an svn server set up, reachable within our network under "svn.mydomain.at". the svn is also used from one user outside of our network reachable under its public ip.
the problem:
when the outside user commits new files to the svn, and i try to update my solution the svn trys to update from the public adress instead of using svn.mydomain.at
Any tips what i've done wrong?
Thanks in advance!


text:
Q: Problems loading resources from function C++/SFML I have a stucture that I use to declare Textures, Sprites, Music, Fonts,  Sounds, etc in a header. I then use a corresponding .cpp file to set said textures to their corresponding sprites, and so on.
I have created the struct object in main, and called the function. But When I build my program, I get a million "undeclared identifier" errors. What am I doing wrong? Here's my code:
resources.h:
#ifndef __SFML__resources__
#define __SFML__resources__

#include "SFML/Audio.hpp"
#include "SFML/Graphics.hpp"

struct resources
{
float opacity = 1.0;

sf::Texture texturePlayer;
sf::Texture textureSettingsMenu;
sf::Sprite spriteSaveMenu;
sf::Sprite spriteSettingsMenu;
//start screen texture
sf::Texture textureStart;
//gamestate background sprite
sf::Sprite spriteScreen;
sf::Font font;
sf::Font font2;
int loadResources();
// hundreds more lines of declarations below
//...
};
#endif

resources.cpp:
#include "resources.h"

int resources::loadResources()
{
if (!textureSaveMenu.loadFromFile("images/magicmenu3.png"))
    return EXIT_FAILURE;

if (!textureSettingsMenu.loadFromFile("images/inventorymenu.png"))
    return EXIT_FAILURE;

spriteSaveMenu.setTexture(textureSaveMenu);
spriteSettingsMenu.setTexture(textureSettingsMenu);

if (!textureStart.loadFromFile("images/skyocean.png"))
    return EXIT_FAILURE;

if (!font.loadFromFile("fonts/arial.ttf"))
    return EXIT_FAILURE;

if (!font2.loadFromFile("fonts/dominican.ttf"))
    return EXIT_FAILURE;

if (!musicBattle.openFromFile("audio/musicBattle.ogg"))
    return EXIT_FAILURE;
musicBattle.setVolume(20);
musicBattle.setLoop(true);

if (!musicOpening.openFromFile("audio/maintheme.ogg"))
    return EXIT_FAILURE;
musicOpening.setVolume(30);
musicOpening.setLoop(true);

if (!musicDefeat.openFromFile("audio/defeat.ogg"))
    return EXIT_FAILURE;
musicDefeat.setVolume(50);
musicDefeat.setLoop(true);

if (!musicForest.openFromFile("audio/forest.ogg"))
    return EXIT_FAILURE;
musicForest.setVolume(10);
musicForest.setLoop(true);

if (!musicWorldMap.openFromFile("audio/bluefields.ogg"))
    return EXIT_FAILURE;
musicWorldMap.setVolume(40);
musicWorldMap.setLoop(true);

if (!musicVillage.openFromFile("audio/welcomehome.ogg"))
    return EXIT_FAILURE;
musicVillage.setVolume(40);
musicVillage.setLoop(true);

//every single declared resource is set within this function
//but the function is too large to display fully here
}

main.cpp:
 #include "SFML/Audio.hpp"
 #include "SFML/Graphics.hpp"
 #include <iostream>
 #include "random.h"
 #include "player.h"
 #include "entity.h"
 #include "projectile.h"
 #include "enemy.h"
 #include "textDisplay.h"
 #include "pickup.h"
 #include "wall.h"
 #include "sword.h"
 #include "npc.h"
 #include "battlemenu.h"
 #include "cursor.h"
 #include "name.h"
 #include "itemshop.h"
 #include "characterselection.h"
 #include "mainmenu.h"
 #include "exp.h"
 #include "drops.h"
 #include "weaponshop.h"
 #include "armorshop.h"
 #include "startmenu.h"
 #include "room.h"
 #include "resources.h"

int main()
{
//create the main window
sf::RenderWindow window(sf::VideoMode(720, 500), "Sky Ocean");
window.setFramerateLimit(60);
window.setKeyRepeatEnabled(false);

//View
sf::View view1(sf::FloatRect(200, 200, 300, 200));
view1.setSize(sf::Vector2f(window.getSize().x, window.getSize().y));
view1.setCenter(sf::Vector2f(view1.getSize().x / 2, view1.getSize().y / 2));
window.setView(view1);

//load resources
struct resources resources1;
resources1.loadResources();

//class object
class player Player1;
Player1.sprite.setTexture(texturePlayer);

class player Player2;
Player2.sprite.setTexture(texturePlayer);
Player2.rect.setScale(1.6, 1.6);
Player2.sprite.setScale(1.6, 1.6);

//...
}

A: Firstly, I recommend you to read something about header files.

resources.h indeed doesn't contain declaration of identifiers used.
You will have to #include header file which contains those declarations so compiler will be able to see them. Please read SFML declaration to see which modules need to be included and #include them into header file, now you're including them only into main.cpp so only main.cpp contains declaration of identifiers. When compiler reads resources.cpp it doesn't see those declaration, henceundeclared identifier error.
resources.h for example should look like this:
//...

#include "entity.h"

#include <SFML/Graphics.hpp>
#include <Whatever.hpp>

struct resources
{

//...


text:
Q: Is a reference of a shared_ptr still a pointer? Recently I have a doubt in my work about the reference of a shared_ptr. Here is the code.
for (const auto & aRef : aVec) {
    THROW_RUNTIME_IFNULLPTR(aRef);
    // do sth
}

This is the code of my colleague. In my mind, aRef is a reference which can never be null. While I was told that (by auto &) aRef is still a pointer so it's possible that it's null. The reference is just to not increment the counter. I'm very confused about that.
However, it should be like
for (const auto & aRef : aVec) {
    // THROW_RUNTIME_IFNULLPTR(aRef);
    if ( aRef ) {
        aRef->getX();
    }
    // do sth
}

Am I wrong about this? I don't think that aRef is a pointer.

A:
In my mind, aRef is a reference which can never be null.

Yes and no. A reference can be everything which the object it refers to can be. If that object is, say, an int or a std::string or a std::vector<double>, then of course it cannot be null (or nullptr, to be precise).
If that object, however, is a pointer, for example an int*, or a void*, or a MyClass*, then it can be nullptr because the pointer can be nullptr.
Now in your case, the object being referred to is a std::shared_ptr. It cannot technically be nullptr, but it can represent nullptr by being in a state in which get() returns nullptr.

While I was told that (by auto &) aRef is still a pointer so it's possible that it's null.

More precisely: aRef is still a std::shared_ptr, so it's possible that it still represents nullptr.

A: std::shared_ptr has explicit operator bool(), so in this code
if ( aRef )

that operator will be called, and it returns true if underlying pointer is not null.

A: aRef is a reference. It is an alias for an object.
A pointer is a separate object that perhaps points to another object.
In this case aRef is a reference to an object of type std::shared_ptr<Something>.
The code is roughly equivalent to this:
auto first = aVec.begin();
auto last = aVec.end();
for( ; first != last ; ++first) {
    std::shared_ptr<Something> const& aRef = *first;
    if (aRef.get() != nullptr) {
        aRef->getX();
    }
    else {
        // handle the case where aRef is not pointing at an object
    }
}


text:
Q: How to pass MongoDB collection name as a parameter to a DB connection function-Python I need to write a DB connection function as ,
def func(col_name):
    conn = pymongo.MongoClient("localhost" , 27017)
    db   = conn.dbname.col_name
    return db

collection name should be passed as a parameter to the function. Above function is not working. it is working if I hard-coded the collection name in the code.
Please help.

A: You can use getattr to get attribute of an object by attribute name:
getattr(conn.dbname, col_name)

A: def func(col_name):
    conn = pymongo.MongoClient("localhost" , 27017)
    return conn.dbname[col_name]

You can do the same from the client if you want to pass in the database name:
def func(db_name, col_name):
    conn = pymongo.MongoClient("localhost" , 27017)
    return conn[db_name][col_name]


text:
Q: How to remove border of tabcontrol in winform I have a tabcontrol and on my tabcontrol which is vertically aligned i have borderlike this http://prntscr.com/bdfh0j between each tabs. I wish to remove these border of the tabcontrol like this http://prntscr.com/bdfhwa . Which property can help me achieve this ?
Any idea how it can be acieved ?


text:
Q: How to use JMeter for Login Authentication through Identity server 5.2 for ASP.Net MVC Web Application I am trying to do the performance test for the ASP.Net MVC Web Application,
the Application is working with the Identity Server 5.2 to Login authentication.
I'm facing problem with login through the identity server.
Jmeter Version: 5.1.1
Description of the case:

*

*Open URL of the website.

*It will redirect you to the Identity website

*Fill username and password

*Log in to the application

*Final URL will be the same as in point 1.

I was following the instruction below,
https://www.youtube.com/watch?time_continue=10&v=hGkrSFKcj10
base on this I created a Jmeter test plan

*

*Test Plan

*Thread Group

*First HTTP Req - GET the "https://CorrectURL.com/

*

*Assertion

*View result three

*Second HTTP Req - Post the username and Password on the https://identity.com/core/identityTokenUniqueForEverySingleLogin

*

*Assertion

*View result three

First HTTP request was successful:
I received Sampler Results:

*

*HTTP Request - GET the Identity-0  Response code: 301

*HTTP Request - GET the Identity-1  Response code: 302

*HTTP Request - GET the Identity-2  Response code: 302

*HTTP Request - GET the Identity-3  Response code: 302

*HTTP Request - GET the Identity-4  Response code: 200
Second response:
Because every time Identity token is different, I don't know how can I take the token and use it during login.
Also what kind of information do I need to do the HTTP POST?
Can I Find then somewhere in Development tool?
I used also BlazeMeter to record the login process but when I'm running it again I'm receiving:

*

*Response code: 405 Method Not Allowed

*Response code: 500  Internal Server Error

Any advice will be appreciated

A: Looking into Identity Server documentation it appears to be using a cookie therefore my expectation is that adding a HTTP Cookie Manager should solve the problem (at least partially).
Not knowing the details of your Identity Server configuration details and seeing request/response sequence it is hard to come up with the comprehensive instructions, however my expectation is that it is the matter of simple correlation to wit:

*

*Open your application login page (make sure that HTTP Cookie Manager is there)

*Open identity server

*Extract the token from the response if needed using a suitable JMeter PostProcessor and save the value into a JMeter Variable

*Use the JMeter Variable from the step 3 instead of recorded hard-coded token


text:
Q: Correct way to apply CSS style to active state to one button but not other buttons within different class OK so I found the :not pseudo element and wanted to apply a style to all buttons that are active EXCEPT one within another class. This is the CSS decleration I came up with but Dreamweaver, and more importantly the browser, does not like it and voids the whole decleration...
.button:active:not(.success .button:active) {
    position:relative;
    top:4px;
}

It looks like it makes sense to me logically but is there something about all these colons which confuses CSS?
PS. Its important because the button in the 'success' class is absolutely positioned, and adding this top:4px; screws everything up there.
Thanks

A: Are you looking for something like
.button:not(.success):active {
    position:relative;
    top:4px;
}

as example: https://jsfiddle.net/nh4f821y/

.button {
    padding: 10px;
    background: rgba(0,0,0,0.1);
    float: left;
}

.button:not(:last-child){
    margin-right: 10px;
}

.button:not(.success):active {
    background: rgba(0,0,0,0.2);
}

1

2

3

4

5

On click, the background only change for divs 3 and 4

Good Luck'

A: When you say "in the 'success' class", does that mean that you have an element with the class "success" and the button inside it? Something like this:

    <button class="button"></button>

If so, :not() is not the selector to use. The solution is to add another class onto the button and apply your styles to that:

    <button class="button button-success"></button>

and in the CSS:
.button:active {
    position: relative;
    top: 4px;
}

.button-success:active {
    position: absolute;
    top: auto;
}


text:
Q: Why is there sequential non-compactness in this? A sequence of points in the closure of an epsilon neighborhood around the origin of the topologist's sine curve does not converge because, someone told me that 0,1 is not in the curve. However, we're just considering the subspace topology on the curve so doesn't that mean the limit points in the vertical line x=0 are negligible and the curve is locally compact after all? I am a bit confused due to that - thank you.

A: If you define the topologist's sine curve as on Wikipedia, so
$$ T = \{(0,0)\} \cup \{(x, \sin(\frac1x)\mid x \in (0,1]\}$$
then a closed epsilon neighbourhood of $(0,0)$ is of the form $\{(x,y) \in T: \|(x,y)\| \le \epsilon\}$ and this has infinitely many points of the form $(x_n, \frac{\varepsilon}{2})$ with $x_n \to 0$. This has no convergent subsequence in $T$.


text:
Q: How to define multiple locations Using Google Maps API to drop pin for every post in a list of posts generated by a loop This question might be answered in other posts, but I haven't found the specific answer and I'm having trouble discerning how to logically think through this. I have a site where each post has an address. On each post page I've used the Google Maps API to translate the address into a map location and to show a map with a pin at that address. Works great.
What I need to do now is to show a map at the top of my archive/category/etc pages (pages with a list of posts generated by a query and a loop) and to list a pin for every post that shows up in that particular query. I also need the map to automatically resize to show all of the pins, and not show extraneous map outside of the pins boundaries.
The way it seems that this would happen is that I could create the markers with a script that's inside the loop, so that each time the loop runs, it would generate a new marker and add it to the map.
Another possible method that seems like it has potential would be to add the location to an array for each turn of the loop, and then show the array of pins when the loop is done.
Can anyone give me some advice on how to accomplish this? At this point I'm using the following code which gives me a map and the location of the last post in the list generated by the loop. This code is outside of the loop. I need to know which part I should move inside the loop, and how to adjust it so that I won't simply rewrite the marker during every iteration of the loop.
<script type="text/javascript">
    function initialize() {
        geocoder = new google.maps.Geocoder();
        var mapOptions = {
            zoom: 3,
        }
        var myAddress = document.getElementById('theAddress');
        var address = myAddress.textContent;
        geocoder.geocode({
            'address': address
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,

                });

            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });

        var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

A: You need to add markers in a loop. this was taken from a project i was working.
var locations = ["Denver, CO, United States"];
var markers = [];
var iterator = 0;

for (var i = 0; i < locations.length; i++) {
    setTimeout(function() {
            geocoder.geocode({'address': locations[iterator]}, function(results, status){
        if (status == google.maps.GeocoderStatus.OK) {
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                animation: google.maps.Animation.DROP
            });
            bounds.extend(marker.getPosition());
            map.fitBounds(bounds);
        } else {
            log('Geocode was not successful for the following reason: ' + status);
        }
    });
    iterator++;

    }, i * 250);
}


text:
Q: How to filter or query using abstract parent class in Django model? This one is interesting to solve. I am building a module to register address for hospital, medical store and doctors. There is an abstracted model PrimaryAddress and a subclass called MedicalStorePrimaryAddress, and more subclasses will use the same abstracted model. I am using django rest framework to get the listings based on proximity (latitude, longitude and city). Now how could I filter it all using parent class, i.e PrimaryAddress model as I want to filter all the entities, i.e hospital, medical store and doctor nearby.
I have looked into django-polymorphic library but it doesnt help with geodjango and abstract class.
Any help suggestion is appreciated. Thanks
Here is the code sample:
#  MODELS

class PrimaryAddress(gismodels.Model):
    street = gismodels.CharField(max_length=255)
    city = gismodels.CharField(max_length=60)
    state = gismodels.CharField(max_length=100,
                                choices=settings.US_STATES,
                                default="CT")
    landmark = gismodels.TextField()
    latitude = gismodels.FloatField(null=True, blank=True)
    longitude = gismodels.FloatField(null=True, blank=True)
    location = gismodels.PointField(null=True, blank=True)

    objects = gismodels.GeoManager()

    def __unicode__(self):
        return self.street

    class Meta:
        verbose_name = "Address"
        verbose_name_plural = "Addresses"
        abstract = True

    def save(self, *args, **kwargs):
        if self.latitude and self.longitude:
            self.location = Point(self.longitude, self.latitude)

        super(PrimaryAddress, self).save(*args, **kwargs)

class MedicalStoreAddress(PrimaryAddress):
    medical_store = gismodels.OneToOneField(MedicalStore, related_name="medical_store_address",
                                            on_delete=gismodels.CASCADE, null=True, blank=True)

    # objects = gismodels.GeoManager()

    def __unicode__(self):
        return self.street

    class Meta:
        verbose_name = "Medical Store Address"
        verbose_name_plural = "Medical Store Addresses"

    def save(self, *args, **kwargs):
        if self.latitude and self.longitude:
            self.location = Point(self.longitude, self.latitude)

        super(MedicalStoreAddress, self).save(*args, **kwargs)

# VIEW
class ProximityFilter(ListAPIView):
    serializer_class = AddressSerializer
    # authentication_classes = (authentication.TokenAuthentication, authentication.SessionAuthentication,)
    # permission_classes = (permissions.IsAuthenticated,)
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        longitude = self.kwargs.get('longitude')
        latitude = self.kwargs.get('latitude')
        city = self.kwargs.get('city')
        current_point = GEOSGeometry('POINT(%s %s)' % (longitude, latitude), srid=4326)
        # raise
        queryset = MedicalStoreAddress.objects.filter(city__iexact=city, location__distance_lte=(current_point, D(mi=700000000))).distance(
            current_point).order_by('distance')
        return queryset

# SERIALIZER

class AddressSerializer(HyperlinkedModelSerializer):

    class Meta:
        model = DoctorPrimaryAddress
        fields = ('pk', 'street', 'latitude', 'longitude', 'city')

This paste expires on 2018-03-29 21:26:23. View raw. Remove now (Why am I seeing this?) Pasted through web.


text:
Q: JavaScript undefined variable in an anonymous function This code is supposed to switch the display property of all children elements of #slide-container to "block" with time delay two seconds between the switches.
var magic = window.setInterval(function(){
    if (document.readyState === "complete") {
            var children = document.getElementById('slide-container').children;
            for (var i = 0; children.length > i; i++ ) {
                setTimeout(function(){
                    children[i].style.display = "block";
                    console.log(i);
                },2000);
            }
            magic = window.clearInterval(magic);
        } else {
            console.log("...");
        }
}, 1000);

I am using it along with this html:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

I get error Uncaught TypeError: Cannot read property 'style' of undefined
It says it cannot find children or children[0]. But that variable has been specified and the dom nodes exist.

A: Try encasing the setTimeout in an IIFE (Immediately invoked function expression)
 for (var i = 0; children.length > i; i++) {
      (function (index) {
                setTimeout(function () {
                    children[index].style.display = "block";
                    console.log(i);
                }, 2000);
            })(i);
        }

Check Fiddle
The reference of i is common to all the functions executed by setTimeout . So by the time the function inside executes , the value of i will point to children.length .
But there is no element that refers to children[children.length] which does not exist and throws an error.

A: By the time setTimeout is ready i will be the length of children so you have to capture the value of i
try this
var time = 2000;
for (var i = 0; children.length > i; i++ ) {
    (function( child, time) {
       window.setTimeout(function() {
          child.style.display = "block";
       }, time);
    }( children[i], time));
    time += 2000;
}

or you could do this. ...  I have fixed the delay thing
var hideElement = function( element, time) {
   window.setTimeout(function() {
      element.style.display = 'block';
   }, time);
};

var time = 2000;
for (var i = 0; children.length > i; i++ ) {
   hideElement(children[i], time);
   time += 2000;
}

A: Closure issue.
Try adding a 3rd parameter to the setTimeout (doesn't work):
setTimeout(function(i){
   children[i].style.display = "block";
   console.log(i);
}, 2000, i);

Example
Another formate:
    var i = 0;
    var timer = setInterval(function () {
        children[i].style.display = "block";
        i++;
        if (i == children.length) {
            clearInterval(timer);
        }
    }, 2000);

EXAMPLE
ES6 is around the corner, the let statement is especially built for situations like this:
for (let i = 0; children.length > i; i++ ) {
   setTimeout(function(){
      children[i].style.display = "block";
      console.log(i);
   }, 2000);
}

However this is not the answer you need for right now. This was just a note.


text:
Q: Issue with Struts2 checkbox tag Issue with Struts2 checkbox tag
<s:checkbox name="user.secondaryContactRequired" />

Here secondaryContactRequired is a boolean type in User Entity. When I click on check box value of secondaryContactRequired is true.
But when I uncheck the checkbox then secondaryContactRequired is taking as true only, but I want this value as false
Why this is happening? Please advise me what's wrong with this.
Thanks in advance

A: I have included interceptor...Now its' working...Thanks to all for sharing your valuable solutions


text:
Q: R trace doesn't work correctly inside functions? trace doesn't seem to work correctly inside precompiled functions
For example, in this snippet
xx <- 2:7
nu <- seq(-10, 9, length.out = 2001)
op <- par(lab = c(16, 5, 7))
matplot(nu, t(outer(xx, nu, besselI)), type = "l", ylim = c(-50, 200),
        main = expression(paste("Bessel ", I[nu](x), " for fixed ", x,
                                ",  as ", f(nu))),
        xlab = expression(nu))

Simple trace for xy.coords works fine
trace(xy.coords)
matplot(nu, t(outer(xx, nu, besselI)), type = "l", ylim = c(-50, 200),
        main = expression(paste("Bessel ", I[nu](x), " for fixed ", x,
                                ",  as ", f(nu))),
        xlab = expression(nu))
# trace: xy.coords
# trace: xy.coords
# trace: xy.coords
# trace: xy.coords
# trace: xy.coords
# trace: xy.coords
# trace: xy.coords

But tracing with function doesn't seem to work
trace(xy.coords, tracer = quote(cat("test\n")))
# Tracing function "xy.coords" in package "grDevices"
# [1] "xy.coords"
matplot(nu, t(outer(xx, nu, besselI)), type = "l", ylim = c(-50, 200),
        main = expression(paste("Bessel ", I[nu](x), " for fixed ", x,
                                ",  as ", f(nu))),
        xlab = expression(nu))

While direct call works fine
xy.coords(1:3, 1:2, recycle = TRUE)
# Tracing xy.coords(1:3, 1:2, recycle = TRUE) on entry
# test
# $x
# [1] 1 2 3
#
# $y
# [1] 1 2 1
#
# $xlab
# NULL
#
# $ylab
# NULL

What is going on and what do I need to change that?
Update I disable compilation of grDevices and other base packages, but trace still doesn't work correctly. When debugging matplot, xy.coords appears to be without tracing.
Update 2 This seems to be related to Override a function that is imported in a namespace, but after trying everything suggested there with assigning in namespace the traced object, the old one still gets called.

A: Acting on the imports of graphics (where matplot belongs) seems to do the trick:
xx <- 2:7
nu <- seq(-10, 9, length.out = 2001)
op <- par(lab = c(16, 5, 7))

trace(xy.coords, tracer = quote(cat("test\n")))

# get the imports env of graphics
nsi <- parent.env(getNamespace('graphics'))

unlockBinding("xy.coords", nsi)
assign('xy.coords', xy.coords, nsi)

matplot(nu, t(outer(xx, nu, besselI)), type = "l", ylim = c(-50, 200),
        main = expression(paste("Bessel ", I[nu](x), " for fixed ", x,
                                ",  as ", f(nu))),
        xlab = expression(nu))

Tracing xy.coords(x, y, xlabel, ylabel, log = log) on entry
test
Tracing xy.coords(x, y, xlabel, ylabel, log) on entry
test
Tracing xy.coords(x, y) on entry
test
Tracing xy.coords(x, y) on entry
test
Tracing xy.coords(x, y) on entry
test
Tracing xy.coords(x, y) on entry
test
Tracing xy.coords(x, y) on entry
test


text:
Q: VSCode extension development: How can I get the definition file of a type? I am writing a VSCode C++ extension. I would add an include instruction to the current file (which uses the type).
It is like an import instruction in JS.
How can I get the file path of the file where the type is defined?
Is there a way to get the file of goToTypeDefinition or goToDefinition?

A: you can get the path of the current file with
vscode.window.activeTextEditor.document.uri


text:
Q: Page layout analysis using Tesseract? Tesseract 3 is able to perform page layout analysis. However, I couldn't find any sample code or documentation on how to use the library for such purposes. I hope someone here can explain how to perform layout analysis on an image and how to parse the resulting data.

A: First, initialize TessBaseAPI instance. You can either use Init() (if you want to perform further text recognition) or InitForAnalysePage() (if you're interested just in text boxes).
Second, set the image using SetImage().
And finally, call AnalyseLayout() to get PageIterator which provides you with text boxes.
tesseract::TessBaseAPI tessApi;
tessApi.InitForAnalysePage();

// tessApi.SetImage(...);

tesseract::PageIterator *iter = tessApi.AnalyseLayout();

// Instead of RIL_WORD you can use any other PageSegMode
while (iter->Next(tesseract::RIL_WORD)) {
    int left, top, right, bottom;

    iter->BoundingBox(
            tesseract::RIL_WORD,
            &left, &top, &right, &bottom
    );
}

A: There is an option since 3.04:
tesseract -c preserve_interword_spaces=1 test.tif test

Here is a reference to what looks like the related development thread.

A: Tesseract can be given a page mode parameter (-psm) which can have the following values:

*

*0 = Orientation and script detection (OSD) only.

*1 = Automatic page segmentation with OSD.

*2 = Automatic page segmentation, but no OSD, or OCR

*3 = Fully automatic page segmentation, but no OSD. (Default)

*4 = Assume a single column of text of variable sizes.

*5 = Assume a single uniform block of vertically aligned text.

*6 = Assume a single uniform block of text.

*7 = Treat the image as a single text line.

*8 = Treat the image as a single word.

*9 = Treat the image as a single word in a circle.

*10 = Treat the image as a single character.

Example:
tesseract image.tif image.txt -l eng -psm 0

However, I am not sure that it is possible to use the layout analysis in standalone mode.

A: Not sure if this exactly answers your question, but I landed here looking for ways to get the bbox-coordinates info (and text recognised inside the bbox optionally) given an input image. The solution to which is now possible using tesseract.
$> tesseract test.tiff test.txt -l eng -psm 1 tsv

The params to notice in above code-snippet are 'psm' and 'tsv'. 'psm' selects the page segmentation mode and 'tsv' generates a nice tabular output file with all the information (page-block-line number, bbox coods, confidence, predicted text) you'd need on your text-image (shown below)
level   page_num    block_num   par_num line_num    word_num    left    top width   height  conf    text
1   1   0   0   0   0   0   0   5500    4250    -1
2   1   1   0   0   0   327 285 2218    53  -1
3   1   1   1   0   0   327 285 2218    53  -1
4   1   1   1   1   0   327 285 2218    53  -1
5   1   1   1   1   1   327 285 246 38  87  INFOPAC
5   1   1   1   1   2   620 287 165 38  87  PAGE
5   1   1   1   1   3   952 290 100 37  95  NAME
5   1   1   1   1   4   1173    292 1082    45  39  ENTRYDATE
5   1   1   1   1   5   2333    302 212 36  48  EMAIL


text:
Q: How to rename a logical volume when there are multiple volume groups with the same name I installed Fedora 24 on my main drive, but later decided to install it on my solid state drive instead. After doing so, I tried to mount my main drive (after running cryptsetup), but this happened:
# lvrename /dev/fedora/home /dev/fedora/althome
  Multiple VGs found with the same name: skipping fedora
  Use the VG UUID with --select vg_uuid=<uuid>

# lvdisplay

: above lists my partitions uuids

# lvrename --select vg_uuid=my-vg-uuid /dev/fedora/home /dev/fedora/althome

lvrename: unrecognized option '--select'

Since the given instructions don't work, how do I resolve this?

A: Use vgdisplay to find the volume group's UUID (not the logical volume's UUID) and then:
vgrename my-vg-id oldfedora

This appears to be a bug in Fedora 24.

A: TLDR - the only thing that works is:
lvm vgrename <vg uuid from vgdisplay> <new_vg_name>
Thank you to @koppor!
I too had two fedora_localhost-live VGs (pulled the drive out of a smoked machine and trying to get data off of it.).
I tried about 15 different combinations with vgrename then about 5 with lvm vgrename
The only one that works is this:
# vgdisplay
<snip>
  --- Volume group ---
  VG Name               fedora_localhost-live
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  7
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                1
  Open LV               1
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               236.87 GiB
  PE Size               4.00 MiB
  Total PE              60639
  Alloc PE / Size       60639 / 236.87 GiB
  Free  PE / Size       0 / 0
  VG UUID               5UVnsQ-duSo-0AxN-BXkx-kchz-3LIv-eHb6Cp
# lvm vgrename 5UVnsQ-duSo-0AxN-BXkx-kchz-3LIv-eHb6Cp vg_polonium


text:
Q: Gradle Multi-Module groovy 'Project' object not getting evaluated in helper files I have a multi-module setup for a Java project with following structure.
mainApp
|--> core-module
|       |--> src
|       |--> build.gradle
|       |--> gradle.properties
|
|--> lib-module
|       |--> src
|       |--> build.gradle
|       |--> gradle.properties
|--> lib-another-module
|       |--> src
|       |--> build.gradle
|       |--> gradle.properties
|--> settings.gradle
|--> build.gradle

And in my settings.gradle I've specified.
rootProject.name = 'mainApp'

include 'core-module'
include 'lib-module'
include 'lib-another-module'

in my mainApp/build.gradle file, I've written a helper as helper-tasks.gradle and imported that file in my $rootDir/build.gradle file as
apply from: "$rootDir/helpers/helper-tasks.gradle"

task('bundleJar', type: Jar) is a part of subprojects { subproject -> } closure and I'll be just calling ./gradlew bundleJar. Here expectations are it should iterate through each sub-project and collect the classes for my final bundle
in helper-tasks.gradle file I wrote a gradle tasks as below
task('bundleJar', type: Jar) {

    manifest {
        attributes 'Manifest-Version': "1.0"
        attributes 'Built-By': USER_NAME
        attributes 'Created-By': "Java Version: " + JAVA_VERSION
        attributes 'Implementation-Version': BUNDLE_VERSION + " Build " + GIT_COMMIT_HASH
        attributes 'Build-Timestamp': BUILD_TIME
    }
    baseName('lib-module')
    from project('lib-module').sourceSets.main.output.classesDirs
}

Here project('lib-module').sourceSets.main.output.classesDirs doesn't pick-up relative path of sub-module project $rootDir/lib-module/build/classes/java/main but still referring to "$rootDir/build/classes/java/main. Why? and how can I provide my settings to helper files?

A: There is a working example here on GitHub.
Consider the build.gradle at the root:
subprojects {
    apply plugin: 'java-library'
    apply from: "${rootProject.projectDir}/helpers/helper-tasks.gradle"
}

and helpers/helper-tasks.gradle:
task('bundleJar', type: Jar) {
    manifest {
        attributes 'Manifest-Version': "1.0"
        attributes 'Built-By': USER_NAME
        attributes 'Created-By': "Java Version: " + JAVA_VERSION
        attributes 'Implementation-Version': BUNDLE_VERSION + " Build " + GIT_COMMIT_HASH
        attributes 'Build-Timestamp': BUILD_TIME
    }
    baseName("${project.name}")
    from project.sourceSets.main.output.classesDirs
}

Note that the name of the file now matches the project name. In the example, gradle lib-module:bundleJar will generate ./lib-module/build/libs/lib-module.jar with appropriate classes.
Similarly, gradle lib-another-module:bundleJar will generate ./lib-another-module/build/libs/lib-another-module.jar (with appropriate classes).