问:
Using SQL & Perl together - Which should be used for common functions?
I didn't find any dupes of this question, but if there is one or more, I'm sorry - please comment with link.

The question is basic, as probably is the answer.  If I'm using Perl to execute & act upon a database, which avenue (Perl vs. SQL) should I place the burden on when shared functions are involved?

Functions like - LEN, IF/ELSE, CONCAT and many more as well as arithmetic functions, for example are common to both systems.

This SQL statement is loaded with case blocks and other operations that can be replicated with Perl.  So, if the same logic could be implemented in Perl, is it worth re-writing?  What conditions influence the decision to take the burden of one system and place it on the other?

```<code>SELECT DISTINCT     s.id stu_id,
                    stu_id.fullname stu_name,
                    p.major1 major,
                    p.minor1 minor,
                    s.reg_hrs,
                    NVL(st.cum_earn_hrs,0) ttl_hrs,
                    p.adv_id curr_adv_id,
                    adv_id.fullname curr_adv_name,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    (1165)
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    (35808)
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    (9179)
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    (70897)
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    (52125)
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    (24702)
                            WHEN    (p.minor1 = 'NURS')                                     THEN    (51569)
                            WHEN    (p.major1 = 'LEG')                                      THEN    (13324)
                            WHEN    (p.major1 = 'CC')                                       THEN    (73837)
                            WHEN    (p.major1 = 'CCRE')                                     THEN    (1133)
                            WHEN    ((p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                                    OR (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                                    OR (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                                    OR ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat <> 'A' OR max_stu <= 0))
                                    OR ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0)))
                            THEN    (9238)
                            ELSE    (p.adv_id)
                    END     new_adv_id,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    ('Deborah')
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    ('Veronica')
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    ('Stella')
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    ('Lisa')
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    ('Joanne')
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    ('Barbara')
                            WHEN    (p.minor1 = 'NURS')                                     THEN    ('Karen')
                            WHEN    (p.major1 = 'LEG')                                      THEN    ('Nancy')
                            WHEN    (p.major1 = 'CC')                                       THEN    ('Alberta')
                            WHEN    (p.major1 = 'CCRE')                                     THEN    ('Naomi')
                            WHEN    ((p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                                    OR (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                                    OR (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                                    OR ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat <> 'A' OR max_stu <= 0))
                                    OR ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0)))
                            THEN    ('Staff')
                            ELSE    (adv_id.fullname)
                    END     new_adv_name,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    ('NS majors not assigned to Veronica go to Debbie')
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    ('NS majors stay with Veronica')
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    ('DART majors stay with Stella')
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    ('RT-RESP minors go to Lisa')
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    ('CDSC-CDSD majors go to Joanne')
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    ('CA-CB majors go to Barbara')
                            WHEN    (p.minor1 = 'NURS')                                     THEN    ('NURS minors go to Karen')
                            WHEN    (p.major1 = 'LEG')                                      THEN    ('LEG majors go to Nancy')
                            WHEN    (p.major1 = 'CC')                                       THEN    ('CC majors go to Alberta')
                            WHEN    (p.major1 = 'CCRE')                                     THEN    ('CCRE majors go to Naomi')
                            WHEN    (p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                            THEN    ('Current advisor is inactive')
                            WHEN    (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                            THEN    ('Total credits for this student did not meet the advisor reqs for this major')
                            WHEN    (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                            THEN    ('This student did not attend '||si.prev_sess||si.prev_yr)
                            WHEN    ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE (stat <> 'A' OR max_stu <= 0)))
                            THEN    ('Current advisor is not advising students with this major')
                            WHEN    ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0))
                            THEN    ('Current advisor is not advising students with this major')
                            ELSE    ('Student will stay with current advisor')
                    END     change_comm
FROM                stu_acad_rec s,
                    prog_enr_rec p,
                    OUTER stu_stat_rec st,
                    id_rec stu_id,
                    id_rec adv_id,
                    sess_info si
WHERE               s.id = p.id
                    AND s.id = st.id
                    AND s.id = stu_id.id
                    AND p.adv_id = adv_id.id
                    AND s.yr = si.curr_yr
                    AND s.sess = si.curr_sess
                    AND s.reg_hrs > 0
                    AND s.reg_stat IN ('C','R')
                    AND s.prog = 'UNDG'
                    AND p.prog = 'UNDG'
                    AND st.prog = 'UNDG'
                    AND s.id NOT IN (3,287,9238,59999) {System test use IDs}
INTO TEMP           stu_list
WITH NO LOG;
</code>```

答:
i would look at this from a performance perspective, and a re-use perspective.

If you try it on both sides, you may find one to be much faster than the other - that would be a good indicator for which to prefer.

If you will re-use some query in more than one place, then you would want to incorporate much of the business logic in the query as possible, so you do not need to replicate that in the GUI.

(and i have to say, although not strictly part of your question, that much of that case logic looks like you could do a good model in the schema and replace the case with a normal join to some associative tables)

Body:
I didn't find any dupes of this question, but if there is one or more, I'm sorry - please comment with link.

The question is basic, as probably is the answer.  If I'm using Perl to execute & act upon a database, which avenue (Perl vs. SQL) should I place the burden on when shared functions are involved?

Functions like - LEN, IF/ELSE, CONCAT and many more as well as arithmetic functions, for example are common to both systems.

This SQL statement is loaded with case blocks and other operations that can be replicated with Perl.  So, if the same logic could be implemented in Perl, is it worth re-writing?  What conditions influence the decision to take the burden of one system and place it on the other?

SELECT DISTINCT     s.id stu_id,
                    stu_id.fullname stu_name,
                    p.major1 major,
                    p.minor1 minor,
                    s.reg_hrs,
                    NVL(st.cum_earn_hrs,0) ttl_hrs,
                    p.adv_id curr_adv_id,
                    adv_id.fullname curr_adv_name,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    (1165)
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    (35808)
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    (9179)
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    (70897)
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    (52125)
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    (24702)
                            WHEN    (p.minor1 = 'NURS')                                     THEN    (51569)
                            WHEN    (p.major1 = 'LEG')                                      THEN    (13324)
                            WHEN    (p.major1 = 'CC')                                       THEN    (73837)
                            WHEN    (p.major1 = 'CCRE')                                     THEN    (1133)
                            WHEN    ((p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                                    OR (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                                    OR (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                                    OR ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat <> 'A' OR max_stu <= 0))
                                    OR ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0)))
                            THEN    (9238)
                            ELSE    (p.adv_id)
                    END     new_adv_id,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    ('Deborah')
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    ('Veronica')
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    ('Stella')
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    ('Lisa')
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    ('Joanne')
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    ('Barbara')
                            WHEN    (p.minor1 = 'NURS')                                     THEN    ('Karen')
                            WHEN    (p.major1 = 'LEG')                                      THEN    ('Nancy')
                            WHEN    (p.major1 = 'CC')                                       THEN    ('Alberta')
                            WHEN    (p.major1 = 'CCRE')                                     THEN    ('Naomi')
                            WHEN    ((p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                                    OR (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                                    OR (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                                    OR ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat <> 'A' OR max_stu <= 0))
                                    OR ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0)))
                            THEN    ('Staff')
                            ELSE    (adv_id.fullname)
                    END     new_adv_name,
                    CASE    WHEN    (p.adv_id <> 35808 AND p.major1 = 'NS')                 THEN    ('NS majors not assigned to Veronica go to Debbie')
                            WHEN    (p.adv_id = 35808 AND p.major1 = 'NS')                  THEN    ('NS majors stay with Veronica')
                            WHEN    (p.adv_id = 9179 AND p.major1 = 'DART')                 THEN    ('DART majors stay with Stella')
                            WHEN    (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24)   THEN    ('RT-RESP minors go to Lisa')
                            WHEN    (p.major1 IN ('CDSC','CDSD'))                           THEN    ('CDSC-CDSD majors go to Joanne')
                            WHEN    (p.major1 IN ('CA','CB'))                               THEN    ('CA-CB majors go to Barbara')
                            WHEN    (p.minor1 = 'NURS')                                     THEN    ('NURS minors go to Karen')
                            WHEN    (p.major1 = 'LEG')                                      THEN    ('LEG majors go to Nancy')
                            WHEN    (p.major1 = 'CC')                                       THEN    ('CC majors go to Alberta')
                            WHEN    (p.major1 = 'CCRE')                                     THEN    ('CCRE majors go to Naomi')
                            WHEN    (p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I'))
                            THEN    ('Current advisor is inactive')
                            WHEN    (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24))
                            THEN    ('Total credits for this student did not meet the advisor reqs for this major')
                            WHEN    (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG'))
                            THEN    ('This student did not attend '||si.prev_sess||si.prev_yr)
                            WHEN    ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE (stat <> 'A' OR max_stu <= 0)))
                            THEN    ('Current advisor is not advising students with this major')
                            WHEN    ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0))
                            THEN    ('Current advisor is not advising students with this major')
                            ELSE    ('Student will stay with current advisor')
                    END     change_comm
FROM                stu_acad_rec s,
                    prog_enr_rec p,
                    OUTER stu_stat_rec st,
                    id_rec stu_id,
                    id_rec adv_id,
                    sess_info si
WHERE               s.id = p.id
                    AND s.id = st.id
                    AND s.id = stu_id.id
                    AND p.adv_id = adv_id.id
                    AND s.yr = si.curr_yr
                    AND s.sess = si.curr_sess
                    AND s.reg_hrs > 0
                    AND s.reg_stat IN ('C','R')
                    AND s.prog = 'UNDG'
                    AND p.prog = 'UNDG'
                    AND st.prog = 'UNDG'
                    AND s.id NOT IN (3,287,9238,59999) {System test use IDs}
INTO TEMP           stu_list
WITH NO LOG;


来源: stackexchange

问:
Force binary number display Signed Integer?
The binary representation of number 53 is 0b00110101 and -53 is 11001010.

I used 1's complement of 53 to get the binary value of -53.

But when i try to print those binary number as

```<code>print(0b00110101) //53
print(0b11001010) //-53
</code>```

I get the following output.

53

202

How can i make the compiler return the negative representation of the binary value?

答:
0b11001010 is an integer literal and in print(0b11001010) its type is Int and the value is 202.

But you can create a signed 8-bit value with the same bit pattern:

```<code>let x = Int8(bitPattern: 0b11001010)
// Equivalent to:
// let x = Int8(bitPattern: 202)
print(x) // -54
</code>```

using the Int8(bitPattern:) initializer:

Creates a new instance with the same memory representation as the given value.

(Here the compiler infers the type of the integer literal as UInt8.)

ContentLicense: CC BY-SA 3.0

Body:
The binary representation of number 53 is 0b00110101 and -53 is 11001010.

I used 1's complement of 53 to get the binary value of -53.

But when i try to print those binary number as

print(0b00110101) //53
print(0b11001010) //-53

I get the following output.

53

202

How can i make the compiler return the negative representation of the binary value?

Body:
0b11001010 is an integer literal and in print(0b11001010) its type is Int and the value is 202.

But you can create a signed 8-bit value with the same bit pattern:

let x = Int8(bitPattern: 0b11001010)
// Equivalent to:
// let x = Int8(bitPattern: 202)
print(x) // -54

using the Int8(bitPattern:) initializer:

Creates a new instance with the same memory representation as the given value.

(Here the compiler infers the type of the integer literal as UInt8.)


问:
Laravel elixir compile multiple less files
I have this two files in resources/assets/less folder style.less and admin/style.less. I want to compile this files to diffrent paths as the following:

style.less compiled to public/css/

and the other one compiled to public/admin/styles/

this is What i did in the gulpfile.js

```<code>elixir(function(mix) {
    mix.less('style.less', 'public/css/');
    mix.less('admin/style.less', 'public/admin/styles/');
});
</code>```

but this compile only one file.
What is the problem and how can i fix this issue?

答:
I have a project that compiles two different less files to two different css files.
The only difference that I see is that I specify the full destination path including the file name.

So, for your case, it will be:

```<code>elixir(function(mix) {
    mix.less('style.less', 'public/css/style.css')
       .less('admin/style.less', 'public/admin/styles/style.css');
});
</code>```

Body:
I have this two files in resources/assets/less folder style.less and admin/style.less. I want to compile this files to diffrent paths as the following:

style.less compiled to public/css/

and the other one compiled to public/admin/styles/

this is What i did in the gulpfile.js

elixir(function(mix) {
    mix.less('style.less', 'public/css/');
    mix.less('admin/style.less', 'public/admin/styles/');
});

but this compile only one file.
What is the problem and how can i fix this issue?

Body:
I have a project that compiles two different less files to two different css files.
The only difference that I see is that I specify the full destination path including the file name.

So, for your case, it will be:

elixir(function(mix) {
    mix.less('style.less', 'public/css/style.css')
       .less('admin/style.less', 'public/admin/styles/style.css');
});


问:
How to fix edged Signed Distance Fields output?
I try to render some text/font with OpenGL ES 2.0 and Signed Distance Fields. I create a SDF Bitmap for a font and can render some text to the screen, but the displayed text is very edged.

Here you can see a part of my Signed Distance Field Input: Input

Here you can see my output on screen: output

Generate Texture and fill with Bitmap:

```<code>    GL.Enable(EnableCap.Texture2D);
    GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
    GL.GenTextures(1, out TextureId);
    GL.BindTexture(TextureTarget.Texture2D, TextureId); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) TextureMinFilter.NearestMipmapLinear);
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) TextureMagFilter.Linear);
    GL.GenerateMipmap(TextureTarget.Texture2D);
    GL.TexImage2D(TextureTarget2d.Texture2D,0,TextureComponentCount.Rgba,Width,Height,0,PixelFormat.Rgba,PixelType.UnsignedByte,ImageData);
    GL.GenerateMipmap(TextureTarget.Texture2D);
</code>```

Fragment Shader:

```<code>void main()
{
    float distance = texture2D(tex_object, tc).a;
    float alpha = smoothstep(0.5 - 0.05, 0.5 + 0.05, distance);
    fragColor = vec4(fColor.rgb, fColor.a * alpha);
}
</code>```

Shader is correct compiled and values are passed correct, because letters are displayed.
Does somebody know how to fix this and make it smoother?

答:
You're using NearestMipmapLinear where you should be using LinearMipmapNearest.

NearestMipmapLinear is smoothly interpolating between mipmap levels, and doing point filtering within mips.

LinearMipmapNearest is point filtering between mipmap levels and bilinear filtering within mips.

Body:
I try to render some text/font with OpenGL ES 2.0 and Signed Distance Fields. I create a SDF Bitmap for a font and can render some text to the screen, but the displayed text is very edged.

Here you can see a part of my Signed Distance Field Input: Input

Here you can see my output on screen: output

Generate Texture and fill with Bitmap:

    GL.Enable(EnableCap.Texture2D);
    GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
    GL.GenTextures(1, out TextureId);
    GL.BindTexture(TextureTarget.Texture2D, TextureId); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) TextureMinFilter.NearestMipmapLinear);
    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) TextureMagFilter.Linear);
    GL.GenerateMipmap(TextureTarget.Texture2D);
    GL.TexImage2D(TextureTarget2d.Texture2D,0,TextureComponentCount.Rgba,Width,Height,0,PixelFormat.Rgba,PixelType.UnsignedByte,ImageData);
    GL.GenerateMipmap(TextureTarget.Texture2D);

Fragment Shader:

void main()
{
    float distance = texture2D(tex_object, tc).a;
    float alpha = smoothstep(0.5 - 0.05, 0.5 + 0.05, distance);
    fragColor = vec4(fColor.rgb, fColor.a * alpha);
}

Shader is correct compiled and values are passed correct, because letters are displayed.
Does somebody know how to fix this and make it smoother?


问:
EXTJS 5: Get the current cursor position in a textfield or lookupfield
I need to find the current position of the cursor so I can store it in a variable. I've looked at a few SO answers and none have been successful.

What I have so far:

```<code>function getCaretPos(id) {
    var el = Ext.getCmp(id);
       var rng, ii=-1;
    var currSelection = window.getSelection();
    if(currSelection){
        currSelection.modify("character", el.value.length);
       // get the current position
       // ii = currentPosition
    }
    return ii;
};
</code>```

For example: I have a textfield displaying data.

MYWORD

When I place the cursor between the Y and W it should return 2. I've seen a few examples for older versions of IE but none seem to work for me in Chrome.

Does anyone know how this can be done?

答:
I have tried this code in an old version of extjs (2+) on a textfield and it works for me (just tested on IE)

It's about capture the position from the DOM.

```<code>var position = item.el.dom.selectionStart;
</code>```

In your example it will be like:

```<code>    function getCaretPos(id) {
        var element = Ext.getCmp(id);
        var currSelection = element.el.dom.selectionStart;
    }
</code>```

If you want to change the position you just need to set de selectionEnd value to the position you want.

```<code>element.el.dom.selectionEnd = position;
</code>```

Body:
I need to find the current position of the cursor so I can store it in a variable. I've looked at a few SO answers and none have been successful.

What I have so far:

function getCaretPos(id) {
    var el = Ext.getCmp(id);
       var rng, ii=-1;
    var currSelection = window.getSelection();
    if(currSelection){
        currSelection.modify("character", el.value.length);
       // get the current position
       // ii = currentPosition
    }
    return ii;
};

For example: I have a textfield displaying data.

MYWORD

When I place the cursor between the Y and W it should return 2. I've seen a few examples for older versions of IE but none seem to work for me in Chrome.

Does anyone know how this can be done?

Body:
I have tried this code in an old version of extjs (2+) on a textfield and it works for me (just tested on IE)

It's about capture the position from the DOM.

var position = item.el.dom.selectionStart;

In your example it will be like:

    function getCaretPos(id) {
        var element = Ext.getCmp(id);
        var currSelection = element.el.dom.selectionStart;
    }

If you want to change the position you just need to set de selectionEnd value to the position you want.

element.el.dom.selectionEnd = position;


问:
ADODB SQL Syntax - Access table Inner Join with Excel worksheet
I have a project where users will need to fill out an Excel file and then export the data to an Access database. The data collected in the Excel file will need to be exported in 3 steps: (1) export data set 1 record, (2) query Access for the primary key (auto-number) of the newly imported record, (3) export data set 2 record, which includes the primary key populated as the foreign key.

I am able to accomplish the first step by establishing and opening an ADODB connection. However, I am running into trouble in the second step where I need to do an inner join on the Access table and the Excel.

```<code>wlodb.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\" &userSID & "\Desktop\WLO R&C Database_10-4-16.accdb"

sqlFindREMPK = "Select ID " _
& "FROM [test1] a " _
& "INNER JOIN [Excel 8.0;HDR=YES;IMEX=2;DATABASE=C:\User\RED-WIP.xlsm].[REM Upload$] b " _
& "ON a.[REM_ID_Database] = b.[REM_ID_Database] " _
& "WHERE (((a.[REM_ID_Database])=""REM9811044""));"

WLOrs.Open sqlFindREMPK, wlodb

ActiveSheet.Range("A10").CopyFromRecordset (WLOrs)
</code>```

The table and the worksheet name have the same field names. The problem is with the SELECT clause. If I leave as is, I will get an error saying the field could refer to more than one table in the FROM clause. If I add the table name such as [test1].[ID] then I will get the message saying no value given for required parameters. If I change the Excel field name slightly to ID1 and leave the SELECT clause as just ID the code runs fine.

答:
Once you provide an alias for a table, you have to use that alias when referring to that table. You cannot access the table by its original name any more.</p>

```<code>sqlFindREMPK = "Select a.ID " _
  & "FROM [test1] a " _
  & "INNER JOIN [Excel 8.0;HDR=YES;IMEX=2;DATABASE=C:\User\RED-WIP.xlsm].[REM Upload$] b " _
  & "ON a.[REM_ID_Database] = b.[REM_ID_Database] " _
  & "WHERE (((a.[REM_ID_Database])=""REM9811044""));"
</code>```

Body:
I have a project where users will need to fill out an Excel file and then export the data to an Access database. The data collected in the Excel file will need to be exported in 3 steps: (1) export data set 1 record, (2) query Access for the primary key (auto-number) of the newly imported record, (3) export data set 2 record, which includes the primary key populated as the foreign key.

I am able to accomplish the first step by establishing and opening an ADODB connection. However, I am running into trouble in the second step where I need to do an inner join on the Access table and the Excel.

