问:
Google Sheets Programmatically Apply Custom Currency Symbols Number Format
I would like to programatically apply a custom number format so that I can use custom currency symbols in my cells (such as for cryptocurrency) and keep them as numbers so that I can do math with them or chart the values.

I have looked at the following options already:

If I use the spreadsheet function "CONCATENATE", I get a string and cannot do math or chart with the final value.

Spreadsheet function TEXT() can get the number format to display how I want but not all custom currency symbols "work" - the following for instance turns the value into a text string and I cannot do math/charts with it.

Ex: =TEXT(SUM(C5:C7),"Ƀ#,##0.00000000")

reference on TEXT(): https://support.google.com/docs/answer/3094139?hl=en

If I create a custom function, say format(cell), and use JS to add any text strings to the value, it's no longer a number type.

Ex: function GBP(amt) { return '£' + parseFloat(amt).toFixed(2)); }

This won't work either as resulting string is not a number:

function BTC(amt) { return parseFloat('Ƀ' + parseFloat(amt).toFixed(2)); }

setNumberFormat(format) cannot be used in a custom function to be called via spreadsheet formulas.

Copying another cells formatting? I also see this as a workaround but it looks really not efficient if I have to copy and paste formatting for every cell I want the proper formatting : Applying "Automatic" number formatting

Copying the values into another column just for conditional formatting and the original numbers only range used for maths/charting. This is more a workaround a not a clean solution.

In short, I just want to add custom currency symbols to my numbers and still be able to do math and charts with them. Does anyone know a working, direct way to do so via Google Apps Scripts or spreadsheet functions/menus?

答:
To programmatically apply a currency format to a single number and to keep it as a number in order to do arithmetic operations with it use setNumberFormat(string).

NOTES:

A custom function can't be used to apply a number format as custom functions can't modified the cell format.

Conditional Formatting doesn't apply number formatting

The Google documentation doesn't include currency formats. They could be got from the Google Sheets UI. First set the desired currency format for a cell by clicking on Format > More Formats > More Currencies, the click on Format > More Formats > Custom Number Formats... and copy the format from the text box.

Example:

The setNumberFormat is a partially implemented Google Apps Script function that currently applies Pound sterling currency format ([$£-809]#,##0.00) or a default format (#,##0.00) . The test function is used to call it assigning 'Pound sterling' to the format parameter.

```<code>function test(){
  setNumberFormat('Pound sterling');
}

function setNumberFormat(format) {
  var range = SpreadsheetApp.getActiveRange();
  var numberFormat = '';
  try {
    switch (format){
      case 'Pound sterling':
        numberFormat = '[$£-809]#,##0.00';
        break;
      default:
        numberFormat = '#,##0.00';
        break;
    }
    range.setNumberFormat(numberFormat);
  } catch (e){
    throw new Error('There was an error: ' + e);
  }
}
</code>```

Related Q&A

Set cell format to text with google apps script

References

Date and Number Formats

Custom functions in Google Sheets

Body:
To programmatically apply a currency format to a single number and to keep it as a number in order to do arithmetic operations with it use setNumberFormat(string).

NOTES:

A custom function can't be used to apply a number format as custom functions can't modified the cell format.

Conditional Formatting doesn't apply number formatting

The Google documentation doesn't include currency formats. They could be got from the Google Sheets UI. First set the desired currency format for a cell by clicking on Format > More Formats > More Currencies, the click on Format > More Formats > Custom Number Formats... and copy the format from the text box.

Example:

The setNumberFormat is a partially implemented Google Apps Script function that currently applies Pound sterling currency format ([$£-809]#,##0.00) or a default format (#,##0.00) . The test function is used to call it assigning 'Pound sterling' to the format parameter.

function test(){
  setNumberFormat('Pound sterling');
}

function setNumberFormat(format) {
  var range = SpreadsheetApp.getActiveRange();
  var numberFormat = '';
  try {
    switch (format){
      case 'Pound sterling':
        numberFormat = '[$£-809]#,##0.00';
        break;
      default:
        numberFormat = '#,##0.00';
        break;
    }
    range.setNumberFormat(numberFormat);
  } catch (e){
    throw new Error('There was an error: ' + e);
  }
}

Related Q&A

Set cell format to text with google apps script

References

Date and Number Formats

Custom functions in Google Sheets


来源: stackexchange

问:
R data.table by list of conditionals or row indices
I have a data table that includes distances. I want to run various operations within the data.table by my "id" variable and an inclusive distance threshold (e.g. Dist<1, Dist<2, etc.). I know how to run an operation by id and distance "by=list(id,Dist)", but I really want a by variable more like, "by=list(id,c(Dist<=1,Dist<=2,Dist<=3,Dist<=4,Dist<=5). Below is an example of my data structure and objective.

```<code>#load library
    library(data.table)
#create data
    set.seed(123L)
    dt<-data.table(id=factor(rep(1:10,5)),V1=rnorm(50,5,5),Dist=sample(1:5,50,replace=T))
#calculate mean of V1 by id and distance (wrong results)
    dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,Dist)]
#calculate mean of V1 by id and conditional distance (right results, wrong method)
    dt2.1<-dt[Dist<=1,.(MeanV1=mean(V1)),by=id]
    dt2.2<-dt[Dist<=2,.(MeanV1=mean(V1)),by=id]
    dt2.3<-dt[Dist<=3,.(MeanV1=mean(V1)),by=id]
    dt2.4<-dt[Dist<=4,.(MeanV1=mean(V1)),by=id]
    dt2.5<-dt[Dist<=5,.(MeanV1=mean(V1)),by=id]
    dt2<-rbind(dt2.1,dt2.2,dt2.3,dt2.4,dt2.5)
#ideal methods if either were valid
    #syntax 1
        dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,c(Dist<=1,Dist<=2,Dist<=3,Dist<=4,Dist<=5))]
    #syntax 2
        rowindices<-list(dt$Dist<=1,dt$Dist<=2,dt$Dist<=3,dt$Dist<=4,dt$Dist<=5)
        dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,rowindices)]
</code>```

Thanks in advance.

答:
As a supplement to Scott's answer, his solution can be written more concisely as

```<code>dt[.(1:5), on = .(Dist < V1), allow = TRUE, nomatch = 0][
  , .(mean_Dist_by_threshold = mean(V1)), by = .(threshold = Dist)]
</code>```

Here, .(1:5) creates thresholds on the fly and the data.table expressions are chained.

Alternatively, the aggregation can be done during the join using by = .EACHI:

```<code>dt[.(1:5), on = .(Dist < V1), nomatch = 0,
   .(mean_Dist_by_threshold = mean(V1)), by = .EACHI][
     , setnames(.SD, "Dist", "threshold")]
</code>```

The call to setnames() is just for convenience to return the same result as Scott's answer.

Benchmark code

```<code>library(data.table)
# create data
nr <- 5e2L
set.seed(123L) # to make the data reproducible
dt <-
  data.table(
    id = factor(rep(1:10, nr / 10)),
    V1 = rnorm(nr, 5, 5),
    Dist = sample(1:5, nr, replace = T)
  )
str(dt)

microbenchmark::microbenchmark(
  scott = {
    thresholds <- data.table(dist_threshold=1:5)
    passes_threshold <-
      dt[thresholds, on = .(Dist < dist_threshold), # non-equi join
         allow.cartesian = TRUE, # Fixes error, see details in ?data.table
         nomatch = 0 # Do not include thresholds which no row satisfies (i.e. Dist < 1)
         ]
    passes_threshold[, .(mean_Dist_by_threshold = mean(V1)), by = .(threshold = Dist)]
  },
  uwe1 = {
    dt[.(1:5), on = .(Dist < V1), allow = TRUE, nomatch = 0][
      , .(mean_Dist_by_threshold = mean(V1)), by = .(threshold = Dist)]
  },
  uwe2 = {
    dt[.(1:5), on = .(Dist < V1), nomatch = 0,
       .(mean_Dist_by_threshold = mean(V1)), by = .EACHI][
         , setnames(.SD, "Dist", "threshold")]
  },
  times = 100L
)
</code>```

Benchmark results

With 500 rows, there are only slight differences between the 3 variants, with the chaining slightly ahead of Scott's and by = .EACHI behind.

```<code>Unit: milliseconds
  expr      min       lq     mean   median       uq       max neval cld
 scott 1.460058 1.506854 1.618048 1.526019 1.726257  4.768493   100  a
  uwe1 1.302760 1.327686 1.487237 1.338926 1.372498 12.733933   100  a
  uwe2 1.827756 1.864777 1.944920 1.888349 2.020097  2.233269   100   b
</code>```

With 50000 rows, chaining is still slightly ahead of Scott's but by = .EACHI has outperformed the others.

```<code>Unit: milliseconds
  expr      min       lq     mean   median       uq       max neval cld
 scott 3.692545 3.811466 4.016152 3.826423 3.853489 10.336598   100   b
  uwe1 3.560786 3.632999 3.936583 3.642526 3.657992 13.579008   100   b
  uwe2 2.503508 2.545722 2.577735 2.566869 2.602586  2.798692   100  a
</code>```

With 5 M rows, this becomes much more evident:

```<code>Unit: milliseconds
  expr      min       lq     mean   median       uq      max neval cld
 scott 641.9945 675.3749 743.0761 708.7552 793.6170 878.4787     3   b
  uwe1 587.1724 587.5557 589.1360 587.9391 590.1178 592.2965     3   b
  uwe2 130.9358 134.6688 157.1860 138.4019 170.3110 202.2202     3  a
</code>```

One explanation of the speed difference might be the shear size of the intermediate result passes_threshold of more than 10 M rows (this is why allow.cartesian = TRUE is required).

ContentLicense: CC BY-SA 3.0

Body:
I have a data table that includes distances. I want to run various operations within the data.table by my "id" variable and an inclusive distance threshold (e.g. Dist<1, Dist<2, etc.). I know how to run an operation by id and distance "by=list(id,Dist)", but I really want a by variable more like, "by=list(id,c(Dist<=1,Dist<=2,Dist<=3,Dist<=4,Dist<=5). Below is an example of my data structure and objective.

#load library
    library(data.table)
#create data
    set.seed(123L)
    dt<-data.table(id=factor(rep(1:10,5)),V1=rnorm(50,5,5),Dist=sample(1:5,50,replace=T))
#calculate mean of V1 by id and distance (wrong results)
    dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,Dist)]
