问:
sql server Using IF statment before UNION
I am adding a UNION statement and I need to add an IF statement for the UNION but I get an "Incorrect syntax near 'IF'. Expecting ')', EXCEPT, or SELECT   " error.

To improve processor efficiency, I like to only call the UNION if there is a special character in the variable string. Here is my select statement. Any help is appreciated. Thanks.

```<code>set @DelimitedKeyWord = ( select replace(@KeyWord, '-', '') )
set @DelimiterExists = ( select CHARINDEX('-', @KeyWord) )

select distinct top (@MaxHits)
    results.MYID as ItemId
  , results.Rank0 as [RANK]
from (
  select
      [MYID]
    , [RANK] as Rank0
  from [rcl].[MyTable] rm
    inner join CONTAINSTABLE([MyTable], *, @KeyWord) as CNT
      on CNT.[Key] = rm.RecallID

  if (@DelimiterExists > 0)
    begin
      union
      select
          [MYID]
        , [RANK] as Rank0
      from [rcl].[MyTable] rm
      inner join CONTAINSTABLE([MyTable], *, @DelimitedKeyWord) as DCNT
        on DCNT.[Key] = rm.RecallID
    end
  ) as results
</code>```

答:
Could this work?  </p>

```<code>set @DelimitedKeyWord = (select replace(@KeyWord, '-', ''))
             set @DelimiterExists = (select CHARINDEX('-', @KeyWord))

IF (@DelimiterExists > 0)

    BEGIN
        SELECT DISTINCT TOP(@MaxHits)
                    results.MYID AS ItemId,
                    results.Rank0 AS [RANK]
                    FROM
                           (
                                 SELECT
                                        [MYID],
                                        [RANK] AS Rank0
                                 FROM  [rcl].[MyTable] rm
                                        JOIN CONTAINSTABLE ([MyTable], *, @KeyWord) AS CNT
                                               ON CNT.[Key] = rm.RecallID

                                 UNION ALL

                                 SELECT
                                        [MYID],
                                        [RANK] AS Rank0
                                        FROM  [rcl].[MyTable] rm

                                               JOIN CONTAINSTABLE ([MyTable], *, @DelimitedKeyWord) AS DCNT ON DCNT.[Key] = rm.RecallID

                                 ) AS results

    END

ELSE

    BEGIN

    SELECT DISTINCT TOP(@MaxHits)
            results.MYID AS ItemId,
            results.Rank0 AS [RANK]
            FROM
                   (
                         SELECT
                                [MYID],
                                [RANK] AS Rank0
                         FROM  [rcl].[MyTable] rm
                                JOIN CONTAINSTABLE ([MyTable], *, @KeyWord) AS CNT
                                       ON CNT.[Key] = rm.RecallID
                     ) AS results

    END
</code>```

Body:
I am adding a UNION statement and I need to add an IF statement for the UNION but I get an "Incorrect syntax near 'IF'. Expecting ')', EXCEPT, or SELECT   " error.

To improve processor efficiency, I like to only call the UNION if there is a special character in the variable string. Here is my select statement. Any help is appreciated. Thanks.

set @DelimitedKeyWord = ( select replace(@KeyWord, '-', '') )
set @DelimiterExists = ( select CHARINDEX('-', @KeyWord) )

select distinct top (@MaxHits)
    results.MYID as ItemId
  , results.Rank0 as [RANK]
from (
  select
      [MYID]
    , [RANK] as Rank0
  from [rcl].[MyTable] rm
    inner join CONTAINSTABLE([MyTable], *, @KeyWord) as CNT
      on CNT.[Key] = rm.RecallID

  if (@DelimiterExists > 0)
    begin
      union
      select
          [MYID]
        , [RANK] as Rank0
      from [rcl].[MyTable] rm
      inner join CONTAINSTABLE([MyTable], *, @DelimitedKeyWord) as DCNT
        on DCNT.[Key] = rm.RecallID
    end
  ) as results

Body:
Could this work?

set @DelimitedKeyWord = (select replace(@KeyWord, '-', ''))
             set @DelimiterExists = (select CHARINDEX('-', @KeyWord))

IF (@DelimiterExists > 0)

    BEGIN
        SELECT DISTINCT TOP(@MaxHits)
                    results.MYID AS ItemId,
                    results.Rank0 AS [RANK]
                    FROM
                           (
                                 SELECT
                                        [MYID],
                                        [RANK] AS Rank0
                                 FROM  [rcl].[MyTable] rm
                                        JOIN CONTAINSTABLE ([MyTable], *, @KeyWord) AS CNT
                                               ON CNT.[Key] = rm.RecallID

                                 UNION ALL

                                 SELECT
                                        [MYID],
                                        [RANK] AS Rank0
                                        FROM  [rcl].[MyTable] rm

                                               JOIN CONTAINSTABLE ([MyTable], *, @DelimitedKeyWord) AS DCNT ON DCNT.[Key] = rm.RecallID

                                 ) AS results

    END

ELSE

    BEGIN

    SELECT DISTINCT TOP(@MaxHits)
            results.MYID AS ItemId,
            results.Rank0 AS [RANK]
            FROM
                   (
                         SELECT
                                [MYID],
                                [RANK] AS Rank0
                         FROM  [rcl].[MyTable] rm
                                JOIN CONTAINSTABLE ([MyTable], *, @KeyWord) AS CNT
                                       ON CNT.[Key] = rm.RecallID
                     ) AS results

    END


来源: stackexchange

问:
Calclulating a set of lines slopes after using Xlim in Matlab
I'm plotting a series of lines in MATLAB and the figure is like this:

As you can see the X-axis is Frequency, I want to limit the frequency spectrum so I use Xlim function in my code to select my desired bandwidth while plotting.

