Q: Can i store a pointer to RAM in flash at compile time My problem explained:
On my microcontroller (Atmel AT90CAN128) i have about 2500 bytes of RAM left.
In those 2500 bytes i need to store 5 times 100 data sets (size could change in the future). The data sets have a predefined but varying length between 1 and 9 bytes. The total bytes that the pure data sets occupy is about 2000 bytes. I now need to be able to access the data sets in an array like fashion by passing a uint8 to a function and get a pointer to the data set in return.
But i only have about 500 bytes left, so an array with pointers to each data set (calculated at start of run time) is simply not possible.
My attempt:
i use one big uint8 array[2000] (in RAM) and the length of the data sets is stored in flash as const uint8[] = {1, 5, 9, ...};.
The position of the data set in the big array is the accumulated length of the sets before it. So i would have to iterate through the length array and add the values up and then use it as an offset to the pointer of the big data array.
At runtime this gives me bad performance. The position of the data sets within the big array IS KNOWN at compile time, I just dont know how to put this information into an array that the compiler can store into flash.
As the amount of data sets could change, i need a solution that automatically calculates the positions.
Goal:
something like that
uint8 index = 57;
 uint8 *pointer_to_data = pointer_array[57];
Is this even possible, as the compiler is a 1 pass comiler ?
(I am using Codevision, not avr gcc)
My solution
The pure C solution/answer is technically the right answer for my question but it just seems overly complicated (from my perspective). The idea with the build script seemed better but codevision is not very practical in that way.
So i ended up with a bit of a mix.
I wrote a javascript that writes the C code/definition of the variables for me. The raw-definitions are easy to edit and i just copy paste the whole thing into a html text file and open it in a browser and copy paste the content back into my C file.
In the beginning i was missing a crucial element and that is the position of the 'flash' keyword in the definition. The following is a simplified output of my javascript that compiles just the way i like it.
flash uint8 len[150] = {4, 4, 0, 2, ...};

uint8 data1[241] = {0}; //accumulated from above

uint8 * flash pointers_1[150] = {data1 +0, data1 +4, data1 +0, data1 +8, ...};