#calculate mean of V1 by id and conditional distance (right results, wrong method)
    dt2.1<-dt[Dist<=1,.(MeanV1=mean(V1)),by=id]
    dt2.2<-dt[Dist<=2,.(MeanV1=mean(V1)),by=id]
    dt2.3<-dt[Dist<=3,.(MeanV1=mean(V1)),by=id]
    dt2.4<-dt[Dist<=4,.(MeanV1=mean(V1)),by=id]
    dt2.5<-dt[Dist<=5,.(MeanV1=mean(V1)),by=id]
    dt2<-rbind(dt2.1,dt2.2,dt2.3,dt2.4,dt2.5)
#ideal methods if either were valid
    #syntax 1
        dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,c(Dist<=1,Dist<=2,Dist<=3,Dist<=4,Dist<=5))]
    #syntax 2
        rowindices<-list(dt$Dist<=1,dt$Dist<=2,dt$Dist<=3,dt$Dist<=4,dt$Dist<=5)
        dt2<-dt[,.(MeanV1=mean(V1)),by=list(id,rowindices)]

Thanks in advance.

Body:
As a supplement to Scott's answer, his solution can be written more concisely as

dt[.(1:5), on = .(Dist < V1), allow = TRUE, nomatch = 0][
  , .(mean_Dist_by_threshold = mean(V1)), by = .(threshold = Dist)]

Here, .(1:5) creates thresholds on the fly and the data.table expressions are chained.

Alternatively, the aggregation can be done during the join using by = .EACHI:

dt[.(1:5), on = .(Dist < V1), nomatch = 0,
   .(mean_Dist_by_threshold = mean(V1)), by = .EACHI][
     , setnames(.SD, "Dist", "threshold")]

The call to setnames() is just for convenience to return the same result as Scott's answer.

Benchmark code

library(data.table)
# create data
nr <- 5e2L
set.seed(123L) # to make the data reproducible
dt <-
  data.table(
    id = factor(rep(1:10, nr / 10)),
    V1 = rnorm(nr, 5, 5),
    Dist = sample(1:5, nr, replace = T)
  )
str(dt)

microbenchmark::microbenchmark(
  scott = {
    thresholds <- data.table(dist_threshold=1:5)
    passes_threshold <-
      dt[thresholds, on = .(Dist < dist_threshold), # non-equi join
         allow.cartesian = TRUE, # Fixes error, see details in ?data.table
         nomatch = 0 # Do not include thresholds which no row satisfies (i.e. Dist < 1)
         ]
    passes_threshold[, .(mean_Dist_by_threshold = mean(V1)), by = .(threshold = Dist)]
  },
  uwe1 = {
    dt[.(1:5), on = .(Dist < V1), allow = TRUE, nomatch = 0][
      , .(mean_Dist_by_threshold = mean(V1)), by = .(threshold = Dist)]
  },
  uwe2 = {
    dt[.(1:5), on = .(Dist < V1), nomatch = 0,
       .(mean_Dist_by_threshold = mean(V1)), by = .EACHI][
         , setnames(.SD, "Dist", "threshold")]
  },
  times = 100L
)

Benchmark results

With 500 rows, there are only slight differences between the 3 variants, with the chaining slightly ahead of Scott's and by = .EACHI behind.

Unit: milliseconds
  expr      min       lq     mean   median       uq       max neval cld
 scott 1.460058 1.506854 1.618048 1.526019 1.726257  4.768493   100  a
  uwe1 1.302760 1.327686 1.487237 1.338926 1.372498 12.733933   100  a
  uwe2 1.827756 1.864777 1.944920 1.888349 2.020097  2.233269   100   b

With 50000 rows, chaining is still slightly ahead of Scott's but by = .EACHI has outperformed the others.

Unit: milliseconds
  expr      min       lq     mean   median       uq       max neval cld
 scott 3.692545 3.811466 4.016152 3.826423 3.853489 10.336598   100   b
  uwe1 3.560786 3.632999 3.936583 3.642526 3.657992 13.579008   100   b
  uwe2 2.503508 2.545722 2.577735 2.566869 2.602586  2.798692   100  a

With 5 M rows, this becomes much more evident:

Unit: milliseconds
  expr      min       lq     mean   median       uq      max neval cld
 scott 641.9945 675.3749 743.0761 708.7552 793.6170 878.4787     3   b
  uwe1 587.1724 587.5557 589.1360 587.9391 590.1178 592.2965     3   b
  uwe2 130.9358 134.6688 157.1860 138.4019 170.3110 202.2202     3  a

One explanation of the speed difference might be the shear size of the intermediate result passes_threshold of more than 10 M rows (this is why allow.cartesian = TRUE is required).


问:
If network speed is less than 1kb/s then why SFTP connection fails more frequently
If network speed is less than 1kb/s then why SFTP connection fails more frequently.

If i increase network speed then no sftp connection fails.

答: Consider also using an sftp client that can recover from broken connections as for instance lftp.</p>

ContentLicense: CC BY-SA 2.5


问:
Count vowels in a string with ruby
My objective is to return the number of vowels in a given string. I've tried this code:

```<code>def count_vowels(string)
  vowels = ['a', 'e', 'i', 'o', 'u']
  chars_ary = string.split(//)
  ary_with_vowels = chars_ary.take_while {|letter| vowels.include?(letter)}
  return ary_with_vowels.length
end
</code>```

and it doesn't pass the majority of test cases. I understand that there are multiple other ways to solve this problem, but I want to solve it using the code that I provided.

Can someone give me some insight as to why this isn't working?

答:
Let's benchmark a few approaches.

```<code>require 'fruity'
require 'set'

SET_OF_VOWELS = %w| a e i o u |.to_set

def string_count(str)
  str.count('aeiou')
end

def set_include?(str)
  str.each_char.count { |c| SET_OF_VOWELS.include?(c) }
end

def use_hash(str)
  h = str.each_char.with_object(Hash.new(0)) { |c,h| h[c] += 1 }
  SET_OF_VOWELS.sum { |c| h[c] }
end

alpha = ('a'..'z').to_a

[1_000, 10_000, 100_000, 1_000_000].each do |n|

  puts "\nString length = #{n}"
  str = Array.new(n) { alpha.sample }.join

  compare(
    string_count: -> { string_count(str) },
    set_include?: -> { set_include?(str) },
    use_hash:     -> { use_hash(str) }
  )
end
</code>```

The results are as follows.

```<code>String length = 1000
Running each test 1024 times. Test will take about 9 seconds.
string_count is faster than set_include? by 159x ± 1.0
set_include? is faster than use_hash by 37.999999999999986% ± 1.0%

String length = 10000
Running each test 128 times. Test will take about 11 seconds.
string_count is faster than set_include? by 234x ± 1.0
set_include? is faster than use_hash by 35.00000000000001% ± 1.0%

String length = 100000
Running each test 16 times. Test will take about 14 seconds.
string_count is faster than set_include? by 246x ± 1.0
set_include? is faster than use_hash by 35.00000000000001% ± 1.0%

String length = 1000000
Running each test 2 times. Test will take about 18 seconds.
string_count is faster than set_include? by 247x ± 1.0
set_include? is faster than use_hash by 34.00000000000001% ± 1.0%
</code>```

Title: Count vowels in a string with ruby

Body:
My objective is to return the number of vowels in a given string. I've tried this code:

def count_vowels(string)
  vowels = ['a', 'e', 'i', 'o', 'u']
  chars_ary = string.split(//)
  ary_with_vowels = chars_ary.take_while {|letter| vowels.include?(letter)}
  return ary_with_vowels.length
end

and it doesn't pass the majority of test cases. I understand that there are multiple other ways to solve this problem, but I want to solve it using the code that I provided.

Can someone give me some insight as to why this isn't working?

Body:
Let's benchmark a few approaches.

require 'fruity'
require 'set'

SET_OF_VOWELS = %w| a e i o u |.to_set

def string_count(str)
  str.count('aeiou')
end

def set_include?(str)
  str.each_char.count { |c| SET_OF_VOWELS.include?(c) }
end

def use_hash(str)
  h = str.each_char.with_object(Hash.new(0)) { |c,h| h[c] += 1 }
  SET_OF_VOWELS.sum { |c| h[c] }
end

alpha = ('a'..'z').to_a

[1_000, 10_000, 100_000, 1_000_000].each do |n|

  puts "\nString length = #{n}"
  str = Array.new(n) { alpha.sample }.join

  compare(
    string_count: -> { string_count(str) },
    set_include?: -> { set_include?(str) },
    use_hash:     -> { use_hash(str) }
  )
end

The results are as follows.

String length = 1000
Running each test 1024 times. Test will take about 9 seconds.
string_count is faster than set_include? by 159x ± 1.0
set_include? is faster than use_hash by 37.999999999999986% ± 1.0%

String length = 10000
Running each test 128 times. Test will take about 11 seconds.
string_count is faster than set_include? by 234x ± 1.0
set_include? is faster than use_hash by 35.00000000000001% ± 1.0%

String length = 100000
Running each test 16 times. Test will take about 14 seconds.
string_count is faster than set_include? by 246x ± 1.0
set_include? is faster than use_hash by 35.00000000000001% ± 1.0%

String length = 1000000
Running each test 2 times. Test will take about 18 seconds.
string_count is faster than set_include? by 247x ± 1.0
set_include? is faster than use_hash by 34.00000000000001% ± 1.0%


问:
c++ winapi SendInput unexpected behavior
I have the following code, compiled using Visual C++ compiler

```<code>#include<iostream>
#include<Windows.h>

using namespace std;

int main() {
    SetProcessDPIAware();

    POINT p;
    GetCursorPos(&p);
    cout << p.x << " " << p.y << endl;

    int screenWidth = GetSystemMetrics(SM_CXSCREEN);
    int screenHeight = GetSystemMetrics(SM_CYSCREEN);

    INPUT in;
    in.type = INPUT_MOUSE;
    in.mi = {
        screenWidth / 2,
        screenHeight / 2,
        0,
        MOUSEEVENTF_MOVE,
        0,
        NULL
    };

    SendInput(1, &in, sizeof(in));

    GetCursorPos(&p);
    cout << p.x << " " << p.y << endl;

    return 0;
}
</code>```

My display is 1920x1080. From the doc, it seems that if I use relative movement (which I am in this case), dx and dy should be the difference in pixels.

When I ran this code, I placed my cursor at the top-left corner of my display and I was expecting it to end up at the center, however it ended up at (1243, 699), way past the center. Couldn't figure out why.

The exact reading of the 2 cout are

```<code>0 0
1243 699
</code>```

答:
Use MOUSEEVENTF_ABSOLUTE flag and convert the points to mouse coordinates (0 to 0xFFFF) to set the mouse coordinates. Otherwise the x/y coordinates are regarded as relative positions.

mouse_event

If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain
  normalized absolute coordinates between 0 and 65,535. The event
  procedure maps these coordinates onto the display surface. Coordinate
  (0,0) maps onto the upper-left corner of the display surface,
  (65535,65535) maps onto the lower-right corner.

If the MOUSEEVENTF_ABSOLUTE value is not specified, dx and dy specify
  relative motions from when the last mouse event was generated (the
  last reported position). Positive values mean the mouse moved right
  (or down); negative values mean the mouse moved left (or up).

Relative mouse motion is subject to the settings for mouse speed and
  acceleration level. An end user sets these values using the Mouse
  application in Control Panel. An application obtains and sets these
  values with the SystemParametersInfo function...

Use an array for the second parameter in SendInput

```<code>int main()
{
    SetProcessDPIAware();

    POINT p;
    GetCursorPos(&p);
    cout << p.x << " " << p.y << endl;

    int screenWidth = GetSystemMetrics(SM_CXSCREEN);
    int screenHeight = GetSystemMetrics(SM_CYSCREEN);
    cout << screenWidth << " " << screenHeight << endl;

    p.x = screenWidth / 2;
    p.y = screenHeight / 2;

    INPUT in[1] = { 0 };
    in[0].type = INPUT_MOUSE;
    in[0].mi.dx = (p.x * 0xFFFF) / (GetSystemMetrics(SM_CXSCREEN) - 1);
    in[0].mi.dy = (p.y * 0xFFFF) / (GetSystemMetrics(SM_CYSCREEN) - 1);
    in[0].mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;

    SendInput(1, in, sizeof(INPUT));

    GetCursorPos(&p);
    cout << p.x << " " << p.y << endl;

    return 0;
}
</code>```

Body:
I have the following code, compiled using Visual C++ compiler

#include<iostream>
#include<Windows.h>

using namespace std;

int main() {
    SetProcessDPIAware();

    POINT p;
    GetCursorPos(&p);
    cout << p.x << " " << p.y << endl;

    int screenWidth = GetSystemMetrics(SM_CXSCREEN);
    int screenHeight = GetSystemMetrics(SM_CYSCREEN);

    INPUT in;
    in.type = INPUT_MOUSE;
    in.mi = {
        screenWidth / 2,
        screenHeight / 2,
        0,
        MOUSEEVENTF_MOVE,
        0,
        NULL
    };

    SendInput(1, &in, sizeof(in));

    GetCursorPos(&p);
    cout << p.x << " " << p.y << endl;

    return 0;
}

My display is 1920x1080. From the doc, it seems that if I use relative movement (which I am in this case), dx and dy should be the difference in pixels.

When I ran this code, I placed my cursor at the top-left corner of my display and I was expecting it to end up at the center, however it ended up at (1243, 699), way past the center. Couldn't figure out why.

The exact reading of the 2 cout are

0 0
1243 699

Body:
Use MOUSEEVENTF_ABSOLUTE flag and convert the points to mouse coordinates (0 to 0xFFFF) to set the mouse coordinates. Otherwise the x/y coordinates are regarded as relative positions.

mouse_event

If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain
  normalized absolute coordinates between 0 and 65,535. The event
  procedure maps these coordinates onto the display surface. Coordinate
  (0,0) maps onto the upper-left corner of the display surface,
  (65535,65535) maps onto the lower-right corner.

If the MOUSEEVENTF_ABSOLUTE value is not specified, dx and dy specify
  relative motions from when the last mouse event was generated (the
  last reported position). Positive values mean the mouse moved right
  (or down); negative values mean the mouse moved left (or up).

Relative mouse motion is subject to the settings for mouse speed and
  acceleration level. An end user sets these values using the Mouse
  application in Control Panel. An application obtains and sets these
  values with the SystemParametersInfo function...

Use an array for the second parameter in SendInput

int main()
{
    SetProcessDPIAware();

    POINT p;
    GetCursorPos(&p);
    cout << p.x << " " << p.y << endl;

    int screenWidth = GetSystemMetrics(SM_CXSCREEN);
    int screenHeight = GetSystemMetrics(SM_CYSCREEN);
    cout << screenWidth << " " << screenHeight << endl;

    p.x = screenWidth / 2;
    p.y = screenHeight / 2;

    INPUT in[1] = { 0 };
    in[0].type = INPUT_MOUSE;
    in[0].mi.dx = (p.x * 0xFFFF) / (GetSystemMetrics(SM_CXSCREEN) - 1);
    in[0].mi.dy = (p.y * 0xFFFF) / (GetSystemMetrics(SM_CYSCREEN) - 1);
    in[0].mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;

    SendInput(1, in, sizeof(INPUT));

    GetCursorPos(&p);
    cout << p.x << " " << p.y << endl;

    return 0;
}


问:
How can I monitor memory used by specific process in AWS cloudwatch?
I want to monitor memory used by particular process under cloudwatch in AWS. Do I have to use script to do so? If yes, let me know the steps or some guideline or Can I use cloudwatch logs to report memory utilized by particular process in real time? Tell me the other alternatives as well.

答:
While the reason provided by @EJBrennan in his answer is correct, a more recent update to this question is to simply install the scripts as provided in this excellent documentation from AWS

AWS Documentation for Memory & Disk Metrics

So you need to

Install the scripts in your EC2 server

PUT the logs to Cloudwatch using   ./mon-put-instance-data.pl --mem-util --mem-used-incl-cache-buff --mem-used --mem-avail

Setup a dashboard in your cloudwatch to see the metrics.

Alternatively, you can also setup a cron job to get the metrics on a periodic basis.

Hope that helps


问:
using !! symbol before the scope variable in ng-show what would represent this ( !! )symbol
what is the real meaning of using (!)before the scope variable in angularjs.
ng-show="!!file". What would indicate if I use this symbol in angularjs ng-directives</p>

答:
var nonEmptyString = "nonempty string";
var emptyString = "";

console.log(!!nonEmptyString);
console.log(!!emptyString);```


问:
Bash - Why $(sudo cat file) cannot find a file which exists?

Question

Why $(sudo cat) cannot find a file which exists?

This works:

```<code>for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash << EOF
        sudo cat /etc/origin/master/ca-bundle.crt
EOF
done
</code>```

-----BEGIN CERTIFICATE-----

  XYZ...

  -----END CERTIFICATE-----

This does not work but no idea why:

```<code>for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash << EOF
        RESULT="$(sudo cat /etc/origin/master/ca-bundle.crt; echo x)"
        echo "${RESULT%x}"
EOF
done
</code>```

"cat: /etc/origin/master/ca-bundle.crt: No such file or directory"

Fix

Based on the answer, fixed as below and worked. Thanks a lot.

```<code>#!/bin/bash
set -u
for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash <<'EOF'
RESULT="$(sudo cat /etc/origin/master/ca-bundle.crt; echo x)"
echo "${RESULT%x}"
EOF
done
</code>```

答:
The problem is occurring because command and variable substitutions are performed in here-documents before they're passed to the command. Thus, $(sudo cat /etc/origin/master/ca-bundle.crt; echo x) and ${RESULT%x} are both evaluated on the local computer (where /etc/origin/master/ca-bundle.crt presumably doesn't exist and RESULT isn't defined). As a result, this is what gets sent to the remote computer:

```<code>    RESULT="x"
    echo ""
</code>```

Which isn't what you wanted at all.

To avoid this, you can either escape the $ characters in the here-document, or quote the here-document delimiter (<<'EOF'). BTW, the indent characters in the here-document will be passed over the ssh connection, which can have unfortunate consequences (e.g. invoking the remote shell's autocomplete features). I'd either outdent the here-document, or prefix the delimiter with "-" (<<-'EOF') and use tabs (not spaces) for the indentation.

EDIT: After thinking about @tripleee's answer, I'm not sure I agree with all of his suggested rewrites, but he's certainly right that parts of the loop are more complex and/or fragile than they should be. Here are my suggestions for changes:

Unless there's more being done on the remote computer than is shown in the question, the ssh part can (and should) be drastically simplified. There's no need to put the content of the certificate file in a variable and then echo the variable, just output it directly. And note that the entire problem arose because of the complications of handing getting it into and out of the variable; if the remote part was just sudo cat /etc/origin/master/ca-bundle.crt, the whole thing would've just worked. Furthermore, there's no need to explicitly run a remote bash shell and use a redirect to give it the command to run, just use ssh ${host} sudo cat /etc/origin/master/ca-bundle.crt.

Ok, there is one thing the variable stuff did do. It added a blank line after the content of the certificate file. This happens because the "x" trick carefully preserves the final newline in the file's contents (normally, $( ) removes trailing newlines), and then echo adds another newline, resulting in a blank line. But if this was intentional, it's much easier (and clearer) to do just by adding another echo command with no arguments.

The pipeline to list the hostnames is much longer than it needs to be, but here there's a tradeoff between complexity and readability/clarity. tripleee's version is much shorter, but it's harder to read off what it's doing (unless you're fluent in awk), and that means there's more risk of bugs, it's harder to maintain, etc. But there are still some simplifications I'd recommend:

Don't use cat to feed a single file into a pipeline. Either use a <filename redirect, or (if the command supports it) just give it the command the filename and let it read from it:

```<code>cut -d ' ' -f 1 /etc/ansible/hosts | ...
cut -d ' ' -f 1 </etc/ansible/hosts | ...
</code>```

This may seem less natural than using cat |, but it's the best (and most standard) way to do things. Frankly, if it seems unnatural or confusing, that just means you haven't done it enough. So do it more.

Your pipeline has each command doing just on thing: cut gets the first field, grep selects those that start with "master-", sort puts them in order, and uniq removes duplicates. But sort is perfectly capable of removing duplicates itself, so I'd use sort -u instead of sort | uniq. And awk can do almost everything all by itself (but gets hard to read/understand if you make it do too much). Personally, I'd use:

```<code>awk '$1 ~ /^master-/ {print $1}' /etc/ansible/hosts | sort -u
</code>```

(That awk script can be read as "if the first field starts with 'master-', print it.)

Then there's the question of how to iterate over the list of hosts. for var in $(somecommand) is widely considered an antipattern, because of the number of things that can go wrong. It breaks the output of the command into "words" (which might or might not correspond to lines), and then tries to expand any wildcards it finds into lists of matching files (which can have really weird effects), and then iterates over the result of that.

In this particular case, I think you're safe (unless you redefined $IFS). There shouldn't be any word delimiters (spaces, tabs, and newlines) in your entries because you're already selecting just the first field. There shouldn't be any wildcards in the entries, because "*", "?", and "[" aren't generally allowed in hostnames. I suppose there might be a raw IPv6 address in "[hexdigits:hexdigits::hexdigits]" format -- which is a shell wildcard and will cause trouble if there are matching files -- but those aren't going to be selected by the ^master- pattern.

The alternatives are to use pipe the list to either an xargs command (as in @tripleee's answer) or a while read loop. These both have a different potential problem in that ssh can steal hostnames from the input stream if you're not careful. ssh -n will prevent this.

In this case, I think I'd just use the for loop. So with all of this, here's my suggested rewrite:

```<code>#!/bin/bash
set -u
for host in $(awk '$1 !~ /^master-/ {print $1}' /etc/ansible/hosts | sort -u); do
    ssh "${host}" sudo cat /etc/origin/master/ca-bundle.crt
    echo
done
</code>```

Body:
Question

Why $(sudo cat) cannot find a file which exists?

This works:

for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash << EOF
        sudo cat /etc/origin/master/ca-bundle.crt
EOF
done

-----BEGIN CERTIFICATE-----

  XYZ...

  -----END CERTIFICATE-----

This does not work but no idea why:

for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash << EOF
        RESULT="$(sudo cat /etc/origin/master/ca-bundle.crt; echo x)"
        echo "${RESULT%x}"
EOF
done

"cat: /etc/origin/master/ca-bundle.crt: No such file or directory"

Fix

Based on the answer, fixed as below and worked. Thanks a lot.

#!/bin/bash
set -u
for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash <<'EOF'
RESULT="$(sudo cat /etc/origin/master/ca-bundle.crt; echo x)"
echo "${RESULT%x}"
EOF
done

Body:
The problem is occurring because command and variable substitutions are performed in here-documents before they're passed to the command. Thus, $(sudo cat /etc/origin/master/ca-bundle.crt; echo x) and ${RESULT%x} are both evaluated on the local computer (where /etc/origin/master/ca-bundle.crt presumably doesn't exist and RESULT isn't defined). As a result, this is what gets sent to the remote computer:

    RESULT="x"
    echo ""

Which isn't what you wanted at all.

To avoid this, you can either escape the $ characters in the here-document, or quote the here-document delimiter (<<'EOF'). BTW, the indent characters in the here-document will be passed over the ssh connection, which can have unfortunate consequences (e.g. invoking the remote shell's autocomplete features). I'd either outdent the here-document, or prefix the delimiter with "-" (<<-'EOF') and use tabs (not spaces) for the indentation.

EDIT: After thinking about @tripleee's answer, I'm not sure I agree with all of his suggested rewrites, but he's certainly right that parts of the loop are more complex and/or fragile than they should be. Here are my suggestions for changes:

Unless there's more being done on the remote computer than is shown in the question, the ssh part can (and should) be drastically simplified. There's no need to put the content of the certificate file in a variable and then echo the variable, just output it directly. And note that the entire problem arose because of the complications of handing getting it into and out of the variable; if the remote part was just sudo cat /etc/origin/master/ca-bundle.crt, the whole thing would've just worked. Furthermore, there's no need to explicitly run a remote bash shell and use a redirect to give it the command to run, just use ssh ${host} sudo cat /etc/origin/master/ca-bundle.crt.

Ok, there is one thing the variable stuff did do. It added a blank line after the content of the certificate file. This happens because the "x" trick carefully preserves the final newline in the file's contents (normally, $( ) removes trailing newlines), and then echo adds another newline, resulting in a blank line. But if this was intentional, it's much easier (and clearer) to do just by adding another echo command with no arguments.

The pipeline to list the hostnames is much longer than it needs to be, but here there's a tradeoff between complexity and readability/clarity. tripleee's version is much shorter, but it's harder to read off what it's doing (unless you're fluent in awk), and that means there's more risk of bugs, it's harder to maintain, etc. But there are still some simplifications I'd recommend:

Don't use cat to feed a single file into a pipeline. Either use a <filename redirect, or (if the command supports it) just give it the command the filename and let it read from it:

cut -d ' ' -f 1 /etc/ansible/hosts | ...
cut -d ' ' -f 1 </etc/ansible/hosts | ...

This may seem less natural than using cat |, but it's the best (and most standard) way to do things. Frankly, if it seems unnatural or confusing, that just means you haven't done it enough. So do it more.

Your pipeline has each command doing just on thing: cut gets the first field, grep selects those that start with "master-", sort puts them in order, and uniq removes duplicates. But sort is perfectly capable of removing duplicates itself, so I'd use sort -u instead of sort | uniq. And awk can do almost everything all by itself (but gets hard to read/understand if you make it do too much). Personally, I'd use:

awk '$1 ~ /^master-/ {print $1}' /etc/ansible/hosts | sort -u

(That awk script can be read as "if the first field starts with 'master-', print it.)

Then there's the question of how to iterate over the list of hosts. for var in $(somecommand) is widely considered an antipattern, because of the number of things that can go wrong. It breaks the output of the command into "words" (which might or might not correspond to lines), and then tries to expand any wildcards it finds into lists of matching files (which can have really weird effects), and then iterates over the result of that.

In this particular case, I think you're safe (unless you redefined $IFS). There shouldn't be any word delimiters (spaces, tabs, and newlines) in your entries because you're already selecting just the first field. There shouldn't be any wildcards in the entries, because "*", "?", and "[" aren't generally allowed in hostnames. I suppose there might be a raw IPv6 address in "[hexdigits:hexdigits::hexdigits]" format -- which is a shell wildcard and will cause trouble if there are matching files -- but those aren't going to be selected by the ^master- pattern.

The alternatives are to use pipe the list to either an xargs command (as in @tripleee's answer) or a while read loop. These both have a different potential problem in that ssh can steal hostnames from the input stream if you're not careful. ssh -n will prevent this.

In this case, I think I'd just use the for loop. So with all of this, here's my suggested rewrite:

#!/bin/bash
set -u
for host in $(awk '$1 !~ /^master-/ {print $1}' /etc/ansible/hosts | sort -u); do
    ssh "${host}" sudo cat /etc/origin/master/ca-bundle.crt
    echo
done


问:
Running CircleCI 2.0 workflows on tags, REGEX
I have a circleci integrated github repository, I am running CircleCI 2.0
I want one workflow, test, to run on all branches and tags, so long as the tag does not match the pattern v*.. with an optional ending. And anything matching the pattern v*.. should be run through the deploy workflow. For example these tags should, v0.0.1 be run through deploy, v0.0.1beta should be run through deploy, v0.1beta or betav0.1.1 should be run through test instead. What would the appropriate regex to match this be, and if you are familiar with circleci 2.0, what changes do I need to make to this section of the configuration file in order for this to work.

workflows:
  version: 2
  test:
    jobs:
      - build:
          filters:
            tags:
              ignore:
                - /^v[0-9]\.[0-9]\.[0-9].+/
            branches:
              only:
                - /.*/
      - lint:
          requires:
            - build
  deploy:
    jobs:
      - build
          filters:
            tags:
              only:
                - /^v[0-9]\.[0-9]\.[0-9].+/
            branches:
              ignore:
                - /.*/
      - lint:
          requires:
            - build
      - deploy:
          requires:
            - lint

Body:
Try this:

^v\d\.\d\.\d\w{0,5}$


问:
What class is responsible for recording sound in Objective-C?
I wanted to make a decibel counter for the iPhone, but don't know what class is responsible for recording sound. </p>

答: It's the AVAudioRecorder. You need to add the AVFoundation.framework to your project to use the class.</p>


问:
cannot get clients ip address in web.api
I'm building a Web.Api (mvc & web.api) and try to get the clients ip adress with this code..

```<code>[System.Web.Http.HttpPut]
public HttpResponseMessage Update([FromBody] BookInformation bookStatus)
{
  // Stuff...

  // Retrieve clients IP#
  var clientIp = (System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.UserHostAddress
}
</code>```

But I get this error:

'System.Web.HttpRequestBase' does not contain a definition for
  'Properties' and no extension method 'Properties' accepting a first
  argument of type 'System.Web.HttpRequestBase' could be found (are you
  missing a using directive or an assembly reference?)

What am I missing here?

答:
you should add reference
 System.ServiceModel
 and
 System.ServiceModel.channel</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm building a Web.Api (mvc & web.api) and try to get the clients ip adress with this code..

[System.Web.Http.HttpPut]
public HttpResponseMessage Update([FromBody] BookInformation bookStatus)
{
  // Stuff...

  // Retrieve clients IP#
  var clientIp = (System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.UserHostAddress
}

But I get this error:

'System.Web.HttpRequestBase' does not contain a definition for
  'Properties' and no extension method 'Properties' accepting a first
  argument of type 'System.Web.HttpRequestBase' could be found (are you
  missing a using directive or an assembly reference?)

What am I missing here?


问:
Passing a backslash string in Java gives me unicode error exception
I have Java code running

```<code>SparkAppHandle handler =
    new SparkLauncher(options).setSparkHome("\usr\hdp\2.6.3.0-235\spark2");
</code>```

I need to define the path as exactly like above but the compiler gives exception "Invalid Unicode"

答:
Escape \ using \\ inside Strings. Like this:

```<code>.setSparkHome("\\usr\\hdp...
</code>```

Which becomes

```<code>\usr\hdp...
</code>```

when you print it out, etc.

Body:
I have Java code running

SparkAppHandle handler =
    new SparkLauncher(options).setSparkHome("\usr\hdp\2.6.3.0-235\spark2");

I need to define the path as exactly like above but the compiler gives exception "Invalid Unicode"

Body:
Escape \ using \\ inside Strings. Like this:

.setSparkHome("\\usr\\hdp...

Which becomes

\usr\hdp...

when you print it out, etc.


问:
How to build a dictionary with the values of each country in the same group
I have the following data in a dictionary or a list:

```<code>{'time': '2016 Nov', 'value': 8.0, 'Country': 'Denmark'}
{'time': '2016 Dec', 'value': 8.5, 'Country': 'Denmark'}
{'time': '2017 Jan', 'value': 11.9, 'Country': 'Denmark'}
{'time': '2017 Feb', 'value': 13.5, 'Country': 'Denmark'}
{'time': '2017 Mar', 'value': 13.9, 'Country': 'Denmark'}
{'time': '2017 Apr', 'value': 14.6, 'Country': 'Denmark'}
{'time': '2017 May', 'value': 13.4, 'Country': 'Denmark'}
{'time': '2017 Jun', 'value': 15.0, 'Country': 'Denmark'}
{'time': '2017 Jul', 'value': 16.6, 'Country': 'Denmark'}
{'time': '2017 Aug', 'value': 14.7, 'Country': 'Denmark'}
{'time': '2017 Sep', 'value': 16.2, 'Country': 'Denmark'}
{'time': '2017 Oct', 'value': 14.9, 'Country': 'Denmark'}
{'time': '2016 Nov', 'value': 19.9, 'Country': 'Finland'}
{'time': '2016 Dec', 'value': 22.4, 'Country': 'Finland'}
{'time': '2017 Jan', 'value': 22.6, 'Country': 'Finland'}
{'time': '2017 Feb', 'value': 20.9, 'Country': 'Finland'}
{'time': '2017 Mar', 'value': 23.2, 'Country': 'Finland'}
{'time': '2017 Apr', 'value': 23.6, 'Country': 'Finland'}
{'time': '2017 May', 'value': 24.5, 'Country': 'Finland'}
{'time': '2017 Jun', 'value': 24.3, 'Country': 'Finland'}
{'time': '2017 Jul', 'value': 24.7, 'Country': 'Finland'}
{'time': '2017 Aug', 'value': 25.5, 'Country': 'Finland'}
{'time': '2017 Sep', 'value': 27.1, 'Country': 'Finland'}
{'time': '2017 Oct', 'value': 27.2, 'Country': 'Finland'}
</code>```

I would like to know how can I buld a dictionary that for each date, it shows the value for each country like this:

```<code>{'time': '2016 Nov', 'Denmark': 8.0, 'Finland': 19.9 },
{'time': '2016 Dec', 'Denmark': 8.5, 'Finland': 22.4 },
</code>```

And so on...

答:
Using cytoolz.dicttoolz.merge and defaultdict

```<code>from cytoolz.dicttoolz import merge
from collections import defaultdict

d = defaultdict(lambda: defaultdict(dict))

for r in lod:
    d[r['time']][r['Country']] = r['value']

[merge({'time': k}, v) for k, v in d.items()]

[{'Denmark': 8.0, 'Finland': 19.9, 'time': '2016 Nov'},
 {'Denmark': 8.5, 'Finland': 22.4, 'time': '2016 Dec'},
 {'Denmark': 11.9, 'Finland': 22.6, 'time': '2017 Jan'},
 {'Denmark': 13.5, 'Finland': 20.9, 'time': '2017 Feb'},
 {'Denmark': 13.9, 'Finland': 23.2, 'time': '2017 Mar'},
 {'Denmark': 14.6, 'Finland': 23.6, 'time': '2017 Apr'},
 {'Denmark': 13.4, 'Finland': 24.5, 'time': '2017 May'},
 {'Denmark': 15.0, 'Finland': 24.3, 'time': '2017 Jun'},
 {'Denmark': 16.6, 'Finland': 24.7, 'time': '2017 Jul'},
 {'Denmark': 14.7, 'Finland': 25.5, 'time': '2017 Aug'},
 {'Denmark': 16.2, 'Finland': 27.1, 'time': '2017 Sep'},
 {'Denmark': 14.9, 'Finland': 27.2, 'time': '2017 Oct'}]
</code>```

Setup

```<code>lod = [
    {'time': '2016 Nov', 'value': 8.0, 'Country': 'Denmark'},
    {'time': '2016 Dec', 'value': 8.5, 'Country': 'Denmark'},
    {'time': '2017 Jan', 'value': 11.9, 'Country': 'Denmark'},
    {'time': '2017 Feb', 'value': 13.5, 'Country': 'Denmark'},
    {'time': '2017 Mar', 'value': 13.9, 'Country': 'Denmark'},
    {'time': '2017 Apr', 'value': 14.6, 'Country': 'Denmark'},
    {'time': '2017 May', 'value': 13.4, 'Country': 'Denmark'},
    {'time': '2017 Jun', 'value': 15.0, 'Country': 'Denmark'},
    {'time': '2017 Jul', 'value': 16.6, 'Country': 'Denmark'},
    {'time': '2017 Aug', 'value': 14.7, 'Country': 'Denmark'},
    {'time': '2017 Sep', 'value': 16.2, 'Country': 'Denmark'},
    {'time': '2017 Oct', 'value': 14.9, 'Country': 'Denmark'},
    {'time': '2016 Nov', 'value': 19.9, 'Country': 'Finland'},
    {'time': '2016 Dec', 'value': 22.4, 'Country': 'Finland'},
    {'time': '2017 Jan', 'value': 22.6, 'Country': 'Finland'},
    {'time': '2017 Feb', 'value': 20.9, 'Country': 'Finland'},
    {'time': '2017 Mar', 'value': 23.2, 'Country': 'Finland'},
    {'time': '2017 Apr', 'value': 23.6, 'Country': 'Finland'},
    {'time': '2017 May', 'value': 24.5, 'Country': 'Finland'},
    {'time': '2017 Jun', 'value': 24.3, 'Country': 'Finland'},
    {'time': '2017 Jul', 'value': 24.7, 'Country': 'Finland'},
    {'time': '2017 Aug', 'value': 25.5, 'Country': 'Finland'},
    {'time': '2017 Sep', 'value': 27.1, 'Country': 'Finland'},
    {'time': '2017 Oct', 'value': 27.2, 'Country': 'Finland'}
]
</code>```

Body:
I have the following data in a dictionary or a list:

{'time': '2016 Nov', 'value': 8.0, 'Country': 'Denmark'}
{'time': '2016 Dec', 'value': 8.5, 'Country': 'Denmark'}
{'time': '2017 Jan', 'value': 11.9, 'Country': 'Denmark'}
{'time': '2017 Feb', 'value': 13.5, 'Country': 'Denmark'}
{'time': '2017 Mar', 'value': 13.9, 'Country': 'Denmark'}
{'time': '2017 Apr', 'value': 14.6, 'Country': 'Denmark'}
{'time': '2017 May', 'value': 13.4, 'Country': 'Denmark'}
{'time': '2017 Jun', 'value': 15.0, 'Country': 'Denmark'}
{'time': '2017 Jul', 'value': 16.6, 'Country': 'Denmark'}
{'time': '2017 Aug', 'value': 14.7, 'Country': 'Denmark'}
{'time': '2017 Sep', 'value': 16.2, 'Country': 'Denmark'}
{'time': '2017 Oct', 'value': 14.9, 'Country': 'Denmark'}
{'time': '2016 Nov', 'value': 19.9, 'Country': 'Finland'}
{'time': '2016 Dec', 'value': 22.4, 'Country': 'Finland'}
{'time': '2017 Jan', 'value': 22.6, 'Country': 'Finland'}
{'time': '2017 Feb', 'value': 20.9, 'Country': 'Finland'}
{'time': '2017 Mar', 'value': 23.2, 'Country': 'Finland'}
{'time': '2017 Apr', 'value': 23.6, 'Country': 'Finland'}
{'time': '2017 May', 'value': 24.5, 'Country': 'Finland'}
{'time': '2017 Jun', 'value': 24.3, 'Country': 'Finland'}
{'time': '2017 Jul', 'value': 24.7, 'Country': 'Finland'}
{'time': '2017 Aug', 'value': 25.5, 'Country': 'Finland'}
{'time': '2017 Sep', 'value': 27.1, 'Country': 'Finland'}
{'time': '2017 Oct', 'value': 27.2, 'Country': 'Finland'}

I would like to know how can I buld a dictionary that for each date, it shows the value for each country like this:

{'time': '2016 Nov', 'Denmark': 8.0, 'Finland': 19.9 },
{'time': '2016 Dec', 'Denmark': 8.5, 'Finland': 22.4 },

And so on...

Body:
Using cytoolz.dicttoolz.merge and defaultdict

from cytoolz.dicttoolz import merge
from collections import defaultdict

d = defaultdict(lambda: defaultdict(dict))

for r in lod:
    d[r['time']][r['Country']] = r['value']

[merge({'time': k}, v) for k, v in d.items()]

[{'Denmark': 8.0, 'Finland': 19.9, 'time': '2016 Nov'},
 {'Denmark': 8.5, 'Finland': 22.4, 'time': '2016 Dec'},
 {'Denmark': 11.9, 'Finland': 22.6, 'time': '2017 Jan'},
 {'Denmark': 13.5, 'Finland': 20.9, 'time': '2017 Feb'},
 {'Denmark': 13.9, 'Finland': 23.2, 'time': '2017 Mar'},
 {'Denmark': 14.6, 'Finland': 23.6, 'time': '2017 Apr'},
 {'Denmark': 13.4, 'Finland': 24.5, 'time': '2017 May'},
 {'Denmark': 15.0, 'Finland': 24.3, 'time': '2017 Jun'},
 {'Denmark': 16.6, 'Finland': 24.7, 'time': '2017 Jul'},
 {'Denmark': 14.7, 'Finland': 25.5, 'time': '2017 Aug'},
 {'Denmark': 16.2, 'Finland': 27.1, 'time': '2017 Sep'},
 {'Denmark': 14.9, 'Finland': 27.2, 'time': '2017 Oct'}]

Setup

lod = [
    {'time': '2016 Nov', 'value': 8.0, 'Country': 'Denmark'},
    {'time': '2016 Dec', 'value': 8.5, 'Country': 'Denmark'},
    {'time': '2017 Jan', 'value': 11.9, 'Country': 'Denmark'},
    {'time': '2017 Feb', 'value': 13.5, 'Country': 'Denmark'},
    {'time': '2017 Mar', 'value': 13.9, 'Country': 'Denmark'},
    {'time': '2017 Apr', 'value': 14.6, 'Country': 'Denmark'},
    {'time': '2017 May', 'value': 13.4, 'Country': 'Denmark'},
    {'time': '2017 Jun', 'value': 15.0, 'Country': 'Denmark'},
    {'time': '2017 Jul', 'value': 16.6, 'Country': 'Denmark'},
    {'time': '2017 Aug', 'value': 14.7, 'Country': 'Denmark'},
    {'time': '2017 Sep', 'value': 16.2, 'Country': 'Denmark'},
    {'time': '2017 Oct', 'value': 14.9, 'Country': 'Denmark'},
    {'time': '2016 Nov', 'value': 19.9, 'Country': 'Finland'},
    {'time': '2016 Dec', 'value': 22.4, 'Country': 'Finland'},
    {'time': '2017 Jan', 'value': 22.6, 'Country': 'Finland'},
    {'time': '2017 Feb', 'value': 20.9, 'Country': 'Finland'},
    {'time': '2017 Mar', 'value': 23.2, 'Country': 'Finland'},
    {'time': '2017 Apr', 'value': 23.6, 'Country': 'Finland'},
    {'time': '2017 May', 'value': 24.5, 'Country': 'Finland'},
    {'time': '2017 Jun', 'value': 24.3, 'Country': 'Finland'},
    {'time': '2017 Jul', 'value': 24.7, 'Country': 'Finland'},
    {'time': '2017 Aug', 'value': 25.5, 'Country': 'Finland'},
    {'time': '2017 Sep', 'value': 27.1, 'Country': 'Finland'},
    {'time': '2017 Oct', 'value': 27.2, 'Country': 'Finland'}
]


问:
How to move the three images and text towards right in layout?
I have an icon with images at left followed by text.

And towards right, there should be three images and three text below the three images. I done everything but problem is i couldn't move the three images and text towards right side.

Though I gave in LinearLayout (for reference: android:id="@+id/right_side_layout") android:gravity="right|end" it's not moving towards right side.

Here is layout and screenshot.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:src="@drawable/ic_mark" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:src="@drawable/ic_profile" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="@string/route_plan_default_number"
                android:textColor="@color/black"
                android:textSize="@dimen/text_size_very_small" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="@string/route_plan_default_name"
                android:textColor="@color/dark_green"
                android:textSize="@dimen/text_size_very_small" />

        </LinearLayout>
  <!--
        This layout should be right side. Though I given  android:gravity="right|end" it's not moving right.
    -->
        <LinearLayout
            android:id="@+id/right_side_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="28dp"
            android:layout_weight="1"
            android:gravity="right|end"
            android:orientation="horizontal">

            <RelativeLayout
                android:id="@+id/relative"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/sell_in_red"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_sell_in_red" />

                <TextView
                    android:id="@+id/textLabel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/sell_in_red"
                    android:layout_centerInParent="true"
                    android:paddingTop="2dp"
                    android:text="In"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="9dp"
                android:layout_marginRight="9dp">

                <ImageView
                    android:id="@+id/sell_in_yellow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_in_yellow" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/sell_in_yellow"
                    android:layout_centerInParent="true"
                    android:paddingTop="2dp"
                    android:text="Out"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/growth_icon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_sell_in_green" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/growth_icon"
                    android:layout_centerInParent="true"
                    android:gravity="center"
                    android:paddingTop="2dp"
                    android:text="growth"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>
</code>```

You can see the below image where three circular icons are not moving towards right side.

答:
Change width of nested linear layout (2nd from top) to match_parent.</p>

```<code> <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:orientation="horizontal">
</code>```

Body:
I have an icon with images at left followed by text.

And towards right, there should be three images and three text below the three images. I done everything but problem is i couldn't move the three images and text towards right side.

Though I gave in LinearLayout (for reference: android:id="@+id/right_side_layout") android:gravity="right|end" it's not moving towards right side.

Here is layout and screenshot.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:src="@drawable/ic_mark" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:layout_weight="1"
            android:src="@drawable/ic_profile" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="@string/route_plan_default_number"
                android:textColor="@color/black"
                android:textSize="@dimen/text_size_very_small" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:text="@string/route_plan_default_name"
                android:textColor="@color/dark_green"
                android:textSize="@dimen/text_size_very_small" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/right_side_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="28dp"
            android:layout_weight="1"
            android:gravity="right|end"
            android:orientation="horizontal">

            <RelativeLayout
                android:id="@+id/relative"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/sell_in_red"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_sell_in_red" />

                <TextView
                    android:id="@+id/textLabel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/sell_in_red"
                    android:layout_centerInParent="true"
                    android:paddingTop="2dp"
                    android:text="In"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="9dp"
                android:layout_marginRight="9dp">

                <ImageView
                    android:id="@+id/sell_in_yellow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_in_yellow" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/sell_in_yellow"
                    android:layout_centerInParent="true"
                    android:paddingTop="2dp"
                    android:text="Out"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:id="@+id/growth_icon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_sell_in_green" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/growth_icon"
                    android:layout_centerInParent="true"
                    android:gravity="center"
                    android:paddingTop="2dp"
                    android:text="growth"
                    android:textSize="@dimen/text_size_very_small"
                    android:textStyle="bold" />
            </RelativeLayout>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

You can see the below image where three circular icons are not moving towards right side.

Body:
Change width of nested linear layout (2nd from top) to match_parent.

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:orientation="horizontal">


问:
How do you generate a list of prime numbers using list comprehension from 1 to 10?
So, I've made this code:

```<code>y = 10
prime_num = [x for x in range(1,y) if y%x != 0]
</code>```

It's returned me:

[3, 4, 6, 7, 8, 9]

The purpose of this code is to generate prime numbers within 1 to 10, it returned me an odd number which I do not quiet get. I was expecting this to work since my list comprehension was an attempted replica of:

```<code>def is_prime(x):
    if x < 2:
        return False
    else:
        for n in range(2, x-1):
            if x % n == 0:
                return False
        return True
</code>```

Which I've created from codecademy, I've simply changed "x%n == 0" to "x%n != 0".

答:
I don't think your code follows the given code from codeacacdemy .This is somewhat closer to the code from  codeacademy</p>

```<code>y = 10
factor_array = [x for x in range(2,y) if y%x == 0 ]
if not factor_array :
  print("prime")
else :
  print ("composite")
</code>```

Body:
So, I've made this code:

y = 10
prime_num = [x for x in range(1,y) if y%x != 0]

It's returned me:

[3, 4, 6, 7, 8, 9]

The purpose of this code is to generate prime numbers within 1 to 10, it returned me an odd number which I do not quiet get. I was expecting this to work since my list comprehension was an attempted replica of:

def is_prime(x):
    if x < 2:
        return False
    else:
        for n in range(2, x-1):
            if x % n == 0:
                return False
        return True

Which I've created from codecademy, I've simply changed "x%n == 0" to "x%n != 0".

Body:
I don't think your code follows the given code from codeacacdemy .This is somewhat closer to the code from  codeacademy

y = 10
factor_array = [x for x in range(2,y) if y%x == 0 ]
if not factor_array :
  print("prime")
else :
  print ("composite")


问:
How to draw a line connector between two icons displayed in two different div.
I have displayed one Icons in one Div element. I need to draw a connecting line between those Icons. Please note that the Div is a dynamic element.

I have displayed the current Image below.

Expected image is displayed below.

Please guide me how to do that. Thanks in advance.

答:
The concept is to draw a div with absolute position inside of "starting point" and rotate it on an angle between 2 points:

```<code>// a,b  = jquery results i.e. a=$('#smile1'), b=$('#smile2'),
  function dist(a,b) {
      let o1 = a.offset(), o2 = b.offset();
       return Math.sqrt(Math.pow(o1.top  - o2.top,2) + Math.pow(o1.left - o2.left,2));
    }
    function angle(a, b) {
       let ao = a.offset(), bo = b.offset();
           dx = ao.left-bo.left, dy = ao.top-bo.top;
       return Math.PI + Math.atan2(dy, dx);
    }
    function drawConnection(a,b) {
       $('.line').remove();
       let d = dist(a,b);
       a.removeClass('first');
       let ang = d<10
           ? 0
           : (angle(a,b) * 180)/ Math.PI;
       a.append(
          $('<div>').addClass('line')
              .css({
                  width: Math.round(d) +'px',
                  transform: 'rotate(' + Math.round(ang) + 'deg)'
              })
       );
       return ang;
    }
</code>```

CSS for the line should be:

```<code>.line {
   position: absolute;
   transform-origin: top left; // to make it rotate around top-left
   border-top: solid 2px blue; // set any color
   top: 10px; // center of your "smile"
   left: 10px;
}
</code>```

Here is the working example

Body:
The concept is to draw a div with absolute position inside of "starting point" and rotate it on an angle between 2 points:

// a,b  = jquery results i.e. a=$('#smile1'), b=$('#smile2'),
  function dist(a,b) {
      let o1 = a.offset(), o2 = b.offset();
       return Math.sqrt(Math.pow(o1.top  - o2.top,2) + Math.pow(o1.left - o2.left,2));
    }
    function angle(a, b) {
       let ao = a.offset(), bo = b.offset();
           dx = ao.left-bo.left, dy = ao.top-bo.top;
       return Math.PI + Math.atan2(dy, dx);
    }
    function drawConnection(a,b) {
       $('.line').remove();
       let d = dist(a,b);
       a.removeClass('first');
       let ang = d<10
           ? 0
           : (angle(a,b) * 180)/ Math.PI;
       a.append(
          $('<div>').addClass('line')
              .css({
                  width: Math.round(d) +'px',
                  transform: 'rotate(' + Math.round(ang) + 'deg)'
              })
       );
       return ang;
    }

CSS for the line should be:

.line {
   position: absolute;
   transform-origin: top left; // to make it rotate around top-left
   border-top: solid 2px blue; // set any color
   top: 10px; // center of your "smile"
   left: 10px;
}

Here is the working example


问:
Caching with Guava
What Guava classes are suitable for thread-safe caching? I use a composed key, which gets constructed on the fly, so softKeys() makes no sense, right? I saw somewhere ConcurentLinkedHashMap, is it the way to go? Is it already in the recent release? Sorry for the chaotic way of asking...

Update

This question is pretty old and looking through he answers could possible be a waste of time. Since long there's a CacheBuilder which is the way to go.

答:
Sounds like you want MapMaker.makeComputingMap, but you mention softKeys so I assume you are already familiar with that class.

You are right about softKeys - it will not work if you compose keys on-the-fly, because softKeys causes the map to use == instead of equals for key comparison.  But you should be fine with softValues and expiration, as long as there is no side-effect from recreating an evicted entry.

Title: Caching with Guava


问:
Fragments not working?
I want to create multi fragments. When device is in portrait mode the list fragment and detail fragment should replace each other and when the device rotates the list and detail fragment should display side by side i.e., 50-50. However, I'm not getting my desired results the UI is blank/ error in setContentView(R.layout.activity_main).
Here is my code

DetFrag.java (Detail Fragment)

```<code> public class DetFrag extends Fragment {

        public DetFrag() {
            // Required empty public constructor
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_det, container, false);
        }

    }
</code>```

Listfrag.java (List Fragment)

```<code>public class Listfrag extends ListFragment {
    ArrayList<String> myList = new ArrayList<String>();
    @Override
    public void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myList.add(0, "1");
        myList.add(1, "2");
        myList.add(2, "3");
        myList.add(3, "4");
        myList.add(4, "5");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, myList);
        setListAdapter(myAdapter);
        return super.onCreateView(inflater, container, savedInstanceState);
    }
}
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fManag = getFragmentManager();
        FragmentTransaction fTrans ;

        if (findViewById(R.id.fragHolder) == null) {
            Fragment flist = fManag.findFragmentById(R.id.listFrag);
            Fragment fDet = fManag.findFragmentById(R.id.detFrag);
            fTrans = fManag.beginTransaction();
            fTrans.add(R.id.listFrag, flist);
            fTrans.add(R.id.detFrag, fDet);
            fTrans.commit();
        }
        else {
            Fragment list = fManag.findFragmentById(R.id.fragHolder);
            fTrans = fManag.beginTransaction();
            fTrans.add(R.id.fragHolder, list);
            fTrans.commit();
            Intent i = new Intent(this, Portrait.class);
            startActivity(i);

        }
       }
       }
</code>```

Portrait.java (To start new activity when in portrait)

```<code>public class Portrait extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_portrait);

        FragmentManager fManag = getFragmentManager();
        FragmentTransaction fTrans ;

        Fragment detFrag = fManag.findFragmentById(R.id.detailFragHolder);
        fTrans = fManag.beginTransaction();
        fTrans.add(R.id.detailFragHolder, detFrag);
        fTrans.commit();
    }
}
</code>```

activity_main.xml (portrait)

```<code><?xml version="1.0" encoding="utf-8"?>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragHolder"/>
</FrameLayout>
</code>```

landscape(activity_main)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/listFrag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight=".5"
        />

    <fragment
        android:id="@+id/detFrag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight=".5"/>

</LinearLayout>
</code>```

fragment_det.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="oryx.com.blueprint.DetFrag">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="44dp"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="Button" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="56dp"
        android:text="Button" />
</RelativeLayout>
</code>```

activity_portrait.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/detailFragHolder">

</FrameLayout>
</code>```

答:
Instead of this:

```<code>@Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_det, container, false);
        }
</code>```

Use this:

```<code>@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
    final View view = inflater.inflate(R.layout.detFrag, container, false);
        return view;
    }