Now I want to calculate the slope of those lines in the chosen frequency bandwidth (what's in the plot window), not the entire band but if I choose the basic fitting option, it's clearly giving me a linear fit for the line over the entire frequency band.

Any advice?
Thanks.

答:
You can do this in the matlab script: </p>

```<code>% your data
f = linspace(2e7,11e7,100);
x = linspace(-0.5,-2.5,100)+0.1*rand(1,100);
% Linear fit in a specific range:
[~,i] = find( f>3e7 & f<9e7 ); % <= set your range here
p = polyfit(f(i),x(i),1); % <= note the (i) for both variables

figure;
hold all
plot(f,x,'r.-')
plot(f(i),polyval(p,f(i)),'k-','LineWidth',2) % <= polyval takes the 'p' from polyfit + the data on the x-axis
% the fit is y = p(1)*x+p(2)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can do this in the matlab script:

% your data
f = linspace(2e7,11e7,100);
x = linspace(-0.5,-2.5,100)+0.1*rand(1,100);
% Linear fit in a specific range:
[~,i] = find( f>3e7 & f<9e7 ); % <= set your range here
p = polyfit(f(i),x(i),1); % <= note the (i) for both variables

figure;
hold all
plot(f,x,'r.-')
plot(f(i),polyval(p,f(i)),'k-','LineWidth',2) % <= polyval takes the 'p' from polyfit + the data on the x-axis
% the fit is y = p(1)*x+p(2)


问:
Error (10500): VHDL syntax error at lab_06.vhd(54) near text "shifta";
enter image description here

Error (10500): VHDL syntax error at lab_06.vhd(54) near text "shifta";

```<code>Info: *******************************************************************
Info: Running Quartus II 64-Bit Analysis & Synthesis
    Info: Version 13.0.1 Build 232 06/12/2013 Service Pack 1 SJ Web Edition
    Info: Processing started: Mon Nov 13 18:53:13 2017
Info: Command: quartus_map --read_settings_files=on --write_settings_files=off lab_06 -c lab_06
Warning (20028): Parallel compilation is not licensed and has been disabled
Error (10500): VHDL syntax error at lab_06.vhd(30) near text "ktj";  expecting "component"
Error (10500): VHDL syntax error at lab_06.vhd(54) near text "shifta";  expecting "entity", or "architecture", or "use", or "library", or "package", or "configuration"
Info (12021): Found 0 design units, including 0 entities, in source file lab_06.vhd
Error: Quartus II 64-Bit Analysis & Synthesis was unsuccessful. 2 errors, 1 warning
    Error: Peak virtual memory: 485 megabytes
    Error: Processing ended: Mon Nov 13 18:53:14 2017
    Error: Elapsed time: 00:00:01
    Error: Total CPU time (on all processors): 00:00:01
Error (293001): Quartus II Full Compilation was unsuccessful. 4 errors, 1 warning
</code>```

答: It looks to me like you've tried to instantiate lab_06 outside the architecture Behavior. Had you written end architecture Behavior;, I think the problem would have stared you in the face.

Body:
enter image description here

Error (10500): VHDL syntax error at lab_06.vhd(54) near text "shifta";

Info: *******************************************************************
Info: Running Quartus II 64-Bit Analysis & Synthesis
    Info: Version 13.0.1 Build 232 06/12/2013 Service Pack 1 SJ Web Edition
    Info: Processing started: Mon Nov 13 18:53:13 2017
Info: Command: quartus_map --read_settings_files=on --write_settings_files=off lab_06 -c lab_06
Warning (20028): Parallel compilation is not licensed and has been disabled
Error (10500): VHDL syntax error at lab_06.vhd(30) near text "ktj";  expecting "component"
Error (10500): VHDL syntax error at lab_06.vhd(54) near text "shifta";  expecting "entity", or "architecture", or "use", or "library", or "package", or "configuration"
Info (12021): Found 0 design units, including 0 entities, in source file lab_06.vhd
Error: Quartus II 64-Bit Analysis & Synthesis was unsuccessful. 2 errors, 1 warning
    Error: Peak virtual memory: 485 megabytes
    Error: Processing ended: Mon Nov 13 18:53:14 2017
    Error: Elapsed time: 00:00:01
    Error: Total CPU time (on all processors): 00:00:01
Error (293001): Quartus II Full Compilation was unsuccessful. 4 errors, 1 warning


问:
Eclipse/Java9: how to access internal javafx packages?
My context:

Eclipse IDE for Java Developers, Version: Oxygen.1a Release (4.7.1a), Build id: 20171005-1200oxygen

jdk9.0.1

win10

Something simple like:

```<code>import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;

import javafx.application.Application;
import javafx.stage.Stage;

public class ImportCom extends Application {

    @Override
    public void start(Stage arg0) throws Exception {
        new LambdaMultiplePropertyChangeListenerHandler();

    }

}
</code>```

won't compile due to

```<code>The type com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler is not accessible
</code>```

What to do?

looks similar but now for internal classes ;) Had been compiling until patch 530 of the beta9 support but not after - so keeping that oldish oxygen as a gold treasure ...

Note: cross-posted to eclipse forum

Edit:

Just checked that the behavior of javac on the commandline:

```<code>C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac first\ImportCom.java
first\ImportCom.java:3: error: package com.sun.javafx.scene.control is not visible
import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;
                           ^
  (package com.sun.javafx.scene.control is declared in module javafx.controls, which does not export it to the unnamed module)
1 error
</code>```

The error is similar to the one in Eclipse. Works fine with --add-exports:

```<code>C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac --add-exports=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED first\ImportCom.java
</code>```

So the question boils down to: where/how to configure Eclipse such that it compiles access to internal classes just the same way as javac?

答:
In order to solve this issue you have to add the compiler argument
--add-exports=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED.
This can be done in Eclipse too but I have to admit at a very hidden place.

Go to the properties of your project and then to the Java Build Path.
Select Modulepath and then the JRE System library (should be java 9).
Inside that you find an item "is modular". Select that. Then open "Edit"
on the right and a menu will open. At the top select "Details". There you will see a table where you can add your exports. Believe it or not but it works :-) I had to clean and re-build the project though in order to really get this compiled.

Body:
My context:

Eclipse IDE for Java Developers, Version: Oxygen.1a Release (4.7.1a), Build id: 20171005-1200oxygen

jdk9.0.1

win10

Something simple like:

import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;

import javafx.application.Application;
import javafx.stage.Stage;

public class ImportCom extends Application {

    @Override
    public void start(Stage arg0) throws Exception {
        new LambdaMultiplePropertyChangeListenerHandler();

    }

}

won't compile due to

The type com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler is not accessible

What to do?

looks similar but now for internal classes ;) Had been compiling until patch 530 of the beta9 support but not after - so keeping that oldish oxygen as a gold treasure ...

Note: cross-posted to eclipse forum

Edit:

Just checked that the behavior of javac on the commandline:

C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac first\ImportCom.java
first\ImportCom.java:3: error: package com.sun.javafx.scene.control is not visible
import com.sun.javafx.scene.control.LambdaMultiplePropertyChangeListenerHandler;
                           ^
  (package com.sun.javafx.scene.control is declared in module javafx.controls, which does not export it to the unnamed module)
1 error

The error is similar to the one in Eclipse. Works fine with --add-exports:

C:\Users\kleopatra\ox-1a-64\dummy\src>\java\jdk\190-64\bin\javac --add-exports=javafx.controls/com.sun.javafx.scene.control=ALL-UNNAMED first\ImportCom.java

So the question boils down to: where/how to configure Eclipse such that it compiles access to internal classes just the same way as javac?


问:
Responsive grid, how to add margin between columns?
I'm watching course about html & css and use modified responsive grid from here:
http://www.responsivegridsystem.com/calculator/

If browser width decreases, divs go to new lines and finally are shown in one column. It works, but

cannot add horizontal spacing between elements:

jsfiddle

index.html

```<code> <!-- FIRST ROW -->
<div class="row">
    <div class="col span-1-of-2 box">
        <h3>first-row span-1</h3>
    </div>
    <div class="col span-1-of-2 box">
        <h3>first-row span-2</h3>
    </div>
</div>

<!-- SECOND ROW -->
<div class="row">
    <div class="col span-1-of-4 box">
        <h3>second-row span-1</h3>
        <p>You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
            work with the best chefs in each town to ensure that you're 100% happy.</p>
    </div>
    <div class="col span-1-of-4 box">
        <h3>second-row span-2</h3>
        <p>You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
            work with the best chefs in each town to ensure that you're 100% happy.</p>
    </div>
    <div class="col span-1-of-4 box">
        <h3>second-row span-3</h3>
        <p>You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
            work with the best chefs in each town to ensure that you're 100% happy.</p>
    </div>
    <div class="col span-1-of-4 box">
        <h3>second-row span-4</h3>
        <p>You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
            work with the best chefs in each town to ensure that you're 100% happy.</p>
    </div>
</div>
</code>```

Media.css

```<code>/* small phones to small tyablets 481 to 767 */
@media only screen and (max-width: 767px) {
    .col {  margin: 1% 0 1% 0%; }
    .span-1-of-2 { width: 98%; padding-right: 1%;}
    .span-1-of-4, .span-2-of-4, .span-3-of-4, .span-4-of-4 { width: 45%; }
}

/* small phones 0 to 480 */
@media only screen and (max-width: 480px) {
    .col {  margin: 1% 1% 1% 1%; }
    .span-1-of-4, .span-2-of-4, .span-3-of-4, .span-4-of-4 { width: 100%; }
}
</code>```

styles.css

```<code>/* -------- REUSABLE COMPONENETS -------- */
* {
    margin: 0%;
    padding: 0%;
    box-sizing: border-box;
}

html {
    background-color: #fff;
    color: #555;
    font-family: 'Lato', 'Arial', sans-serif;
    font-size: 20px;
    font-weight: 300;
    text-rendering: optimizeLegibility;
}

.clearfix {zoom: 1;}
.clearfix:after {
    content: ' ';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

/* row class from grid css */
.row {
    width: 1140px;
    margin: 0 auto;
}

section {
    padding: 80px 0;
}

 /* class to modify out-of-the-box grid classes (like 'span-1-of-4') */
.box {

    background-color: #1ba1e2;
    border: 1px solid gray;
}
</code>```

grid.css

```<code>/*  SECTIONS  ============================================================================= */

.section {
    clear: both;
    padding: 0px;
    margin: 0px;
}

/*  GROUPING  ============================================================================= */

.row {
    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}

.row:before,
.row:after {
    content:"";
    display:table;
}
.row:after {
    clear:both;
}

/*  GRID COLUMN SETUP   ==================================================================== */

.col {
    display: block;
    float:left;
    margin: 1% 0 1% 1.6%;
}

.col:first-child { margin-left: 0; } /* all browsers except IE6 and lower */

/*  REMOVE MARGINS AS ALL GO FULL WIDTH AT 480 PIXELS */

@media only screen and (max-width: 480px) {
    .col {
        /*margin: 1% 0 1% 0%;*/
        margin: 0;
    }
}

/*  GRID OF TWO   ============================================================================= */

.span-2-of-2 {
    width: 100%;
}

.span-1-of-2 {
    width: 49.2%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-2-of-2 {
        width: 100%;
    }
    .span-1-of-2 {
        width: 100%;
    }
}

/*  GRID OF THREE   ============================================================================= */

.span-3-of-3 {
    width: 100%;
}

.span-2-of-3 {
    width: 66.13%;
}

.span-1-of-3 {
    width: 32.26%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-3-of-3 {
        width: 100%;
    }
    .span-2-of-3 {
        width: 100%;
    }
    .span-1-of-3 {
        width: 100%;
    }
}

/*  GRID OF FOUR   ============================================================================= */

.span-4-of-4 {
    width: 100%;
}

.span-3-of-4 {
    width: 74.6%;
}

.span-2-of-4 {
    width: 49.2%;
}

.span-1-of-4 {
    width: 23.8%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-4-of-4 {
        width: 100%;
    }
    .span-3-of-4 {
        width: 100%;
    }
    .span-2-of-4 {
        width: 100%;
    }
    .span-1-of-4 {
        width: 100%;
    }
}

/*  GRID OF FIVE   ============================================================================= */

.span-5-of-5 {
    width: 100%;
}

.span-4-of-5 {
    width: 79.68%;
}

.span-3-of-5 {
    width: 59.36%;
}

.span-2-of-5 {
    width: 39.04%;
}

.span-1-of-5 {
    width: 18.72%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-5-of-5 {
        width: 100%;
    }
    .span-4-of-5 {
        width: 100%;
    }
    .span-3-of-5 {
        width: 100%;
    }
    .span-2-of-5 {
        width: 100%;
    }
    .span-1-of-5 {
        width: 100%;
    }
}

/*  GRID OF SIX   ============================================================================= */

.span-6-of-6 {
    width: 100%;
}

.span-5-of-6 {
    width: 83.06%;
}

.span-4-of-6 {
    width: 66.13%;
}

.span-3-of-6 {
    width: 49.2%;
}

.span-2-of-6 {
    width: 32.26%;
}

.span-1-of-6 {
    width: 15.33%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-6-of-6 {
        width: 100%;
    }
    .span-5-of-6 {
        width: 100%;
    }
    .span-4-of-6 {
        width: 100%;
    }
    .span-3-of-6 {
        width: 100%;
    }
    .span-2-of-6 {
        width: 100%;
    }
    .span-1-of-6 {
        width: 100%;
    }
}

/*  GRID OF SEVEN   ============================================================================= */

.span-7-of-7 {
    width: 100%;
}

.span-6-of-7 {
    width: 85.48%;
}

.span-5-of-7 {
    width: 70.97%;
}

.span-4-of-7 {
    width: 56.45%;
}

.span-3-of-7 {
    width: 41.94%;
}

.span-2-of-7 {
    width: 27.42%;
}

.span-1-of-7 {
    width: 12.91%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-7-of-7 {
        width: 100%;
    }
    .span-6-of-7 {
        width: 100%;
    }
    .span-5-of-7 {
        width: 100%;
    }
    .span-4-of-7 {
        width: 100%;
    }
    .span-3-of-7 {
        width: 100%;
    }
    .span-2-of-7 {
        width: 100%;
    }
    .span-1-of-7 {
        width: 100%;
    }
}

/*  GRID OF EIGHT   ============================================================================= */

.span-8-of-8 {
    width: 100%;
}

.span-7-of-8 {
    width: 87.3%;
}

.span-6-of-8 {
    width: 74.6%;
}

.span-5-of-8 {
    width: 61.9%;
}

.span-4-of-8 {
    width: 49.2%;
}

.span-3-of-8 {
    width: 36.5%;
}

.span-2-of-8 {
    width: 23.8%;
}

.span-1-of-8 {
    width: 11.1%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-8-of-8 {
        width: 100%;
    }
    .span-7-of-8 {
        width: 100%;
    }
    .span-6-of-8 {
        width: 100%;
    }
    .span-5-of-8 {
        width: 100%;
    }
    .span-4-of-8 {
        width: 100%;
    }
    .span-3-of-8 {
        width: 100%;
    }
    .span-2-of-8 {
        width: 100%;
    }
    .span-1-of-8 {
        width: 100%;
    }
}

/*  GRID OF NINE   ============================================================================= */

.span-9-of-9 {
    width: 100%;
}

.span-8-of-9 {
    width: 88.71%;
}

.span-7-of-9 {
    width: 77.42%;
}

.span-6-of-9 {
    width: 66.13%;
}

.span-5-of-9 {
    width: 54.84%;
}

.span-4-of-9 {
    width: 43.55%;
}

.span-3-of-9 {
    width: 32.26%;
}

.span-2-of-9 {
    width: 20.97%;
}

.span-1-of-9 {
    width: 9.68%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-9-of-9 {
        width: 100%;
    }
    .span-8-of-9 {
        width: 100%;
    }
    .span-7-of-9 {
        width: 100%;
    }
    .span-6-of-9 {
        width: 100%;
    }
    .span-5-of-9 {
        width: 100%;
    }
    .span-4-of-9 {
        width: 100%;
    }
    .span-3-of-9 {
        width: 100%;
    }
    .span-2-of-9 {
        width: 100%;
    }
    .span-1-of-9 {
        width: 100%;
    }
}

/*  GRID OF TEN   ============================================================================= */

.span-10-of-10 {
    width: 100%;
}

.span-9-of-10 {
    width: 89.84%;
}

.span-8-of-10 {
    width: 79.68%;
}

.span-7-of-10 {
    width: 69.52%;
}

.span-6-of-10 {
    width: 59.36%;
}

.span-5-of-10 {
    width: 49.2%;
}

.span-4-of-10 {
    width: 39.04%;
}

.span-3-of-10 {
    width: 28.88%;
}

.span-2-of-10 {
    width: 18.72%;
}

.span-1-of-10 {
    width: 8.56%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-10-of-10 {
        width: 100%;
    }
    .span-9-of-10 {
        width: 100%;
    }
    .span-8-of-10 {
        width: 100%;
    }
    .span-7-of-10 {
        width: 100%;
    }
    .span-6-of-10 {
        width: 100%;
    }
    .span-5-of-10 {
        width: 100%;
    }
    .span-4-of-10 {
        width: 100%;
    }
    .span-3-of-10 {
        width: 100%;
    }
    .span-2-of-10 {
        width: 100%;
    }
    .span-1-of-10 {
        width: 100%;
    }
}

/*  GRID OF ELEVEN   ============================================================================= */

.span-11-of-11 {
    width: 100%;
}

.span-10-of-11 {
    width: 90.76%;
}

.span-9-of-11 {
    width: 81.52%;
}

.span-8-of-11 {
    width: 72.29%;
}

.span-7-of-11 {
    width: 63.05%;
}

.span-6-of-11 {
    width: 53.81%;
}

.span-5-of-11 {
    width: 44.58%;
}

.span-4-of-11 {
    width: 35.34%;
}

.span-3-of-11 {
    width: 26.1%;
}

.span-2-of-11 {
    width: 16.87%;
}

.span-1-of-11 {
    width: 7.63%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-11-of-11 {
        width: 100%;
    }
    .span-10-of-11 {
        width: 100%;
    }
    .span-9-of-11 {
        width: 100%;
    }
    .span-8-of-11 {
        width: 100%;
    }
    .span-7-of-11 {
        width: 100%;
    }
    .span-6-of-11 {
        width: 100%;
    }
    .span-5-of-11 {
        width: 100%;
    }
    .span-4-of-11 {
        width: 100%;
    }
    .span-3-of-11 {
        width: 100%;
    }
    .span-2-of-11 {
        width: 100%;
    }
    .span-1-of-11 {
        width: 100%;
    }
}

/*  GRID OF TWELVE   ============================================================================= */

.span-12-of-12 {
    width: 100%;
}

.span-11-of-12 {
    width: 91.53%;
}

.span-10-of-12 {
    width: 83.06%;
}

.span-9-of-12 {
    width: 74.6%;
}

.span-8-of-12 {
    width: 66.13%;
}

.span-7-of-12 {
    width: 57.66%;
}

.span-6-of-12 {
    width: 49.2%;
}

.span-5-of-12 {
    width: 40.73%;
}

.span-4-of-12 {
    width: 32.26%;
}

.span-3-of-12 {
    width: 23.8%;
}

.span-2-of-12 {
    width: 15.33%;
}

.span-1-of-12 {
    width: 6.86%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-12-of-12 {
        width: 100%;
    }
    .span-11-of-12 {
        width: 100%;
    }
    .span-10-of-12 {
        width: 100%;
    }
    .span-9-of-12 {
        width: 100%;
    }
    .span-8-of-12 {
        width: 100%;
    }
    .span-7-of-12 {
        width: 100%;
    }
    .span-6-of-12 {
        width: 100%;
    }
    .span-5-of-12 {
        width: 100%;
    }
    .span-4-of-12 {
        width: 100%;
    }
    .span-3-of-12 {
        width: 100%;
    }
    .span-2-of-12 {
        width: 100%;
    }
    .span-1-of-12 {
        width: 100%;
    }
}
</code>```

I'll attach folder with example, which could be opened in HTML Editor
https://mega.nz/#!fh0zSLQR!sNWr7joNedcOPfmEb9BwCAZdTncizAfm9EsQ7ITh8Zk

Body:
I'm watching course about html & css and use modified responsive grid from here:
http://www.responsivegridsystem.com/calculator/

If browser width decreases, divs go to new lines and finally are shown in one column. It works, but

cannot add horizontal spacing between elements:

jsfiddle

index.html

first-row span-1

first-row span-2

second-row span-1

You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
            work with the best chefs in each town to ensure that you're 100% happy.

second-row span-2

You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
            work with the best chefs in each town to ensure that you're 100% happy.

second-row span-3

You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
            work with the best chefs in each town to ensure that you're 100% happy.

second-row span-4

You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
            work with the best chefs in each town to ensure that you're 100% happy.

Media.css

/* small phones to small tyablets 481 to 767 */
@media only screen and (max-width: 767px) {
    .col {  margin: 1% 0 1% 0%; }
    .span-1-of-2 { width: 98%; padding-right: 1%;}
    .span-1-of-4, .span-2-of-4, .span-3-of-4, .span-4-of-4 { width: 45%; }
}

/* small phones 0 to 480 */
@media only screen and (max-width: 480px) {
    .col {  margin: 1% 1% 1% 1%; }
    .span-1-of-4, .span-2-of-4, .span-3-of-4, .span-4-of-4 { width: 100%; }
}

styles.css

/* -------- REUSABLE COMPONENETS -------- */
* {
    margin: 0%;
    padding: 0%;
    box-sizing: border-box;
}

html {
    background-color: #fff;
    color: #555;
    font-family: 'Lato', 'Arial', sans-serif;
    font-size: 20px;
    font-weight: 300;
    text-rendering: optimizeLegibility;
}

.clearfix {zoom: 1;}
.clearfix:after {
    content: ' ';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

/* row class from grid css */
.row {
    width: 1140px;
    margin: 0 auto;
}

section {
    padding: 80px 0;
}

 /* class to modify out-of-the-box grid classes (like 'span-1-of-4') */
.box {

    background-color: #1ba1e2;
    border: 1px solid gray;
}

grid.css

/*  SECTIONS  ============================================================================= */

.section {
    clear: both;
    padding: 0px;
    margin: 0px;
}

/*  GROUPING  ============================================================================= */

.row {
    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}

.row:before,
.row:after {
    content:"";
    display:table;
}
.row:after {
    clear:both;
}

/*  GRID COLUMN SETUP   ==================================================================== */

.col {
    display: block;
    float:left;
    margin: 1% 0 1% 1.6%;
}

.col:first-child { margin-left: 0; } /* all browsers except IE6 and lower */

/*  REMOVE MARGINS AS ALL GO FULL WIDTH AT 480 PIXELS */

@media only screen and (max-width: 480px) {
    .col {
        /*margin: 1% 0 1% 0%;*/
        margin: 0;
    }
}

/*  GRID OF TWO   ============================================================================= */

.span-2-of-2 {
    width: 100%;
}

.span-1-of-2 {
    width: 49.2%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-2-of-2 {
        width: 100%;
    }
    .span-1-of-2 {
        width: 100%;
    }
}

/*  GRID OF THREE   ============================================================================= */

.span-3-of-3 {
    width: 100%;
}

.span-2-of-3 {
    width: 66.13%;
}

.span-1-of-3 {
    width: 32.26%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-3-of-3 {
        width: 100%;
    }
    .span-2-of-3 {
        width: 100%;
    }
    .span-1-of-3 {
        width: 100%;
    }
}

/*  GRID OF FOUR   ============================================================================= */

.span-4-of-4 {
    width: 100%;
}

.span-3-of-4 {
    width: 74.6%;
}

.span-2-of-4 {
    width: 49.2%;
}

.span-1-of-4 {
    width: 23.8%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-4-of-4 {
        width: 100%;
    }
    .span-3-of-4 {
        width: 100%;
    }
    .span-2-of-4 {
        width: 100%;
    }
    .span-1-of-4 {
        width: 100%;
    }
}

/*  GRID OF FIVE   ============================================================================= */

.span-5-of-5 {
    width: 100%;
}

.span-4-of-5 {
    width: 79.68%;
}

.span-3-of-5 {
    width: 59.36%;
}

.span-2-of-5 {
    width: 39.04%;
}

.span-1-of-5 {
    width: 18.72%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-5-of-5 {
        width: 100%;
    }
    .span-4-of-5 {
        width: 100%;
    }
    .span-3-of-5 {
        width: 100%;
    }
    .span-2-of-5 {
        width: 100%;
    }
    .span-1-of-5 {
        width: 100%;
    }
}

/*  GRID OF SIX   ============================================================================= */

.span-6-of-6 {
    width: 100%;
}

.span-5-of-6 {
    width: 83.06%;
}

.span-4-of-6 {
    width: 66.13%;
}

.span-3-of-6 {
    width: 49.2%;
}

.span-2-of-6 {
    width: 32.26%;
}

.span-1-of-6 {
    width: 15.33%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-6-of-6 {
        width: 100%;
    }
    .span-5-of-6 {
        width: 100%;
    }
    .span-4-of-6 {
        width: 100%;
    }
    .span-3-of-6 {
        width: 100%;
    }
    .span-2-of-6 {
        width: 100%;
    }
    .span-1-of-6 {
        width: 100%;
    }
}

/*  GRID OF SEVEN   ============================================================================= */

.span-7-of-7 {
    width: 100%;
}

.span-6-of-7 {
    width: 85.48%;
}

.span-5-of-7 {
    width: 70.97%;
}

.span-4-of-7 {
    width: 56.45%;
}

.span-3-of-7 {
    width: 41.94%;
}

.span-2-of-7 {
    width: 27.42%;
}

.span-1-of-7 {
    width: 12.91%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-7-of-7 {
        width: 100%;
    }
    .span-6-of-7 {
        width: 100%;
    }
    .span-5-of-7 {
        width: 100%;
    }
    .span-4-of-7 {
        width: 100%;
    }
    .span-3-of-7 {
        width: 100%;
    }
    .span-2-of-7 {
        width: 100%;
    }
    .span-1-of-7 {
        width: 100%;
    }
}

/*  GRID OF EIGHT   ============================================================================= */

.span-8-of-8 {
    width: 100%;
}

.span-7-of-8 {
    width: 87.3%;
}

.span-6-of-8 {
    width: 74.6%;
}

.span-5-of-8 {
    width: 61.9%;
}

.span-4-of-8 {
    width: 49.2%;
}

.span-3-of-8 {
    width: 36.5%;
}

.span-2-of-8 {
    width: 23.8%;
}

.span-1-of-8 {
    width: 11.1%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-8-of-8 {
        width: 100%;
    }
    .span-7-of-8 {
        width: 100%;
    }
    .span-6-of-8 {
        width: 100%;
    }
    .span-5-of-8 {
        width: 100%;
    }
    .span-4-of-8 {
        width: 100%;
    }
    .span-3-of-8 {
        width: 100%;
    }
    .span-2-of-8 {
        width: 100%;
    }
    .span-1-of-8 {
        width: 100%;
    }
}

/*  GRID OF NINE   ============================================================================= */

.span-9-of-9 {
    width: 100%;
}

.span-8-of-9 {
    width: 88.71%;
}

.span-7-of-9 {
    width: 77.42%;
}

.span-6-of-9 {
    width: 66.13%;
}

.span-5-of-9 {
    width: 54.84%;
}

.span-4-of-9 {
    width: 43.55%;
}

.span-3-of-9 {
    width: 32.26%;
}

.span-2-of-9 {
    width: 20.97%;
}

.span-1-of-9 {
    width: 9.68%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-9-of-9 {
        width: 100%;
    }
    .span-8-of-9 {
        width: 100%;
    }
    .span-7-of-9 {
        width: 100%;
    }
    .span-6-of-9 {
        width: 100%;
    }
    .span-5-of-9 {
        width: 100%;
    }
    .span-4-of-9 {
        width: 100%;
    }
    .span-3-of-9 {
        width: 100%;
    }
    .span-2-of-9 {
        width: 100%;
    }
    .span-1-of-9 {
        width: 100%;
    }
}

/*  GRID OF TEN   ============================================================================= */

.span-10-of-10 {
    width: 100%;
}

.span-9-of-10 {
    width: 89.84%;
}

.span-8-of-10 {
    width: 79.68%;
}

.span-7-of-10 {
    width: 69.52%;
}

.span-6-of-10 {
    width: 59.36%;
}

.span-5-of-10 {
    width: 49.2%;
}

.span-4-of-10 {
    width: 39.04%;
}

.span-3-of-10 {
    width: 28.88%;
}

.span-2-of-10 {
    width: 18.72%;
}

.span-1-of-10 {
    width: 8.56%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-10-of-10 {
        width: 100%;
    }
    .span-9-of-10 {
        width: 100%;
    }
    .span-8-of-10 {
        width: 100%;
    }
    .span-7-of-10 {
        width: 100%;
    }
    .span-6-of-10 {
        width: 100%;
    }
    .span-5-of-10 {
        width: 100%;
    }
    .span-4-of-10 {
        width: 100%;
    }
    .span-3-of-10 {
        width: 100%;
    }
    .span-2-of-10 {
        width: 100%;
    }
    .span-1-of-10 {
        width: 100%;
    }
}

/*  GRID OF ELEVEN   ============================================================================= */

.span-11-of-11 {
    width: 100%;
}

.span-10-of-11 {
    width: 90.76%;
}

.span-9-of-11 {
    width: 81.52%;
}

.span-8-of-11 {
    width: 72.29%;
}

.span-7-of-11 {
    width: 63.05%;
}

.span-6-of-11 {
    width: 53.81%;
}

.span-5-of-11 {
    width: 44.58%;
}

.span-4-of-11 {
    width: 35.34%;
}

.span-3-of-11 {
    width: 26.1%;
}

.span-2-of-11 {
    width: 16.87%;
}

.span-1-of-11 {
    width: 7.63%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-11-of-11 {
        width: 100%;
    }
    .span-10-of-11 {
        width: 100%;
    }
    .span-9-of-11 {
        width: 100%;
    }
    .span-8-of-11 {
        width: 100%;
    }
    .span-7-of-11 {
        width: 100%;
    }
    .span-6-of-11 {
        width: 100%;
    }
    .span-5-of-11 {
        width: 100%;
    }
    .span-4-of-11 {
        width: 100%;
    }
    .span-3-of-11 {
        width: 100%;
    }
    .span-2-of-11 {
        width: 100%;
    }
    .span-1-of-11 {
        width: 100%;
    }
}

/*  GRID OF TWELVE   ============================================================================= */

.span-12-of-12 {
    width: 100%;
}

.span-11-of-12 {
    width: 91.53%;
}

.span-10-of-12 {
    width: 83.06%;
}

.span-9-of-12 {
    width: 74.6%;
}

.span-8-of-12 {
    width: 66.13%;
}

.span-7-of-12 {
    width: 57.66%;
}

.span-6-of-12 {
    width: 49.2%;
}

.span-5-of-12 {
    width: 40.73%;
}

.span-4-of-12 {
    width: 32.26%;
}

.span-3-of-12 {
    width: 23.8%;
}

.span-2-of-12 {
    width: 15.33%;
}

.span-1-of-12 {
    width: 6.86%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
    .span-12-of-12 {
        width: 100%;
    }
    .span-11-of-12 {
        width: 100%;
    }
    .span-10-of-12 {
        width: 100%;
    }
    .span-9-of-12 {
        width: 100%;
    }
    .span-8-of-12 {
        width: 100%;
    }
    .span-7-of-12 {
        width: 100%;
    }
    .span-6-of-12 {
        width: 100%;
    }
    .span-5-of-12 {
        width: 100%;
    }
    .span-4-of-12 {
        width: 100%;
    }
    .span-3-of-12 {
        width: 100%;
    }
    .span-2-of-12 {
        width: 100%;
    }
    .span-1-of-12 {
        width: 100%;
    }
}

I'll attach folder with example, which could be opened in HTML Editor
https://mega.nz/#!fh0zSLQR!sNWr7joNedcOPfmEb9BwCAZdTncizAfm9EsQ7ITh8Zk

Body:
I made some changes in your custom grid css.

Updated fiddle: https://jsfiddle.net/t0g0chrh/3/

/*  SECTIONS  ============================================================================= */

.section {
 clear: both;
 padding: 0px;
 margin: 0px;
}

/*  GROUPING  ============================================================================= */

.row {
    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}

.row:before,
.row:after {
    content:"";
    display:table;
}
.row:after {
    clear:both;
}

/*  GRID COLUMN SETUP   ==================================================================== */

.col {
 display: block;
 float:left;
 margin: 1% 0 1% 1.6%;
}

.col:first-child { margin-left: 0; } /* all browsers except IE6 and lower */

/*  REMOVE MARGINS AS ALL GO FULL WIDTH AT 480 PIXELS */

@media only screen and (max-width: 480px) {
 .col {
  /*margin: 1% 0 1% 0%;*/
        margin: 0;
 }
}

/*  GRID OF TWO   ============================================================================= */

.span-2-of-2 {
 width: 100%;
}

.span-1-of-2 {
 width: 49.2%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-2-of-2 {
  width: 100%;
 }
 .span-1-of-2 {
  width: 100%;
 }
}

/*  GRID OF THREE   ============================================================================= */

.span-3-of-3 {
 width: 100%;
}

.span-2-of-3 {
 width: 66.13%;
}

.span-1-of-3 {
 width: 32.26%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-3-of-3 {
  width: 100%;
 }
 .span-2-of-3 {
  width: 100%;
 }
 .span-1-of-3 {
  width: 100%;
 }
}

/*  GRID OF FOUR   ============================================================================= */

.span-4-of-4 {
 width: 100%;
}

.span-3-of-4 {
 width: 74.6%;
}

.span-2-of-4 {
 width: 49.2%;
}

.span-1-of-4 {
 width: 23.8%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-4-of-4 {
  width: 100%;
 }
 .span-3-of-4 {
  width: 100%;
 }
 .span-2-of-4 {
  width: 100%;
 }
 .span-1-of-4 {
  width: 100%;
 }
}

/*  GRID OF FIVE   ============================================================================= */

.span-5-of-5 {
 width: 100%;
}

.span-4-of-5 {
   width: 79.68%;
}

.span-3-of-5 {
   width: 59.36%;
}

.span-2-of-5 {
   width: 39.04%;
}

.span-1-of-5 {
   width: 18.72%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-5-of-5 {
  width: 100%;
 }
 .span-4-of-5 {
  width: 100%;
 }
 .span-3-of-5 {
  width: 100%;
 }
 .span-2-of-5 {
  width: 100%;
 }
 .span-1-of-5 {
  width: 100%;
 }
}

/*  GRID OF SIX   ============================================================================= */

.span-6-of-6 {
 width: 100%;
}

.span-5-of-6 {
   width: 83.06%;
}

.span-4-of-6 {
   width: 66.13%;
}

.span-3-of-6 {
   width: 49.2%;
}

.span-2-of-6 {
   width: 32.26%;
}

.span-1-of-6 {
   width: 15.33%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-6-of-6 {
  width: 100%;
 }
 .span-5-of-6 {
  width: 100%;
 }
 .span-4-of-6 {
  width: 100%;
 }
 .span-3-of-6 {
  width: 100%;
 }
 .span-2-of-6 {
  width: 100%;
 }
 .span-1-of-6 {
  width: 100%;
 }
}

/*  GRID OF SEVEN   ============================================================================= */

.span-7-of-7 {
 width: 100%;
}

.span-6-of-7 {
 width: 85.48%;
}

.span-5-of-7 {
   width: 70.97%;
}

.span-4-of-7 {
   width: 56.45%;
}

.span-3-of-7 {
   width: 41.94%;
}

.span-2-of-7 {
   width: 27.42%;
}

.span-1-of-7 {
   width: 12.91%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-7-of-7 {
  width: 100%;
 }
 .span-6-of-7 {
  width: 100%;
 }
 .span-5-of-7 {
  width: 100%;
 }
 .span-4-of-7 {
  width: 100%;
 }
 .span-3-of-7 {
  width: 100%;
 }
 .span-2-of-7 {
  width: 100%;
 }
 .span-1-of-7 {
  width: 100%;
 }
}

/*  GRID OF EIGHT   ============================================================================= */

.span-8-of-8 {
 width: 100%;
}

.span-7-of-8 {
 width: 87.3%;
}

.span-6-of-8 {
 width: 74.6%;
}

.span-5-of-8 {
 width: 61.9%;
}

.span-4-of-8 {
 width: 49.2%;
}

.span-3-of-8 {
 width: 36.5%;
}

.span-2-of-8 {
 width: 23.8%;
}

.span-1-of-8 {
 width: 11.1%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-8-of-8 {
  width: 100%;
 }
 .span-7-of-8 {
  width: 100%;
 }
 .span-6-of-8 {
  width: 100%;
 }
 .span-5-of-8 {
  width: 100%;
 }
 .span-4-of-8 {
  width: 100%;
 }
 .span-3-of-8 {
  width: 100%;
 }
 .span-2-of-8 {
  width: 100%;
 }
 .span-1-of-8 {
  width: 100%;
 }
}

/*  GRID OF NINE   ============================================================================= */

.span-9-of-9 {
 width: 100%;
}

.span-8-of-9 {
 width: 88.71%;
}

.span-7-of-9 {
 width: 77.42%;
}

.span-6-of-9 {
 width: 66.13%;
}

.span-5-of-9 {
 width: 54.84%;
}

.span-4-of-9 {
 width: 43.55%;
}

.span-3-of-9 {
 width: 32.26%;
}

.span-2-of-9 {
 width: 20.97%;
}

.span-1-of-9 {
 width: 9.68%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-9-of-9 {
  width: 100%;
 }
 .span-8-of-9 {
  width: 100%;
 }
 .span-7-of-9 {
  width: 100%;
 }
 .span-6-of-9 {
  width: 100%;
 }
 .span-5-of-9 {
  width: 100%;
 }
 .span-4-of-9 {
  width: 100%;
 }
 .span-3-of-9 {
  width: 100%;
 }
 .span-2-of-9 {
  width: 100%;
 }
 .span-1-of-9 {
  width: 100%;
 }
}

/*  GRID OF TEN   ============================================================================= */

.span-10-of-10 {
 width: 100%;
}

.span-9-of-10 {
 width: 89.84%;
}

.span-8-of-10 {
 width: 79.68%;
}

.span-7-of-10 {
 width: 69.52%;
}

.span-6-of-10 {
 width: 59.36%;
}

.span-5-of-10 {
 width: 49.2%;
}

.span-4-of-10 {
 width: 39.04%;
}

.span-3-of-10 {
 width: 28.88%;
}

.span-2-of-10 {
 width: 18.72%;
}

.span-1-of-10 {
 width: 8.56%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-10-of-10 {
  width: 100%;
 }
 .span-9-of-10 {
  width: 100%;
 }
 .span-8-of-10 {
  width: 100%;
 }
 .span-7-of-10 {
  width: 100%;
 }
 .span-6-of-10 {
  width: 100%;
 }
 .span-5-of-10 {
  width: 100%;
 }
 .span-4-of-10 {
  width: 100%;
 }
 .span-3-of-10 {
  width: 100%;
 }
 .span-2-of-10 {
  width: 100%;
 }
 .span-1-of-10 {
  width: 100%;
 }
}

/*  GRID OF ELEVEN   ============================================================================= */

.span-11-of-11 {
 width: 100%;
}

.span-10-of-11 {
 width: 90.76%;
}

.span-9-of-11 {
 width: 81.52%;
}

.span-8-of-11 {
 width: 72.29%;
}

.span-7-of-11 {
 width: 63.05%;
}

.span-6-of-11 {
 width: 53.81%;
}

.span-5-of-11 {
 width: 44.58%;
}

.span-4-of-11 {
 width: 35.34%;
}

.span-3-of-11 {
 width: 26.1%;
}

.span-2-of-11 {
 width: 16.87%;
}

.span-1-of-11 {
 width: 7.63%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-11-of-11 {
  width: 100%;
 }
 .span-10-of-11 {
  width: 100%;
 }
 .span-9-of-11 {
  width: 100%;
 }
 .span-8-of-11 {
  width: 100%;
 }
 .span-7-of-11 {
  width: 100%;
 }
 .span-6-of-11 {
  width: 100%;
 }
 .span-5-of-11 {
  width: 100%;
 }
 .span-4-of-11 {
  width: 100%;
 }
 .span-3-of-11 {
  width: 100%;
 }
 .span-2-of-11 {
  width: 100%;
 }
 .span-1-of-11 {
  width: 100%;
 }
}

/*  GRID OF TWELVE   ============================================================================= */

.span-12-of-12 {
 width: 100%;
}

.span-11-of-12 {
 width: 91.53%;
}

.span-10-of-12 {
 width: 83.06%;
}

.span-9-of-12 {
 width: 74.6%;
}

.span-8-of-12 {
 width: 66.13%;
}

.span-7-of-12 {
 width: 57.66%;
}

.span-6-of-12 {
 width: 49.2%;
}

.span-5-of-12 {
 width: 40.73%;
}

.span-4-of-12 {
 width: 32.26%;
}

.span-3-of-12 {
 width: 23.8%;
}

.span-2-of-12 {
 width: 15.33%;
}

.span-1-of-12 {
 width: 6.86%;
}

/*  GO FULL WIDTH AT LESS THAN 480 PIXELS */

@media only screen and (max-width: 480px) {
 .span-12-of-12 {
  width: 100%;
 }
 .span-11-of-12 {
  width: 100%;
 }
 .span-10-of-12 {
  width: 100%;
 }
 .span-9-of-12 {
  width: 100%;
 }
 .span-8-of-12 {
  width: 100%;
 }
 .span-7-of-12 {
  width: 100%;
 }
 .span-6-of-12 {
  width: 100%;
 }
 .span-5-of-12 {
  width: 100%;
 }
 .span-4-of-12 {
  width: 100%;
 }
 .span-3-of-12 {
  width: 100%;
 }
 .span-2-of-12 {
  width: 100%;
 }
 .span-1-of-12 {
  width: 100%;
 }
}

/* MEDIA.CSS*/

/* small phones to small tyablets 481 to 767 */
@media only screen and (max-width: 767px) {
    .col {  margin: 1% 0 1% 0%; }
    .span-1-of-2 { width: 98%; padding-right: 1%;}
    .span-1-of-4, .span-2-of-4, .span-3-of-4, .span-4-of-4 { width: 48%; }
    .span-1-of-4:nth-child(2n) {
      margin-left: 2%;
    }
}

/* small phones 0 to 480 */
@media only screen and (max-width: 480px) {
 .col {  margin: 1% 1% 1% 0%; }
   .span-1-of-2 { width: 100%; padding-right: 1%;}
    .span-1-of-4, .span-2-of-4, .span-3-of-4, .span-4-of-4 { width: 100%; }
    .span-1-of-4:nth-child(2n) {
      margin-left: 0;
    }
}

/* STYLE.CSS */

/* -------- REUSABLE COMPONENETS -------- */
* {
    margin: 0%;
    padding: 0%;
    box-sizing: border-box;
}

html {
    background-color: #fff;
    color: #555;
    font-family: 'Lato', 'Arial', sans-serif;
    font-size: 20px;
    font-weight: 300;
    text-rendering: optimizeLegibility;
}

.clearfix {zoom: 1;}
.clearfix:after {
    content: ' ';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

/* row class from grid css */
.row {
    width: 1140px;
 margin: 0 auto;
}

section {
    padding: 80px 0;
}

 /* class to modify out-of-the-box grid classes (like 'span-1-of-4') */
.box {

 background-color: #1ba1e2;
 border: 1px solid gray;
}

<body>
    <!-- FIRST ROW -->
    <div class="row">
        <div class="col span-1-of-2 box">
            <h3>first-row span-1</h3>
        </div>
        <div class="col span-1-of-2 box">
            <h3>first-row span-2</h3>
        </div>
    </div>

    <!-- SECOND ROW -->
    <div class="row">
        <div class="col span-1-of-4 box">
            <h3>second-row span-1</h3>
            <p>You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
                work with the best chefs in each town to ensure that you're 100% happy.</p>
        </div>
        <div class="col span-1-of-4 box">
            <h3>second-row span-2</h3>
            <p>You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
                work with the best chefs in each town to ensure that you're 100% happy.</p>
        </div>
        <div class="col span-1-of-4 box">
            <h3>second-row span-3</h3>
            <p>You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
                work with the best chefs in each town to ensure that you're 100% happy.</p>
        </div>
        <div class="col span-1-of-4 box">
            <h3>second-row span-4</h3>
            <p>You're only twenty minutes away from your delicious and super healthy meals delivered right to your home. We
                work with the best chefs in each town to ensure that you're 100% happy.</p>
        </div>
    </div>
</body>


问:
How to get the name of a file from a file handle in Windows using C?
I'm trying to retrieve a file name from a given file handle.

I've seen that GetFileInformationByHandle could be useful, but the structure it returns does not contain any file name information (http://msdn.microsoft.com/en-us/library/aa363788%28v=VS.85%29.aspx).

How can I do this?

EDIT:

I've tried installing the Windows FileID APIs to get GetFileInformationByHandleEx working on Windows XP.
But when including fileextd.h I get the following errors

```<code>c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(16) : error C2011: '_FILE_INFO_BY_HANDLE_CLASS' : 'enum' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13900) : see declaration of '_FILE_INFO_BY_HANDLE_CLASS'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(32) : error C2011: '_FILE_BASIC_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13917) : see declaration of '_FILE_BASIC_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(40) : error C2011: '_FILE_STANDARD_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13925) : see declaration of '_FILE_STANDARD_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(48) : error C2011: '_FILE_NAME_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13933) : see declaration of '_FILE_NAME_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(53) : error C2011: '_FILE_RENAME_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13938) : see declaration of '_FILE_RENAME_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(60) : error C2011: '_FILE_ALLOCATION_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13945) : see declaration of '_FILE_ALLOCATION_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(64) : error C2011: '_FILE_END_OF_FILE_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13949) : see declaration of '_FILE_END_OF_FILE_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(68) : error C2011: '_FILE_STREAM_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13953) : see declaration of '_FILE_STREAM_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(76) : error C2011: '_FILE_COMPRESSION_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13961) : see declaration of '_FILE_COMPRESSION_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(85) : error C2011: '_FILE_ATTRIBUTE_TAG_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13970) : see declaration of '_FILE_ATTRIBUTE_TAG_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(90) : error C2011: '_FILE_DISPOSITION_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13975) : see declaration of '_FILE_DISPOSITION_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(94) : error C2011: '_FILE_ID_BOTH_DIR_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13979) : see declaration of '_FILE_ID_BOTH_DIR_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(130) : error C2011: '_FILE_ID_TYPE' : 'enum' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(14026) : see declaration of '_FILE_ID_TYPE'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(135) : error C2011: 'FILE_ID_DESCRIPTOR' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(14032) : see declaration of 'FILE_ID_DESCRIPTOR'
c:\documents and settings\lab\documenti\visual studio 2008\projects\sandbox\sandbox\funcs_files.cpp(26) : error C2079: 'lpFileInformation' uses undefined struct '_FILE_NAME_INFO'
c:\documents and settings\lab\documenti\visual studio 2008\projects\sandbox\sandbox\funcs_files.cpp(35) : error C2228: left of '.FileName' must have class/struct/union
        type is 'int'
</code>```

From the following code:

```<code>#include <windows.h>
#include <fileextd.h>

LPVOID GetFileNameFromHandle(HANDLE hFile) {
    FILE_NAME_INFO lpFileInformation;
    BOOL bWorked;

    bWorked = GetFileInformationByHandleEx(
        hFile,
        FileNameInfo,
        &lpFileInformation,
        sizeof(FILE_NAME_INFO));

    return lpFileInformation.FileName;
}
</code>```

答:
For Vista and later take a look at GetFinalPathNameByHandle (like mehrdad wrote)

It is more convenient IMO and allows more customization than GetFileInformationByHandleEx, and it removes the hassle of allocating a custom size FILE_NAME_INFO struct.

Example:

```<code>DWORD size = GetFinalPathNameByHandleW(handle, NULL, 0, VOLUME_NAME_DOS);
if (size == 0) return L"(NOT FOUND)";
std::wstring fname(size, L'0');
size = GetFinalPathNameByHandleW(handle, &fname.front(), size, VOLUME_NAME_DOS);
</code>```

Notice, it will prepend \\?\ to the returning name.

(I used C++ std::wstring to avoid C boilerplate for memory handling. Use malloc for your needs).

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to retrieve a file name from a given file handle.

I've seen that GetFileInformationByHandle could be useful, but the structure it returns does not contain any file name information (http://msdn.microsoft.com/en-us/library/aa363788%28v=VS.85%29.aspx).

How can I do this?

EDIT:

I've tried installing the Windows FileID APIs to get GetFileInformationByHandleEx working on Windows XP.
But when including fileextd.h I get the following errors

c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(16) : error C2011: '_FILE_INFO_BY_HANDLE_CLASS' : 'enum' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13900) : see declaration of '_FILE_INFO_BY_HANDLE_CLASS'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(32) : error C2011: '_FILE_BASIC_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13917) : see declaration of '_FILE_BASIC_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(40) : error C2011: '_FILE_STANDARD_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13925) : see declaration of '_FILE_STANDARD_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(48) : error C2011: '_FILE_NAME_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13933) : see declaration of '_FILE_NAME_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(53) : error C2011: '_FILE_RENAME_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13938) : see declaration of '_FILE_RENAME_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(60) : error C2011: '_FILE_ALLOCATION_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13945) : see declaration of '_FILE_ALLOCATION_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(64) : error C2011: '_FILE_END_OF_FILE_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13949) : see declaration of '_FILE_END_OF_FILE_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(68) : error C2011: '_FILE_STREAM_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13953) : see declaration of '_FILE_STREAM_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(76) : error C2011: '_FILE_COMPRESSION_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13961) : see declaration of '_FILE_COMPRESSION_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(85) : error C2011: '_FILE_ATTRIBUTE_TAG_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13970) : see declaration of '_FILE_ATTRIBUTE_TAG_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(90) : error C2011: '_FILE_DISPOSITION_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13975) : see declaration of '_FILE_DISPOSITION_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(94) : error C2011: '_FILE_ID_BOTH_DIR_INFO' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(13979) : see declaration of '_FILE_ID_BOTH_DIR_INFO'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(130) : error C2011: '_FILE_ID_TYPE' : 'enum' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(14026) : see declaration of '_FILE_ID_TYPE'
c:\programmi\microsoft visual studio 9.0\vc\include\fileextd.h(135) : error C2011: 'FILE_ID_DESCRIPTOR' : 'struct' type redefinition
        c:\programmi\microsoft sdks\windows\v6.1\include\winbase.h(14032) : see declaration of 'FILE_ID_DESCRIPTOR'
c:\documents and settings\lab\documenti\visual studio 2008\projects\sandbox\sandbox\funcs_files.cpp(26) : error C2079: 'lpFileInformation' uses undefined struct '_FILE_NAME_INFO'
c:\documents and settings\lab\documenti\visual studio 2008\projects\sandbox\sandbox\funcs_files.cpp(35) : error C2228: left of '.FileName' must have class/struct/union
        type is 'int'

From the following code:

#include <windows.h>
#include <fileextd.h>

LPVOID GetFileNameFromHandle(HANDLE hFile) {
    FILE_NAME_INFO lpFileInformation;
    BOOL bWorked;

    bWorked = GetFileInformationByHandleEx(
        hFile,
        FileNameInfo,
        &lpFileInformation,
        sizeof(FILE_NAME_INFO));

    return lpFileInformation.FileName;
}

Body:
For Vista and later take a look at GetFinalPathNameByHandle (like mehrdad wrote)

It is more convenient IMO and allows more customization than GetFileInformationByHandleEx, and it removes the hassle of allocating a custom size FILE_NAME_INFO struct.

Example:

DWORD size = GetFinalPathNameByHandleW(handle, NULL, 0, VOLUME_NAME_DOS);
if (size == 0) return L"(NOT FOUND)";
std::wstring fname(size, L'0');
size = GetFinalPathNameByHandleW(handle, &fname.front(), size, VOLUME_NAME_DOS);

Notice, it will prepend \\?\ to the returning name.

(I used C++ std::wstring to avoid C boilerplate for memory handling. Use malloc for your needs).


问:
Espresso, Dagger2 set ViemodelProvider.Factory on BaseActivity
I have an abstract AccountRequiredActivity that looks like this (and works fine):

```<code>public abstract class AccountRequiredActivity extends LifecycleActivity {

    @Inject
    ViewModelProvider.Factory viewModelFactory;

    private AccountViewModel accountViewModel;

    public abstract void doOnCreate(Bundle savedInstanceState);
    public abstract void doOnResume();

    @Override
    protected final void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading_app);
        AndroidInjection.inject(this);
        accountViewModel = ViewModelProviders.of(this, viewModelFactory).get(AccountViewModel.class);

        if(!accountViewModel.isAuthenticated()) {
            redirectToLogin();
        } else {
            doOnCreate(savedInstanceState);
        };

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!accountViewModel.isAuthenticated()) {
            redirectToLogin();
        } else {
            doOnResume();
        };
    }

    private void redirectToLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

}
</code>```

The problem during tests is that there is no way for me to set the viewModelFactory on the activity.

When an activity has a fragment, I can just do something like:

```<code>@Before
public void init() {
    LoginFragment fragment = LoginFragment.newInstance();
    viewModel = mock(AccountViewModel.class);
    when(viewModel.getAuthenticatedUserResource()).thenReturn(authenticatedUser);

    fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
    activityRule.getActivity().setFragment(fragment);
}
</code>```

The problem however in this case is that I use this in my tests (HomeActivity extends AccountRequiredActivity):

```<code>@Rule
public ActivityTestRule<HomeActivity> activityTestRule = new ActivityTestRule<>(HomeActivity.class, true, false);
</code>```

So there is no way to dynamically set the viewModelFactory, as onCreate immediately gets called. There doesn't seem to be a way to get access to the Activity object before onCreate gets called.

How to fix this problem?

Note: I use Dagger 2.11 with AndroidInjector.

Also see this question that I posted yesterday for follow-up info:

Inject ViewModelFactory.Provider in activity for espresso testing

答:
It’s possible to set injected activity attribute by registering a custom ActivityLifecycleCallbacks in your TestApp in the @Before Method.

Example:

```<code> @Before
public void init(){

UserFragment fragment = UserFragment.create("foo");
viewModel = mock(UserViewModel.class);
when(viewModel.getUser()).thenReturn(userData);
when(viewModel.getRepositories()).thenReturn(repoListData);
navigationController = mock(NavigationController.class);

TestApp testApp = ((TestApp) InstrumentationRegistry.getContext().getApplicationContext());
testApp.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        //will be called before the onCreate method of your activity
        activity.setViewModelFactory(ViewModelUtil.createFor(viewModel));
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
});

fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
fragment.navigationController = navigationController;
fragment.dataBindingComponent = () -> fragmentBindingAdapters;

activityRule.getActivity().setFragment(fragment);

}
</code>```

Body:
I have an abstract AccountRequiredActivity that looks like this (and works fine):

public abstract class AccountRequiredActivity extends LifecycleActivity {

    @Inject
    ViewModelProvider.Factory viewModelFactory;

    private AccountViewModel accountViewModel;

    public abstract void doOnCreate(Bundle savedInstanceState);
    public abstract void doOnResume();

    @Override
    protected final void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading_app);
        AndroidInjection.inject(this);
        accountViewModel = ViewModelProviders.of(this, viewModelFactory).get(AccountViewModel.class);

        if(!accountViewModel.isAuthenticated()) {
            redirectToLogin();
        } else {
            doOnCreate(savedInstanceState);
        };

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!accountViewModel.isAuthenticated()) {
            redirectToLogin();
        } else {
            doOnResume();
        };
    }

    private void redirectToLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

}

The problem during tests is that there is no way for me to set the viewModelFactory on the activity.

When an activity has a fragment, I can just do something like:

@Before
public void init() {
    LoginFragment fragment = LoginFragment.newInstance();
    viewModel = mock(AccountViewModel.class);
    when(viewModel.getAuthenticatedUserResource()).thenReturn(authenticatedUser);

    fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
    activityRule.getActivity().setFragment(fragment);
}

The problem however in this case is that I use this in my tests (HomeActivity extends AccountRequiredActivity):

@Rule
public ActivityTestRule<HomeActivity> activityTestRule = new ActivityTestRule<>(HomeActivity.class, true, false);

So there is no way to dynamically set the viewModelFactory, as onCreate immediately gets called. There doesn't seem to be a way to get access to the Activity object before onCreate gets called.

How to fix this problem?

Note: I use Dagger 2.11 with AndroidInjector.

Also see this question that I posted yesterday for follow-up info:

Inject ViewModelFactory.Provider in activity for espresso testing

Body:
It’s possible to set injected activity attribute by registering a custom ActivityLifecycleCallbacks in your TestApp in the @Before Method.

Example:

 @Before
public void init(){

UserFragment fragment = UserFragment.create("foo");
viewModel = mock(UserViewModel.class);
when(viewModel.getUser()).thenReturn(userData);
when(viewModel.getRepositories()).thenReturn(repoListData);
navigationController = mock(NavigationController.class);

TestApp testApp = ((TestApp) InstrumentationRegistry.getContext().getApplicationContext());
testApp.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        //will be called before the onCreate method of your activity
        activity.setViewModelFactory(ViewModelUtil.createFor(viewModel));
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
});

fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
fragment.navigationController = navigationController;
fragment.dataBindingComponent = () -> fragmentBindingAdapters;

activityRule.getActivity().setFragment(fragment);

}


问:
how to simplify scala's function literal like this?
I'm new to scala and trying to write a function literal that check whether a given integer is odd or not.
my first attempt is:

val isOdd = (x:Int) => (x & 1) == 1

it works great, and,  since the parameter x only appears once within this function literal, I'm tempted to use the "_" notation to simplify it further, like this:

val isOdd = ((_:Int) & 1 ) == 1

however this time the compiler complains :

```warning: comparing a fresh object using `==' will always yield false
val isOdd = ((_:Int) & 1 ) == 1
```