wlodb.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\" &userSID & "\Desktop\WLO R&C Database_10-4-16.accdb"

sqlFindREMPK = "Select ID " _
& "FROM [test1] a " _
& "INNER JOIN [Excel 8.0;HDR=YES;IMEX=2;DATABASE=C:\User\RED-WIP.xlsm].[REM Upload$] b " _
& "ON a.[REM_ID_Database] = b.[REM_ID_Database] " _
& "WHERE (((a.[REM_ID_Database])=""REM9811044""));"

WLOrs.Open sqlFindREMPK, wlodb

ActiveSheet.Range("A10").CopyFromRecordset (WLOrs)

The table and the worksheet name have the same field names. The problem is with the SELECT clause. If I leave as is, I will get an error saying the field could refer to more than one table in the FROM clause. If I add the table name such as [test1].[ID] then I will get the message saying no value given for required parameters. If I change the Excel field name slightly to ID1 and leave the SELECT clause as just ID the code runs fine.

Body:
Once you provide an alias for a table, you have to use that alias when referring to that table. You cannot access the table by its original name any more.

sqlFindREMPK = "Select a.ID " _
  & "FROM [test1] a " _
  & "INNER JOIN [Excel 8.0;HDR=YES;IMEX=2;DATABASE=C:\User\RED-WIP.xlsm].[REM Upload$] b " _
  & "ON a.[REM_ID_Database] = b.[REM_ID_Database] " _
  & "WHERE (((a.[REM_ID_Database])=""REM9811044""));"


问:
Compiling vs Transpiling
While searching about the difference, I came across these definitions:

Compiling is the general term for taking source code written in one language and transforming into another.

Transpiling is a specific term for taking source code written in one language and transforming into another language that has a similar level of abstraction.

I understand what Abstraction is.

But what does "similar level of abstraction" mean in the above definition? And how do we find the level of abstraction in a language?

答:
The definition you have quoted above is too general for a beginner to understand completely and so let me just simplify it to something we see practically.

Compiler: is an umbrella term to describe a program that takes source code written in one language and produce a (or many) output file in some other language.
In practice we mostly use this term to describe a compiler such as gcc which takes in C code as input and produces a binary executable (machine code) as output.

Transpilers are also known as source-to-source compilers. So in essence they are a subset of compilers which take in a source code file and convert it to another source code file in some other language or a different version of the same language. The ouput is generally understandable by a human. This output still has to go through a compiler or interpreter to be able to run on the machine.

Some examples of transpilers:

Emscripten: Transpiles C/C++ to JavaScript

Babel: Transpiles ES6+ code to ES5 (ES6 and ES5 are different versions or generations of the JavaScript language)

Now, what do they mean by "similar level of abstraction":
As I said it compiles/transpiles to a source file, one can argue that assembly language is also a source file and thus gcc is also a transpiler. So, this argument is what this similar level of abstraction voids.

The notion of categorizing languages into lower, middle and higher level is based on the level of abstraction they provide from the actual working of the machine/architecture.

Lower level languages like assembly are very close to the processor architecture i.e. have different instructions for different processors. While C/C++/Java/JavaScript, abstract all this away providing more abstraction.

So, a transpiler compiles to a language that is closer to the language you started with in the terms of this abstraction (or is closer to the level of that language in the lower-middle-higher level language ladder).

Title: Compiling vs Transpiling

ContentLicense: CC BY-SA 4.0


问:
Mixing Ruby on Rails and ASP .Net
I’ve scoured the Internet via Google and could not find if it is possible to host ASP .Net and Ruby on Rails on the same server!

Do you know if it is possible?

If not, would I be able to do this?

– www.abc.com – redirects to Page A (hosted on Ruby on Rails server)

– jobs.abc.com OR www.abc.com/jobs - redirects user to Page B (hosted on ASP .Net server)

So from the user point of view, they’re both under the same domain name and appear seamless? So perhaps jobs.abc.com points to a different IP address.

Has anyone done this before?

Thank you all.

答:
You'll not find a host that supports both I guess.

I'm thinking of something similar. Seems a Windows VPS hosting is the way to go, and then I can install Ruby to IIS as FastCGI filter, or even have another  server side by side but I don't expect this to work flawlessly when both servers will need to listen to port 80 (doable I guess, but probably troubling).

BTW, for the jobs.abc.com scenario you don't need the two apps on the same server. You can have them on two servers and manage the difference via DNS.

ContentLicense: CC BY-SA 2.5

Title: Mixing Ruby on Rails and ASP .Net


问:
Frustrating Formula - Help Needed with Google Sheets formula/method
I am struggling to come up with a formula that fits certain criteria and was hoping someone with a better math brain than me might be able to help. What I have is a Google Sheets based tool that determines how much a someone has purchased of a product and then calculates the amount of times a special additional offer will be redeemed based on the amount spent.

As an example, the offer has three tiers to it. Though the actual costs will be variable for different offers let's say the first tier is gained with a $10 purchase, the second with a $20 purchase and the third with a $35 purchase (the only real relationship between the prices is that they get higher for each tier but there is no specific pattern to the costing of different offers). So if the customer bought $35 worth of goods they would get three free gifts, if they bought $45 worth they would get 4 and then an additional spend of $5 (totaling $50) would then allow them to redeem 5 gifts in total. It can be considered like filling a bucket, each time you hit the red line you get a new gift, when the bucket is full it's emptied and the process begins again.

If each tier of the offer was the same cost (e.g. $5, $10 and $15) this would be a simple case of division by the total purchase amount but as there is no specific relationship between the cost of the tiers (they are based on the value of the contents) I am having trouble coming up with a simple 'bucket filling' formula or calculation method that will work for any price ranges given to it. My current solution involved taking the modulus, subtracting offer amounts from the purchase amount etc. but provides plenty of cases where it breaks . If anyone could give me a start or provide some information that might help in my quest I would be highly appreciative and let me know if my explanation is unclear.! Thanks in advance and all the best

EDIT:
The user has three tiers and then the offer wraps around to the start after the initial three are unlocked once, looping until the offer has been maxed out. Avoiding a long sheet with a dynamic column of prices would be preferable and a small, multicell formula would be ideal

答: What you need is a lookup table. Create a table with the tier value in the left column, and the corresponding number of gifts for that tier value in the right column. Then you can use Vlookup to match the amount spent to correct tier.


问:
How to get the user friends list using LinkedIn?
I tried bellow code but it's not working.

```<code>AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:[NSString stringWithFormat:@"https://api.linkedin.com/v1/people/~/connections:(picture-url,first-name,last-name,id,industry,positions:(company:(name),title),specialties,date-of-birth,interests,languages,siteStandardProfileRequest)?oauth2_access_token=%@&format=json",accessToken] parameters:nil  progress:nil success:^(NSURLSessionTask *task, id responseObject) {

 NSLog(@"%@",responseObject);

     } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Fail");

    }];
</code>```

After hitting this api i get bellow responce. Please help me how to get the linkedin friends list.

```<code>   <error>
   <status>403</status>
   <timestamp>1498049304917</timestamp>
   <request-id>G6GU8W51BY</request-id>
   <error-code>0</error-code>
   <message>Access to connections denied</message>
   </error>
</code>```

答:
Update: LinkedIn has restricted their open API access, and to get the properties of user friends list no longer works.

The Connections API is only for LinkedIn partners now.

On February 12th 2015 Linkedin announced a series of changes in their developer program.  These changes have now begun to take effect and will be rolled out to the entire LinkedIn application base between May 12th - May 19th, 2015.  You can see more details here

Body:
I tried bellow code but it's not working.

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:[NSString stringWithFormat:@"https://api.linkedin.com/v1/people/~/connections:(picture-url,first-name,last-name,id,industry,positions:(company:(name),title),specialties,date-of-birth,interests,languages,siteStandardProfileRequest)?oauth2_access_token=%@&format=json",accessToken] parameters:nil  progress:nil success:^(NSURLSessionTask *task, id responseObject) {

 NSLog(@"%@",responseObject);

     } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Fail");

    }];

After hitting this api i get bellow responce. Please help me how to get the linkedin friends list.

   <error>
   <status>403</status>
   <timestamp>1498049304917</timestamp>
   <request-id>G6GU8W51BY</request-id>
   <error-code>0</error-code>
   <message>Access to connections denied</message>
   </error>


问:
What is the correct way to detect Opera using jQuery?
Amazon.com recently updated their javascript, and it's causing problems with some Opera browsers.

Their browser detection code looks like so, but it's faulty:

```<code>    function sitbReaderIsCompatibleBrowser() {
        if (typeof(jQuery) == 'undefined') {
            return false;
        } else {
            var version = jQuery.browser.version || "0";
            var splitVersion = version.split('.');
            return (
                   (jQuery.browser.msie && splitVersion[0] >= 6)  // IE 6 and higher
                || (jQuery.browser.mozilla && (
                       (splitVersion[0] == 1 && splitVersion[1] >= 8) // Firefox 2 and higher
                    || (splitVersion[0] >= 2)
                   ))
                || (jQuery.browser.safari && splitVersion[0] >= 500) // Safari 5 and higher
                || (jQuery.browser.opera && splitVersion[0] >= 9) // Opera 5 and higher
            );
        }
}
</code>```

Nothing obviously wrong jumps out at me with this code, but I've never used jQuery before so I don't know.

Even though this code looks like it's attempting to let Opera users through, when I visit the page with Opera 9.64 I get an "unsupported browser" message. If I change Opera's settings to report itself as Firefox, the page works perfectly! With that in mind, I'm pretty sure it's a problem with the script and not the browser.

Any jQuery experts have a suggestion?

You can replicate the behavior by visiting any book on Amazon and clicking the "look inside this book" link.

答:
The main reason why Amazon fails on Opera is because the send different code from the server side already... If you visit the same page with Firefox and then save that page and reopen it in Opera it works fine...

But they promised to fix that sometime in January...

OwnerDisplayName: Lisa

LastEditorDisplayName: splattne

Body:
Amazon.com recently updated their javascript, and it's causing problems with some Opera browsers.