</code>```

And instead of this:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, myList);
    setListAdapter(myAdapter);
    return super.onCreateView(inflater, container, savedInstanceState);
}
</code>```

Use this:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.listFrag, container, false);
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, myList);
setListAdapter(myAdapter);
return view;
}
</code>```

Title: Fragments not working?

Body:
I want to create multi fragments. When device is in portrait mode the list fragment and detail fragment should replace each other and when the device rotates the list and detail fragment should display side by side i.e., 50-50. However, I'm not getting my desired results the UI is blank/ error in setContentView(R.layout.activity_main).
Here is my code

DetFrag.java (Detail Fragment)

 public class DetFrag extends Fragment {

        public DetFrag() {
            // Required empty public constructor
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_det, container, false);
        }

    }

Listfrag.java (List Fragment)

public class Listfrag extends ListFragment {
    ArrayList<String> myList = new ArrayList<String>();
    @Override
    public void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myList.add(0, "1");
        myList.add(1, "2");
        myList.add(2, "3");
        myList.add(3, "4");
        myList.add(4, "5");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, myList);
        setListAdapter(myAdapter);
        return super.onCreateView(inflater, container, savedInstanceState);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fManag = getFragmentManager();
        FragmentTransaction fTrans ;

        if (findViewById(R.id.fragHolder) == null) {
            Fragment flist = fManag.findFragmentById(R.id.listFrag);
            Fragment fDet = fManag.findFragmentById(R.id.detFrag);
            fTrans = fManag.beginTransaction();
            fTrans.add(R.id.listFrag, flist);
            fTrans.add(R.id.detFrag, fDet);
            fTrans.commit();
        }
        else {
            Fragment list = fManag.findFragmentById(R.id.fragHolder);
            fTrans = fManag.beginTransaction();
            fTrans.add(R.id.fragHolder, list);
            fTrans.commit();
            Intent i = new Intent(this, Portrait.class);
            startActivity(i);

        }
       }
       }

Portrait.java (To start new activity when in portrait)

public class Portrait extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_portrait);

        FragmentManager fManag = getFragmentManager();
        FragmentTransaction fTrans ;

        Fragment detFrag = fManag.findFragmentById(R.id.detailFragHolder);
        fTrans = fManag.beginTransaction();
        fTrans.add(R.id.detailFragHolder, detFrag);
        fTrans.commit();
    }
}

activity_main.xml (portrait)

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragHolder"/>
</FrameLayout>

landscape(activity_main)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/listFrag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight=".5"
        />

    <fragment
        android:id="@+id/detFrag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight=".5"/>

</LinearLayout>

fragment_det.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="oryx.com.blueprint.DetFrag">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="44dp"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="Button" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="56dp"
        android:text="Button" />
</RelativeLayout>

activity_portrait.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/detailFragHolder">

</FrameLayout>

Body:
Instead of this:

@Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_det, container, false);
        }

Use this:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
    final View view = inflater.inflate(R.layout.detFrag, container, false);
        return view;
    }

And instead of this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, myList);
    setListAdapter(myAdapter);
    return super.onCreateView(inflater, container, savedInstanceState);
}

Use this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.listFrag, container, false);
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, myList);
setListAdapter(myAdapter);
return view;
}


问:
How to validate date field with format MMM/DD/YY or MMM/DD/YYYY?
My field contains the string values like JUL/11/2017, JAN/11/17. Though it is a valid field, i am not able to validate it using is_date function

```<code>SET DATEFORMAT MDY;
if isdate('JUL/11/2017')=1
print 'VALID_DATE'
else
print 'invalid date'
</code>```

If the field value is DD/MMM/YY or DD/MMM/YYYY , it works fine. Any one can help me validating this field.

Note:I have tried using set language option too.

答:
You know for sure that the following format are OK, right?

```<code>DD/MMM/YY
DD/MMM/YYYY
</code>```

Then, what can we do is to transform the MMM/DD/YY and the MMM/DD/YYYY formats like them, and the to check if the date is valid:

```<code>DECLARE @Date01 VARCHAR(12) = 'JAN/11/17';
DECLARE @Date02 VARCHAR(12) = 'JAN/11/2017';