what does this warning mean? why does the compiler recognize ((_ :Int) & 1) as fresh object rather than a bitwise operation that results in a value? is there any way to write this function literal using the "_" notation?

答:
There you go:</p>

```<code>val isOdd = ((_: Int) & 1) andThen (1 ==)
</code>```

Body:
I'm new to scala and trying to write a function literal that check whether a given integer is odd or not.
my first attempt is:

val isOdd = (x:Int) => (x & 1) == 1

it works great, and,  since the parameter x only appears once within this function literal, I'm tempted to use the "_" notation to simplify it further, like this:

val isOdd = ((_:Int) & 1 ) == 1

however this time the compiler complains :

warning: comparing a fresh object using `==' will always yield false
val isOdd = ((_:Int) & 1 ) == 1

what does this warning mean? why does the compiler recognize ((_ :Int) & 1) as fresh object rather than a bitwise operation that results in a value? is there any way to write this function literal using the "_" notation?

Body:
There you go:

val isOdd = ((_: Int) & 1) andThen (1 ==)


问:
Scheme error when programming point-distance formula - attempt to apply non-procedure
I am attempting to program the point distance formula using Scheme. I am very close to getting it, except I am getting an error.

The exact error is:

```<code>Traceback (most recent call last):

File "In [54]", line 5, col 11, in 'application'