Their browser detection code looks like so, but it's faulty:

    function sitbReaderIsCompatibleBrowser() {
        if (typeof(jQuery) == 'undefined') {
            return false;
        } else {
            var version = jQuery.browser.version || "0";
            var splitVersion = version.split('.');
            return (
                   (jQuery.browser.msie && splitVersion[0] >= 6)  // IE 6 and higher
                || (jQuery.browser.mozilla && (
                       (splitVersion[0] == 1 && splitVersion[1] >= 8) // Firefox 2 and higher
                    || (splitVersion[0] >= 2)
                   ))
                || (jQuery.browser.safari && splitVersion[0] >= 500) // Safari 5 and higher
                || (jQuery.browser.opera && splitVersion[0] >= 9) // Opera 5 and higher
            );
        }
}

Nothing obviously wrong jumps out at me with this code, but I've never used jQuery before so I don't know.

Even though this code looks like it's attempting to let Opera users through, when I visit the page with Opera 9.64 I get an "unsupported browser" message. If I change Opera's settings to report itself as Firefox, the page works perfectly! With that in mind, I'm pretty sure it's a problem with the script and not the browser.

Any jQuery experts have a suggestion?

You can replicate the behavior by visiting any book on Amazon and clicking the "look inside this book" link.


问:
How to add a second condition in a rails Active Record query
I want to do something like SQL AND to add a second condition to this:

```<code>Article
  .where("date_trunc('day', created_at) = ?", Date.yesterday-(params[:increment].to_i))
  .order('articles.created_at DESC')
</code>```

The second condition is if the 'site_id' attribute = "HIDE".

Thanks in advance for any tips.

答:
You can use AND inside your where statement:

```<code>Article
  .where("date_trunc('day', created_at) = ? AND site_id = 'HIDE'", Date.yesterday-(params[:increment].to_i))
  .order("articles.created_at DESC")
</code>```

Body:
I want to do something like SQL AND to add a second condition to this:

Article
  .where("date_trunc('day', created_at) = ?", Date.yesterday-(params[:increment].to_i))
  .order('articles.created_at DESC')

The second condition is if the 'site_id' attribute = "HIDE".

Thanks in advance for any tips.

Body:
You can use AND inside your where statement:

Article
  .where("date_trunc('day', created_at) = ? AND site_id = 'HIDE'", Date.yesterday-(params[:increment].to_i))
  .order("articles.created_at DESC")


问:
Regex find procedures exec without named parameters
I'm creating a T-SQL script validation file so they follow standards.
I need a regex, which will be executed in python that identifies executions of procedures without the explicit indication of the parameters.

Right:

```<code>exec schema.sp_procedure_name @parameterOne = 1, @parameter2 = 2
@parameter3 = 3, @parameter4 = 4
</code>```

or

```<code>exec schema.sp_procedure_name
@parameterOne = 1,
@parameter2 = 2
@parameter3 = 3,
@parameter4 = 4
</code>```

Wrong:

```<code>exec schema.sp_procedure_name 1, 2, 3, 4
</code>```

or

```<code>exec schema.sp_procedure_name2
1,
2,
3,
4
</code>```

I need to identify what is wrong, so the regex should match in the second case, I've read some manuals, handouts and regex forums, but I still can not get to a thought to be able to create such an expression, I have managed to get to that so far, But you do not answer me yet:

```<code>(exec(ute)?\s*\w+\.\w+\s*)(\w+\s*\,|.*\w+\s*\,)
</code>```

Can you help me with a functional code and explain why it works? Taking into consideration that things can come in broken lines, as in the examples above, or all on the same line

答:
This is a start, but this is actually a really hard problem.

This regex is a start:

```<code>exec(ute)?\s+\S+\s+[^@]

exec(ute)?
\s+ whitespace
\S+ non-whitespace
\s+ whitespace
[^@]  - any character that is not @
</code>```

This will only check that the first parameter is an "@"

It could also fail if someone put a space like   "schema.   procedurename", which I think is valid SQL.  People could also probably screw it up by putting comments in the SQL.

Body:
I'm creating a T-SQL script validation file so they follow standards.
I need a regex, which will be executed in python that identifies executions of procedures without the explicit indication of the parameters.

Right:

exec schema.sp_procedure_name @parameterOne = 1, @parameter2 = 2
@parameter3 = 3, @parameter4 = 4

or

exec schema.sp_procedure_name
@parameterOne = 1,
@parameter2 = 2
@parameter3 = 3,
@parameter4 = 4

Wrong:

exec schema.sp_procedure_name 1, 2, 3, 4

or

exec schema.sp_procedure_name2
1,
2,
3,
4

I need to identify what is wrong, so the regex should match in the second case, I've read some manuals, handouts and regex forums, but I still can not get to a thought to be able to create such an expression, I have managed to get to that so far, But you do not answer me yet:

(exec(ute)?\s*\w+\.\w+\s*)(\w+\s*\,|.*\w+\s*\,)

Can you help me with a functional code and explain why it works? Taking into consideration that things can come in broken lines, as in the examples above, or all on the same line

Body:
This is a start, but this is actually a really hard problem.

This regex is a start:

exec(ute)?\s+\S+\s+[^@]

exec(ute)?
\s+ whitespace
\S+ non-whitespace
\s+ whitespace
[^@]  - any character that is not @

This will only check that the first parameter is an "@"

It could also fail if someone put a space like   "schema.   procedurename", which I think is valid SQL.  People could also probably screw it up by putting comments in the SQL.


问:
I want to cache Django database objects without changing every single line that does a DB lookup
Short Version: In Django (ideally Django 1.7), I want to read certain database objects just once each day at 2 AM and cache them. Each time I do MyModel.objects.get() it will not touch the database, it will use the cache. Then I will manually refresh the cache at 2 AM. I do not want to change every single line that has a query like MyModel.objects.get() because I would need to change 100+ lines and it would get verbose.

Long Version:

I am working with a very large Django project that is old and not entirely sensible. Once each day (at 2 AM after backups, during scheduled downtime), the Django application reads a set of protected database objects (rows, model instances), checks them for consistency, and then it uses exactly those values until the next day. These database objects (rows) can only be changed during the scheduled downtime at 2 AM, and changing them in the middle of the day would corrupt data and make things confusing.

I already wrote a pre_save hook that errors out if you try to modify these database objects when it is not in scheduled downtime. I also gave very few people access to these database tables via the Django Admin Console.

But it is low performance, because it actually does hit the database every single time these objects are used, despite the fact that it should only hit the database once each day.

Sadly, there are over 100 lines of code that lookup and then use the tables, like this:

```<code># In views.py:
from myapp.models import WidgetType

# In literally over 100 places:
widget_t1 = WidgetType.objects.get(pk=1)
local_var.part_num = widget_t1.part_num
</code>```

Every single time it says WidgetType.objects.get, I want it to use a cached version of the database object. I only want to refresh the cache manually once per day at 2 AM, for performance and extra safety against data corruption.

I do not want to use the cache module every single time I do a database lookup, because that would require changing over 100 lines of code, and it would make the code more verbose.

答:
django-cacheops gives you the option of automatic caching. Here is a sample configuration that automatically caches some DB reads and enables manual caching with .cache() for others:

```<code>CACHEOPS = {
    # Automatically cache any User.objects.get() calls for 15 minutes
    # This includes request.user or post.author access,
    # where Post.author is a foreign key to auth.User
    'auth.user': {'ops': 'get', 'timeout': 60*15},

    # Automatically cache all gets and queryset fetches
    # to other django.contrib.auth models for an hour
    'auth.*': {'ops': ('fetch', 'get'), 'timeout': 60*60},

    # Cache all queries to Permission
    # 'all' is just an alias for {'get', 'fetch', 'count', 'aggregate', 'exists'}
    'auth.permission': {'ops': 'all', 'timeout': 60*60},

    # Enable manual caching on all other models with default timeout of an hour
    # Use Post.objects.cache().get(...)
    #  or Tags.objects.filter(...).order_by(...).cache()
    # to cache particular ORM request.
    # Invalidation is still automatic
    '*.*': {'ops': (), 'timeout': 60*60},

    # And since ops is empty by default you can rewrite last line as:
    '*.*': {'timeout': 60*60},
}
</code>```

Body:
Short Version: In Django (ideally Django 1.7), I want to read certain database objects just once each day at 2 AM and cache them. Each time I do MyModel.objects.get() it will not touch the database, it will use the cache. Then I will manually refresh the cache at 2 AM. I do not want to change every single line that has a query like MyModel.objects.get() because I would need to change 100+ lines and it would get verbose.

Long Version:

I am working with a very large Django project that is old and not entirely sensible. Once each day (at 2 AM after backups, during scheduled downtime), the Django application reads a set of protected database objects (rows, model instances), checks them for consistency, and then it uses exactly those values until the next day. These database objects (rows) can only be changed during the scheduled downtime at 2 AM, and changing them in the middle of the day would corrupt data and make things confusing.

I already wrote a pre_save hook that errors out if you try to modify these database objects when it is not in scheduled downtime. I also gave very few people access to these database tables via the Django Admin Console.

But it is low performance, because it actually does hit the database every single time these objects are used, despite the fact that it should only hit the database once each day.

Sadly, there are over 100 lines of code that lookup and then use the tables, like this:

# In views.py:
from myapp.models import WidgetType

# In literally over 100 places:
widget_t1 = WidgetType.objects.get(pk=1)
local_var.part_num = widget_t1.part_num

Every single time it says WidgetType.objects.get, I want it to use a cached version of the database object. I only want to refresh the cache manually once per day at 2 AM, for performance and extra safety against data corruption.

I do not want to use the cache module every single time I do a database lookup, because that would require changing over 100 lines of code, and it would make the code more verbose.

Body:
django-cacheops gives you the option of automatic caching. Here is a sample configuration that automatically caches some DB reads and enables manual caching with .cache() for others:

CACHEOPS = {
    # Automatically cache any User.objects.get() calls for 15 minutes
    # This includes request.user or post.author access,
    # where Post.author is a foreign key to auth.User
    'auth.user': {'ops': 'get', 'timeout': 60*15},

    # Automatically cache all gets and queryset fetches
    # to other django.contrib.auth models for an hour
    'auth.*': {'ops': ('fetch', 'get'), 'timeout': 60*60},

    # Cache all queries to Permission
    # 'all' is just an alias for {'get', 'fetch', 'count', 'aggregate', 'exists'}
    'auth.permission': {'ops': 'all', 'timeout': 60*60},

    # Enable manual caching on all other models with default timeout of an hour
    # Use Post.objects.cache().get(...)
    #  or Tags.objects.filter(...).order_by(...).cache()
    # to cache particular ORM request.
    # Invalidation is still automatic
    '*.*': {'ops': (), 'timeout': 60*60},

    # And since ops is empty by default you can rewrite last line as:
    '*.*': {'timeout': 60*60},
}