DECLARE @NewDate VARCHAR(12);

DECLARE @xml XML;
SET @xml = CAST(N'<t>' + REPLACE(@Date01,'/','</t><t>') + '</t>' AS XML);

SELECT STUFF
(
    (
        SELECT '/' + c.value('.','varchar(MAX)') as item
        FROM  @xml.nodes('/t') as T(c)
        ORDER BY CASE ROW_NUMBER() OVER(ORDER BY T.c)
                 WHEN 1 THEN 2
                 WHEN 2 THEN 1
                 WHEN 3 THEN 3
                 END
        FOR XML PATH(''), TYPE
    ).value('.', 'VARCHAR(12)')
    ,1
    ,1
    ,''
);
</code>```

Body:
My field contains the string values like JUL/11/2017, JAN/11/17. Though it is a valid field, i am not able to validate it using is_date function

SET DATEFORMAT MDY;
if isdate('JUL/11/2017')=1
print 'VALID_DATE'
else
print 'invalid date'

If the field value is DD/MMM/YY or DD/MMM/YYYY , it works fine. Any one can help me validating this field.

Note:I have tried using set language option too.

Body:
You know for sure that the following format are OK, right?

DD/MMM/YY
DD/MMM/YYYY

Then, what can we do is to transform the MMM/DD/YY and the MMM/DD/YYYY formats like them, and the to check if the date is valid:

DECLARE @Date01 VARCHAR(12) = 'JAN/11/17';
DECLARE @Date02 VARCHAR(12) = 'JAN/11/2017';

DECLARE @NewDate VARCHAR(12);

DECLARE @xml XML;
SET @xml = CAST(N'<t>' + REPLACE(@Date01,'/','</t><t>') + '</t>' AS XML);

SELECT STUFF
(
    (
        SELECT '/' + c.value('.','varchar(MAX)') as item
        FROM  @xml.nodes('/t') as T(c)
        ORDER BY CASE ROW_NUMBER() OVER(ORDER BY T.c)
                 WHEN 1 THEN 2
                 WHEN 2 THEN 1
                 WHEN 3 THEN 3
                 END
        FOR XML PATH(''), TYPE
    ).value('.', 'VARCHAR(12)')
    ,1
    ,1
    ,''
);


问:
Login program from external text file
I'm having issues with a code where I have to get a user to type details about themselves, which saves to a text file. When the user tries to log in, it will check the text file for their details. Here is my code below. It works at first, where the user is granted access, but whenever I do a restart to my computer, or Python itself, it only grants the last user access. Some help would be appreciated, thank you:

This is what it looks like in the text file:

```<code>Adam16,adam123,Adam,Sunderland,16
Johnny18,johnny150,Johnny,Vane,18
</code>```

This is the source code:

```<code>import csv