The ugly part (lots of manual labor without script) is adding up the length for each pointer as the compiler will only compile if the pointer is increased by a constant and not a value stored in a constant array.
The raw definitions that are fed to the javascript then look like this
var strings = [
"len[0] = 4;",
"len[1] = 4;",
"len[3] = 2;",
...

Within the javascript it is an array of strings, this way i could copy my old definitions into it and just add some quotes. I only need to define the ones that i want to use, index 2 is not defined and the script uses length 0 for it but does include it. The macro would have needed an entry with 0 i guess, which is bad for overview in my case.
It is not a one click solution but it is very readable and tidy which makes up for the copy-paste.

A: One common method of packing variable-length data sets to a single continuous array is using one element to describe the length of the next data sequence, followed by that many data items, with a zero length terminating the array.
In other words, if you have data "strings" 1, 2 3, 4 5 6, and 7 8 9 10, you can pack them into an array of 1+1+1+2+1+3+1+4+1 = 15 bytes as 1 1 2 2 3 3 4 5 6 4 7 8 9 10 0.
The functions to access said sequences are quite simple, too. In OP's case, each data item is an uint8:
uint8  dataset[] = { ..., 0 };

To loop over each set, you use two variables: one for the offset of current set, and another for the length:
uint16 offset = 0;

while (1) {
    const uint8  length = dataset[offset];
    if (!length) {
        offset = 0;
        break;
    } else
        ++offset;

    /* You have 'length' uint8's at dataset+offset. */

    /* Skip to next set. */
    offset += length;
}

To find a specific dataset, you do need to find it using a loop. For example:
uint8 *find_dataset(const uint16  index)
{
    uint16  offset = 0;
    uint16  count = 0;

    while (1) {
        const uint8  length = dataset[offset];
        if (length == 0)
            return NULL;
        else
        if (count == index)
            return dataset + offset;

        offset += 1 + length;
        count++;
    }
}

The above function will return a pointer to the length item of the index'th set (0 referring to the first set, 1 to the second set, and so on), or NULL if there is no such set.
It is not difficult to write functions to remove, append, prepend, and insert new sets. (When prepending and inserting, you do need to copy the rest of the elements in the dataset array forward (to higher indexes), by 1+length elements, first; this means that you cannot access the array in an interrupt context or from a second core, while the array is being modified.)

If the data is immutable (for example, generated whenever a new firmware is uploaded to the microcontroller), and you have sufficient flash/rom available, you can use a separate array for each set, an array of pointers to each set, and an array of sizes of each set:
static const uint8   dataset_0[] PROGMEM = { 1 };
static const uint8   dataset_1[] PROGMEM = { 2, 3 };
static const uint8   dataset_2[] PROGMEM = { 4, 5, 6 };
static const uint8   dataset_3[] PROGMEM = { 7, 8, 9, 10 };

#define  DATASETS  4

static const uint8  *dataset_ptr[DATASETS] PROGMEM = {
    dataset_0,
    dataset_1,
    dataset_2,
    dataset_3,
};

static const uint8   dataset_len[DATASETS] PROGMEM = {
    sizeof dataset_0,
    sizeof dataset_1,
    sizeof dataset_2,
    sizeof dataset_3,
};

When this data is generated at firmware compile time, it is common to put this into a separate header file, and simply include it from the main firmware .c source file (or, if the firmware is very complicated, from the specific .c source file that accesses the data sets). If the above is dataset.h, then the source file typically contains say
#include "dataset.h"

const uint8  dataset_length(const uint16  index)
{
    return (index < DATASETS) ? dataset_len[index] : 0;
}

const uint8 *dataset_pointer_P(const uint16  index)
{
    return (index < DATASETS) ? dataset_ptr[index] : NULL;
}

i.e., it includes the dataset, and then defines the functions that access the data. (Note that I deliberately made the data itself static, so they are only visible in the current compilation unit; but the dataset_length() and dataset_pointer(), the safe accessor functions, are accessible from other compilation units (C source files), too.)
When the build is controlled via a Makefile, this is trivial. Let's say the generated header file is dataset.h, and you have a shell script, say generate-dataset.sh, that generates the contents for that header. Then, the Makefile recipe is simply
dataset.h: generate-dataset.sh
    @$(RM) $@
    $(SHELL) -c "$^ > $@"

with the recipes for the compilation of the C source files that need it, containing it as a prerequisite:
main.o: main.c dataset.h
    $(CC) $(CFLAGS) -c main.c

Do note that the indentation in Makefiles always uses Tabs, but this forum does not reproduce them in code snippets. (You can always run sed -e 's|^  *|\t|g' -i Makefile to fix copy-pasted Makefiles, though.)
OP mentioned that they are using Codevision, that does not use Makefiles (but a menu-driven configuration system). If Codevision does not provide a pre-build hook (to run an executable or script before compiling the source files), then OP can write a script or program run on the host machine, perhaps named pre-build, that regenerates all generated header files, and run it by hand before every build.

In the hybrid case, where you know the length of each data set at compile time, and it is immutable (constant), but the sets themselves vary at run time, you need to use a helper script to generate a rather large C header (or source) file. (It will have 1500 lines or more, and nobody should have to maintain that by hand.)
The idea is that you first declare each data set, but do not initialize them. This makes the C compiler reserve RAM for each:
static uint8  dataset_0_0[3];
static uint8  dataset_0_1[2];
static uint8  dataset_0_2[9];
static uint8  dataset_0_3[4];
/*                      : :  */
static uint8  dataset_0_97[1];
static uint8  dataset_0_98[5];
static uint8  dataset_0_99[7];
static uint8  dataset_1_0[6];
static uint8  dataset_1_1[8];
/*                      : :  */
static uint8  dataset_1_98[2];
static uint8  dataset_1_99[3];
static uint8  dataset_2_0[5];
/*                    : : :  */
static uint8  dataset_4_99[9];

Next, declare an array that specifies the length of each set. Make this constant and PROGMEM, since it is immutable and goes into flash/rom:
static const uint8  dataset_len[5][100] PROGMEM = {
    sizeof dataset_0_0, sizeof dataset_0_1, sizeof dataset_0_2,
    /* ... */
    sizeof dataset_4_97, sizeof dataset_4_98, sizeof dataset_4_99
};

Instead of the sizeof statements, you can also have your script output the lengths of each set as a decimal value.
Finally, create an array of pointers to the datasets. This array itself will be immutable (const and PROGMEM), but the targets, the datasets defined first above, are mutable:
static uint8 *const dataset_ptr[5][100] PROGMEM = {
    dataset_0_0, dataset_0_1, dataset_0_2, dataset_0_3,
    /* ... */
    dataset_4_96, dataset_4_97, dataset_4_98, dataset_4_99
};

On AT90CAN128, the flash memory is at addresses 0x0 .. 0x1FFFF (131072 bytes total). Internal SRAM is at addresses 0x0100 .. 0x10FF (4096 bytes total). Like other AVRs, it uses Harvard architecture, where code resides in a separate address space -- in Flash. It has separate instructions for reading bytes from flash (LPM, ELPM).
Because a 16-bit pointer can only reach half the flash, it is rather important that the dataset_len and dataset_ptr arrays are "near", in the lower 64k. Your compiler should take care of this, though.
To generate correct code for accessing the arrays from flash (progmem), at least AVR-GCC needs some helper code:
#include <avr/pgmspace.h>

uint8 subset_len(const uint8 group, const uint8 set)
{
    return pgm_read_byte_near(&(dataset_len[group][set]));
}

uint8 *subset_ptr(const uint8 group, const uint8 set)
{
    return (uint8 *)pgm_read_word_near(&(dataset_ptr[group][set]));
}

The assembly code, annotated with the cycle counts, avr-gcc-4.9.2 generates for at90can128 from above, is
subset_len:
    ldi  r25, 0                     ; 1 cycle
    movw r30, r24                   ; 1 cycle
    lsl  r30                        ; 1 cycle
    rol  r31                        ; 1 cycle
    add  r30, r24                   ; 1 cycle
    adc  r31, r25                   ; 1 cycle
    add  r30, r22                   ; 1 cycle
    adc  r31, __zero_reg__          ; 1 cycle
    subi r30, lo8(-(dataset_len))   ; 1 cycle
    sbci r31, hi8(-(dataset_len))   ; 1 cycle
    lpm  r24, Z                     ; 3 cycles
    ret

subset_ptr:
    ldi  r25, 0                     ; 1 cycle
    movw r30, r24                   ; 1 cycle
    lsl  r30                        ; 1 cycle
    rol  r31                        ; 1 cycle
    add  r30, r24                   ; 1 cycle
    adc  r31, r25                   ; 1 cycle
    add  r30, r22                   ; 1 cycle
    adc  r31, __zero_reg__          ; 1 cycle
    lsl  r30                        ; 1 cycle
    rol  r31                        ; 1 cycle
    subi r30, lo8(-(dataset_ptr))   ; 1 cycle
    sbci r31, hi8(-(dataset_ptr))   ; 1 cycle
    lpm  r24, Z+                    ; 3 cycles
    lpm  r25, Z                     ; 3 cycles
    ret

Of course, declaring subset_len and subset_ptr as static inline would indicate to the compiler you want them inlined, which increases the code size a bit, but might shave off a couple of cycles per invocation.
Note that I have verified the above (except using unsigned char instead of uint8) for at90can128 using avr-gcc 4.9.2.

A: First, you should put the predefined length array in flash using PROGMEM, if you haven't already.
You could write a script, using the predefined length array as input, to generate a .c (or cpp) file that contains the PROGMEM array definition. Here is an example in python:
# Assume the array that defines the data length is in a file named DataLengthArray.c
# and the array is of the format
# const uint16 dataLengthArray[] PROGMEM = {
#      2, 4, 5, 1, 2,
#      4 ... };

START_OF_ARRAY = "const uint16 dataLengthArray[] PROGMEM = {"
outFile = open('PointerArray.c', 'w')
with open("DataLengthArray.c") as f:
    fc = f.read().replace('\n', '')
    dataLengthArray=fc[fc.find(START_OF_ARRAY)+len(START_OF_ARRAY):]
    dataLengthArray=dataLengthArray[:dataLengthArray.find("}")]
    offsets = [int(s) for s in dataLengthArray.split(",")]
    outFile.write("extern uint8 array[2000];\n")
    outFile.write("uint8* pointer_array[] PROGMEM = {\n")
    sum = 0
    for offset in offsets:
        outFile.write("array + {}, ".format(sum))
        sum=sum+offset
    outFile.write("};")

Which would output PointerArray.c:
extern uint8 array[2000];
uint8* pointer_array[] = {
array + 0, array + 2, array + 6, array + 11, array + 12, array + 14, };

You could run the script as a Pre-build event, if your IDE supports it. Otherwise you will have to remember to run the script every time you update the offsets.

A: You mention that the data set lengths are pre-defined, but not how they are defined - so I'm going to make the assumption of how the lengths are written into code is up for grabs..
If you define your flash array in terms of offsets instead of lengths, you should immediately get a run-time benefit.
With lengths in flash, I expect you have something like this:
const uint8_t lengths[] = {1, 5, 9, ...};

uint8_t get_data_set_length(uint16_t index)
{
    return lengths[index];
}
uint8_t * get_data_set_pointer(uint16_t index)
{
    uint16_t offset = 0;
    uint16_t i = 0;
    for ( i = 0; i < index; ++i )
    {
        offset += lengths[index];
    }
    return &(array[offset]);
}

With offsets in flash, the const array has gone from uint8_t to uint16_t, which doubles the flash usage, plus an additional element to be speed up calculating the length of the last element.
const uint16_t offsets[] = {0, 1, 6, 15, ..., /* last offset + last length */ };

uint8_t get_data_set_length(uint16_t index)
{
    return offsets[index+1] - offsets[index];
}
uint8_t * get_data_set_pointer(uint16_t index)
{
    uint16_t offset = offsets[index];
    return &(array[offset]);
}

If you can't afford that extra flash memory, ou could also combine the two by having the lengths for all elements and offsets for a fraction of the indices, e.g every 16 element in the example below, trading off run-time cost vs flash memory cost.
uint8_t get_data_set_length(uint16_t index)
{
    return lengths[index];
}
uint8_t * get_data_set_pointer(uint16_t index)
{
    uint16_t i;
    uint16_t offset = offsets[index / 16];
    for ( i = index & 0xFFF0u; i < index; ++i )
    {
        offset += lengths[index];
    }
    return &(array[offset]);
}

To simplify the encoding, you can consider using x-macros, e.g.
#define DATA_SET_X_MACRO(data_set_expansion) \
  data_set_expansion( A, 1 ) \
  data_set_expansion( B, 5 ) \
  data_set_expansion( C, 9 )

uint8_t array[2000];
#define count_struct(tag,len) uint8_t tag;
#define offset_struct(tag,len) uint8_t tag[len];
#define offset_array(tag,len) (uint16_t)(offsetof(data_set_offset_struct,tag)),
#define length_array(tag,len) len,
#define pointer_array(tag,len) (&(array[offsetof(data_set_offset_struct,tag)])),

typedef struct
{
    DATA_SET_X_MACRO(count_struct)
}   data_set_count_struct;

typedef struct
{
    DATA_SET_X_MACRO(offset_struct)
}   data_set_offset_struct;

const uint16_t offsets[] =
{
    DATA_SET_X_MACRO(offset_array)
};

const uint16_t lengths[] =
{
    DATA_SET_X_MACRO(length_array)
};

uint8_t * const pointers[] =
{
    DATA_SET_X_MACRO(pointer_array)
};

The preprocessor turns that into:
typedef struct
{
    uint8_t A;
    uint8_t B;
    uint8_t C;
}   data_set_count_struct;

typedef struct
{
    uint8_t A[1];
    uint8_t B[5];
    uint8_t C[9];
}   data_set_offset_struct;

typedef struct
{
    uint8_t A[1];
    uint8_t B[5];
    uint8_t C[9];
}   data_set_offset_struct;

const uint16_t offsets[] = { 0,1,6, };

const uint16_t lengths[] = { 1,5,9, };

uint8_t * const pointers[] =
{
    array+0,
    array+1,
    array+6,
};

This just shows an example of what the x-macro can expand to. A short main() can show these in action:
int main()
{
    printf("There are %d individual data sets\n", (int)sizeof(data_set_count_struct) );
    printf("The total size of the data sets is %d\n", (int)sizeof(data_set_offset_struct) );
    printf("The data array base address is  %x\n", array );
    int i;
    for ( i = 0; i < sizeof(data_set_count_struct); ++i )
    {
        printf( "elem %d: %d bytes at offset %d, or address %x\n", i, lengths[i], offsets[i], pointers[i]);
    }

    return 0;
}

With sample output
There are 3 individual data sets
The total size of the data sets is 15
The data array base address is  601060
elem 0: 1 bytes at offset 0, or address 601060
elem 1: 5 bytes at offset 1, or address 601061
elem 2: 9 bytes at offset 6, or address 601066

The above require you to give a 'tag' - a valid C identifier for each data set, but if you have 500 of these, pairing each length with a descriptor is probably not a bad thing. With that amount of data, I would also recommend using an include file for the x-macro, rather than a #define, in particular if the data set definitions can be exported somewhere else.
The benefit of this approach is that you have the data sets defined in one place, and everything is generated from this one definition. If you re-order the definition, or add to it, the arrays will be generated at compile-time. It is also purely using the compiler toolchain, in particular the pre-processor, but there's no need for writing external scripts or hooking in pre-build scripts.

A: You said that you want to store the address of each data set but it seems like it would be much simpler if you store the offset of each data set.  Storing the offsets instead of the addresses means that you don't need to know the address of big array at compile time.
Right now you have an array of constants containing the length of each data set.
const uint8_t data_set_lengths[] = { 1, 5, 9...};

Just change that to be an array of constants containing the offset of each data set in the big array.
const uint8_t data_set_offsets[] = { 0, 1, 6, 15, ...};

You should be able to calculate these offsets at design time given that you already know the lengths.  You said yourself, just accumulate the lengths to get the offsets.
With the offsets precalculated the code won't have the bad performance of accumulating at run time.  And you can find the address of any data set at run time simply by adding the data set's offset to the address of the big array.  And the address of big array doesn't need to be settled until link time.


Q: Extremely concerned with Puzzling.SE answer quality It's quickly turning into Yahoo Answers.
Question quality is getting better. That isn't the issue.
The issue is answer quality.
Most users will disagree with me, but the quality of answers on that site is getting closer and closer to that of Y! Answers.   Much of this has to do with solving puzzles.  People will argue that solving puzzles requires lateral thinking, that there's no "one" solution.  I can agree with that, but they go on, saying that since anything goes, anything is an acceptable answer.
This means we get extremely low quality answers that don't really answer questions well but sound like they were created by ignorant children. We get answers like the following:

I entered the maze, intrigued by the difficulty caused by the fact
  that the exit was blocked off by a wall. Attached to my belt, I had
  one less powerful grenade and two more powerful grenades. I was glad
  to find out that the walls were made of a less sturdy material,
  meaning that a grenade could easily knock down the wall. I tested the
  weak grenade on an unnecessary wall, and to my delight, it worked! I
  proceeded by using a larger grenade on the wall that was blocking the
  exit. Not to my delight, there was a police officer guarding the exit!
  I used my last grenade and ran towards the exit. I made it out of the
  maze successfully.

Like seriously, that answer sounds so stupid to the question, yet it still received overwhelming community support, at least more than I thought possible. Creativity should not be an excuse for low-quality answers.
Meta.puzzling.stackexchange is hard for me, because there seems to be less and less of a unified community support to enforce strong rules in the community. People are using the "it's a young site, it's a beta, it's a new site" excuse to let bad answers and bad questions off the hook. I really don't know where to take this. From what I can tell, the mods I trying their best to take care of this but it doesn't look like anything will be changed soon.
That's why I'm asking you guys. I'm not sure what you think, but I'd like to hear from your opinions what you make of this.  I think it's especially noticeable when you have puzzling.SE questions constantly hitting the Hot Questions list, yet the quality you see is completely outrageous.


Q: Power Query Assistance: How to return the range of three consecutive fields across a row with highest value out of all fields New to Power Query.  Have pieced together what I've needed until now.
I need to return the sum of the three consecutive cells with highest value out of a range of cells.  See the screenshot I provided as an example.  This wouldn't necessarily include the MAX value of a specific cell in the given range.
I can do this all day long in a spreadsheet with MAX function and overlapping arrays.  I can't seem to figure it out with Power Query although I am pretty certain List.Max will be involved somehow.
Help is appreciated.

March 23rd Edit:
I've revised and tried both code suggestions but either the code runs on for a very long period for the first suggestion (I killed it after one hour) or the 2nd suggestion errors out unable to find column 'Material 1' (what I renamed the 'Part Number' field in my screenshot).
I failed to mention that my data table has over 20k rows.  I'm having trouble interpreting the M code suggestions you both provided, but are they looping thru each row one-by-one?  Perhaps this is what is causing the lag.  Maybe I would just be better off using VBA to prep the table in advance of Power Query by entering/filling a formula in a new column finding MAX(B1:N^1+C1:N^2+D1:N^3)?  Seems like it might actually be faster in this case?
My version of both code suggestions:
1st Method:
let
Source = Excel.CurrentWorkbook(){[Name="tblSource"]}[Content],
#"Promoted Headers" = Table.PromoteHeaders(Source),
#"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Material 1", type text}, {"Sold Month 1", Int64.Type}, {"Sold Month 2", Int64.Type}, {"Sold Month 3", Int64.Type}, {"Sold Month 4", Int64.Type}, {"Sold Month 5", Int64.Type}, {"Sold Month 6", Int64.Type}, {"Sold Month 7", Int64.Type}, {"Sold Month 8", Int64.Type}, {"Sold Month 9", Int64.Type}, {"Sold Month 10", Int64.Type}, {"Sold Month 11", Int64.Type}, {"Sold Month 12", Int64.Type}}),

#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type",{"Material 1"}, "Attribute", "Value"),
#"Added Index" = Table.AddIndexColumn(#"Unpivoted Other Columns", "Index", 0, 1),
#"Reordered Columns" = Table.ReorderColumns(#"Added Index",{"Index", "Material 1", "Attribute", "Value"}),
#"Added Custom" = Table.AddColumn(#"Reordered Columns" ,"Sum",(i)=>
    List.Sum(Table.SelectRows(#"Reordered Columns", each [Material 1]=i[Material 1] and [Index]=i[Index]) [Value])+
    List.Sum(Table.SelectRows(#"Reordered Columns", each [Material 1]=i[Material 1] and [Index]=i[Index]+1) [Value])+
    List.Sum(Table.SelectRows(#"Reordered Columns", each [Material 1]=i[Material 1] and [Index]=i[Index]+2) [Value])
    , type number),
#"Grouped Rows" = Table.Group(#"Reordered Columns", {"Material 1"}, {{"Max", each List.Max([Sum]), type number}}),
// Merge the max into the original table
#"Merged Queries" = Table.NestedJoin(#"Grouped Rows", {"Material 1"}, #"Grouped Rows",{"Material 1"},"Table1",JoinKind.LeftOuter),
#"Expanded Table1" = Table.ExpandTableColumn(#"Merged Queries", "Table1", {"Max"}, {"Max2"})
in #"Expanded Table1"`

2nd Method:
let
Source = Excel.CurrentWorkbook(){[Name="tblSource"]}[Content],
#"Promoted Headers" = Table.PromoteHeaders(Source),
#"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"Material 1", type text}, {"Sold Month 1", Int64.Type}, {"Sold Month 2", Int64.Type}, {"Sold Month 3", Int64.Type}, {"Sold Month 4", Int64.Type}, {"Sold Month 5", Int64.Type}, {"Sold Month 6", Int64.Type}, {"Sold Month 7", Int64.Type}, {"Sold Month 8", Int64.Type}, {"Sold Month 9", Int64.Type}, {"Sold Month 10", Int64.Type}, {"Sold Month 11", Int64.Type}, {"Sold Month 12", Int64.Type}}),
i = {"i"}, k = {"Material 1"},
base = Table.UnpivotOtherColumns(#"Changed Type", k, "Col", "Val"),
f = (n)=>let x = Table.Group(base, k, {"t", each Table.AddIndexColumn(_, "i", n)})
         in Table.Combine(x[t]),
a = f(0),
b = f(1),
c = f(2),
join = Table.NestedJoin(Table.NestedJoin(a,i&k,b,i&k,"a"),i&k,c,i&k,"b"),
add = Table.AddColumn(join, "sum", each List.Sum({[Val],[a][Val]{0}?,[b][Val]{0}?})),
group = Table.Group(add, k, {"max", each List.Max([sum])}),
final = Table.Join(Source, k, group, k)

in final

A: Sample code below
Main trick is unpivot, then using custom column and index to add the current, next, and next+1 row if they are the same Part Number
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Part Number", type text}}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type" , {"Part Number"}, "Attribute", "Value"),
#"Added Index" = Table.AddIndexColumn(#"Unpivoted Other Columns", "Index", 0, 1),
#"Added Custom" = Table.AddColumn(#"Added Index" ,"Sum",(i)=>
    List.Sum(Table.SelectRows(#"Added Index" , each [Part Number]=i[Part Number] and [Index]=i[Index]) [Value])+
    List.Sum(Table.SelectRows(#"Added Index" , each [Part Number]=i[Part Number] and [Index]=i[Index]+1) [Value])+
    List.Sum(Table.SelectRows(#"Added Index" , each [Part Number]=i[Part Number] and [Index]=i[Index]+2) [Value])
    , type number),
#"Grouped Rows" = Table.Group(#"Added Custom", {"Part Number"}, {{"Max", each List.Max([Sum]), type number}}),

// Merge the max into the original table
#"Merged Queries" = Table.NestedJoin(#"Changed Type",{"Part Number"}, #"Grouped Rows",{"Part Number"},"Table1",JoinKind.LeftOuter),
#"Expanded Table1" = Table.ExpandTableColumn(#"Merged Queries", "Table1", {"Max"}, {"Max"})
in #"Expanded Table1"

A: Slightly different way:
let
    Source = Excel.CurrentWorkbook(){[Name="Table"]}[Content],
    i = {"i"}, k = {"Part Number"},
    base = Table.UnpivotOtherColumns(Source, k, "Col", "Val"),
    f = (n)=>let x = Table.Group(base, k, {"t", each Table.AddIndexColumn(_, "i", n)})
             in Table.Combine(x[t]),
    a = f(0),
    b = f(1),
    c = f(2),
    join = Table.NestedJoin(Table.NestedJoin(a,i&k,b,i&k,"a"),i&k,c,i&k,"b"),
    add = Table.AddColumn(join, "sum", each List.Sum({[Val],[a][Val]{0}?,[b][Val]{0}?})),
    group = Table.Group(add, k, {"max", each List.Max([sum])}),
    final = Table.Join(Source, k, group, k)
in
    final


Q: How to display Bootstrap Autocloseable alert message on asp.net button click? How to display Bootstrap Autocloseable alert message on asp.net button click?
Code as follows:

    <asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="btn btn-block org"
        Style="margin-top: 0px" OnClick="btnLogin_Click showalertmsg();" ValidationGroup="Login" />

closeable code using javascript

I called function name"showalertmsg" on asp button click it gives error?
error gives as follows while compiling
Compiler Error Message: CS1026: ) expected

A: Issues in the asp.net button
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="btn btn-block org"
        Style="margin-top: 0px" OnClick="btnLogin_Click" ValidationGroup="Login" OnClientClick="showalertmsg(); return false;" />

A: you can't call javascript fuction like this
OnClick="btnLogin_Click showalertmsg();"

But
use OnClientClick="showalertmsg();"
and also call return false at the end to stop postback
function showalertmsg(message, alerttype) {

        $('#alert_placeholder').append('
×' + message + '
')

        setTimeout(function () {
            $("#alertdiv").remove();

        }, 5000);

return false;
    }


Q: How conv2D function change the input layer In my ResNet32 network coded using Tensorflow, the input size is 32 x 32 x 3 and the output of the
layer is 32 x 32 x 32. Why 32 channel is used ?
tf.contrib.layers.conv2d(
    inputs,
    **num_outputs**,  /// how to determine the number of channel to be used in my layer?
    kernel_size,
    stride=1,
    padding='SAME',
    data_format=None,
    rate=1,
    activation_fn=tf.nn.relu,
    normalizer_fn=None,
    normalizer_params=None,
    weights_initializer=initializers.xavier_initializer(),
    weights_regularizer=None,
    biases_initializer=tf.zeros_initializer(),
    biases_regularizer=None,
    reuse=None,
    variables_collections=None,
    outputs_collections=None,
    trainable=True,
    scope=None
)

Thank's in advance,

A: The 3 in input is the number to represent that the input image is RGB (color image), also known as color channels, and if it were a black and white image then it would have been 1 (monochrome image).
The 32 in output of this represents the number of neurons\number of features\number of channels you are using, so basically you are representing the image in 3 colors with 32 channels.
This helps in learning more complex and different set of features of the image. For example, it can make the network learn better edges.

A: By assigning stride=2 you can reduce the spatial size of input tensor so that the height and width of output tensor becomes half of that input tensor. That means, if your input tensor shape is (batch, 32, 32, 3) (3 is for RGB channel) to a Convolution layer having 32 kernels/filters with stride=2 then the shape of output tensor will be (batch, 16, 16, 32). Alternatively, Pooling is also widely used to reduce the output tensor size.
The ability of learning hierarchical representation by stacking conv layer is considered as the key to success of CNN. In CNN, as we go deeper the spatial size of the tensor reduces whereas the number of channel increases that helps to handle the variations in appearance of complex target object . This reduction of spatial size drastically decreases the required number of arithmetic operations and computation time with the motive of extracting prominent features contributing towards final output/decision. However, finding this optimal number of filter/kernel/output channel is time consuming and, therefore, people follow the proven earlier architectures e.g. VGG.


Q: Failed to resolve libraries when changing from jcenter() to mavenCentral() So I am working on an old project and Android Studio warned me to change from jcenter() to mavenCentral() as jcenter() is not beeing updated.
So this was my initial project build.gradle:
buildscript {
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.1'
        classpath 'com.google.gms:google-services:4.3.13
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And I have changed it to the following one:
buildscript {
    repositories {
        google()
        mavenCentral()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.1'
        classpath 'com.google.gms:google-services:4.3.13
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

With the initial build.gradle using jcenter() everything was working fine, but using mavenCentral it fails to resolve these 2 github libraries:
"Failed to resolve: com.loopeer.lib:shadow:0.0.3"
"Failed to resolve: com.vatsal.imagezoomer:image-zoomer:1.0.2"
I don´t know why with jcenter() I don´t have any problem and using mavenCentral() yes, could there be any solution or maybe they can be only working with jcenter()?
The curious thing is that for example I have searched for information of one of this libraries and supposedly it should work with mavenCentral -> "ImageZoomer is available in the MavenCentral, so getting it as simple as adding it as a dependency" (This is what it is said in this github library)


Q: Real-time website traffic monitoring for operations teams Working on medium sized websites we've always built our own real-time traffic graphing solutions and displayed those on a big screen mission control style so that if traffic starts to climb, load start to climb, latency increases, etc we can start watching it pro-actively before the monitoring system goes off.
Now I'm starting at a new company and we need the same thing, are there companies that have mission control style real-time website monitoring software products? Not web analytics, but real-time graphing of things like simultaneous users, page views, hits, avg HTML render time, etc. It would require installing some kind of agent on each web server (or the load balancer) since Javascript tracking is insufficient to detect for example when a spam-bot starts pummeling the site. I've googled and can't find anything.

A: Best tool i have seen is http://www.splunk.com it looks at your logfiles in real time and charts data based on your queries.

A: Sounds like something Reconnoiter could do, maybe combined with (sys)log shipping or some form of statistics from the httpd

A: Maybe some RUM monitoring tool would do the job, as it monitors performance from the perspective of users. You could try simple RUM tools like http://www.gear5.me (requires only simple js snippet) or more complex such as http://www.newrelic.com ,which requires a module on server for data acquisition.

A: There are a number of companies that sell appliances that tap the network, sniff the traffic, and put together the kinds of stats you're looking for.
CoRadiant, CA Wily CEM, CA NetQos Super Agent, ...
Or you can build one with WireShark :-)
(Disclaimer: I am occasionally a paid CEM consultant)

A: Can't see how you would do "avg HTML render time" without a bit of Javascript, but everything else you can script up using MRTG, assuming your server environment is *nix or you have Cygwin installed.
Being Pro-active is great, but your monitoring package should go off if anything out of the normal happens, not after something goes critical. Unless you plan to have someone watch graphs 24/7.

A: We're using collectd to gather data and different web-frontends for rrd: collection3, Drraw to display it.

A: I am not sure if you have a budget for such tools -- if you do, I would suggest using Splunk.  I use it for a similar monitoring setup.  Web server access / error logs are sent via syslog to Splunk and we've built dashboards to provide us with specific views into that data. We can also display dashboard graphs in real time since the newest version of Splunk now includes a "real-time" timeframe.
Since there is also logic in our applications that feed data to Splunk via syslog, we are then able to correlate application performance data together with traditional web server logs and extract useful information from it. One of those things happens to be processing and rendering metrics that you mentioned.
YMMV as Splunk really needs the knowledge and acumen of a good administrator to set up and architect.  I've seen more than a handful of people swear off Splunk only to find out it's because its hardware needs were architected so poorly that it was basically tripping over itself to fail.  Its search language also has a bit of a learning curve if you're not already a power user.  It's not for everyone, though I can attest that when it's architected correctly and you seed it with lots of data, it quickly becomes an indispensable monitoring and reporting tool.


Q: Python pylab chart plot and loops I'm just learning Python and I'm wondering if someone could help me get the chart to render properly in the following code, i.e. plot the sequence of data points.
I have put print statements so I can see if the calculations are correct which they are.
Thanks
from pylab import *

def some_function(ff, dd):
    if dd >=0 and dd <=200:
        tt = (22/-90)*ff+24
    elif dd >=200 and dd <=1000:
        st = (22/-90)*(ff)+24
        gg = (st-2)/-800
        tt = gg*dd+(gg*-1000+2)
    else:
        tt = 2.0
    return tt

ff = float(25)
for dd in range (0, 1200, 100):
    tt1 = some_function(ff, dd)
    plot(dd,tt1)
    print(dd)
    print(tt1)
title("Something")
xlabel("x label")
ylabel("y label")
show()

A: Since you are plotting one point at a time, you need either a scatter plot or a plot with markers
for dd in range (0, 1200, 100):
    tt1 = some_function(ff, dd)
    scatter(dd, tt1) # Way number 1
    # plot(dd,tt1, 'o') # Way number 2

EDIT (answering your second question in the comments below): Save the results in a list and plot outside the for loop
result = []
dd_range = range (0, 1200, 100)
for dd in dd_range:
    tt1 = some_function(ff, dd)
    result.append(tt1)
plt.plot(dd_range, result, '-o')

A: You can vectorize your function and work with NumPy arrays to avoid the for-loop and better inform matplotlib of what you want to plot
import numpy as np
from pylab import *

def some_function(ff, dd):
    if dd >=0 and dd <=200:
        tt = (22/-90)*ff+24
    elif dd >=200 and dd <=1000:
        st = (22/-90)*(ff)+24
        gg = (st-2)/-800
        tt = gg*dd+(gg*-1000+2)
    else:
        tt = 2.0
    return tt

vectorized_some_function = np.vectorize(some_function)

ff = float(25)
dd = np.linspace(0, 1100, 12)
tt = vectorized_some_function(ff, dd)
plot(dd, tt)
title("Something")
xlabel("x label")
ylabel("y label")
show()


Q: How to generate flexible number of tabs in php? Hello guys I really need your help.
I am very new php or programming in general. So maybe my question is already solved but I wasn't able to adjust the code in correct way or see the correct solution. I have the following problem: I need a procedure that can handle flexible numbers of tabs. For example if I have 5 keywords, there should be 5 tabs generated. For 3 keywords 3 tabs and so on...
I know how to handle tabs their number is known and doesn't change (like for example always three tabs with 'home', 'news' and 'registration'). But in my case, number of tabs change in time.
I tried this code:
My php part:
<?php

/* How it was handled before I tried to make it dynamically:
<button class="tablink" onclick="openPage('Home', this, 'red')" id="defaultOpen">Home</button>
<button class="tablink" onclick="openPage('News', this, 'green')">News</button>
<button class="tablink" onclick="openPage('Contact', this, 'blue')">Contact</button>
<button class="tablink" onclick="openPage('About', this, 'orange')">About</button>

Home

 home...

News

 news...

Contact

 contact...

About

 about...

My try making the number of tabs dynamically:
*/

$current_tab_number = 0; //Number of tabs generated
$end_number=3; //this should be the number of tabs at the end

while($current_tab_number < $end_number){
    $current_tab_number = current_tab_number + 1;
?>
    <button class="tablink" onclick="openPage('$current_tab_number', this, 'red')">Name</button>

Name

 Some text...

<?php
}

This is my javascript:

As you can see, I only changed the php part. But since I'm a beginner, code doesen't work as expected and I have really no clue, how to adjust in correct way.
In addition it would be fantatstic, if tabs could be named flexible,too. Like 'tab 1', 'tab 2',...
I really hope, someone could help me.
So far, have a great day!

A: You need to know a name for each tab and how many to create, so create an array with the names you want, that tells you how many are needed and the name that should be used in the javascript call.
/*
My try making the number of tabs dynamically:
*/

$tabs = ['Home', 'News', 'Contact', 'About'];

foreach ($tabs as $tab){
?>
    <button class="tablink" onclick="openPage('<?php echo $tab;?>', this, 'red')>Name</button>
    <div id="<?php echo $tab;?>" class="tabcontent">

Name

 Some text...

<?php
} // endforeach

A: Key Issue
The reason your code doesn't work is because you've missed a $ symbol from the line:
$current_tab_number = current_tab_number + 1;

So, effectively, your while loop becomes infinite as you don't increment the $current_tab_number variable.
Replace that line with:
$current_tab_number = current_tab_number + 1;
// OR
$current_tab_number++;

Which then becomes:
while($current_tab_number < $end_number){
    $current_tab_number++;
    // Print tabs here
}

Alternatively you could use a for loop like:
for($i = 0; $i < $end_number; $i++){
    // print tabs here
}

Additionally
Using variables outside of PHP tags
This line:
<button class="tablink" onclick="openPage('$current_tab_number', this, 'red')">Name</button>

Will literally print the string $current_tab_number what it should be is:
<button class="tablink" onclick="openPage('<?php echo $current_tab_number; ?>', this, 'red')">Name</button>

Same here:

<div id="<?php echo $current_tab_number; ?>" class="tabcontent">

We could easily get around this by just using echo to print the html instead. For example:
echo <<<EOT

    <button class="tablink" onclick="openPage('{$current_tab_number}', this, 'red')">Name</button>

Name

 Some text...

EOT;

This method doesn't add data to the divs
The output of this code is expected to be:
<button class="tablink" onclick="openPage('Home', this, 'red')" id="defaultOpen">Home</button>
<button class="tablink" onclick="openPage('News', this, 'green')">News</button>

Home

 home...

News

 news...

But will actually be:
<button class="tablink" onclick="openPage('<?php echo $current_tab_number; ?>', this, 'red')">Name</button>
<div id="<?php echo $current_tab_number; ?>" class="tabcontent">

Name

 Some text...

<button class="tablink" onclick="openPage('<?php echo $current_tab_number; ?>', this, 'red')">Name</button>
<div id="<?php echo $current_tab_number; ?>" class="tabcontent">

Name

 Some text...

To add data to the output we need to source it from somewhere, for example:
$tab_list = [
    1 => [
        "name"    => "Home",
        "content" => "Some text for content..."
    ],
    2 => [
        "name"    => "About",
        "content" => "Some text for about..."
    ]
];

foreach($tab_list as $tab_number => $tab){
    echo "
    <button class=\"tablink\" onclick=\"openPage('{$tab_number}', this, 'red')\">Name</button>

{$tab["name"]}

{$tab["content"]}

    ";
}

A: You can iterate over the tab names and concatenate the string to generate the html code for tabs. For example:
$tab_names = ['home', 'about', 'contact'];
$resulting_html_code = "";
foreach ($tab_names as $tab){
    $resulting_html_code .= "{$resulting_html_code}
{$tab}
";
}


Q: Can I write in a user input in Python? I would like to add a "default value" to an input().
Something like this:
>>> x = input("Enter a number: ", value="0")
Enter a number: 0

So that the user can edit it, like the value attribute in html <input>
I tried using pyautogui:
import pyautogui

def input_value():
    x = input("Enter a number: ")
    pyautogui.hotkey("0")return x

But naturally it doesn't work because pyautogui.hotkey() is called after input().
Is there any way to do this?

A: Take a look at pyinputplus for enhanced input() functionality. If the online documentation isn't enough, you can also read Automate the Boring Stuff with Python for a good guide on using the module
https://pypi.org/project/PyInputPlus/
All input functions have the following parameters:
default (str, None): A default value to use should the user time out or exceed the number of tries to enter valid input.


Q: system.webServer/security/authorization in web.config how to migrate to aspcore I'm using a asp.net webapp which uses system.webServer in web.config and have a list of user accounts as roles.
<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <security>
      <authorization>
        <remove users="*" roles="" verbs="" />
        <add accessType="Allow" roles="MOON\USER1" />
        <add accessType="Allow" roles="MARS\USER2" />
      </authorization>
    </security>
</system.webServer>

and to achieve this authorization in asp.net core i tried to use different approaches and none seems working. What is the right and best way in asp.net core to implement authorization of web app to load for restricted users.

A: I don't know if you managed to find the solution to your issue but the first problem in that config file is that the auth rules are matched in order. All your requests are matching the deny first and you never get to evaluate the access for USER1 and USER2.


Q: StandardOutput.ReadToEnd() always NULL I have a problem with this function. It is supposed to output an install command to a textbox but install.StandardOutput.ReadToEnd() is always null.
I get the error: Expression cannot be evaluated because there is a native frame at the top of the call stack
Can you help me out with this?
Process install = new Process();
install.StartInfo.FileName = "cmd.exe";
install.StartInfo.UseShellExecute = false;
install.StartInfo.Arguments = "/all";
install.StartInfo.CreateNoWindow = true;
install.StartInfo.RedirectStandardInput = true;
install.StartInfo.RedirectStandardOutput = true;
install.Start();

if (CB_MultiADB.Checked == true)
{
    install.StandardInput.WriteLine("FOR /F \"skip=1\" %%x IN ('adb devices') DO start cmd.exe @cmd /k" + InstallOption + InstallPfad + "\"");
}
else
{
    install.StandardInput.WriteLine("adb install" + InstallOption + InstallPfad + "\"");

    InstallAusgabe = install.StandardOutput.ReadToEnd();
    string Index = "adb install";
    int Indexnr = InstallAusgabe.IndexOf(Index);
    string SubInstall = InstallAusgabe.Substring(Indexnr, 100);
    TB_Ausgabe.Text = SubInstall;
}


Q: Register a Facebook user for an existing web app I have a Flex application that I would like to embed in a Facebook canvas. The app already runs on my website and is accessible there once the user has created an account. I am trying to work out the flow of integrating with Facebook:

*

*User accesses my app in Facebook;

*The app.facebook.com/myApp page loads;

*The Facebook SDk in myApp checks if the user is already logged into Facebook, and if not asks them to do so;

*Once I know the user is logged into Facebook myApp will redirect to my server which will check if the Facebook response.username already has an account.

*

*If the user does not have an account then I create one for them, log them in and redirect them back to the app page with a parameter hasAccount=true so that I know they do have an account. I then show them the app;

*If the user does have an account then I redirect them with hasAccount=true and show them the app.

Can anyone comment on that control-flow, is that normal or have I made it overly complicated?


Q: TFS Sub-area name change I would like to know if its possible to edit the name of a sub-area in TFS. I know I can create new areas and delete but I can't seem to find a way to rename. There might be implications around this that would keep someone from performing this task.

A: In TFS 2012, you should be able to go the same screen you create the areas and double click (or right click on select edit) on the area you want to rename. At that point, you should be able to modify the name accordingly.


Q: How to abort only the current git cherry-pick and not previous ones? I have cherry picked multiple commits by doing git cherry-pick -x <SHA> and one of them failed (due to conflicts). I haven't pushed anything to the branch yet and I just want to abort the last cherry pick alone (the failed one) and keep everything else. Should I simply do git push to my branch and checkout all the files to discard the changes? Is there a command to abort just this?
git status shows something like this:
# On branch bugs-br # You are currently cherry-picking.
#   (fix conflicts and run "git commit")
#
# Changes to be committed:
#
#       modified:  oper/svc/oper.cc
#
# Unmerged paths:
#   (use "git add <file>..." to mark resolution)
#
#       both modified:    oper/svc_thread.cc

A: The command git cherry-pick --abort will only abort the last cherry pick you started. Previous complete cherry-pick operations are already committed, so they will not be affected.
So that's all you need to do at this point.


Q: What is the probability that a unit disk centered at a random point $P$ has exactly two lattice points in its interior?
A point $P$ is chosen at random in the coordinate plane.  What is the probability that the unit disk with center $P$ contains exactly two lattice points in its interior?

In short I've been trying to wrap my head around this problem but I have not been able to produce anything of value. Below I provide my thinking:
In the Cartesian plane we'll use grid lines as reference points for our coordinate system (each integer is represented by the intersection of two grid lines).

As you can see in the image above (I just worked on first quadrant for sake of simplicity), we can achieve our scope if and only if the point $P$ lies exactly on any grid line but without being on any crossroads or exactly strictly below any vertical line or "strictly" to the left or right of any horizontal grid line.
(I know, I am abusing the meaning of the word "strictly".)

A: There is no uniform measure on the plane, so strictly speaking, one cannot make rigorous sense of choosing a random point in the plane. The number of points contained within the unit circle centered at a point $(x, y) \in \Bbb R^2$ is, however, invariant under adding integers to $x, y$, so it preserves the spirit of the problem to reformulate it as follows:

What is the probability $\color{#bf0000}{P_2}$ that the unit circle centered at a point in the unit square $[0, 1) \times [0, 1)$ (randomly chosen with uniform probability) contains exactly two lattice points?

(More symmetrically, one could ask this about a random point in the compact quotient $\Bbb R^2 / \Bbb Z^2$, which is just the torus.) Now, the unit circle centered at a point $P$ containing exactly two lattice points is equivalent to $P$ being with $1$ unit of exactly two lattice points. So, if we draw the unit square and the unit disks centered at the lattice points at the corners of the square, we see that the set of points in the square within $1$ unit of exactly two lattice points is precisely the red region in the following diagram:

Since the unit square has area $1$, the probability that a uniformly selected random point is in the red region is precisely the area of that region, and some elementary geometry gives that it is
$$\color{#bf0000}{\boxed{P_2 = 4 - \sqrt{3} - \frac{2 \pi}{3} \approx 0.174.}}$$
Similar, the probability that the unit circle centered at a point contains $3$ lattice points is
$$\color{#00bf00}{P_3 = -4 + 2 \sqrt{3} + \frac{\pi}{3} \approx 0.511,}$$
and the probability that the unit circle centered at a point contains $4$ lattice points is
$$\color{#0000bf}{P_4 = 1 - \sqrt{3} + \frac{\pi}{3} \approx 0.315.} .$$
This recovers, for example, that the expected number of lattice points is just $$2 \color{#bf0000}{P_2} + 3 \color{#00bf00}{P_3} + 4 \color{#0000bf}{P_4} = \pi .$$

A: Consider the square $x_0=(0,0)$, $x_1=(1,0)$, $x_2=(0,1)$ and $x_3=(1,1)$.
If $P$ lies in/on this square, the lattice points in the circle can only be one of the four points above.
So let $P = (a,b)$, then $x_i$ lies in the interior of the circle

*

*iff $d(P,x_i) < 1$

*iff $P$ lies in the interior of the circle around $x_i$.

As this problem is invariant under rotation by $90^\circ$, we can consider the case $x_0$ and $x_2$ and multiply by $4$ in the end.
If $x_0$ and $x_2$ do not lie in the circle around $P$, $P$ lies above the circles around $x_0$ and $x_1$, convince yourself that $x_2$ and $x_3$ then lie in the interior.
So we are interested in the point where $y=\sqrt{1-x^2}$ and $y=\sqrt{1-(x-1)^2}$ intersect, which is at $(x,y)=(\frac{1}{2},\frac{\sqrt{3}}{2})$, then the area we are interested in is
$$O = 1 - 2 \int_0^\frac{1}{2} \sqrt{1-x^2} \textrm{d}x = 1 -\frac{ \sqrt{3}} {4}- \frac{\pi}{6}.$$
Now multiply by four, convince yourself that the areas are mutually exclusive for two different pairs $x_i,x_j$ and $x_{i'},x_{j'}$ and that $x_1$ and $x_2$ cannot lie in the same circle.
Then the answer is $4-\sqrt{3} - \frac{2\pi}{3}$.
Please note that convincing yourself is easy by drawing the four unit circles all at once. Furthermore, you know have to translate this probability from one unit square to the infinite two-dimensional plane.


Q: TwentyFourteen Theme : Changing grid layout I have been plugging away making my new site and it is going great with only one issue so far.
How would I go about changing the featured posts grid so that instead of displaying 3 featured posts per row, it will display either two featured posts per row or four (either will work).
Any help on how to accomplish this would be amazing!
Thanks again!

A: Figured this out - had to change the container to hold image widths of 24.9% or 50% depending on layout, remove the clear from both post divs and stretch the .site width to 100%. From there I had either 4 horizontal images or two x two set-up. If anyone has any questions about this feel free to ask.


Q: VBA: Replace text from txt for each line and save as Could somebody help me with the following? I tried making it on my own, but all I could do is open a txt and replace a static word with static word.
VBA script:
Open and Read first line of ThisVbaPath.WordsToUse.txt
Open and Find USER_INPUT in ThisVbaPath.BaseDoc.docx (or txt)
Replace all occurrence of USER_INPUT with first line from WordsToUse.txt
Save BaseDoc.docx as BaseDoc&First_Line.docx
Close all
Go next line and do same, but don't ask for user input, use previous one
If error go next
When done show if there were any errors (unlikely I guess)
I would use it about weekly for 150-ish lines.
Thanks!

A: I think something like this should work?
Sub test()

  Dim text, textReplace, findMe As String

  findMe = InputBox("What Text To Find?")
  Open "C:\Excel Scripts\test.txt" For Input As #1
  Open "C:\Excel Scripts\test2.txt" For Input As #2
  Open "C:\Excel Scripts\output.txt" For Output As #3

  While Not EOF(1)
    Line Input #1, text
      While Not EOF(2)
        Line Input #2, textReplace
        Write #3, Replace(text, findMe, textReplace)
      Wend
  Wend

  Close #1
  Close #2
  Close #3

End Sub

A: Sub TextFile_FindReplace()
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String

FilePath = Application.ActiveWorkbook.Path & "\NEWTEST.txt"
TextFile = FreeFile
Open FilePath For Input As TextFile
FileContent = Input(LOF(TextFile), TextFile)

FileContent = Replace(FileContent, "FOO", "BAR")

Print #TextFile, FileContent
Close TextFile
End Sub


Q: Number of bijections from a finite set to itself We claim that a set $A$ with $n$ elements has $n!$ bijections from $A$ to itself.
Let $A = \{a_1,\ldots,a_n\}$ be a set. We will show that there are $n!$ bijections from $A$ to itself.
For $a_1,$ we can map it to any of $a_1,\ldots,a_n$ which gives us $n$ choices for the image of $a_1$. Suppose, without loss of generality, $a_1$ is mapped to $a_n$. Now, we consider $a_2$, which can be mapped to any of $a_1,\ldots,a_{n-1}$ owing to the fact that the map is injective. This gives us $n-1$ choices.
Continuing in this fashion, we have that the number of choices keeps decreasing by 1 and as $A$ is a finite set, this process must terminate. We have
$$n(n-1)(n-2)\dots(1) = n!$$
choices in total. These are the number of bijective maps and we are done.
While I think that my argument is correct, I am not sure whether my proof is rigorous or complete. Please see if this is correct and suggest a better way to write the same.


Q: Display an overlay when submitting a form I want to display an overlay when the user is submitting a form. I'm using $('form').submit(function { [...] }) to achieve this.
The problem is that I'm using client-side validation. The immediate solution is of course to manually validate the form: if ($('form').validate().valid()) { .. }
The ultimate solution would be to hook onto some event which is invoked when the POST is made.  (To support any other plugins that might prevent the form from submitting and when the validation plugin is not used.)

A: Assuming you're using jQuery validate, you can use the submitHandler property to run code when the validation passes, for example:
$("#myForm").validate({
    submitHandler: function(form) {
        // display overlay

        form.submit();
    }
});

Further reading

A: Try to return false; on validation errors while submiting.


Q: mysql utf8 turkish characters not correct recognized In mysql utf8 coded turkish data i can't search "İ" and "ı". when i search its giving result contains "Y" or "y". Because in latin1 "İ" displaying as "Ý" and "ı" as "ý".
in latin1 data i was used latin1_general_ci for correct result. but there is not alternative collation for utf8. its already utf8_general_ci.
is there any other people have some problems or do you have a solution.
thanks.
i have tried stackoverflow search engine to for this problem. if its have mysql and utf8 then my work true. try search "alİ" and "ali". both search give another result. but both same in turkish. the "İ" is capital i and capital "I" is "ı" in turkish.
there is a solution but not fully.
i you use utf8_turkish_ci then the result give "İ" but also "Y".

A: the problem is temporary solved. i you use all collations uf8_turkish_ci you can get correct result. but i am wondering why i have to use turkish_ci.
try collate all columns utf8_turkish_ci, tables utf8_turkish_ci, and database too.
good luck


Q: Does Facebook allow CORS headers? How can I discover if Facebook allowes cross domain requests? Can I make a JavaScript which can handle a Cross Domain Request to Facebook?

A: Are you talking about the Facebook API? Anyway:
http://www.test-cors.org


Q: How to bulk load JSON with values into Synapse SQL dedicated pool I'm attempting to bulk load json files, along with their filenames and paths into a synapse analytics dedicated sql table but I'm just stumped on how to accomplish it. I can load the json files solo without a problem, but I really need the additional values as well.
This is what I'm trying but it doesn't work:
Copy INTO dbo.PolicyStagingJsonOnly
SELECT  jsonContent,
        [result].filename() as fn,
        [result].filepath() as fp
FROM
    OPENROWSET(
        BULK 'https://datalakexxxx.blob.core.windows.net/staging/policy/*.json',
        FORMAT = 'CSV',
        FIELDQUOTE = '0x0b',
        FIELDTERMINATOR ='0x0b',
        rowterminator = '0x0c'
    )
    WITH (
        jsonContent varchar(MAX)
    ) AS [result]


Q: How to install TCPDF lib without composer in Magento 2? Followed these steps:

*

*Download TCPDF from https://github.com/tecnickcom/tcpdf

*Change the name of the file root directory after extraction to TCPDF

*Inside this directory, there is a tcpdf.php file, change the name to TCPDF

*Open the file and change the class name from tcpdf to TCPDF_TCPDF

*Copy the files into your Magento “lib” folder in the root Magento installation directory. i.e lib/TCPDF
And can be called this class by $tcpdf = new TCPDF_TCPDF() from anywhere in Magento. Here is Source
But this is not working!!
Getting Error like: Fatal error:

Class 'Vendor\Module\Controller\Adminhtml\Generatepdf\TCPDF_TCPDF' not
  found in
  E:\Xampp\htdocs\magento\app\code\Vendor\Module\Controller\Adminhtml\Generatepdf\CreatePdf.php
  on line 35

Installation with composer works fine and I get PDF generated! But I have to send this complete package and cannot ask client to run composer command for this module.I think autoloader is not getting aware of this library. How can I integrate it?
This is my class:
<?php

namespace Vendor\Module\Controller\Adminhtml\Generatepdf;

use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;

class CreatePdf extends \Magento\Backend\App\Action  {

protected $_dir;
protected $customerName;
protected $order;
public function __construct(
    Context $context,
    Order $order,
    DirectoryList $dir

)
{
    $this->order = $order;
    $this->_dir = $dir;

    parent::__construct($context);
}

public function execute() {

     $tcpdf = new TCPDF_TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    //$tcpdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $tcpdf->SetCreator(PDF_CREATOR);

    $tcpdf->SetTitle('Title');

    $tcpdf->setPrintHeader(false);

    $tcpdf->setPrintFooter(false);

    // set default monospaced font

    $tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    // set margins

    $tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

    $tcpdf->SetHeaderMargin(PDF_MARGIN_HEADER);

    $tcpdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    // set auto page breaks

    $tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    // set image scale factor

    $tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    // set some language-dependent strings (optional)

    if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {

        require_once(dirname(__FILE__) . '/lang/eng.php');

        $tcpdf->setLanguageArray($l);

    }

    // ---------------------------------------------------------

    // set default font subsetting mode

    $tcpdf->setFontSubsetting(true);

    //your htmls here

    $html=$this->getHtml();

    // set some language dependent data:

    $lg = Array();

    $lg['a_meta_charset'] = 'UTF-8';

    $tcpdf->setLanguageArray($lg);

    // set font

    //dejavusans & freesans For Indian Rupees symbol

    $tcpdf->SetFont('freesans', '', 12);

    // remove default header/footer

    //$tcpdf->setPrintHeader(false);

    $tcpdf->setPrintFooter(false);

    $tcpdf->AddPage();

    $tcpdf->writeHTML($html, true, false, true, false, '');

    $tcpdf->lastPage();

    //$tcpdf->Output('report_per_route.pdf', 'I');

    //$this->logger->debug('report_per_route');
    $baseurl = $this->getDirPath();
    $filename = $baseurl .'/export/'. 'Sample_pdf'. time().'.pdf';
    $tcpdf->Output($filename, 'I');
}

}
?>

A: Here is the successfully tested way to do this:

*

*Download TCPDF from https://github.com/tecnickcom/tcpdf

*Change the name of the file root directory after extraction to TCPDF

*Inside this directory, there is a tcpdf.php file, change the name to TCPDF

*Open the file and change the class name from tcpdf to TCPDF_TCPDF

*Copy the files into your Magento “lib/internal” folder in the root Magento installation directory.
=>So it should look like this: lib/internal/TCPDF
Now, write below statement in the class where you want to make tcpdf object:
require_once('lib/internal/TCPDF/TCPDF.php');

And use this class as:
$tcpdf = new \TCPDF_TCPDF();

Example Code is:
<?php

namespace Vendor\Module\Controller\Adminhtml\Generatepdf;

use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;

require_once('lib/internal/TCPDF/TCPDF.php');

class CreatePdf extends \Magento\Backend\App\Action  {

protected $_dir;
protected $customerName;
protected $order;
public function __construct(
Context $context,
Order $order,
DirectoryList $dir

)
{
$this->order = $order;
$this->_dir = $dir;

parent::__construct($context);
}

public function execute() {

$tcpdf = new \TCPDF_TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$tcpdf->SetCreator(PDF_CREATOR);

$tcpdf->SetTitle('Title');

$tcpdf->setPrintHeader(false);

$tcpdf->setPrintFooter(false);

// set default monospaced font

$tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins

$tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

$tcpdf->SetHeaderMargin(PDF_MARGIN_HEADER);

$tcpdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks

$tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor

$tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)

if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {

    require_once(dirname(__FILE__) . '/lang/eng.php');

    $tcpdf->setLanguageArray($l);

}

// ---------------------------------------------------------

// set default font subsetting mode

$tcpdf->setFontSubsetting(true);

//your htmls here

$html=$this->getHtml();

// set some language dependent data:

$lg = Array();

$lg['a_meta_charset'] = 'UTF-8';

$tcpdf->setLanguageArray($lg);

// set font

//dejavusans & freesans For Indian Rupees symbol

$tcpdf->SetFont('freesans', '', 12);

// remove default header/footer

//$tcpdf->setPrintHeader(false);

$tcpdf->setPrintFooter(false);

$tcpdf->AddPage();

$tcpdf->writeHTML($html, true, false, true, false, '');

$tcpdf->lastPage();

//$tcpdf->Output('report_per_route.pdf', 'I');

//$this->logger->debug('report_per_route');
$baseurl = $this->getDirPath();
$filename = $baseurl .'/export/'. 'Sample_pdf'. time().'.pdf';
$tcpdf->Output($filename, 'I');
}

}
?>

Happy coding :)


Q: How to check for bounced emails in rails? I'm currently creating an email app that is able to send emails to many users. However, I want to know whether there are bounced emails. I'm currently using Amazon SES to notify me if the email is bounced. However, I want the bounced email's data to be automatically entered into my Rails application instead of typing it manually based to the mailer daemons I get from Amazon. Is there are way to do so?

A: If you are willing to pay, this SaaS site called bouncely seems to provide an interface and an api wrapper around SES bounces.

A: send_email() returns a response object which can be interrogated for the response metadata.
Compare the status of this with the code you are interested in, perhaps a 550.

A: I couldn't find any clean existing solution for this, so I wrote a gem (email_events) that allows you to put a email event handler method (including for bounce events) right in your mailer class:  https://github.com/85x14/email_events.  It supports SES and Sendgrid, so should work for you if you still need it.


Q: Sql view from multiple tables I am stuck in a query, please help.
I want to create view.
Table1
ID | Acode | Bcode | Ccode |
1  | 10    | 101   | 102   |
2  | 11    | 100   | 101   |
3  | 10    | 100   | 102   |

Table2
Acode | Adescription |
10    | English      |
11    | Math         |

Table3
Bcode | Bdescription |
100   | Grade A      |
101   | Grade B      |

Table4
Ccode | Cdescription |
 100  | Level A      |
 101  | Level B      |
 102  | Level C      |

I want to print all rows in Table1 with description from other tables based on code in table1.
Output should be:
data
NewView
ID | Acode |Adescription | Bcode | Bdescription | Ccode | Cdescription |
1  | 10    | English     | 101   |   Grade B    |  102  |   Level C    |
2  | 11    | Math        | 100   |   Grade A    |  101  |   Level B    |

    3  | 10    | English     | 100   |   Grade A    |  102  |   Level C    |
I created left join but it returns more rows than actual in table1. I want to have only all records from table1 with description from other tables.
Please help

A: Below is an example.  Since you didn't post your original query attempt, we can't really say why you were getting multiple rows.  No need for a LEFT JOIN unless you are missing codes in the joined tables.
SELECT  Table1.ID
      , Table1.Acode
      , Table2.Adescription
      , Table1.Bcode
      , Table3.Bdescription
      , Table1.Ccode
      , Table4.Cdescription
FROM    dbo.Table1
        JOIN dbo.Table2 ON Table2.Acode = Table1.Acode
        JOIN dbo.Table3 ON Table3.Bcode = Table1.Bcode
        JOIN dbo.Table4 ON Table4.Ccode = Table1.Ccode;

A: Thanks for help
LEFT Join worked well. I tried to narrow down the tables one by one and found the table where I was getting duplicate records. After finding table I found that I forgot to add Unique key and 1 record (Description) was entered twice which was giving duplicate records and total number of rows were increased.
Thanks all to help me out,and Dan Guzman to point me for duplicate codes.


Q: How to get artist and title information using python-vlc? I'm trying to record and get song information (title and artist) from web radios using python-vlc lib.
The recording functionality is working well but the media parse to get the song information doesn't work!
This is my code:
inst = vlc.Instance() # Create a VLC instance

p = inst.media_player_new() # Create a player instance
cmd1 = "sout=file/ts:%s" % outfile
media = inst.media_new("http://playerservices.streamtheworld.com/api/livestream-redirect/JBFMAAC1.aac", cmd1)
media.get_mrl()

p.set_media(media)
p.play()

media.parse()

for i in range(13):
    print("{} - {}".format(i, media.get_meta(i)))

It's always returning "MediaParsedStatus.skipped" status. And all song information returns "None". I tested the same radio in VLC App and there it works fine.
Anyone can help me?
thanks in advance

A: Since this is a stream, libvlc will not parse it by default (only local files).
You need to use a flag to tell libvlc to parse the media even if it is a network stream.
Use libvlc_media_parse_with_options with MediaParseFlag set to network (1).


Q: badimageformatexception dynamic code generation I'm trying to dynamically generate an executable with the CSharpCodeProvider whose only purpose is to invoke one single method from a specific dll. When I execute the generated file I get a BadImageFormatException.
I already set the platform to x86. When I manually write the code which invokes the method and debug it in Visual Studio, it works perfectly fine.
This is the code for the executable:
using DLLName;

namespace ExampleNamespace
{
    class Program
    {
        public static void Main(string[] args)
        {
            MyClass obj = new MyClass();
            obj.MyMethod();
        }
    }
}

Before dynamically compiling the code I add the assembly via
compilerParameters.ReferencedAssemblies.Add("PathToDLL");

I write the executable to the same directory as the dll.
EDIT
This is the code that I use to invoke the compiler:
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();

parameters.GenerateExecutable = true;
parameters.GenerateInMemory = false;
parameters.OutputAssembly = @"DirectoryOfDLL\MyMethod.exe";
parameters.ReferencedAssemblies.Add("PathToDLL");

provider.CompileAssemblyFromSource(parameters, code);


Q: Distinguish swipe and click in Angular I use ng-click to show details of an item in a list and also I attach jQuery mobile swipe event to the list item to show delete button when a user swipes to the left.
The problem is that when I swipe on the element, it doesn't only emit swipe event, but click event as well. So, when I want to swipe to delete an element, it shows the delete button and opens details view.
What can I do about this? It would be cool to have something like ng-swipe.

A: The most recent unstable angularjs (1.1.4+) builds include both an ngSwipeLeft and ngSwipeRight directive. You must take care to reference the angular-mobile.js library.
https://github.com/angular/angular.js/blob/master/src/ngMobile/directive/ngSwipe.js


Q: iOS - How to set nil in UITextField (It should be visible) I know this is tricky question.
Is there any way to visible nil value in UITextField?
I tried with this code but TextField showing blank.
myTextField.text = nil;

For this task we can't use  myTextField.text = @"nil"; (Without using @"nil" I need to complete this task)
But It should be look like.

A: Your requirement isn't valid. The only way to get the text nil to appear in the text field is to assign the actual text @"nil" to the text field.
It makes no sense that you to see nil without using @"nil" to do so.
Perhaps setting the placeholder to @"nil" is a compromise.

A: i think you can use only myTextField.text = @"nil"; or instead of showing nil you can show proper message inside uitextfield or bellow textfiled input is not valid. showing nil is doesn't helps to user. you can use alert to show no input.

A: As others have said, this seems like a strange requirement, but you could create a subclass of UITextField that overrides the getter of the text property so that it returns @"nil" if text was actually nil.

A: Try This self.textFieldName.placeholder  = @"nil";


Q: MacOS Application Reopens After the User Quits I have an app on the Mac App Store and over the last few weeks some people have complained that when they quit the app, it will reopen again.
Since the app is sandboxed, it should be technically impossible for my app to reopen itself (even if I want it to) after the user choose to quit it. So, I have no clue what went wrong and I can't reproduce this issue.
Any ideas?

A: We figured out what went wrong and how to fix it.
First off, since the app is sandboxed it's technically impossible that we caused this with our code. However, according to a user, there was a plist file (named after our app) in the LauchAgents directory that caused the restarting of our app. After deleting that file, everything was fine again. As to why this entry existed in the first place and how it got there:   ¯\ _(ツ)_/¯
Hope this helps anyone who has the same problem.

A: We haven't seen this exact issue, but something similar where we overrode the - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender method.
And in certain circumstances we were returning NSTerminateLater or 'NSTerminateCancelinstead ofNSTerminateNow`. In turn, the application would continue running even after the user told us to quit.


Q: Make nested API call to fetch all list In my scenario, I've got an API call to hit and on the response of the API, I've to call the final API to get records of list.
From the first API, I'll get a flag on which I've to make the conditional API call to get the records.
The problem is, GET_LIST gets called by react-admin and in that, I cannot handle two asynchronous API call.
I tried with Query and custom DataSource.
This is the API type called by the react-admin to fetch list.
GET_LIST: {
      request(params: GetListParams): Ticket {
        return {
          method: 'GET',
          url: `${base}/q`,
          headers: makeHeaders(token),
          query: mapQueryParams(params, universalFilters)
        }
      },

      response(res: Object): {total: number, data: Array<Contact>} {
        const {hits, rows} = res
        return {
          total: hits,
          data: rows.map(row => {
            return {...row, id: getId(row)}
          })
        }
      }
    },

This is the component that is called for the list.
export const ContactList = (props) => {
  return (
    <List {...props} filters={<Search />} bulkActionButtons={<PostBulkActions />}>
      <Datagrid className="data-grid">
        <GravatarField source="email" label="" sortable={false} />

        <LinkField
          source="first"
          label="First Name"
          text={ ({first}) => first }
          deriveUrl={ ({id}) => `/#/contacts/${id}` }
          target='' />

        <LinkField
          source="last"
          label="Last Name"
          text={ ({last}) => last || '(unknown name)' }
          deriveUrl={ ({id}) => `/#/contacts/${id}` }
          target='' />

        <DateField source="lastActivity" />
        <TextField source="email" />
        <PhoneNumberField source="primaryPhone" label="Phone" sortable={false} />
        <MultiTagField source="tags" sortable={false} deletable={false} />
        {/* <DeleteButton /> */}
      </Datagrid>
    </List>
  )
}

A: From what I understand about your code, this should be the job of your dataprovider. As it should return a promise, you can make the two api calls in it and resolve only after you get the second call response


Q: "The SQL statement is not valid. There are no columns detected in the statement" I am merging data from one file that contains six different sheets or tabs. All sheets contain the same headers. For the task I am using PowerPivot.
1st I created a connection using Excel and selected the file/imported Sheet1
2nd I activated my PowerPivot > Design > Existing Connections
3rd Table properties Table Name [Sheet1] > Switch to [Query Editor]
Here's my SQL that resulted the error in the title:
  Select [Sheet1$].* From [Sheet1$]
  UNION ALL
  Select [Sheet2$].* FROM `C:\_TEST\HG.xlsx`.[Shee2$]
  UNION ALL
  Select [Sheet3$].* FROM `C:\_TEST\HG.xlsx`.[Shee3$]
  UNION ALL
  Select [Sheet4$].* FROM `C:\_TEST\HG.xlsx`.[Shee4$]
  UNION ALL
  Select [Sheet5$].* FROM `C:\_TEST\HG.xlsx`.[Shee5$]
  UNION ALL
  Select [Sheet6$].* FROM `C:\_TEST\HG.xlsx`.[Shee6$]

When I validated the statement had the error:

The SQL statement is not valid. There are no columns detected in the statement.

A: To answer and share how I resolved my question I found that when I created the connection I can still select sheets 2 to 6 in the dropdown from existing connections. So I tried this code .........and resolved the error :).
 Select [Sheet1$].* From [Sheet1$]
  UNION ALL
  Select [Sheet2$].* FROM [Shee2$]
  UNION ALL
  Select [Sheet3$].* FROM [Shee3$]
  UNION ALL
  Select [Sheet4$].* FROM [Shee4$]
  UNION ALL
  Select [Sheet5$].* FROM [Shee5$]
  UNION ALL
  Select [Sheet6$].* FROM [Shee6$]


Q: Other processes than formal power series expansions in quantum field theory calculations I am not sure if this question is too naive for this site, but here it goes. In QFT calculations, it seems that everything is rooted in formal power series expansions, i.e. , what dynamical systems people would call Lindstedt series. However, from what I heard, this series (for QFT case) is known to have zero radius of convergence, and it causes tons of difficulties in theory. My question is, are there approaches that start with an iterative process that has a better chance of converging (e.g., a fixed point iteration), and build computational methods for QFT from there?
In other words, when there are so many approaches to approximate the exact solution of, say nonlinear wave (and Klein-Gordon, Yang-Mills-Higgs-Dirac etc) equations on the classical level, why do we choose, when we quantize, only a couple of approaches, such as power series, and lattice regularization (the latter essentially a finite difference method)? Note that it is milder than making QFT completely rigorous, it is just about computing things a bit differently.

A: Are you essentially asking about non-perturbative approaches to QFT?
Lattice QCD (based on Monte-Carlo sampling) and various strong-couplig/weak-coupling dualities (like AdS/CFT) come to mind as most prominent examples.
This is more of a hint than a real answer, of course.

A: I think you will save yourself considerable time by looking at a reference like:
N. Nagaosa QFT in Condensed Matter Physics, pg 78, section 3.4.  From a computational perspective "Lattice Gauge Theory and the Confinement Problem" will explain to you why physicists, when they are interested in introducing a cutoff, in energy or length etc, will need to address how many of the infinite degrees of freedom from the original Hamiltonian remain intact locally on the lattice.  In doing so you learn that modeling fermions can become problematic.  It's a quick read and might help you polish your question with a minimal time investment.

A: In some sense, i understand this question of yours as regarding to more "mathematically precise" approaches to QFT: in the end of the day, your question implies "non-perturbative definitions of QFT" in a form or another — afterall, if you can use some other tool, why not turn the problem around and define your theory based on how you can use such tool?
Along those lines, there's quite a lot to be said, given that there are a few different ways to define a QFT (with different levels of "mathematical rigor"):

*

*Axiomatic QFT, Constructive QFT, Algebraic QFT, and Local Quantum Physics (à la Haag);

*Functional Integration (à la Feynman Path Integrals; White Noise Calculus; etc) and approximating expansions (which is where your question seems to be more naturally formulated);

*Vertex Algebras (VOAs, Borcherds Algebras) and CFTs;

*More probabilistic approaches, eg, Schramm-Loewner equation;

*Chiral and factorization algebras;

*TFTs and higher category theory;

*etc.

So, the use of series expansions is but one of these efforts — and, along those lines, there are other series that are relevant, eg, Large-N expansions.
On the other hand, having said the above, it is true that there are other methods that could have something to add to the usual way that things are done — giving voice to your concern. For example, there are ways to discretize space that are "compatible" with differential geometric objects (such as $n$-forms and so on; largely under the name of "Discrete Differential Geometry" or "Geometric Discretization") which could be used in lattice formulations of QFT and are currently not. Also, there are all sorts of different "finite difference schemes" of discretization, keeping different symmetries of the original problem (diff eq), that could be used to illuminate certain properties of the theory, but a discussion of this issue does not seem to feature in the lattice community.
Thus, in the end of the day, Olaf has a point: if you've got suggestions, by all means, put them forth! ;-)

A: Lack of convergence does not mean there is nothing mathematically rigorous one can extract
from perturbation theory. One can use Borel summation. In fact, Borel summability of perturbation theory has been proved for some QFTs:

*

*by Eckmann-Magnen-Seneor for $P(\phi)$ theories in 2d, see this article.

*by Magnen-Seneor for $\phi^4$ in 3d, see this article.

*by Feldman-Magnen-Rivasseau-Seneor for Gross-Neveu in 2d, see this article.

In fact these articles obtain such results by using an alternative to ordinary perturbation theory called a multiscale (or phase cell or phase space) cluster expansion.
The latter is based on combinatorial structures which mimic Feynman diagrams. However, these expansions converge at small coupling.
Edit as per Timur's comment: Glimm and Jaffe's book is what you want to read in order to understand why one needs cluster expansions. It is excellent at giving the big picture: how axiomatic, Euclidean, constructive QFTs fit together, as well as with scattering theory. But for learning how to do a cluster expansion the book is outdated.
The cluster expansion explained in GJ is the early one invented by Glimm, Jaffe and Spencer in their Annals of Math article. It was the first in the QFT context and as such
quite a mathematical feat. However there has been many improvements and simplifications since then (around 1973). If you want to learn about cluster expansions in 2011, here is a more efficient path:

*

*Learn about the Mayer expansion for the polymer gas: a quick intro is in the "Additional material" at the bottom of my course webpage.

*Learn about the single scale cluster expansion, i.e., controlling the infinite volume limit when both UV and IR cut-offs are present: look at the article "Clustering bounds on n-point correlations for unbounded spin systems" on the same webpage. For a more cleaned up version see the published version, but this is not freely accessible.

*Finally the real McCoy: the multiscale cluster expansion where one tries to do all of the above and remove the cut-offs. This is somewhat like an infinite volume limit in phase space. Here there is no easy reference. All accounts of the subject are extremely difficult to read. I plan to write a pedagogical article on this in the next
few months. In the meantime you could try the following: the book by Rivasseau "From Perturbative to Constructive Renormalization", the book "Wavelets and Renormalization" by Battle, and also this recent article by Unterberger (in French).

A: I think you raise a very important question, but I think you make it sound more trivial than it is. The point is: a lot of physicists would like to have alternative expansions, but it is very difficult to come up with one. If you've got some suggestions, don't hesitate to put it forward.
The standard expansion starts from the time evolution operator $\mathcal{U}(t,t_0)$ and a Hamiltonian $\hat{H}$, which together form the Schroedinger equation:
$$ -i\partial_t \mathcal{U} = \hat{H}\mathcal{U}$$
Integrating this gives,
$$ \mathcal{U}(t,t_0) =  1 - i\int_{t_0}^t dt_1 \hat{H}(t_1)\mathcal{U}(t_1,t_0)$$
and by iterating, i.e. substituing this expression for $\mathcal{U}$ on the right hand side, you can come up with a formal power series for $\mathcal{U}$ called Dyson's series. You can modify it in some ways, like splitting the Hamiltonian into a solvable and perturbative part, and correspondingly for the time evolution operators. In the end you'll end up with expressing correlation functions that you want in terms of a series of correlation functions of some model that you know. And it's natural for this series to be an expansion in terms of the coupling constant of the perturbative part.
So can you get around this expansion? Well, sometimes there are some non-perturbative approaches available. You have, for instance, the realm of exactly solvable models. These rely on the presence of severe symmetry constraints. Examples are certain 2D conformal field theories, in which correlation functions satisfy differential equations. These equations arise due to restriction on the operator algebra (the presence of so-called null-states) and Ward identities associated with the symmetry algebra, which includes the conformal structure. Powerful stuff.
Other examples are the Bethe ansatz and the algebraic Bethe ansatz. As far as I understand these models are based on constructing a full set of eigenstates in some Hilbert space + extension, without an explicit reference to the Hamiltonian (meaning the Hamiltonian is subject to some restrictions, but need not be explicitly known). This is a very powerful technique and valid for the entire range of the coupling constant. But requiring integrability can be quite a constraint.
AdS/CFT was also mentioned, which is a marvellous weak/strong coupling duality. This makes use of the idea that correlation functions are the same for two seemingly different theories, which differ in dimensionality and the presence of gravity. Lattice regularization works also quite well, as far as I know.
An alternative expansion to Dyson's series which comes to mind is the Magnus expansion (see also here). The biggest advantage to this expansion is that it stays unitary once you cut the series off somewhere. But is it a strong alternative..?
My view on the matter is that a new expansion or approach could very well be the next best thing since sliced bread.


Q: Pandas boolean dataframe search returns False but should be True The Problem
I'm attempting to search through a pandas dataframe to find a single value. The dataframe columns I'm searching through are of type float64.
Working Example
Here is a working example of what I'd like, with a dataframe of type int64.
myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
myseries

The output is the following:
0    1
1    4
2    0
3    7
4    5
dtype: int64

Now for the search:
myseries == 4

Results:
0    False
1     True
2    False
3    False
4    False
dtype: bool

Not Working Example
Here is a sample of my data.
df['difference']

Result
0    -2.979296
1    -0.423903
2     0.396515
...
48    0.450493
49   -1.216324
Name: priceDiff1, dtype: float64

As you can see, it is of type float64.
Now here's the issue. If I copy the value on row 2, and create a conditional statement like before, it doesn't return the True.
df['difference'] == 0.396515

Output
0     False
1     False
2     False
...
48    False
49    False
Name: priceDiff1, dtype: bool

Row 2 should be True.
Any assistance at this issue with this issue would be great.
What I believe is happening, is that my query isn't setting the type to float64 and might be assuming it's a different type. I've tested this by downcasting the column type from float64 to float32, with no luck.

A: You want to use Numpy's isclose
np.isclose(s, 0.396515)

array([False, False,  True, False, False, False], dtype=bool)

A: Your python series stores, or points to, numeric data represented as floats, not decimals.
Here is a trivial example:-
import pandas as pd

s = pd.Series([1/3, 1/7, 2, 1/11, 1/3])

# 0    0.333333
# 1    0.142857
# 2    2.000000
# 3    0.090909
# 4    0.333333
# dtype: float64

s.iloc[0] == 0.333333  # False
s.iloc[0] == 1/3       # True

As @piRSquared explains, use np.isclose for such comparisons. Or, alternatively, round your data to a fixed number of decimal places.


Q: Parametric equation for a curve $C_1$ in $\mathbb{R}^3$ such that the angle of its tangent $T$ and the $Y axis$ equals the angle of $T$ and a vector I know that to find the angle between two curves in $\mathbb{R}^3$ at their intersection I differentiate both curves and evaluate at the intersection to find the slope of each tangent line and then do all the dot-product, cross-product, arccosine shenanigans.
But let's say I have some curve $C_1$ on the surface of a cylinder $x^2+y^2=a^2$. I want the parametric equation of $C_1$ such that the angle between the tangent of $C_1$ and the $Y axis$ at any point $P$ of $C_1$ is equal to the angle between the tangent of $C_1$ and a vector $\vec{u}$ starting at the base $(0,0,0)$ of the cylinder and passing through $P$.
I thought of writing both the $Y axis$ and $\vec{u}$ as parametric curves and making it so that both said angles are equal, but I don't know if this makes sense, and even if it did, I don't know how to proceed exactly and find the parametric equation of $C_1$ such that this condition is true for all points of $C_1$.

A: The parametric equations that constrain the curve to the cylinder would just be $t \mapsto \mathbb{R}^2: \langle a\cdot cos(\phi(t)), a\cdot sin(\phi(t))\rangle$.  Then $z(t)$ can be any function:
$$
\vec{C}_1(t) = \left\langle a \cdot cos(\phi(t)), a \cdot sin(\phi(t)), z(t) \right\rangle \\
\frac{d\vec{C}_1}{dt} = \left \langle-a\dot{\phi}sin(\phi), a\dot{\phi} cos(\phi), \dot{z}\right\rangle
$$
Now, we should set the $cos(\theta)$ of the two angles equal.  I would do that by finding the dot product, dividing by the two magnitudes, then setting those two equal.  The dot products are fairly easy to find, but we also need the magnitudes of the vectors (we'll just use $\langle 0, 1, 0 \rangle$ for the y-axis since that already has magnitude $1$:
$$
||\vec{u}|| = ||\vec{C}_1|| = \sqrt{a^2 + z^2} \\
\left|\left|\frac{d\vec{C}_1}{dt}\right|\right| = \sqrt{a^2\dot{\phi}^2 + \dot{z}^2} \\
\frac{d\vec{C}_1}{dt}\circ \hat{y} = a\dot{\phi}cos(\phi) \\
\frac{d\vec{C}_1}{dt}\circ \vec{u} = a^2\dot{\phi}\left(cos(\phi)sin(\phi) - sin(\phi)cos(\phi)\right) + \dot{z}z = z\dot{z}
$$
Now divide by the magnitudes and set them equal (and pray):
$$
\frac{a\dot{\phi}cos(\phi)}{\sqrt{a^2\dot{\phi}^2 + \dot{z}^2}} = \frac{z\dot{z}}{\sqrt{a^2\dot{\phi}^2 + \dot{z}^2}\sqrt{a^2 + z^2}}
$$
This gives the following differential equation:
$$
\sqrt{a^2 + z^2}a\dot{\phi}cos(\phi) = z\dot{z}
$$
So this looks bad, but one thing we can reason right away is that we really want a function $\phi(z)$, then we can simply say $z(t) = t$ and this should give the same curve (we can parameterize it any an infinite number of different ways--this is one particular way).  If we make this substitution then we may be able to integrate to find $\phi(z)$ (note I'm not going to change much here because I'm really saying that I have $\phi(t)$ and $z(t) = t$ so that $\dot{z} = 1$):
$$
\sqrt{a^2 + t^2}acos(\phi)\frac{d\phi}{dt} = t \\
\int \left(a cos(\phi)d\phi = \frac{t}{\sqrt{a^2 + t^2}}dt \right)\\
asin(\phi) = \sqrt{a^2 + t^2} + C
$$
Do you like inverse sines?  I don't, so instead let's just find $t(\phi)$ (which is really $z(\phi)$:
$$
t^2 = \left(a\cdot sin(\phi) - C\right)^2 - a^2 \\
t(\phi) = \sqrt{\left(a\cdot sin(\phi) - C\right)^2 - a^2}
$$
This finally gives a parameterization:
$$
\vec{C}_1(t) = \left\langle a\cdot cos(t), a\cdot sin(t), \sqrt{\left(a\cdot sin(t) - C\right)^2 - a^2}\right\rangle
$$


Q: "I always hate that" Is I always hate that grammatically correct? Is it a common phrase? For example,

You're always taking pictures of everything. I always hate that.

A: Yes, it means "that always annoys me". It's common enough.
Verbs like "like", "hate", "prefer" are usually what are termed stative verbs: they are usde to express a "general, ongoing truth" rather than something that is true at a particular, clearly-defined time. Some verbs can have stative and non-stative uses:

He speaks French. (Stative)
He speaks at the French Assembly
tomorrow. (Non-stative)

Verbs like "hate" are more readily stative. So in the following case, the first sentence seems a bit more usual than the second (to understand the simple present tense forms, we're using them as a "historic present" to describe actions that actually happened in the past in this case):

At four o'clock, he decides to leave the office.
?At four o'clock, he hates what he is doing and decides to leave the office.

On the other hand, such uses aren't absolutely impossible. Many essentially stative verbs like "hate", as in the last example, can be "just about" forced into a non-stative interpretation in the right context. And this is what we witness in "I always hate it when...". Other examples:

How are you liking your new job this time?
Why are you so sarcastic with him every time he expreses his opinion?
He saw the bloody knife in the drawer. At that very moment he knew what had happened.

A: I can see how "always" and "hate" may be partially redundant. "Hate" in the present tense can have a perpetual or longer than fleeting connotation to it (a person's hates or loves generally do not change overnight), so to an extent adding "always" to the statement could be redundant.
In contrast, if it were worded "I have always hated that.", then the use of "always" with "have hated" has no redundancy to it, in my mind, because "have hated" would imply a terminus if without "always".
Is the original statement grammatically correct? Yes. Is it common? Yes, I believe so. Is it logical or consistent in construction? Not perfectly (unless you view it simply as an expression).

A: Apparently an edit brought this back to the top of the stack from 10 months ago, but as long as it's here, a passing thought ...
The question brings up some fairly subtle nuances.
If you said, "You're taking pictures. I hate that", without either "always", there could be an ambiguity: Do you hate that this person takes pictures in general, or do you only hate it today, perhaps because of some special circumstances? But, "You're taking pictures. I always hate that," makes clear that you have a general objection to his picture taking.
It is, of course, possible for someone to hate something at one time and not at another. It would be quite reasonable for someone to say, "I use to hate jogging, but I've come to like it." Or, "I hate living in this town in the winter", implying that you are satisfied with it at other times of year.
Alternatively, "always" could be used with "hate" for emphasis rather than in a strictly literal sense. "You split an infinitive! I ALWAYS hate that!" In such a case it's not really a matter of sometimes you do hate it and sometimes you don't, but rather that you just want to add some weight to your words.


Q: Infinite loop through array of strings in React New to programming, and I'd really appreciate some help in rendering a React component. I have an array of strings, and I'd like to display each string in that array every 5 seconds on an infinite loop. The error I'm running into when trying to set the state is 'this.setState is not a function'. I'm inclined to think I'm using the wrong lifecycle method or there is a binding issue, but I'm lost. Below is the code. I'd really appreciate some help.
import React, {Component} from 'react';

class Home extends Component{
  constructor(props){
    super(props);
    this.state = {
      service: ''
    }
  }
  componentDidMount(){
    var services = ['Delivering professional and personalized care to your loved ones','Home visits with a personalized health plan', 'Transition Assistace', 'Advocacy and Guidance', 'Respite Care']
    let i=0;
    setInterval(function(){
      console.log('set interval working');
      const currentService = services[i];
      this.setState({
        service: currentService
      })
      i++;
      if(i>=services.length){
        i = 0;
      }
    }, 5000);
  }
  render(){
    console.log('this', this.state.service);
    return(

{this.state.service}

    )
  }
}
export default Home;

A: The this in your function in the setInterval isn't the this from ComponentWillMount .. that's why it fails. Do something like:
var that = this;

before you call setInterval and then
that.setState()

You can read more about the this keyword here.


Q: Error when plotting using ggplot2: Error in validate_facets(x) : object 'set' not found I want to plot data in R but I keep getting an error related to facet_grid(-set) which is: Error in validate_facets(x) : object 'set' not found
install.packages('Tmisc')
library(Tmisc)
data(quartet)
View(quartet)

quartet %>%
    group_by(set) %>%
    summarize(mean(x), sd(x), mean(y), sd(y), cor(x,y))
    ggplot(quartet,aes(x,y))
        + geom_point()
        + geom_smooth(method=lm,se=FALSE)
        + facet_wrap(-set)

> Error in validate_facets(x) : object 'set' not found

A: Try this code:
install.packages('Tmisc')
library(Tmisc)
data(quartet)
View(quartet)

    quartet %>%
        group_by(set) %>%
        summarize(mean(x), sd(x), mean(y), sd(y), cor(x,y)) %>%
        ggplot(quartet,aes(x,y))
            + geom_point()
            + geom_smooth(method=lm,se=FALSE)
            + facet_wrap(~set)

you have to use tilde not dash in front of set because set is an independent variable in the quartet dataset. dash is used to remove a column from selection

A: It works with the code:
ggplot(quartet,
       aes(x,y)) +
  geom_point() +
  geom_smooth(method=lm,
              se=FALSE) +
  facet_wrap(~set)

A: Try to install the tidyverse package and then this command supposed to be work. since ggplot function is under the tidyverse package