问:
Spring App cloudfoundry : connection refused
I've a spring boot app running on cloudfoundry and I've to connect to an LDAP server to retrieve some user info, but when trying to connect to LDAP server it gives connection refused exception or for that matter for any external URL connection it gives that exception.
I read up on application security groups on cloudfoundry, but my org role is not allowing me to push the json config. Any help is appreciated.</p>

答:
For updating security group, you can try with this command.</p>

```<code>cf update-security-group SECURITY_GROUP PATH_TO_JSON_RULES_FILE
</code>```

Body:
For updating security group, you can try with this command.

cf update-security-group SECURITY_GROUP PATH_TO_JSON_RULES_FILE


问:
Adding new item into object (Angular, Ionic2)
I guess it's a simple JavaScript question, but still... I can't figure it out, I tried everything (I guess not)...

I'm trying to add multiple items into the this.cart which is stored in Ionic Storage (like LocalStorage).

When I add 2 items to the cart:

```<code>updateCart(id, qty) {
    this.storage.get('cart').then((result) => {
        if(result) {
            this.cart = result;
        }
        else {
            this.cart = [];
        }

        this.cart.push({
            id: id,
            qty: qty
        });
    });

    this.storage.set('cart', this.cart);

    this.storage.get('cart').then((result) => {
        console.log(JSON.stringify(result));
    });
}
</code>```

It returns:

```<code>[{"id":"48131","qty":1}]
</code>```

Instead of:

```<code>[{"id":"48130","qty":1},{"id":"48131","qty":1}...]
</code>```

答:
Move it inside the callback,</p>

```<code> this.storage.get('cart').then((result) => {
        this.cart = result;
        this.cart.push({
        id: id,
        qty: qty
        });
    });
</code>```

Body:
I guess it's a simple JavaScript question, but still... I can't figure it out, I tried everything (I guess not)...

I'm trying to add multiple items into the this.cart which is stored in Ionic Storage (like LocalStorage).

When I add 2 items to the cart:

updateCart(id, qty) {
    this.storage.get('cart').then((result) => {
        if(result) {
            this.cart = result;
        }
        else {
            this.cart = [];
        }

        this.cart.push({
            id: id,
            qty: qty
        });
    });

    this.storage.set('cart', this.cart);

    this.storage.get('cart').then((result) => {
        console.log(JSON.stringify(result));
    });
}

It returns:

[{"id":"48131","qty":1}]

Instead of:

[{"id":"48130","qty":1},{"id":"48131","qty":1}...]

Body:
Move it inside the callback,

 this.storage.get('cart').then((result) => {
        this.cart = result;
        this.cart.push({
        id: id,
        qty: qty
        });
    });


问:
Set lookup property on Navigation Property failing
I am trying to POST the below json using the Microsoft Dynamics WebAPI.  The post returns a success, but in my data the ccseq_employeeid and ccseq_clientid are not set.  What do I need to change to get the fields to post correctly?

Entity Structure

ccseq_expensetransaction has a lookup to ccseq_expensetransactionsets with a relationship that has the name ccseq_ccseq_expensetransactionset_ccseq_expensetransaction_ExpenseTransactionSetID.  The lookups to systemusers and ccseq_clients are a part of the ccseq_expensetransaction entity.

Code

```<code>POST /api/data/v8.0/ccseq_expensetransactionsets HTTP/1.1
Host: url.com
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 24f7ead3-0307-996f-f45a-f959c604c922

{
   "ccseq_importdate":"2017-06-05T04:00:00Z",
   "ccseq_month":"1",
   "ccseq_year":"2017",
   "ccseq_name":"Test 30",
   "ccseq_status":"100000000",
   "ccseq_ccseq_expensetransactionset_ccseq_expensetransaction_ExpenseTransactionSetID":[
      {
         "ExpenseTransaction[ccseq_employeeid@odata.bind]":"/systemusers(6d2fd71b-32d1-dd11-a4f5-001a6449bbe7)",
         "ExpenseTransaction[ccseq_clientid@odata.bind]":"/ccseq_clients(663ebd00-73b9-4faf-90ed-f56bb9c2dc9b)"
      }
   ]
}
</code>```

答:
Modify the body of the request into this:</p>

```<code>{
   "ccseq_importdate": "2017-06-05T04:00:00Z",
   "ccseq_month": "1",
   "ccseq_year": "2017",
   "ccseq_name": "Test 30",
   "ccseq_status": "100000000",
   "ccseq_employeeid@odata.bind": "/systemusers(6d2fd71b-32d1-dd11-a4f5-001a6449bbe7)",
   "ccseq_clientid@odata.bind": "/ccseq_clients(663ebd00-73b9-4faf-90ed-f56bb9c2dc9b)"
}
</code>```

Body:
I am trying to POST the below json using the Microsoft Dynamics WebAPI.  The post returns a success, but in my data the ccseq_employeeid and ccseq_clientid are not set.  What do I need to change to get the fields to post correctly?

Entity Structure

ccseq_expensetransaction has a lookup to ccseq_expensetransactionsets with a relationship that has the name ccseq_ccseq_expensetransactionset_ccseq_expensetransaction_ExpenseTransactionSetID.  The lookups to systemusers and ccseq_clients are a part of the ccseq_expensetransaction entity.

Code

POST /api/data/v8.0/ccseq_expensetransactionsets HTTP/1.1
Host: url.com
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 24f7ead3-0307-996f-f45a-f959c604c922

{
   "ccseq_importdate":"2017-06-05T04:00:00Z",
   "ccseq_month":"1",
   "ccseq_year":"2017",
   "ccseq_name":"Test 30",
   "ccseq_status":"100000000",
   "ccseq_ccseq_expensetransactionset_ccseq_expensetransaction_ExpenseTransactionSetID":[
      {
         "ExpenseTransaction[ccseq_employeeid@odata.bind]":"/systemusers(6d2fd71b-32d1-dd11-a4f5-001a6449bbe7)",
         "ExpenseTransaction[ccseq_clientid@odata.bind]":"/ccseq_clients(663ebd00-73b9-4faf-90ed-f56bb9c2dc9b)"
      }
   ]
}

Body:
Modify the body of the request into this:

{
   "ccseq_importdate": "2017-06-05T04:00:00Z",
   "ccseq_month": "1",
   "ccseq_year": "2017",
   "ccseq_name": "Test 30",
   "ccseq_status": "100000000",
   "ccseq_employeeid@odata.bind": "/systemusers(6d2fd71b-32d1-dd11-a4f5-001a6449bbe7)",
   "ccseq_clientid@odata.bind": "/ccseq_clients(663ebd00-73b9-4faf-90ed-f56bb9c2dc9b)"
}


问:
Is it a good practice for a module to return a JSONArray?
Before I converted my app into a library, I could get a JSONArray from the server and process everything internally, assigning values to my own POJO, which could be sorted into an ArrayList of that POJO type. Now with the new library, I want that POJO to be determined by the third-party developer for flexibility. My question is: is it good practice (regarding both security and structure standards) to return the raw JSONArray to the developer? And if not, what should I return? ArrayList? List? </p>

答:
There is no "one correct answer" here.

All things being equal, the more generic the interface, the better.

In other words, using an "ArrayList" (in your code implementation) and returning a "List" (as your return value) is in some ways "ideal".

But if both you (when you receive the data) and your client (who will process the data) are both using a "JSONArray" ... then why go to the extra overhead of packing and unpacking to and from an ArrayList?  In this case, simply sticking with the JSONArray would be much more efficient.

So the answer is "it depends".


问:
Android Studio 2.2 giving error while creating new project
I just updated my android studio to

Android Studio 2.2
Build #AI-145.3276617, built on September 15, 2016
JRE: 1.8.0_76-release-b03 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Now when I create a new project I am getting build error.

```<code>Error:Failed to resolve: javax.inject:javax.inject:1 <a href="open.dependency.in.project.structure">Show in Project Structure dialog</a>
</code>```

答:
Doublecheck if you need to use the proxy server (i.e working on a corporate workstation from home may still require using the corporate proxy with the VPN link or without. In that case, don't trust the VS HTTP proxy settings, it's not supporting https, rather setup your gradle to use them:

In the gradle.properties file put:

```<code>systemProp.http.proxyHost=your_proxyserver_url
systemProp.http.proxyPort=your_proxyserver_port_number
systemProp.http.proxyUser=your_proxyserver_user_name
systemProp.http.proxyPassword=your_proxyserver_user_password
systemProp.http.nonProxyHosts=localhost
systemProp.http.auth.ntlm.domain=your_corporate_domain_name_url

systemProp.https.proxyHost=your_proxyserver_url
systemProp.https.proxyPort=your_proxyserver_port_number
systemProp.https.proxyUser=your_proxyserver_user_name
systemProp.https.proxyPassword=your_proxyserver_user_password
systemProp.https.nonProxyHosts=localhost
systemProp.https.auth.ntlm.domain=your_corporate_domain_name_url
</code>```

Body:
I just updated my android studio to

Android Studio 2.2
Build #AI-145.3276617, built on September 15, 2016
JRE: 1.8.0_76-release-b03 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Now when I create a new project I am getting build error.

Error:Failed to resolve: javax.inject:javax.inject:1 Show in Project Structure dialog

Body:
Doublecheck if you need to use the proxy server (i.e working on a corporate workstation from home may still require using the corporate proxy with the VPN link or without. In that case, don't trust the VS HTTP proxy settings, it's not supporting https, rather setup your gradle to use them:

In the gradle.properties file put:

systemProp.http.proxyHost=your_proxyserver_url
systemProp.http.proxyPort=your_proxyserver_port_number
systemProp.http.proxyUser=your_proxyserver_user_name
systemProp.http.proxyPassword=your_proxyserver_user_password
systemProp.http.nonProxyHosts=localhost
systemProp.http.auth.ntlm.domain=your_corporate_domain_name_url

systemProp.https.proxyHost=your_proxyserver_url
systemProp.https.proxyPort=your_proxyserver_port_number
systemProp.https.proxyUser=your_proxyserver_user_name
systemProp.https.proxyPassword=your_proxyserver_user_password
systemProp.https.nonProxyHosts=localhost
systemProp.https.auth.ntlm.domain=your_corporate_domain_name_url


问:
Use data in angular directive link?
How i can use data , which passed from controller to directive from tag attribute ?? Its show undefined in console .

```<code>App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
       restrict: 'E',
       scope: {
           gamesList: '=',
       }.
       link: function(scope,attrs){
           console.log(scope.gamesList); //undefined
       }
    }
}])
</code>```

And html:

```<code><applist games-List="games">
    <div ng-repeat="(key, value) in gamesList | groupBy: 'game.id'"> ... </div>
</applist>
</code>```

答:
To get data from directive attribute you can use below code

console.log(scope.gamesList);

Your directive will be

```<code>App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
        restrict: 'E',
       scope: {
           gamesList: '@',
       },
       link: function(scope,attrs){
           console.log(scope.gamesList); //games
       }
    }
}])
</code>```

Title: Use data in angular directive link?

Body:
How i can use data , which passed from controller to directive from tag attribute ?? Its show undefined in console .

App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
       restrict: 'E',
       scope: {
           gamesList: '=',
       }.
       link: function(scope,attrs){
           console.log(scope.gamesList); //undefined
       }
    }
}])