import sys

def register():

    firstname = input("First name: ")
    surname = input("Surname: ")
    age = int(input("Age: "))
    password = input("Password: ")

    username = firstname[:3] + str(age)

    with open("account.txt","a",newline="") as myfile:
        writer = csv.writer(myfile)
        writer.writerow([username,password,firstname,surname,age])
        myfile.close()

    menu()

def login():

    user0 = input("Username: ")
    pass0 = input("Password: ")

    file = open("account.txt","r")

    for line in file:
        details = line.split(",")

    if user0 == details[0] and pass0 == details[1]:
        print("Correct!")
    else:
        print("Fail")

    menu()

def menu():

    selection = int(input("1 or 2: "))

    if selection == 1:
        register()
    else:
        login()

menu()
</code>```

答:
Let me start by saying that I don't like to do complete rewrites if I can avoid it, I prefer to give the answer to the problem with as much of the original code in place.

The reason your code doesn't do what you expect is this bit:

```<code>for line in file:
    details = line.split(",")
</code>```

That only gives you the last line fed in as details is essentially overwritten every time the loop reads the next line in the file. You then come out of that for loop and check against details, so it only knows about the last line.

There's a number of ways you could go about this, I would suggest that the easiest is to use a dictionary instead of a list so that you can fill it up with the contents of the users file. You can also use csv.reader to read the csv file you created straight into a list without needing to split it first:

```<code>import csv
def login():

    user_dict = {}
    with open("account.txt", "r") as csvfile:
        authfile = csv.reader(csvfile)
        for line in authfile:
            user_dict[line[0]] = line[1:]

    user0 = input("Username: ")
    if user_dict.get(user0):
        pass0 = input("Password: ")
        if user_dict.get(user0)[1] == pass0:
            print("Correct!")
            menu()
        else:
            print("Bad Password")
    else:
        print("Bad Username")