File "In [54]", line 5, col 11

RunTimeError: attempt to apply non-procedure '4'
</code>```

Here is my code:

```<code>; code for the distance procedure

(define (distance p1 p2) (sqrt (+ (* (- (car(p2)) (car(p1))) (- (car(p2)) (car(p1)))) (* (- (car(cdr(p2))) (car(cdr(p1)))) (- (car(cdr(p2))) (car(cdr(p1))))))))

(distance (4 5) (3 2))
</code>```

For reference, the point distance formula is:

√((x2 - x1)^2 + (y2 - y1)^2)

答:
It is generally better to format Scheme code correctly instead of putting everything in just one line.

And it is useful to name intermediate values. If your formula contains x1, x2, y1 and y2, create Scheme variables with those names. This makes it easier to understand the solution.

Scheme hast several abbreviations for nested car and cdr functions. If you need the car of a cdr, you can use cadr.

Scheme allows you to use mathematic symbols in variable names. If a variable contains the difference of x2 and x1, you can name it x2-x1. This enhances the readability of Scheme's Polish notation.

```<code>(define (distance p1 p2)
  (let ((x1 (car p1))
        (y1 (cadr p1))
        (x2 (car p2))
        (y2 (cadr p2)))
    (let ((x2-x1 (- x2 x1))
          (y2-y1 (- y2 y1)))
      (sqrt (+ (* x2-x1 x2-x1)
               (* y2-y1 y2-y1))))))