And html:

<applist games-List="games">

 ...

</applist>

Body:
To get data from directive attribute you can use below code

console.log(scope.gamesList);

Your directive will be

App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
        restrict: 'E',
       scope: {
           gamesList: '@',
       },
       link: function(scope,attrs){
           console.log(scope.gamesList); //games
       }
    }
}])


问:
dynamically choose log4j appender depending on the parameter received
I have log4j appenders (appendersB, appendersC) and a specific class like below

```<code>class A { A{Parent a}}
</code>```

where Parent is an interface with two implementations as below

```<code>class B implements Parent {..}
class C implements Parent {..}
</code>```

now I want to tell log4j that whenever class A is instantiated with paramater B it should use appendersB and if it receives C then it should use appendersC.

Is this possible?

答:
Choice of appender is done in the Log4j configuration file, based on the logger name, so to be able to configure it so logging entries go to different appenders, your code should use different loggers.

Normally, the logger name is the fully qualified class name, and the logger is created as a static field of the class. This is done for performance, low memory footprint, and convenience of naming.

You can however make the logger field non-static, and assign it with a dynamically generated name.

As an example, your A class would normally do this:

```<code>package org.example;
public class A {
    private static final Logger log = LogManager.getLogger(A.class);
    // rest of code
}
</code>```

This will create a logger named org.example.A, which can be configured to write any any appender(s) of choice.

To base logger, and hence potentially the appender, on the actual class of object given as parameter to constructor, you could do this:

```<code>package org.example;
public class A {
    private final Logger log; // not static
    public A(Parent p) {
        this.log = LogManager.getLogger(getClass().getName() + "." +
                                        p.getClass().getSimpleName());
    }
}
</code>```

This will create a logger for each instance of A, and the name derives from constructor parameter, e.g.

```<code>new A(new B()) // Logger name: org.example.A.B
new A(new C()) // Logger name: org.example.A.C
</code>```

You can now configure Log4j to direct logger org.example.A.B to appenderB, and logger org.example.A.C to appenderC.

You can of course build the dynamic logger name any way you want to. Logger names don't have to be based on class names, e.g. you could name them bravo.foo and charlie.foo.

Body:
I have log4j appenders (appendersB, appendersC) and a specific class like below

class A { A{Parent a}}

where Parent is an interface with two implementations as below

class B implements Parent {..}
class C implements Parent {..}

now I want to tell log4j that whenever class A is instantiated with paramater B it should use appendersB and if it receives C then it should use appendersC.

Is this possible?

Body:
Choice of appender is done in the Log4j configuration file, based on the logger name, so to be able to configure it so logging entries go to different appenders, your code should use different loggers.

Normally, the logger name is the fully qualified class name, and the logger is created as a static field of the class. This is done for performance, low memory footprint, and convenience of naming.

You can however make the logger field non-static, and assign it with a dynamically generated name.

As an example, your A class would normally do this:

package org.example;
public class A {
    private static final Logger log = LogManager.getLogger(A.class);
    // rest of code
}

This will create a logger named org.example.A, which can be configured to write any any appender(s) of choice.

To base logger, and hence potentially the appender, on the actual class of object given as parameter to constructor, you could do this:

package org.example;
public class A {
    private final Logger log; // not static
    public A(Parent p) {
        this.log = LogManager.getLogger(getClass().getName() + "." +
                                        p.getClass().getSimpleName());
    }
}

This will create a logger for each instance of A, and the name derives from constructor parameter, e.g.

new A(new B()) // Logger name: org.example.A.B
new A(new C()) // Logger name: org.example.A.C

You can now configure Log4j to direct logger org.example.A.B to appenderB, and logger org.example.A.C to appenderC.

You can of course build the dynamic logger name any way you want to. Logger names don't have to be based on class names, e.g. you could name them bravo.foo and charlie.foo.


问:
Where can I find my credentials for putting in a SQL server connection string?
I am currently using asp.net mvc5 where I am following a tutorial. However I have got to a point of the tutorial where it asks me to enter in a connection string </p>

```<code><add name="CountryConnectionString" connectionString="data source=server name,1436;database=Sample;user id=sa;password=123456;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
</code>```

<p>It asks to enter my own credentials but unfortunately I don't think I have ever set a username and password is there a way of finding out? Apologies if this is a silly question. </p>

答:
Well you need to install this to create a SQL Server Intance and your ConnectionString should be like:

```<code><add name="CountryConnectionString" connectionString="data source=CathyServer;database=CathyDataBase;user id=sa;password=123456;" providerName="System.Data.SqlClient"/>
</code>```

In the installation of SQLServer Express the installer ask for those names, and you should be able to change or keep, in the "Next" SQL Server Instalation an exmple should be:

```<code><add name="CountryConnectionString" connectionString="data source=localhost;database=WhateverName;user id=sa;password=123456;" providerName="System.Data.SqlClient"/>
</code>```

Edited:

Ok, in yout Solution Explorer (Maybe hided on right), in the folder App_Data should have a .mdf file named Sample, if you doble click on it (.mdf file) in the left, in server explorer you can see your Data Connections if you right click on your Data Connection (Maybe called, Sample) select Properties and you can see at your right the properties of Sample.mdf in the Connection Section and field Connection String looks like:

Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="c:\users\mmendozat\documents\visual studio 2017\Projects\MyProject\MyProject\App_Data\MyDatabase.mdf";Integrated Security=True

connectionString=" Copy this and put here "

Body:
I am currently using asp.net mvc5 where I am following a tutorial. However I have got to a point of the tutorial where it asks me to enter in a connection string

<add name="CountryConnectionString" connectionString="data source=server name,1436;database=Sample;user id=sa;password=123456;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>

It asks to enter my own credentials but unfortunately I don't think I have ever set a username and password is there a way of finding out? Apologies if this is a silly question.

Body:
Well you need to install this to create a SQL Server Intance and your ConnectionString should be like:

<add name="CountryConnectionString" connectionString="data source=CathyServer;database=CathyDataBase;user id=sa;password=123456;" providerName="System.Data.SqlClient"/>

In the installation of SQLServer Express the installer ask for those names, and you should be able to change or keep, in the "Next" SQL Server Instalation an exmple should be:

<add name="CountryConnectionString" connectionString="data source=localhost;database=WhateverName;user id=sa;password=123456;" providerName="System.Data.SqlClient"/>

Edited:

Ok, in yout Solution Explorer (Maybe hided on right), in the folder App_Data should have a .mdf file named Sample, if you doble click on it (.mdf file) in the left, in server explorer you can see your Data Connections if you right click on your Data Connection (Maybe called, Sample) select Properties and you can see at your right the properties of Sample.mdf in the Connection Section and field Connection String looks like:

Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="c:\users\mmendozat\documents\visual studio 2017\Projects\MyProject\MyProject\App_Data\MyDatabase.mdf";Integrated Security=True

connectionString=" Copy this and put here "


问:
Task<> does not contain a definition for 'GetAwaiter'
Client

```<code>iGame Channel = new ChannelFactory<iGame> ( new BasicHttpBinding ( BasicHttpSecurityMode . None ) , new EndpointAddress ( new Uri ( "http://localhost:58597/Game.svc" ) ) ) . CreateChannel ( );

public Task<SerializableDynamicObject> Client ( SerializableDynamicObject Packet )
{
    return Task<SerializableDynamicObject> . Factory . FromAsync ( Channel . BeginConnection , Channel . EndConnection , Packet , null );
}
</code>```

Contract

```<code>    [OperationContract ( AsyncPattern = true )]
    IAsyncResult BeginConnection ( SerializableDynamicObject Message , AsyncCallback Callback , object State );

    SerializableDynamicObject EndConnection ( IAsyncResult Result );
</code>```

Service

```<code>public IAsyncResult BeginConnection ( SerializableDynamicObject Message , AsyncCallback Callback , object State )
{
    dynamic Request = Message;
    dynamic Response = new SerializableDynamicObject ( );
    if ( Request . Operation = "test" )
    {
        Response . Status = true;
    }
    Response . Status = false;

    return new CompletedAsyncResult<SerializableDynamicObject> ( Response );
}

public SerializableDynamicObject EndConnection ( IAsyncResult Result )
{
    return ( Result as CompletedAsyncResult<SerializableDynamicObject> ) . Data;
}
</code>```

Exposing Service from Silverlight Client

```<code>private async void myButton ( object sender , RoutedEventArgs e )
{
    dynamic Request = new SerializableDynamicObject ( );
    Request . Operation = "test";

    var task = Client ( Request );
    var result = await task;  // <------------------------------ Exception
}
</code>```

Exception

```<code>Task<SerializableDynamicObject > does not contain a definition for 'GetAwaiter'
</code>```

What's wrong ?

Edit 1 :

Briefly,