</code>```

The first section creates the user dictionary and fills it with the details you've saved to file. First entry (username) is the key and the rest of the details are stored in a list under that key.

From there, we get the username and then do a get request on the dictionary to make sure the user exists (dict.get() will return None if it fails and won't raise an exception). If the user exists, we ask for their password and check it. If the password matches it prints out the affirmative answer and loads your menu function. If not, the user is notified that they've supplied a bad password.

I hope that all made sense. Let me know if you have any questions.

edit: I may have misread this one. It looks like everything leads back to the menu function no matter what. I do believe I've engaged in a bit of overkill.

Title: Login program from external text file

Body:
I'm having issues with a code where I have to get a user to type details about themselves, which saves to a text file. When the user tries to log in, it will check the text file for their details. Here is my code below. It works at first, where the user is granted access, but whenever I do a restart to my computer, or Python itself, it only grants the last user access. Some help would be appreciated, thank you:

This is what it looks like in the text file:

Adam16,adam123,Adam,Sunderland,16
Johnny18,johnny150,Johnny,Vane,18

This is the source code:

import csv

import sys

def register():

    firstname = input("First name: ")
    surname = input("Surname: ")
    age = int(input("Age: "))
    password = input("Password: ")

    username = firstname[:3] + str(age)

    with open("account.txt","a",newline="") as myfile:
        writer = csv.writer(myfile)
        writer.writerow([username,password,firstname,surname,age])
        myfile.close()

    menu()

def login():

    user0 = input("Username: ")
    pass0 = input("Password: ")

    file = open("account.txt","r")

    for line in file:
        details = line.split(",")

    if user0 == details[0] and pass0 == details[1]:
        print("Correct!")
    else:
        print("Fail")

    menu()

def menu():

    selection = int(input("1 or 2: "))

    if selection == 1:
        register()
    else:
        login()

menu()

Body:
Let me start by saying that I don't like to do complete rewrites if I can avoid it, I prefer to give the answer to the problem with as much of the original code in place.

The reason your code doesn't do what you expect is this bit:

for line in file:
    details = line.split(",")

That only gives you the last line fed in as details is essentially overwritten every time the loop reads the next line in the file. You then come out of that for loop and check against details, so it only knows about the last line.

There's a number of ways you could go about this, I would suggest that the easiest is to use a dictionary instead of a list so that you can fill it up with the contents of the users file. You can also use csv.reader to read the csv file you created straight into a list without needing to split it first:

import csv
def login():

    user_dict = {}
    with open("account.txt", "r") as csvfile:
        authfile = csv.reader(csvfile)
        for line in authfile:
            user_dict[line[0]] = line[1:]

    user0 = input("Username: ")
    if user_dict.get(user0):
        pass0 = input("Password: ")
        if user_dict.get(user0)[1] == pass0:
            print("Correct!")
            menu()
        else:
            print("Bad Password")
    else:
        print("Bad Username")

The first section creates the user dictionary and fills it with the details you've saved to file. First entry (username) is the key and the rest of the details are stored in a list under that key.

From there, we get the username and then do a get request on the dictionary to make sure the user exists (dict.get() will return None if it fails and won't raise an exception). If the user exists, we ask for their password and check it. If the password matches it prints out the affirmative answer and loads your menu function. If not, the user is notified that they've supplied a bad password.

I hope that all made sense. Let me know if you have any questions.

edit: I may have misread this one. It looks like everything leads back to the menu function no matter what. I do believe I've engaged in a bit of overkill.


问:
React Router v4 - How to prevent redirect loops?
What I'm trying to accomplish is to have my App component redirect to the "/login" route if the state's uid is null. The redirect works correctly and will always redirect you to "/login" if there is a null uid, however the problem is it doesn't stop redirecting once you're on the "/login" route.

The error being thrown is:

Warning: You tried to redirect to the same route you're currently on: "/login"

One last constraint is I need the uid to be null until after a login event fires from the LoginScreen component. So the user needs to be able to view the "/login" route with a null uid in the top-level App component.

My code is as follows:

```<code>class App extends Component {
  constructor() {
    super();
    this.state = {
      uid: null
    }
  }
  render() {
    // Redirect to login if no user
    if (this.state.uid == null) {
      return (
        <Router>
          <Redirect to="/login" />
        </Router>
      );
    }

    return (
      <Router>
        <div>
          <Route path="/login" component={LoginScreen} />
          <Route path="/dashboard" component={DashboardScreen} />
          <Route path="/profile" component={ProfileScreen} />
        </div>
      </Router>
    );
  }
}
</code>```

I hope I explained the situation well. Thanks in advance!

答:
Well as you mention that you have store the uid in the App component state and you are redirecting to the Login component if the uid is not present. However there is a technical fault here.

The state of the component is initilised everytime the component is mounted again and when you redirect from the Login component to the App component, your state in App component is again initialized to null which is why you are redirected again to Login.

What you need to do is to

Either store the uid in localStorage and read it from there in the App component

Or  if you are using Redux, then store the uid in global store and fetch it in the App component.

Body:
What I'm trying to accomplish is to have my App component redirect to the "/login" route if the state's uid is null. The redirect works correctly and will always redirect you to "/login" if there is a null uid, however the problem is it doesn't stop redirecting once you're on the "/login" route.

The error being thrown is:

Warning: You tried to redirect to the same route you're currently on: "/login"

One last constraint is I need the uid to be null until after a login event fires from the LoginScreen component. So the user needs to be able to view the "/login" route with a null uid in the top-level App component.

My code is as follows:

class App extends Component {
  constructor() {
    super();
    this.state = {
      uid: null
    }
  }
  render() {
    // Redirect to login if no user
    if (this.state.uid == null) {
      return (
        <Router>
          <Redirect to="/login" />
        </Router>
      );
    }

    return (
      <Router>

          <Route path="/login" component={LoginScreen} />
          <Route path="/dashboard" component={DashboardScreen} />
          <Route path="/profile" component={ProfileScreen} />

      </Router>
    );
  }
}

I hope I explained the situation well. Thanks in advance!