</code>```

If you want to pass list literals to functions, you have to quote them in order to prevent evaluation.

```<code>(distance '(4 5) '(3 2))
</code>```

Or use evaluation correctly:

```<code>(distance (list 4 5) (list 3 2))
</code>```

Body:
I am attempting to program the point distance formula using Scheme. I am very close to getting it, except I am getting an error.

The exact error is:

Traceback (most recent call last):

File "In [54]", line 5, col 11, in 'application'

File "In [54]", line 5, col 11

RunTimeError: attempt to apply non-procedure '4'

Here is my code:

; code for the distance procedure

(define (distance p1 p2) (sqrt (+ (* (- (car(p2)) (car(p1))) (- (car(p2)) (car(p1)))) (* (- (car(cdr(p2))) (car(cdr(p1)))) (- (car(cdr(p2))) (car(cdr(p1))))))))

(distance (4 5) (3 2))

For reference, the point distance formula is:

√((x2 - x1)^2 + (y2 - y1)^2)

Body:
It is generally better to format Scheme code correctly instead of putting everything in just one line.

And it is useful to name intermediate values. If your formula contains x1, x2, y1 and y2, create Scheme variables with those names. This makes it easier to understand the solution.

Scheme hast several abbreviations for nested car and cdr functions. If you need the car of a cdr, you can use cadr.

Scheme allows you to use mathematic symbols in variable names. If a variable contains the difference of x2 and x1, you can name it x2-x1. This enhances the readability of Scheme's Polish notation.

(define (distance p1 p2)
  (let ((x1 (car p1))
        (y1 (cadr p1))
        (x2 (car p2))
        (y2 (cadr p2)))
    (let ((x2-x1 (- x2 x1))
          (y2-y1 (- y2 y1)))
      (sqrt (+ (* x2-x1 x2-x1)
               (* y2-y1 y2-y1))))))

If you want to pass list literals to functions, you have to quote them in order to prevent evaluation.

(distance '(4 5) '(3 2))

Or use evaluation correctly:

(distance (list 4 5) (list 3 2))


问:
How to add custom fields to Kentico Modules?
I want to use kentico's polls module but I need to add a "tooltip field" and add some extra HTML. Is there a way to clone the module with the same functionality and let me to edit/add fields to the module classes.

I was trying to edit the module but it shows a message saying Classes cannot be created or deleted in installed modules.

答:
Are you trying to modify the class in the module and it's giving that error? Or modify the module info itself?

Some module classes allow edits and additions. If this is not the case for the polling, you have two options.

1: clone or recreate the module and clone the web parts that use it to use your new module. This is the safest but longest task and may require some digging into Kentico drivers using a decompiler like just decompile to find any other code pieces you need to clone and modify.

2: open the database in SQL management studio, and edit the cms_class on that class and manually change the bool values that allow it to be edited. This comes with the risk that on future upgrades it may break it, but it's a small risk.


问:
How to automatically populate a 5x3x2 array with natural numbers from zero to the array's full size?
I need to populate a 3D array automatically, using natural positive numbers (0,1,2,3,4...), up to the array's full dimension. In this case, a 5x3x2 array stores 30 elements. Is there any algorithm, where for-loops could be employed to dynamically populate such array? For example: if I had a 5x3 2D array, I certainly could use the following code, to automatically generate its elements:

```<code>var ray = new Array(5);
for (var make2D = 0; make2D < ray.length; make2D++) {
    ray[make2D] = new Array(3);
}
for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        array[i][j] = i * array[i].length + j;
    }
}
</code>```

The above code would first create a 5 x 3 array and populate this 2D array with elements from 0 to 14.
But, I have struggled to find a 'formula' to populate a 3D array likewise

Like explicit: array[ i ] [ j ] [ z ]= '.....code.....'  using length property values and for-loops?

答:
This is a recursive function that accepts an array that describes an n dimensions array, and populates it with consecutive numbers:

function makeNDArray(dims) {
  var counter = 0;

  function generateArr(dims) {
    var arr = [];
    var nextDims = dims.slice(1);
    var hasNext = nextDims.length > 0;

    for(var i = 0; i < dims[0]; i++) {
      arr.push(hasNext ? generateArr(nextDims) : counter++);
    }

    return arr;
  }

  return generateArr(dims);
}

var result = makeNDArray([3, 5, 2]);

console.log(result);```
</div>
</div>
</p>