Visual studio 2012 RC Silverlight 5 Application consumes Game WCF 4 Service hosted in ASP.net 4 Application with ChannelFactory technique via Shared Portable Library .NET4/SL5 contains the iGame interface with Async CTP

Graph :

ASP.NET <= Class Library ( Game ) <= Portable Library ( iGame ) => Silverlight

Edit 2 :

Microsoft.CompilerServices.AsyncTargetingPack.Silverlight5.dll is added in my SL5 Client

using System . Threading . Tasks;

答:
Just experienced this in a method that executes a linq query.

```<code>public async Task<Foo> GetSomething()
{
    return await (from foo in Foos
                  select foo).FirstOrDefault();
}
</code>```

Needed to use .FirstOrDefaultAsync() instead. N00b mistake.

Body:
Client

iGame Channel = new ChannelFactory<iGame> ( new BasicHttpBinding ( BasicHttpSecurityMode . None ) , new EndpointAddress ( new Uri ( "http://localhost:58597/Game.svc" ) ) ) . CreateChannel ( );

public Task<SerializableDynamicObject> Client ( SerializableDynamicObject Packet )
{
    return Task<SerializableDynamicObject> . Factory . FromAsync ( Channel . BeginConnection , Channel . EndConnection , Packet , null );
}

Contract

    [OperationContract ( AsyncPattern = true )]
    IAsyncResult BeginConnection ( SerializableDynamicObject Message , AsyncCallback Callback , object State );

    SerializableDynamicObject EndConnection ( IAsyncResult Result );

Service

public IAsyncResult BeginConnection ( SerializableDynamicObject Message , AsyncCallback Callback , object State )
{
    dynamic Request = Message;
    dynamic Response = new SerializableDynamicObject ( );
    if ( Request . Operation = "test" )
    {
        Response . Status = true;
    }
    Response . Status = false;

    return new CompletedAsyncResult<SerializableDynamicObject> ( Response );
}

public SerializableDynamicObject EndConnection ( IAsyncResult Result )
{
    return ( Result as CompletedAsyncResult<SerializableDynamicObject> ) . Data;
}

Exposing Service from Silverlight Client

private async void myButton ( object sender , RoutedEventArgs e )
{
    dynamic Request = new SerializableDynamicObject ( );
    Request . Operation = "test";

    var task = Client ( Request );
    var result = await task;  // <------------------------------ Exception
}

Exception

Task<SerializableDynamicObject > does not contain a definition for 'GetAwaiter'

What's wrong ?

Edit 1 :

Briefly,

Visual studio 2012 RC Silverlight 5 Application consumes Game WCF 4 Service hosted in ASP.net 4 Application with ChannelFactory technique via Shared Portable Library .NET4/SL5 contains the iGame interface with Async CTP

Graph :

ASP.NET <= Class Library ( Game ) <= Portable Library ( iGame ) => Silverlight

Edit 2 :

Microsoft.CompilerServices.AsyncTargetingPack.Silverlight5.dll is added in my SL5 Client

using System . Threading . Tasks;

Body:
Just experienced this in a method that executes a linq query.

public async Task<Foo> GetSomething()
{
    return await (from foo in Foos
                  select foo).FirstOrDefault();
}

Needed to use .FirstOrDefaultAsync() instead. N00b mistake.


问:
Sparklyr - Unable to copy data.frames into Spark using copy_to
I'm trying to copy a big dataframe (around 5.8 million records) into Spark using Sparklyr's function copy_to.

First, when loading the data using fread (data.table), and applying the copy_to function, I got the following output error:

Error in as.data.frame.default(x[[i]], optional = TRUE) :
        cannot coerce class ""integer64"" to a data.frame

Then, I changed the only two columns of type integer64 into character, then applied the as.data.frame (it's a data.table, since I used fread) into all data.

Using copy_to again, it takes a long time before and after a progress bar shows up, but the following result is returned:

Error in invoke_method.spark_shell_connection(sc, TRUE, class, method,  :
        No status is returned. Spark R backend might have failed.

No data is copied into Spark.

Any thoughts?

答:
I've run into this. Unfortunately copying dataframes from memory into Sparklyr just isn't the best way to import larger data. It works better through-and-through when I save my dataframe to disk as a .csv then read that into Spark directly.

For peak performance these best thing is to save it into parquet format on disk and read for that. Because Spark works using DAGs, if you have a more efficient on-disk data format for Spark to conduct operations on, your entire Spark operation will be faster when you hit collect, insert or whathaveyou.


问:
How is Activity.Text encoded Microsoft Teams?
I am writing a custom Teams bot. I got some questions about Activity.Text field:

How is it encoded? I see some <at> tags when the bot is @mentioned, but I also see some '. Can I use HttpUtility.HtmlDecodeto decode it?

Is there any document about the details of the Activity.Text field? The schema says it is

Text of the message that is sent from user to bot or bot to user. See the channel's documentation for limits imposed upon the contents of this property.

But it does not talk about the details about the field.

答:
Nothing special about Activity.Text in Teams except for the  tags.  In general, depending on the Activity.TextFormat, the message you send might contain markdown or XML, but in general the message you receive from a user will be plain text.

Anything additional, like if the user sends bold text to your bot, can be extracted from the attachments object in the incoming payload, e.g. :

```<code>"attachments": [
    {
        "contentType": "text/html",
        "content": "<div><span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Teams TestBot</span> |echo| <strong><strong>Hi</strong></strong></div>"
    }
]
</code>```

Body:
Nothing special about Activity.Text in Teams except for the  tags.  In general, depending on the Activity.TextFormat, the message you send might contain markdown or XML, but in general the message you receive from a user will be plain text.

Anything additional, like if the user sends bold text to your bot, can be extracted from the attachments object in the incoming payload, e.g. :

"attachments": [
    {
        "contentType": "text/html",
        "content": "<div><span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Teams TestBot</span> |echo| <strong><strong>Hi</strong></strong></div>"
    }
]


问:
How to ignore SSL policy to perform a HTTPClient request?
I'm trying to ignore ssl policy to do a request with HttpClient but ServerCertificateValidationCallback is never called. What is the correct place to invoke ServerCertificateValidationCallback in ASP.NET Core App? I put it before HttpClient using.

Note: This class is in net462 Class Library.

Code:

```<code> System.Net.ServicePointManager.ServerCertificateValidationCallback +=
 delegate (object sender,
 System.Security.Cryptography.X509Certificates.X509Certificate certificate,
 System.Security.Cryptography.X509Certificates.X509Chain chain,
 System.Net.Security.SslPolicyErrors sslPolicyErrors)
 {
     return true;
 };

 using (var client = new HttpClient())
 {
    client.BaseAddress = new Uri("https://myapi");
    ...

    var result = client.PostAsync(method, httpContent).Result;
    ...
 }
</code>```

答:
Try putting the callback initialization code earlier - before web controls are displayed or the main function.

Credit goes to this answer :https://stackoverflow.com/a/5043083/1709981

Body:
I'm trying to ignore ssl policy to do a request with HttpClient but ServerCertificateValidationCallback is never called. What is the correct place to invoke ServerCertificateValidationCallback in ASP.NET Core App? I put it before HttpClient using.

Note: This class is in net462 Class Library.

Code:

 System.Net.ServicePointManager.ServerCertificateValidationCallback +=
 delegate (object sender,
 System.Security.Cryptography.X509Certificates.X509Certificate certificate,
 System.Security.Cryptography.X509Certificates.X509Chain chain,
 System.Net.Security.SslPolicyErrors sslPolicyErrors)
 {
     return true;
 };

 using (var client = new HttpClient())
 {
    client.BaseAddress = new Uri("https://myapi");
    ...

    var result = client.PostAsync(method, httpContent).Result;
    ...
 }


问:
How to delete only few rows if several rows are duplicated in SQL?
How to delete only few rows (more than 1) if several rows are duplicated? When I try to put condition all rows are getting deleted. I'm using SQL server 2008.</p>

答:
This answer assumes a primary key in the table.

After writing this one out, I looked at the answer linked as a possible duplicate (How to delete duplicate rows in sql server?). I like the CTE method much better.

CREATE TEST DATA

```<code>/* Create test data tables */
IF OBJECT_ID('tempdb.dbo.#td', 'U') IS NOT NULL
  DROP TABLE #td;

CREATE TABLE #td ( id int identity, data int NOT NULL ) ;

INSERT INTO #td (data)
VALUES (1),(1),(2),(3),(3),(3),(1),(3)
;
</code>```

MY ORIGINAL

```<code>/* Test data includes dupes. */
SELECT * FROM #td ;

/* Now find and DELETE the dupes. */
DELETE FROM #td
WHERE id IN (
    SELECT sq.id
    FROM (
        SELECT id, ROW_NUMBER() OVER ( PARTITION BY data ORDER BY (data) ) AS rn
        FROM #td
    ) sq
    WHERE sq.rn > 1
)
;

/* Dupes are gone. */
SELECT * FROM #td ;
</code>```

BETTER

```<code>SELECT * FROM #td ;

WITH CTE AS(
   SELECT data, RN = ROW_NUMBER()OVER(PARTITION BY data ORDER BY data)
   FROM #td
)
DELETE FROM CTE WHERE RN > 1

SELECT * FROM #td ;
</code>```

Body:
This answer assumes a primary key in the table.

After writing this one out, I looked at the answer linked as a possible duplicate (How to delete duplicate rows in sql server?). I like the CTE method much better.

CREATE TEST DATA

/* Create test data tables */
IF OBJECT_ID('tempdb.dbo.#td', 'U') IS NOT NULL
  DROP TABLE #td;

CREATE TABLE #td ( id int identity, data int NOT NULL ) ;

INSERT INTO #td (data)
VALUES (1),(1),(2),(3),(3),(3),(1),(3)
;

MY ORIGINAL

/* Test data includes dupes. */
SELECT * FROM #td ;

/* Now find and DELETE the dupes. */
DELETE FROM #td
WHERE id IN (
    SELECT sq.id
    FROM (
        SELECT id, ROW_NUMBER() OVER ( PARTITION BY data ORDER BY (data) ) AS rn
        FROM #td
    ) sq
    WHERE sq.rn > 1
)
;

/* Dupes are gone. */
SELECT * FROM #td ;

BETTER

SELECT * FROM #td ;

WITH CTE AS(
   SELECT data, RN = ROW_NUMBER()OVER(PARTITION BY data ORDER BY data)
   FROM #td
)
DELETE FROM CTE WHERE RN > 1

SELECT * FROM #td ;


问:
Embedded Web Server
We currently have a web application which should be accessible from multiple sub-domains and from multiple actual domains. E.g. clients sign up and if they want to they can use their own domains. As far as I know this would be achieved by them pointing that domains A record at us and then our web server, which would have to be embedded so we can update at run-time, adding a virtual host dynamically.

Our web application is written in PHP (although playing around with HipHop to convert to C++) with static HTML and CSS. This web application communicates with a back-end Java API that uses the Restlet framework.

Does anyone know of a web server that could be embedded that will work with PHP (and would work with HipHop if we used that)? I have had a look at AppWeb but I wondered if there were any others.

I wonder if maybe I would be better moving my web app to something like Java and using Jetty?

Thanks,

答:
If I understand your question correctly, all you need is to lookup the

```<code>$_SERVER['SERVER_NAME']
</code>```

which would be different as clients uses different domains.

Regarding minimalistic webserver, I've found mongoose to flexible and easy to setup.

(uses php-cgi).

http://code.google.com/p/mongoose/

regards,
//t

Title: Embedded Web Server

Body:
If I understand your question correctly, all you need is to lookup the

$_SERVER['SERVER_NAME']

which would be different as clients uses different domains.

Regarding minimalistic webserver, I've found mongoose to flexible and easy to setup.

(uses php-cgi).

http://code.google.com/p/mongoose/

regards,
//t


问:
Excel vba Error 5 Invalid procedure call or argument with power operand
Please consider this sub:

```<code>Sub TestPower()

    Dim dbl As Double

    dbl = -0.682434999562851

    Debug.Print (-0.682434999562851 ^ 0.2)
    Debug.Print (dbl ^ 0.2)
End Sub
</code>```

On the second "debug.print" command, I'm getting an Error 5: Invalid procedure call or argument.

Excel Office 2016.

Any ideas?

答:
What you are seeing has to do with operator precedence in VBA.

In VBA, exponentiation has a higher precedence than does negation.  So in your first equation, the exponentiation operation occurs first, and then the result is negated.

Actually, it seems the Power function is smarter than the exponentiation operator.  In point of fact, you are trying to take the fifth root of a negative number, which would be a real number.  The Power function recognizes that. The exponentiation operator does not.

EDIT: From VBA Help for the ^:  Remarks A number can be negative only if exponent is an integer value.

So it seems that the explanation for the behavior difference is, indeed, operator precedence, and a limitation of the VBA ^ operator.

Body:
Please consider this sub:

Sub TestPower()

    Dim dbl As Double

    dbl = -0.682434999562851

    Debug.Print (-0.682434999562851 ^ 0.2)
    Debug.Print (dbl ^ 0.2)
End Sub

On the second "debug.print" command, I'm getting an Error 5: Invalid procedure call or argument.

Excel Office 2016.

Any ideas?


问:
Why won't loading js once doesn't work when css works?
This loads css only once just fine.

```<code> if (filetype=="css" && !document.querySelector('.load_once') ) {
    var fileref=document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.setAttribute("href", filename)
    fileref.setAttribute("class", "load_once")
}
</code>```

However, the same script won't work for js files.

```<code> if (filetype=="js" && !document.querySelector('.load_once') ) {
    var fileref=document.createElement('script')
    fileref.setAttribute("type","text/javascript")
    fileref.setAttribute("src", filename)
    fileref.setAttribute("class", "load_once")
}
</code>```

I've solved the problem by emptying out the function after it fires so that the function fires only once.

However, I would still like to learn why the above script only worked for css files & not for js files.

What have I done wrong here?

I can't see why this shouldn't work.

Is this one of those weirdness of javascript?  Some sort of bug inherent in javascript itself?

Edit

Pls. see my reply to Borcuhin's comment below.

My argument is that apple with red color or

red apple != red orange.

So logically, I am arguing that my script above should work; but it doesn't!!

Somebody please explain/correct me & let me know how & why javascript treats/thinks read apple is same as red orange.

答:
You can insert script tag like this:

```<code>var script = document.createElement('script');
script.setAttribute('src', '/script.js');
// put tag to the head
document.getElementsByTagName('head')[0].appendChild(script);
</code>```

UPDATE
You need to use different classes for each file include. Because once you added tag with class some_class_name, selector:  document.querySelector('.some_class_name')
will find 1 element. So you just need to use some_other_class_name for js file or other file, or generate randomly the classname If you can have N different files

Body:
This loads css only once just fine.

 if (filetype=="css" && !document.querySelector('.load_once') ) {
    var fileref=document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.setAttribute("href", filename)
    fileref.setAttribute("class", "load_once")
}

However, the same script won't work for js files.

 if (filetype=="js" && !document.querySelector('.load_once') ) {
    var fileref=document.createElement('script')
    fileref.setAttribute("type","text/javascript")
    fileref.setAttribute("src", filename)
    fileref.setAttribute("class", "load_once")
}

I've solved the problem by emptying out the function after it fires so that the function fires only once.

However, I would still like to learn why the above script only worked for css files & not for js files.

What have I done wrong here?

I can't see why this shouldn't work.

Is this one of those weirdness of javascript?  Some sort of bug inherent in javascript itself?

Edit

Pls. see my reply to Borcuhin's comment below.

My argument is that apple with red color or

red apple != red orange.

So logically, I am arguing that my script above should work; but it doesn't!!

Somebody please explain/correct me & let me know how & why javascript treats/thinks read apple is same as red orange.

Body:
You can insert script tag like this:

var script = document.createElement('script');
script.setAttribute('src', '/script.js');
// put tag to the head
document.getElementsByTagName('head')[0].appendChild(script);

UPDATE
You need to use different classes for each file include. Because once you added tag with class some_class_name, selector:  document.querySelector('.some_class_name')
will find 1 element. So you just need to use some_other_class_name for js file or other file, or generate randomly the classname If you can have N different files


问:
Printing Out File Names that are Different
My code below works and the logic works. However, I want to print out the names of the actual files that are not the same in both folders, which are held in the arrays of fileNames1 and fileNames2. I have been searching for the answer with no solution. I am just getting back into the groove with Java after being away form it a while. Any help would be appreciated.

```<code>import java.io.File;
import java.util.ArrayList;

public class nameCompare {

    public static void main(String[] args) {

        String path1 = "C:/Users/hoflerj/Desktop/test";
        String path2 = "C:/Users/hoflerj/Desktop/test2";

        File folder1 = new File(path1);
        File folder2 = new File(path2);

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        ArrayList<String> fileNames1 = new ArrayList<String>();
        ArrayList<String> fileNames2 = new ArrayList<String>();

        for (int i = 0; i < listOfFiles1.length; i++)
        {

            if (listOfFiles1[i].isFile())
            {
                fileNames1.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {

            if (listOfFiles2[i].isFile())
            {
                fileNames2.add(listOfFiles2[i].getName());//seriously wow
            }
        }

        for ( int i = 0; i < 1; i++ )
        {
            if (fileNames1.equals(fileNames2) )
            {
                System.out.println("Files names are the same");
            }

            else if (fileNames1 != fileNames2 )
            {
                System.out.println("Files names are not equal");
            }
        }

    }

}
</code>```

答:
Just compare every element of both the arrays.</p>

```<code>for( int i = 0; i <= listOfFiles1.length - 1; i++)
{
    for( int j = 0; i <= listOfFiles2.length - 1; i++)
{
    if (listOfFiles1[i].equals(listOfFiles2[j]) )
        {
            System.out.println("Files names are the same");
        }

        else if (listOfFiles1[i]!= listOfFiles2[j])
        {
            System.out.println("Files names are not equal");
        }

}

}
</code>```

Body:
My code below works and the logic works. However, I want to print out the names of the actual files that are not the same in both folders, which are held in the arrays of fileNames1 and fileNames2. I have been searching for the answer with no solution. I am just getting back into the groove with Java after being away form it a while. Any help would be appreciated.

import java.io.File;
import java.util.ArrayList;

public class nameCompare {

    public static void main(String[] args) {

        String path1 = "C:/Users/hoflerj/Desktop/test";
        String path2 = "C:/Users/hoflerj/Desktop/test2";

        File folder1 = new File(path1);
        File folder2 = new File(path2);

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        ArrayList<String> fileNames1 = new ArrayList<String>();
        ArrayList<String> fileNames2 = new ArrayList<String>();

        for (int i = 0; i < listOfFiles1.length; i++)
        {

            if (listOfFiles1[i].isFile())
            {
                fileNames1.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {

            if (listOfFiles2[i].isFile())
            {
                fileNames2.add(listOfFiles2[i].getName());//seriously wow
            }
        }

        for ( int i = 0; i < 1; i++ )
        {
            if (fileNames1.equals(fileNames2) )
            {
                System.out.println("Files names are the same");
            }

            else if (fileNames1 != fileNames2 )
            {
                System.out.println("Files names are not equal");
            }
        }

    }

}

Body:
Just compare every element of both the arrays.

for( int i = 0; i <= listOfFiles1.length - 1; i++)
{
    for( int j = 0; i <= listOfFiles2.length - 1; i++)
{
    if (listOfFiles1[i].equals(listOfFiles2[j]) )
        {
            System.out.println("Files names are the same");
        }

        else if (listOfFiles1[i]!= listOfFiles2[j])
        {
            System.out.println("Files names are not equal");
        }

}

}


问:
ADFS Sign-In Pages Customization
I am working on  a iOS application.

The login page which is showing from ADFS on a UIWebview is not looking good, so I want to customise it.

Is this possible from the client side?

I have tried to get user inputs in a custom login field and autofill the web view form and submit so that user can't see the ugly login screen which is coming from ADFS itself, but I am not getting the desired result. I am totally stuck.

答:
Your app should not interfere with the presentation of the ADFS login process.

Presentation of an unmodified ADFS site helps the user confirm that they are entering their credentials into their organisation's federation portal.

An important part of the federation model is that an untrusted party (such as your app) does not have access to the user's credentials, only the token that results from credential validation.

Organisations can (and should) customise the ADFS form branding on the ADFS server.

Title: ADFS Sign-In Pages Customization