<p>And an ES6 version using Array#from to generate the arrays:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function makeNDArray(dims) {
  let counter = 0;

  const generateArr = (dims) => {
    const nextDims = dims.slice(1);
    const populate = nextDims.length > 0 ? () => generateArr(nextDims) : () => counter++;

    return Array.from({ length: dims[0] }, populate);
  }

  return generateArr(dims);
}

const result = makeNDArray([3, 5, 2]);

console.log(result);</code>```

Body:
I need to populate a 3D array automatically, using natural positive numbers (0,1,2,3,4...), up to the array's full dimension. In this case, a 5x3x2 array stores 30 elements. Is there any algorithm, where for-loops could be employed to dynamically populate such array? For example: if I had a 5x3 2D array, I certainly could use the following code, to automatically generate its elements:

var ray = new Array(5);
for (var make2D = 0; make2D < ray.length; make2D++) {
    ray[make2D] = new Array(3);
}
for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        array[i][j] = i * array[i].length + j;
    }
}

The above code would first create a 5 x 3 array and populate this 2D array with elements from 0 to 14.
But, I have struggled to find a 'formula' to populate a 3D array likewise

Like explicit: array[ i ] [ j ] [ z ]= '.....code.....'  using length property values and for-loops?

Body:
This is a recursive function that accepts an array that describes an n dimensions array, and populates it with consecutive numbers:

function makeNDArray(dims) {
  var counter = 0;

  function generateArr(dims) {
    var arr = [];
    var nextDims = dims.slice(1);
    var hasNext = nextDims.length > 0;

    for(var i = 0; i < dims[0]; i++) {
      arr.push(hasNext ? generateArr(nextDims) : counter++);
    }

    return arr;
  }

  return generateArr(dims);
}

var result = makeNDArray([3, 5, 2]);

console.log(result);

And an ES6 version using Array#from to generate the arrays:

function makeNDArray(dims) {
  let counter = 0;

  const generateArr = (dims) => {
    const nextDims = dims.slice(1);
    const populate = nextDims.length > 0 ? () => generateArr(nextDims) : () => counter++;

    return Array.from({ length: dims[0] }, populate);
  }

  return generateArr(dims);
}

const result = makeNDArray([3, 5, 2]);

console.log(result);


问:
some guidance in modifying the query
I'm using the below query in order to split the value of a column into another column and is working fine, but it is not giving the output that I'm expecting. Below is the query along with the output.

Query:

```<code>SELECT
  upper(regexp_substr(db_attributes, '[^,:]+$',1,1)) AS servername,
   db_attributes FROM
table_name
</code>```

Current Output:

```<code>Servername                                 db_attributes
INPRD1HF                                   hkp04lp0605s-rs6000.hk.hsbc, 50000, AP4INPU1:INPRD1HF
AE000BDS0096\LIVE0096MSSQL                ae000bds0096.hbeu.adroot.hsbc, 60695, AE000BDS0096\LIVE0096MSSQL
NULL                                      ora-abacogp.de.hsbc, 1626, ABACOGP
</code>```

Desired output:

```<code>Servername                                 db_attributes
AP4INPU1                                   hkp04lp0605s-rs6000.hk.hsbc, 50000, AP4INPU1:INPRD1HF
AE000BDS0096\LIVE0096MSSQL                ae000bds0096.hbeu.adroot.hsbc, 60695, AE000BDS0096\LIVE0096MSSQL
ABACOGP                                   ora-abacogp.de.hsbc, 1626, ABACOGP
</code>```

The difference between the current and desired output is in the first line I want the value which is before colon in db_attributes column (i.e. AP4INPU1 not INPRD1HF)

Regards,

Vikas

答:
You may use

```<code>regexp_substr(db_attributes, '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1)
</code>```

Details

([^,:[:space:]]+) - Group 1: one or more chars other than ,, : and whitespace chars

(:\S*)? - an optional group matching 1 or 0 sequences of : and then 0+ non-whitespace chars

$ - end of string.

See the online tests:

```<code>--select regexp_substr('hkp04lp0605s-rs6000.hk.hsbc, 50000, AP4INPU1:INPRD1HF', '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1) AS servername from dual
-- => AP4INPU1
--select regexp_substr('ora-abacogp.de.hsbc, 1626, ABACOGP', '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1) AS servername from dual
-- => ABACOGP
--
select regexp_substr('ae000bds0096.hbeu.adroot.hsbc, 60695, AE000BDS0096\LIVE0096MSSQL', '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1) AS servername from dual
-- => AE000BDS0096\LIVE0096MSSQL
</code>```

Title: some guidance in modifying the query

Body:
I'm using the below query in order to split the value of a column into another column and is working fine, but it is not giving the output that I'm expecting. Below is the query along with the output.

Query:

SELECT
  upper(regexp_substr(db_attributes, '[^,:]+$',1,1)) AS servername,
   db_attributes FROM
table_name

Current Output:

Servername                                 db_attributes
INPRD1HF                                   hkp04lp0605s-rs6000.hk.hsbc, 50000, AP4INPU1:INPRD1HF
AE000BDS0096\LIVE0096MSSQL                ae000bds0096.hbeu.adroot.hsbc, 60695, AE000BDS0096\LIVE0096MSSQL
NULL                                      ora-abacogp.de.hsbc, 1626, ABACOGP

Desired output:

Servername                                 db_attributes
AP4INPU1                                   hkp04lp0605s-rs6000.hk.hsbc, 50000, AP4INPU1:INPRD1HF
AE000BDS0096\LIVE0096MSSQL                ae000bds0096.hbeu.adroot.hsbc, 60695, AE000BDS0096\LIVE0096MSSQL
ABACOGP                                   ora-abacogp.de.hsbc, 1626, ABACOGP

The difference between the current and desired output is in the first line I want the value which is before colon in db_attributes column (i.e. AP4INPU1 not INPRD1HF)

Regards,

Vikas

Body:
You may use

regexp_substr(db_attributes, '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1)

Details

([^,:[:space:]]+) - Group 1: one or more chars other than ,, : and whitespace chars

(:\S*)? - an optional group matching 1 or 0 sequences of : and then 0+ non-whitespace chars

$ - end of string.

See the online tests:

--select regexp_substr('hkp04lp0605s-rs6000.hk.hsbc, 50000, AP4INPU1:INPRD1HF', '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1) AS servername from dual
-- => AP4INPU1
--select regexp_substr('ora-abacogp.de.hsbc, 1626, ABACOGP', '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1) AS servername from dual
-- => ABACOGP
--
select regexp_substr('ae000bds0096.hbeu.adroot.hsbc, 60695, AE000BDS0096\LIVE0096MSSQL', '([^,:[:space:]]+)(:\S*)?$', 1, 1, NULL, 1) AS servername from dual
-- => AE000BDS0096\LIVE0096MSSQL


问:
Cpp calling function from including file
So, as far as my cpp knowledge goes, I can call functions which are declared/defined in header files I #include.

Is there any possibility to call functions from the file that includes?

For example:
"main.cpp" includes "test.h",
So any function from "main.cpp" can make calls to functions from "test.h".

But, in that case, can code from "test.cpp" make calls to functions from "main.cpp" without including it?

答:
No. You cannot call functions declared in another source files from another source files. Also what is the in that? And a good usage separate source from header; Header files include prototypes and declarations while source includes definitions.

eg:

```<code>// Shape.h
#ifndef SHAPE_H
#define SHAPE_H

class Shape{
    //...
};
#endif

// Shape2D.h
#ifndef Shape2D.h
#define Shape2D.h

class Shape2D{
    //...
};
#endif
</code>```

Now source files:

```<code>// Shape.cpp
#include "Shape.h"

// Definitions here:
Shape::Shape(){}

// Shape2D.cpp

#include "Shape2D.h"

// Some definitions here:

Shape2D::Shape2D(){}
</code>```

Now in main.cpp:

```<code>#include "Shape2D.h"
// #include "Shape.h"

int DoSomeStuff();

int main(){

    Shape2D a;
    Shape b;

    return 0;
}

int DoSomeStuff(){
    // ....
}
</code>```

As you can see above I just included Shape2D.h and can use class Shape without including its header file Shape.h That is because Shape2D.h includes it so it's content is added to it then all the content of two files is present in my main source file.

Main.cpp includes Shape.h indirectly.

Also keep in mind that what is declared in a source file is scoped to it which means cannot be seen from outside.

Try to something like this:

In Shape.cpp call DoSomeThing:

```<code>#include "main.cpp"

int x = DoSomeThing();
</code>```

Above there's at least a compile-time errors: At least class Shape and Shape2D are already defined.

What I recommend: Don't include source files, Use Inclusions guards or pragma once to avoid multiple file inclusion.

Body:
No. You cannot call functions declared in another source files from another source files. Also what is the in that? And a good usage separate source from header; Header files include prototypes and declarations while source includes definitions.

eg:

// Shape.h
#ifndef SHAPE_H
#define SHAPE_H

class Shape{
    //...
};
#endif

// Shape2D.h
#ifndef Shape2D.h
#define Shape2D.h

class Shape2D{
    //...
};
#endif

Now source files:

// Shape.cpp
#include "Shape.h"

// Definitions here:
Shape::Shape(){}

// Shape2D.cpp

#include "Shape2D.h"

// Some definitions here:

Shape2D::Shape2D(){}

Now in main.cpp:

#include "Shape2D.h"
// #include "Shape.h"

int DoSomeStuff();

int main(){

    Shape2D a;
    Shape b;

    return 0;
}

int DoSomeStuff(){
    // ....
}

As you can see above I just included Shape2D.h and can use class Shape without including its header file Shape.h That is because Shape2D.h includes it so it's content is added to it then all the content of two files is present in my main source file.

Main.cpp includes Shape.h indirectly.

Also keep in mind that what is declared in a source file is scoped to it which means cannot be seen from outside.

Try to something like this:

In Shape.cpp call DoSomeThing:

#include "main.cpp"

int x = DoSomeThing();

Above there's at least a compile-time errors: At least class Shape and Shape2D are already defined.

What I recommend: Don't include source files, Use Inclusions guards or pragma once to avoid multiple file inclusion.


问:
Error: Cannot find module 'curl' at Function.Module._resolveFilename (module.js:489:15)
I installed node.js with the windows installer. The folder structure formed is C:\Program Files\nodejs\node_modules\npm\node_modules. The last node_modules has all the module folders I guess.

I use the node.js command prompt to execute my js script. When the script is on Desktop, it executes all fine. When I shift my script to another folder in my C: it gives the error. I don't want to give the absolute path as it will have to be changed again and again. Anyways, what path should I give as absolute to make it just work

```<code>Error: Cannot find module 'curl'
    at Function.Module._resolveFilename (module.js:489:15)
</code>```

I have gone through the resolutions mentioned in other discussions. Have made the NODE_PATH environment variable. Have edited PATH variable to make it C:\Program Files\nodejs and not C:\Program Files\nodejs\. Have executed npm install -g npm and nothing seems to work.

答: Sorry for the trouble, if anyone has already started looking into it. I found the solution. In the node.js command prompt, in the project folder I executed the following  'npm install curl' which downloaded the curl packages into a node_modules folder in the folder which has my script. I anyways wonder, then how it worked when I had placed my project on Desktop. It seems that the way node.js finds modules has to be checked. FYI - I have not set the NODE_PATH and the path still has C:\Program Files\nodejs\ after I freshly installed it. Thank you!</p>

Body:
I installed node.js with the windows installer. The folder structure formed is C:\Program Files\nodejs\node_modules\npm\node_modules. The last node_modules has all the module folders I guess.

I use the node.js command prompt to execute my js script. When the script is on Desktop, it executes all fine. When I shift my script to another folder in my C: it gives the error. I don't want to give the absolute path as it will have to be changed again and again. Anyways, what path should I give as absolute to make it just work

Error: Cannot find module 'curl'
    at Function.Module._resolveFilename (module.js:489:15)

I have gone through the resolutions mentioned in other discussions. Have made the NODE_PATH environment variable. Have edited PATH variable to make it C:\Program Files\nodejs and not C:\Program Files\nodejs\. Have executed npm install -g npm and nothing seems to work.


问:
What is the use of hashCode in Java?
In Java, obj.hashCode() returns some value. What is the use of this hash code in programming?

答:
The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal.

By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.

This  answer is from the java SE 8 official tutorial documentation

ContentLicense: CC BY-SA 4.0

Title: What is the use of hashCode in Java?


问:
PHP snippet for translated content. Is it a good practice? Can it get better/simpler?
I am currently developing a website that will have translated content served by different gTLD. (example.com, example.fr, example.de)

The idea is to have them all redirect to the same content on the same server, and based on the gTLD, have a simple php routine that serves the correct language.

Here is the code I am using to detect the domain/language:

```<code><?php

$url_tld = explode("." , $_SERVER['HTTP_HOST'] , 3);
if ($url_tld[2] == "fr") { $language = "FR"; $lang_id = 1;}
elseif ($url_tld[2] == "de") { $language = "DE"; $lang_id = 2;}
elseif ($url_tld[2] == "nl") { $language = "NL"; $lang_id = 3;}
else { $language = "EN"; $lang_id = 0;}

function txt($x) {
    global $lang_id;
    echo $x[$lang_id];
};
</code>```

In the html code I run txt function whenever I need different language content; example:

```<code><h1><?=txt(['Hello World','Bonjour France','Hallo Deutschland','Hallo Nederland'])?></h1>
</code>```

I am trying to avoid using any database as the website will be mostly static.

Can this approach get simpler? Or more eye friendly (for those updating code manually)?

Best regards and thanks in advance.

答:
A short way to do it (you don't need to give an id, just take the key of the array) :</p>

```<code>$url_tld = 'FR';//explode("." , $_SERVER['HTTP_HOST'] , 3);

$lang_available = array('en','fr','de','nl');

$language = strtolower($url_tld);

$lang_id = array_search($language, $lang_available);

txt(['Hello World','Bonjour France','Hallo Deutschland','Hallo Nederland']);
</code>```

Body:
I am currently developing a website that will have translated content served by different gTLD. (example.com, example.fr, example.de)

The idea is to have them all redirect to the same content on the same server, and based on the gTLD, have a simple php routine that serves the correct language.

Here is the code I am using to detect the domain/language:

<?php

$url_tld = explode("." , $_SERVER['HTTP_HOST'] , 3);
if ($url_tld[2] == "fr") { $language = "FR"; $lang_id = 1;}
elseif ($url_tld[2] == "de") { $language = "DE"; $lang_id = 2;}
elseif ($url_tld[2] == "nl") { $language = "NL"; $lang_id = 3;}
else { $language = "EN"; $lang_id = 0;}

function txt($x) {
    global $lang_id;
    echo $x[$lang_id];
};

In the html code I run txt function whenever I need different language content; example:

<?=txt(['Hello World','Bonjour France','Hallo Deutschland','Hallo Nederland'])?>

I am trying to avoid using any database as the website will be mostly static.

Can this approach get simpler? Or more eye friendly (for those updating code manually)?

Best regards and thanks in advance.

Body:
A short way to do it (you don't need to give an id, just take the key of the array) :

$url_tld = 'FR';//explode("." , $_SERVER['HTTP_HOST'] , 3);

$lang_available = array('en','fr','de','nl');

$language = strtolower($url_tld);

$lang_id = array_search($language, $lang_available);

txt(['Hello World','Bonjour France','Hallo Deutschland','Hallo Nederland']);


问:
Typescript differences between import statements and paths
I have a class that I want to import somewhere ("example.ts"):

```<code>export class Example {
  constructor() {
  }

  public someFunction() { }
}
</code>```

Can someone tell me the differences between those three import statements from typescript?

import * as example from "./example.ts"

import { example } from "./example.ts" or import { example } as example from "./example.ts"

import "./example.ts"

There are also differences for the path names:

"./example.ts"

"example.ts"

"example"

When exactly do I have to use which path?

答:
Lets say example.ts looks like this:

```<code>export const PI = 3.14
export function sayHello() { console.log('hi'); }
export default function() { console.log('i am default'); }
</code>```

import * as example from "./example" - this takes everything exported from example.ts and makes it available under example variable. Therefore you will write things like example.sayHello() or example.PI. You may be wondering where is the default export. This one is under default key therefore you can access it using example.default()

import { PI, sayHello } from "./example" this way you import only specific parts from example.ts. In this example only PI variable and sayHello function. You can call it directly: sayHello()

import "./example" - this is used to basically execute the file. For example when there are some side effects. For example in rxjs we use import 'rxjs/add/operator/map' to modify rxjs observable prototype and add the map operator. Exports are not important - the execution is important. This matters especially in nodejs environment where this get transpiled to require('./example').

I will modify your examples a bit here:

"./example" - refers to file in the same directory. You will usually use it to import your modules.

"example" refers to so called non-relative module. These are resolved either relative to baseUrl in your tsconfig.json or using path mapping. Typically path mapping maps to your node_modules so you can import your libraries. Therefore you will use this one usually for importing external modules.

"example.ts" - in typescript the import filename is not allowed to end with .ts. Therefore just use 4. or 5.

Here is reference in TS documentation.

Body:
I have a class that I want to import somewhere ("example.ts"):

export class Example {
  constructor() {
  }

  public someFunction() { }
}

Can someone tell me the differences between those three import statements from typescript?

import * as example from "./example.ts"

import { example } from "./example.ts" or import { example } as example from "./example.ts"

import "./example.ts"

There are also differences for the path names:

"./example.ts"

"example.ts"

"example"

When exactly do I have to use which path?

Body:
Lets say example.ts looks like this:

export const PI = 3.14
export function sayHello() { console.log('hi'); }
export default function() { console.log('i am default'); }

import * as example from "./example" - this takes everything exported from example.ts and makes it available under example variable. Therefore you will write things like example.sayHello() or example.PI. You may be wondering where is the default export. This one is under default key therefore you can access it using example.default()

import { PI, sayHello } from "./example" this way you import only specific parts from example.ts. In this example only PI variable and sayHello function. You can call it directly: sayHello()

import "./example" - this is used to basically execute the file. For example when there are some side effects. For example in rxjs we use import 'rxjs/add/operator/map' to modify rxjs observable prototype and add the map operator. Exports are not important - the execution is important. This matters especially in nodejs environment where this get transpiled to require('./example').

I will modify your examples a bit here:

"./example" - refers to file in the same directory. You will usually use it to import your modules.

"example" refers to so called non-relative module. These are resolved either relative to baseUrl in your tsconfig.json or using path mapping. Typically path mapping maps to your node_modules so you can import your libraries. Therefore you will use this one usually for importing external modules.

"example.ts" - in typescript the import filename is not allowed to end with .ts. Therefore just use 4. or 5.

Here is reference in TS documentation.


问:
Getting data from second table
I have 2 tables.

Table1 has columns like

```<code>ID int
FromAddress int
ToAddress int
</code>```

Table2 has columns like

```<code>ID int
ZipCode int
</code>```

The Connection between 2 tables is based on FromAddress,ToAdress(from Table1) and ID in table2

Rough data is like in Table1

```<code>ID     FROMAddress    ToAddress
1      500            620
</code>```

Roughdata is like in Table2

```<code>ID     ZipCode
500    69999
620    6501
</code>```

I want output like

```<code>ID     FromZipCode     ToZipCode
1      69999           6501
</code>```

I tried to do Query like

```<code>Select T1.ID, T2.ZipCode as FromZipCode, T2.ZipCode as ToZipCode
From Table1 T1 join Table2 T2 on T1.FromAddress = T1.ID and T1.ToAddress = T2.ID
</code>```

But this gives me no result.

答:
Try like this, you need to JOIN twice:

```<code>Select T1.ID
    ,T2.ZipCode as FromZipCode
    ,T22.ZipCode as ToZipCode
From Table1 T1
join Table2 T2
    on T1.FromAddress = T2.ID -- first JOIN to get the info for FromAddress
join Table2 T22
    on T1.ToAddress = T22.ID -- second JOIN to get the info for ToAddress
</code>```

Title: Getting data from second table

Body:
I have 2 tables.

Table1 has columns like

ID int
FromAddress int
ToAddress int

Table2 has columns like

ID int
ZipCode int

The Connection between 2 tables is based on FromAddress,ToAdress(from Table1) and ID in table2

Rough data is like in Table1

ID     FROMAddress    ToAddress
1      500            620

Roughdata is like in Table2

ID     ZipCode
500    69999
620    6501

I want output like

ID     FromZipCode     ToZipCode
1      69999           6501

I tried to do Query like

Select T1.ID, T2.ZipCode as FromZipCode, T2.ZipCode as ToZipCode
From Table1 T1 join Table2 T2 on T1.FromAddress = T1.ID and T1.ToAddress = T2.ID

But this gives me no result.

Body:
Try like this, you need to JOIN twice:

Select T1.ID
    ,T2.ZipCode as FromZipCode
    ,T22.ZipCode as ToZipCode
From Table1 T1
join Table2 T2
    on T1.FromAddress = T2.ID -- first JOIN to get the info for FromAddress
join Table2 T22
    on T1.ToAddress = T22.ID -- second JOIN to get the info for ToAddress