问:
Using reference of Windows.Input for using ICommand in the VM
I am working on a UWP application which is based on the MVVM Pattern. for binding the UI actions I am using ICommand in the VM for which I need to provide a reference to Windows.Input .Is It breaking the MVVM.

If I create a class which implements the ICommand interface and use it for command binding then it breaks the rule of "Coding to Interfaces".

```<code>//This is what i am doing currently

public ICommand command;
command = new RelayCommand();

// I have tried this to remove the reference of windows.input from the VM

public RelayCommand command;
command = new RelayCommand();

//isn't it breaking the rule of coding to interfaces
</code>```

Which approach should I follow

答:
I prefer to use x:Bind over RelayCommands for simplicity as long as you've set your view model in the view.cs file you can just bind a handler for the event

SessionView.xaml.cs:

```<code>Tapped="{x:Bind Path=ViewModel.CancelClick}"
</code>```

SessionView.cs

```<code>    public SessionViewModel ViewModel { get; set; }
    public SessionView() => this.InitializeComponent();

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        var prms = (WindowParameters)e.Parameter;
        prms.Frame = this.Frame;
        this.ViewModel = new SessionViewModel(prms);
        this.DataContext = ViewModel;
        this.ViewModel.LoadFullModel();
    }
</code>```

Body:
I am working on a UWP application which is based on the MVVM Pattern. for binding the UI actions I am using ICommand in the VM for which I need to provide a reference to Windows.Input .Is It breaking the MVVM.

If I create a class which implements the ICommand interface and use it for command binding then it breaks the rule of "Coding to Interfaces".

//This is what i am doing currently

public ICommand command;
command = new RelayCommand();

// I have tried this to remove the reference of windows.input from the VM

public RelayCommand command;
command = new RelayCommand();

//isn't it breaking the rule of coding to interfaces

Which approach should I follow

Body:
I prefer to use x:Bind over RelayCommands for simplicity as long as you've set your view model in the view.cs file you can just bind a handler for the event

SessionView.xaml.cs:

Tapped="{x:Bind Path=ViewModel.CancelClick}"

SessionView.cs

    public SessionViewModel ViewModel { get; set; }
    public SessionView() => this.InitializeComponent();

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        var prms = (WindowParameters)e.Parameter;
        prms.Frame = this.Frame;
        this.ViewModel = new SessionViewModel(prms);
        this.DataContext = ViewModel;
        this.ViewModel.LoadFullModel();
    }


来源: stackexchange

问:
How to set count of c# without altering capacity?
I know exactly how many items I want to keep in a list, they are ordered, I only need it to finish at an specific index I know, but I don't want to alter the capacity or use TrimExcess in order to make it smaller, otherwise after adding an item again it will double the size of the list again.

How can I set the Count instead of using Remove or RemoveAt or RemoveRange?.

My priority is optimization of speed for this operation.

Important: I know I can use an array, but I am not allowed. Also, I'm adding items and removing them all the time. I just want the capacity to stay around a similar amount which I don't know exactly but it will stabilize.

答:
If you remove elements, the Capacity won't change. So if you don't use TrimExcess(), the Capacity will only ever increase (to the maximum you ever used for this list). So there's no performance penalty in removing elements again. You can set the initial capacity in the constructor, which is a good idea if you know how many elements you'll be using (or have an estimate for it), because that will remove the overload of the doubling while initially building up the list.

Note: Insert/Remove in a list is still O(n), because the elements eventually need to be compied around (unless you operate only at the tail end of the list).

ContentLicense: CC BY-SA 4.0


问:
Sorting a list of tuples according to another list's string values
I'm trying to sort a list of financial data according to another list based on financial tickers.

The two lists I have are lists of tuples that contain information about corporations' financial data. prc_list is a list of tuples with elements of the form (company_ticker, price_dataframe) and fin_list is a list of tuples with elements of the form (company_ticker, financial_dataframe, value). Here, "price" simply refers to opening/closing prices and "financial" refers to information you'd typically see when performing fundamental analysis (e.g. ROE, ROA, etc.)

What I'm doing is first I take fin_list and sort it in descending order according to a specific quarter and key. For example, if I want to sort all of the companies according to their ROE in 2013-Q3, then the first company would show the relevant information for the company that has the highest ROE value for the third quarter of 2013.

After doing this operation, I want to sort prc_list so that the order of tickers matches that of fin_list.

My attempts are as follows:

```<code>prc_list = sorted(prc_list, key=(lambda x: fin_list[x][0]))
# Error -> "List indices must be integers or slices, not tuples."

tic_list = [fin_list[i][0] for i in range(len(fin_list))]
prc_list = sorted(prc_list, key=tic_list)
# Same error.
</code>```

How might one go about solving this?

答:
What about this ?</p>

```<code>fin_list = [("ticker 1" , "price 1", 10),
            ("ticker 2" , "price 2", 0),
            ("ticker 3" , "price 3", 20),
            ("ticker 4" , "price 4", 14)]

# sort this list
fin_list_sorted = sorted(fin_list, key=lambda x: x[2])
print(fin_list_sorted)

# if you want to sort it in decreasing order
fin_list_sorted = sorted(fin_list, key=lambda x: -x[2])
print(fin_list_sorted)

# if you only want the attributes company_ticker and price_dataframe
prc_list = list(map(lambda x: x[0:2], fin_list_sorted))
print(prc_list)
</code>```

Body:
I'm trying to sort a list of financial data according to another list based on financial tickers.

The two lists I have are lists of tuples that contain information about corporations' financial data. prc_list is a list of tuples with elements of the form (company_ticker, price_dataframe) and fin_list is a list of tuples with elements of the form (company_ticker, financial_dataframe, value). Here, "price" simply refers to opening/closing prices and "financial" refers to information you'd typically see when performing fundamental analysis (e.g. ROE, ROA, etc.)

What I'm doing is first I take fin_list and sort it in descending order according to a specific quarter and key. For example, if I want to sort all of the companies according to their ROE in 2013-Q3, then the first company would show the relevant information for the company that has the highest ROE value for the third quarter of 2013.

After doing this operation, I want to sort prc_list so that the order of tickers matches that of fin_list.

My attempts are as follows:

prc_list = sorted(prc_list, key=(lambda x: fin_list[x][0]))
# Error -> "List indices must be integers or slices, not tuples."

tic_list = [fin_list[i][0] for i in range(len(fin_list))]
prc_list = sorted(prc_list, key=tic_list)
# Same error.

How might one go about solving this?

Body:
What about this ?

fin_list = [("ticker 1" , "price 1", 10),
            ("ticker 2" , "price 2", 0),
            ("ticker 3" , "price 3", 20),
            ("ticker 4" , "price 4", 14)]

# sort this list
fin_list_sorted = sorted(fin_list, key=lambda x: x[2])
print(fin_list_sorted)

# if you want to sort it in decreasing order
fin_list_sorted = sorted(fin_list, key=lambda x: -x[2])
print(fin_list_sorted)

# if you only want the attributes company_ticker and price_dataframe
prc_list = list(map(lambda x: x[0:2], fin_list_sorted))
print(prc_list)


问:
Facebook Graph API not returning all events
I'm using the Facebook Graph API, via the PHP SDK, to fetch a list of events attached to a Facebook page. The page has 15 events, all public; if I query them from the links in the developer documentation (i.e. with the sample access key it gives you there) I can see all fifteen of them.

That sample URL, the one that works fine, is:

```<code>https://graph.facebook.com/[the name of the page]/events?access_token=[the access token]
</code>```

If, though, I do the same request via the PHP SDK — that is, from calling:

```<code>$facebook = new Facebook(array(
    'appId' => $fb_app_id,
    'secret' => $fb_secret,
    'cookie' => true
));

$result = $facebook->api('[the name of the page]/events');
</code>```

…then it returns only nine events, not the full fifteen. I've tried seemingly every combination of parameters: I've tried limiting it to 10, 15, 100, 500; I've tried setting various offsets; I've set either or both since and until. I've tried to think of all the gotchas: the events are definitely public, and show up if I visit the page's "Events" tab while logged out of Facebook. Whatever I do, I just get those same nine events, mocking me with their incompleteness.

Does anyone have any ideas? The events that aren't showing are the most recently added ones, if that makes any difference, though they were added to Facebook days — rather than hours or minutes — ago. I can't think why that would make a difference, though, and I've had events show up within minutes of being added before.

Thanks in advance guys!

答:
Maybe this links helps, got the same problem reported to bugtracker of facebook...

http://bugs.developers.facebook.net/show_bug.cgi?id=16617

You have to set the flag "Show guestlist", if this is not
checked the event is not available via graph api.

ContentLicense: CC BY-SA 2.5

Body:
I'm using the Facebook Graph API, via the PHP SDK, to fetch a list of events attached to a Facebook page. The page has 15 events, all public; if I query them from the links in the developer documentation (i.e. with the sample access key it gives you there) I can see all fifteen of them.

That sample URL, the one that works fine, is:

https://graph.facebook.com/[the name of the page]/events?access_token=[the access token]

If, though, I do the same request via the PHP SDK — that is, from calling:

$facebook = new Facebook(array(
    'appId' => $fb_app_id,
    'secret' => $fb_secret,
    'cookie' => true
));

$result = $facebook->api('[the name of the page]/events');

…then it returns only nine events, not the full fifteen. I've tried seemingly every combination of parameters: I've tried limiting it to 10, 15, 100, 500; I've tried setting various offsets; I've set either or both since and until. I've tried to think of all the gotchas: the events are definitely public, and show up if I visit the page's "Events" tab while logged out of Facebook. Whatever I do, I just get those same nine events, mocking me with their incompleteness.

Does anyone have any ideas? The events that aren't showing are the most recently added ones, if that makes any difference, though they were added to Facebook days — rather than hours or minutes — ago. I can't think why that would make a difference, though, and I've had events show up within minutes of being added before.

Thanks in advance guys!

ContentLicense: CC BY-SA 3.0


问:
classify a large collection of image files
I have a large collection of image files for a book, andthe publisher wants a list where files are classified by "type" (greyscale graph, b/w halftone image, color image, line drawing, etc.).  This is a hard problem in general, but perhaps I can do some of this automatically using image processing tools, e.g., ImageMagick with the R magick package.

I think ImageMagick is the right tool, but I don't really know how to use it for this purpose.

What I have is just a list of fig numbers & file names:

```<code>1.1 ch01-intro/fig/alcohol-risk.jpg
1.2 ch01-intro/fig/measels.png
1.3 ch01-intro/fig/numbers.png
1.4 ch01-intro/fig/Lascaux-bull-chamber.jpg
...
</code>```

Can someone help get me started?

Edit: This was probably an ill-framed or overly-arching question as initially stated. I thought that ImageMagick identify or the R magick::image_info() function could help, so the initial question perhaps should have been: "How to extract image information from a list of files [in R]". I can pose this separately, if not already asked.

An initial attempt at this gave me the following for my first images,

```<code>library(magick)

# initialize an empty array to hold the results of `image_info`
figinfo <- data.frame(
  format=character(),
  width=numeric(),
  height=numeric(),
  colorspace=character(),
  matte=logical(),
  filesize=numeric(),
  density=character(), stringsAsFactors = FALSE
)

for (i in seq_along(files)) {
  img <- image_read(files[i])
  info <- image_info(img)
  figinfo[i,] <- info
}
</code>```

I get:

```<code>> figinfo
  format width height colorspace matte filesize density
1   JPEG   661    733       sRGB FALSE    41884   72x72
2    PNG   838    591       sRGB  TRUE    98276   38x38
3    PNG   990    721       sRGB  TRUE   427253   38x38
4   JPEG   798    219       sRGB FALSE    99845 300x300
</code>```

I conclude that this doesn't help much in answering the question I posed, of how to classify these images.

Edit2 Before closing this question, the advice to look into direct use of ImageMagick identify was helpful. https://imagemagick.org/script/escape.php
In particular, the %[type] is closer to
what I need. This is not exposed in magick::image_info(), so I may have to write a shell script or call system() in a loop.

For the record, here is how I can extract relevant attributes of these image files using identify directly.

```<code># Get image characteristics via ImageMagick identify
# from: https://imagemagick.org/script/escape.php
#
# -format elements:
# %m image file format
# %f filename
# %[type] image type
# %k number of unique colors
# %h image height in pixels
# %r image class and colorspace

identify -format "%m,%f,%[type],%r,%k,%hx%w" imagefile

>identify -format "%m,%f,%[type],%r,%k,%hx%w" Quipu.png
PNG,Quipu.png,GrayscaleAlpha,DirectClass Gray Matte,16,449x299
</code>```

The %[type] attribute takes me towards what I want.

答:
To close this question:

In an R context, I was successful in using system(, intern=TRUE) for this task, as follows, with some manual fixups

```<code># Use identify directly via system()

# function to run identify for one file
get_info <- function(file) {
  cmd <- 'identify -quiet -format "%f,%m,%[type],%r,%h,%w,%x,%y"'
  info <- system(paste(cmd, file), intern=TRUE)
  unlist(strsplit(info, ","))
}

# This doesn't cause coercion to numeric
figinfo <- data.frame(
  filename=character(),
  format=character(),
  type=character(),
  class=character(),
  height=numeric(),
  width=numeric(),
  xres=numeric(),
  yres=numeric(),
  stringsAsFactors = FALSE
)

for (i in seq_along(files)) {
  info <- get_info(files[i])
  info[4] <- sub("DirectClass ", "", info[4])
 figinfo[i,] <- info
}

figinfo$height <- as.numeric(figinfo$height)
figinfo$width <- as.numeric(figinfo$width)
figinfo$xres=round(as.numeric(figinfo$xres))
figinfo$yres=round(as.numeric(figinfo$yres))
</code>```

Then I have more or less what I want:

```<code>> str(figinfo)
'data.frame':   161 obs. of  8 variables:
 $ filename: chr  "mileyears4.png" "alcohol-risk.jpg" "measels.png" "numbers.png" ...
 $ format  : chr  "PNG" "JPEG" "PNG" "PNG" ...
 $ type    : chr  "Palette" "TrueColor" "TrueColorAlpha" "TrueColorAlpha" ...
 $ class   : chr  "PseudoClass sRGB " "sRGB " "sRGB Matte" "sRGB Matte" ...
 $ height  : num  500 733 591 721 219 ...
 $ width   : num  720 661 838 990 798 ...
 $ xres    : num  72 72 38 38 300 38 300 38 28 38 ...
 $ yres    : num  72 72 38 38 300 38 300 38 28 38 ...
>
</code>```

Body:
I have a large collection of image files for a book, andthe publisher wants a list where files are classified by "type" (greyscale graph, b/w halftone image, color image, line drawing, etc.).  This is a hard problem in general, but perhaps I can do some of this automatically using image processing tools, e.g., ImageMagick with the R magick package.

I think ImageMagick is the right tool, but I don't really know how to use it for this purpose.

What I have is just a list of fig numbers & file names:

1.1 ch01-intro/fig/alcohol-risk.jpg
1.2 ch01-intro/fig/measels.png
1.3 ch01-intro/fig/numbers.png
1.4 ch01-intro/fig/Lascaux-bull-chamber.jpg
...

Can someone help get me started?

Edit: This was probably an ill-framed or overly-arching question as initially stated. I thought that ImageMagick identify or the R magick::image_info() function could help, so the initial question perhaps should have been: "How to extract image information from a list of files [in R]". I can pose this separately, if not already asked.

An initial attempt at this gave me the following for my first images,

library(magick)

# initialize an empty array to hold the results of `image_info`
figinfo <- data.frame(
  format=character(),
  width=numeric(),
  height=numeric(),
  colorspace=character(),
  matte=logical(),
  filesize=numeric(),
  density=character(), stringsAsFactors = FALSE
)

for (i in seq_along(files)) {
  img <- image_read(files[i])
  info <- image_info(img)
  figinfo[i,] <- info
}

I get:

> figinfo
  format width height colorspace matte filesize density
1   JPEG   661    733       sRGB FALSE    41884   72x72
2    PNG   838    591       sRGB  TRUE    98276   38x38
3    PNG   990    721       sRGB  TRUE   427253   38x38
4   JPEG   798    219       sRGB FALSE    99845 300x300

I conclude that this doesn't help much in answering the question I posed, of how to classify these images.

Edit2 Before closing this question, the advice to look into direct use of ImageMagick identify was helpful. https://imagemagick.org/script/escape.php
In particular, the %[type] is closer to
what I need. This is not exposed in magick::image_info(), so I may have to write a shell script or call system() in a loop.

For the record, here is how I can extract relevant attributes of these image files using identify directly.

# Get image characteristics via ImageMagick identify
# from: https://imagemagick.org/script/escape.php
#
# -format elements:
# %m image file format
# %f filename
# %[type] image type
# %k number of unique colors
# %h image height in pixels
# %r image class and colorspace

identify -format "%m,%f,%[type],%r,%k,%hx%w" imagefile

>identify -format "%m,%f,%[type],%r,%k,%hx%w" Quipu.png
PNG,Quipu.png,GrayscaleAlpha,DirectClass Gray Matte,16,449x299

The %[type] attribute takes me towards what I want.

Body:
To close this question:

In an R context, I was successful in using system(, intern=TRUE) for this task, as follows, with some manual fixups

# Use identify directly via system()

# function to run identify for one file
get_info <- function(file) {
  cmd <- 'identify -quiet -format "%f,%m,%[type],%r,%h,%w,%x,%y"'
  info <- system(paste(cmd, file), intern=TRUE)
  unlist(strsplit(info, ","))
}

# This doesn't cause coercion to numeric
figinfo <- data.frame(
  filename=character(),
  format=character(),
  type=character(),
  class=character(),
  height=numeric(),
  width=numeric(),
  xres=numeric(),
  yres=numeric(),
  stringsAsFactors = FALSE
)

for (i in seq_along(files)) {
  info <- get_info(files[i])
  info[4] <- sub("DirectClass ", "", info[4])
 figinfo[i,] <- info
}

figinfo$height <- as.numeric(figinfo$height)
figinfo$width <- as.numeric(figinfo$width)
figinfo$xres=round(as.numeric(figinfo$xres))
figinfo$yres=round(as.numeric(figinfo$yres))

Then I have more or less what I want:

> str(figinfo)
'data.frame':   161 obs. of  8 variables:
 $ filename: chr  "mileyears4.png" "alcohol-risk.jpg" "measels.png" "numbers.png" ...
 $ format  : chr  "PNG" "JPEG" "PNG" "PNG" ...
 $ type    : chr  "Palette" "TrueColor" "TrueColorAlpha" "TrueColorAlpha" ...
 $ class   : chr  "PseudoClass sRGB " "sRGB " "sRGB Matte" "sRGB Matte" ...
 $ height  : num  500 733 591 721 219 ...
 $ width   : num  720 661 838 990 798 ...
 $ xres    : num  72 72 38 38 300 38 300 38 28 38 ...
 $ yres    : num  72 72 38 38 300 38 300 38 28 38 ...
>


问:
Unity how to use native dll or convert to managed
I am trying to use a native c++ UWP component in a unity project for hololens.

I have successfully used a managed dll, but I can;t figure out how to use this native dll/

I want to either convert the dll to a managed dll or find some way to use a native dll.

答:
Memory management works completely different in C++ so it is not possible to use a C++ library direclty in C#.

C++ uses name mangling for encoding method signatures and this name mangling is not standardized (meaning it depends on the compiler).
To solve this you require to export them in an extern "C" section using a static "std call".

This means you need to create a wrapper with static methods for each instance method used in C#.

From Unity Manual (note that importing dll is different for ios, as shown in the code below)

    using UnityEngine;
    using System.Runtime.InteropServices;

    class SomeScript : MonoBehaviour {

       #if UNITY_IPHONE

       // On iOS plugins are statically linked into
       // the executable, so we have to use __Internal as the
       // library name.
       [DllImport ("__Internal")]

       #else

       // Other platforms load plugins dynamically, so pass the name
       // of the plugin's dynamic library.
       [DllImport ("PluginName")]

       #endif

       private static extern float FooPluginFunction ();

       void Awake () {
          // Calls the FooPluginFunction inside the plugin
          // And prints 5 to the console
          print (FooPluginFunction ());
       }
    }
```

You might also read this Unity Answer, for further info.

Body:
Memory management works completely different in C++ so it is not possible to use a C++ library direclty in C#.

C++ uses name mangling for encoding method signatures and this name mangling is not standardized (meaning it depends on the compiler).
To solve this you require to export them in an extern "C" section using a static "std call".

This means you need to create a wrapper with static methods for each instance method used in C#.

From Unity Manual (note that importing dll is different for ios, as shown in the code below)

    using UnityEngine;
    using System.Runtime.InteropServices;

    class SomeScript : MonoBehaviour {

       #if UNITY_IPHONE

       // On iOS plugins are statically linked into
       // the executable, so we have to use __Internal as the
       // library name.
       [DllImport ("__Internal")]

       #else

       // Other platforms load plugins dynamically, so pass the name
       // of the plugin's dynamic library.
       [DllImport ("PluginName")]

       #endif

       private static extern float FooPluginFunction ();

       void Awake () {
          // Calls the FooPluginFunction inside the plugin
          // And prints 5 to the console
          print (FooPluginFunction ());
       }
    }

You might also read this Unity Answer, for further info.


问:
Wordpress - Prevent redirection to main URL
I tried to copy the files of a WordPress website on another domain of mine.
But it keeps redirecting to the old domain name.. I'm not a WordPress expert and it's also not my website - that's why I don't have a GUI and only the files.

How and where can I disable the redirection to the main domain in the files? I can't seem to find it.

Thanks for the efforts.

For example:

WordPress website "test.com" copy paste --> "testtest.com"

"testtest.com" redirects to --> "test.com" when entered in URL

答:
When you transfer a Wordpress install to a new domain, there are 2 values you need to update in your database. One is the homeurl and the other is the siteurl. Typically these changes would be made directly in the database, either by modifying the sql file before importing it on the new server or by accessing the database using PHPMyAdmin or some other form of database management software. However, in the event that you don't have access to the database or do not want to make the change in the database, you can also override the settings in your wp-config.php file using the following options:

```<code>define('WP_HOME','https://yourdomain.com');
define('WP_SITEURL','https://yourdomain.com');
</code>```

Body:
When you transfer a Wordpress install to a new domain, there are 2 values you need to update in your database. One is the homeurl and the other is the siteurl. Typically these changes would be made directly in the database, either by modifying the sql file before importing it on the new server or by accessing the database using PHPMyAdmin or some other form of database management software. However, in the event that you don't have access to the database or do not want to make the change in the database, you can also override the settings in your wp-config.php file using the following options:

define('WP_HOME','https://yourdomain.com');
define('WP_SITEURL','https://yourdomain.com');


问:
React appevent termination
I'm trying to find a way to execute a function upon termination of the app, what function can I use to do this in react native?

Basically, whenever the user closes the app (completely terminate).

答:
You can use the AppState API provided by react-native in your root component where you register/mount your app.

There you can add an onChange eventlistener to AppState which executes your custom function whenever AppState.currentState.match(/inactive|background/) returns true. Your custom function however should be isolated from your other component states.

Title: React appevent termination


问:
dplyr - using mutate() like rowmeans()
I can't find the answer anywhere.

I would like to calculate new variable of data frame which is based on mean of rows.

For example:

```<code>data <- data.frame(id=c(101,102,103), a=c(1,2,3), b=c(2,2,2), c=c(3,3,3))
</code>```

I want to use mutate to make variable d which is mean of a,b and c. And I would like to be able to make that by selecting columns in way d=mean(a,b,c), and also I need to use range of variables (like in dplyr) d=mean(a:c).

And of course

```<code>mutate(data, c=mean(a,b))
</code>```

or

```<code>mutate(data, c=rowMeans(a,b))
</code>```

doesn't work.

Can you give me some tip?

Regards

答:
I think the answer suggesting using data.frame or slicing on . is the best, but could be made simpler and more dplyr-ish like so:

```<code>data %>% mutate(c = rowMeans(select(., a,b)))
</code>```

Or if you want to avoid ., with the penalty of having two inputs to your pipeline:

```<code>data %>% mutate(c = rowMeans(select(data, a,b)))
</code>```

Title: dplyr - using mutate() like rowmeans()

Body:
I can't find the answer anywhere.

I would like to calculate new variable of data frame which is based on mean of rows.

For example:

data <- data.frame(id=c(101,102,103), a=c(1,2,3), b=c(2,2,2), c=c(3,3,3))

I want to use mutate to make variable d which is mean of a,b and c. And I would like to be able to make that by selecting columns in way d=mean(a,b,c), and also I need to use range of variables (like in dplyr) d=mean(a:c).

And of course

mutate(data, c=mean(a,b))

or

mutate(data, c=rowMeans(a,b))

doesn't work.

Can you give me some tip?

Regards

Body:
I think the answer suggesting using data.frame or slicing on . is the best, but could be made simpler and more dplyr-ish like so:

data %>% mutate(c = rowMeans(select(., a,b)))

Or if you want to avoid ., with the penalty of having two inputs to your pipeline:

data %>% mutate(c = rowMeans(select(data, a,b)))


问:
How to trap an error from a shelled process in c#
ive been using this site for a while and have my first question to ask - as the help here is awesome.

Im writing a c# dll (for use in VbScript) and in that DLDL im shelling out a command and wish to trap the return code of that command. So far I have the following c# code:-

```<code>      public int InstallHotfix(String strAppName,string strExe,string strParam)
            {
            ProcessStartInfo startInfo = new ProcessStartInfo(strExe,strParam);
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            Process.Start(startInfo);
            }
</code>```

I am calling this from a VB script but would like to know how to return the result back to VBS. I assume there a 'return' value that I have to enter but im unsure how to achieve this.

Cheers.

答:
```<code>        ProcessStartInfo startInfo = new ProcessStartInfo(strExe, strParam);
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        Process proc = Process.Start(startInfo);
        proc.WaitForExit();
        int exitCode = proc.ExitCode;
</code>```

Body:
ive been using this site for a while and have my first question to ask - as the help here is awesome.

Im writing a c# dll (for use in VbScript) and in that DLDL im shelling out a command and wish to trap the return code of that command. So far I have the following c# code:-

      public int InstallHotfix(String strAppName,string strExe,string strParam)
            {
            ProcessStartInfo startInfo = new ProcessStartInfo(strExe,strParam);
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            Process.Start(startInfo);
            }

I am calling this from a VB script but would like to know how to return the result back to VBS. I assume there a 'return' value that I have to enter but im unsure how to achieve this.

Cheers.


问:
Build fail for Asp.Net Core 3 (Blazor client side)
I've start to develop a web application with ASP.NET Core 3 and Blazor framework.
During few days/weeks, I could build my application.
Since preview 5 announced, I couldn't build my application (with dotnet build command).
I've the next error:

C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor.build\3.0.0-preview5-19227-01\targets\Blazor.MonoRuntime.targets(439,5): error MSB3073: The command "dotnet "" -l
-o "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\linker/"
-x "C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor.build\3.0.0-preview5-19227-01\targets\BuiltInBclLinkerDescriptor.xml"
-x "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\linker.descriptor.xml"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Blazor.dll"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.components\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Components.dll"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.components.browser\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Components.Browser.dll"
-a "C:\Users\a\.nuget\packages\microsoft.extensions.dependencyinjection\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.dll"
-a "C:\Users\a\.nuget\packages\microsoft.extensions.dependencyinjection.abstractions\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll"
-a "C:\Users\a\.nuget\packages\microsoft.jsinterop\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.JSInterop.dll"
-a "C:\Users\a\.nuget\packages\mono.webassembly.interop\3.0.0-preview5.19227.9\lib\netstandard2.0\Mono.WebAssembly.Interop.dll"
-a "C:\Users\a\.nuget\packages\system.componentmodel.annotations\4.6.0-preview5.19224.8\lib\netstandard2.0\System.ComponentModel.Annotations.dll"
-a "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\IdeaStudio.Website.Client.dll"" exited with code 1.
[D:\Repos\IdeaStudio.Website.Client\IdeaStudio.Website.Client.csproj]
```

<p>My <code>csproj</code> looks like :</p>

<pre class="lang-xml prettyprint-override"><code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <RestoreAdditionalProjectSources>
      https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json;
      https://dotnet.myget.org/F/blazor-dev/api/v3/index.json;
    </RestoreAdditionalProjectSources>
    <LangVersion>7.3</LangVersion>
    <RazorLangVersion>3.0</RazorLangVersion>
    <TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netstandard2.0</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.5.1" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.0.0-preview5-19227-01" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.0.0-preview5-19227-01" PrivateAssets="all" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.DevServer" Version="3.0.0-preview5-19227-01" PrivateAssets="all" />
  </ItemGroup>
</Project>
</code>```

I did not understand for several days until...

答:
Maybe when I did the Visual Studio / .NET Core 3 preview 5

dotnet cli can't build an application with a csproj which contains <TargetFramework> and <TargetFrameworks> properties...

Body:
I've start to develop a web application with ASP.NET Core 3 and Blazor framework.
During few days/weeks, I could build my application.
Since preview 5 announced, I couldn't build my application (with dotnet build command).
I've the next error:

C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor.build\3.0.0-preview5-19227-01\targets\Blazor.MonoRuntime.targets(439,5): error MSB3073: The command "dotnet "" -l
-o "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\linker/"
-x "C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor.build\3.0.0-preview5-19227-01\targets\BuiltInBclLinkerDescriptor.xml"
-x "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\linker.descriptor.xml"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.blazor\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Blazor.dll"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.components\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Components.dll"
-a "C:\Users\a\.nuget\packages\microsoft.aspnetcore.components.browser\3.0.0-preview5-19227-01\lib\netstandard2.0\Microsoft.AspNetCore.Components.Browser.dll"
-a "C:\Users\a\.nuget\packages\microsoft.extensions.dependencyinjection\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.dll"
-a "C:\Users\a\.nuget\packages\microsoft.extensions.dependencyinjection.abstractions\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll"
-a "C:\Users\a\.nuget\packages\microsoft.jsinterop\3.0.0-preview5.19227.9\lib\netstandard2.0\Microsoft.JSInterop.dll"
-a "C:\Users\a\.nuget\packages\mono.webassembly.interop\3.0.0-preview5.19227.9\lib\netstandard2.0\Mono.WebAssembly.Interop.dll"
-a "C:\Users\a\.nuget\packages\system.componentmodel.annotations\4.6.0-preview5.19224.8\lib\netstandard2.0\System.ComponentModel.Annotations.dll"
-a "D:\Repos\IdeaStudio.Website.Client\obj\Debug\netstandard2.0\IdeaStudio.Website.Client.dll"" exited with code 1.
[D:\Repos\IdeaStudio.Website.Client\IdeaStudio.Website.Client.csproj]

My csproj looks like :

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <RestoreAdditionalProjectSources>
      https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json;
      https://dotnet.myget.org/F/blazor-dev/api/v3/index.json;
    </RestoreAdditionalProjectSources>
    <LangVersion>7.3</LangVersion>
    <RazorLangVersion>3.0</RazorLangVersion>
    <TargetLatestRuntimePatch>true</TargetLatestRuntimePatch>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netstandard2.0</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.5.1" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.0.0-preview5-19227-01" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.0.0-preview5-19227-01" PrivateAssets="all" />
    <PackageReference Include="Microsoft.AspNetCore.Blazor.DevServer" Version="3.0.0-preview5-19227-01" PrivateAssets="all" />
  </ItemGroup>
</Project>

I did not understand for several days until...


问:
How do I persist the store using persistStore()? I am facing an error 'store does not have a valid reducer'
I believe I am correctly passing 'reducer' inside persistCombineReducers() along with 'config' to create a store that is persistent. But I face an error saying - 'store does not have a valid reducer'

```<code>import { createStore } from 'redux'
import { persistStore, persistCombineReducers } from 'redux-persist'
import storage from 'redux-persist/es/storage'

...

const reducer = (state=initialState, action) => {
  switch(action.type){
    ...
  }
}

...

export const store =
  createStore(persistCombineReducers(config, reducer), initialState)

export const persistor = persistStore(store)

...
</code>```

I expect the store to be persistent. Rather it throws an error - "store does not have a valid reducer"

答:
Use persistReducer instead of persistCombineReducers.

PersistReducer is used when you have only 1 reducer, and ask a function as parameter, while persistCombineReducers ask an object as parameter (an object containing a list of reducers)

Body:
I believe I am correctly passing 'reducer' inside persistCombineReducers() along with 'config' to create a store that is persistent. But I face an error saying - 'store does not have a valid reducer'

import { createStore } from 'redux'
import { persistStore, persistCombineReducers } from 'redux-persist'
import storage from 'redux-persist/es/storage'

...

const reducer = (state=initialState, action) => {
  switch(action.type){
    ...
  }
}

...

export const store =
  createStore(persistCombineReducers(config, reducer), initialState)

export const persistor = persistStore(store)

...

I expect the store to be persistent. Rather it throws an error - "store does not have a valid reducer"


问:
Laravel and multiple queues (AWS SQS)
I'm stuck on dispatching jobs into multiple SQS queues using onQueue('queuename').

The queue names on SQS have prefixes to distinct projects.
It seems that hardcoding each queue name of SQS is not the best way do that. I think that there should be something like an aliases map in queue.php config file.

Is there a known practice to deal with that properly?

答:
In my experience it came VERY useful define the queue name as a combination of Environment Name and Project Queue Name

Using CloudFormation I create the queue like

```<code>QueueName:
  Type: AWS::SQS::Queue
  Properties:
    VisibilityTimeout: 120
    QueueName: !Join ['', [!Ref 'AWS::StackName', 'ProjectQueueName']]
    Tags:
      - Key: Stack
        Value: !Ref 'AWS::StackName'
</code>```

In this way whenever you want to push something in a queue you'll just do

```<code>MyJob::dispatch($payload)->onQueue(env('APP_ENV').'ProjectQueueName');
</code>```

or, if you want to define the queue name in the .env file too,

```<code>MyJob::dispatch($payload)->onQueue(env('APP_ENV').env('ProjectQueueName'));
</code>```

And just to be a little more precise, in the queue.php you define the connection and the default queue, but no map alias, that would be quite useful, to be honest, but there is nothing like that yet, as far as I know

Title: Laravel and multiple queues (AWS SQS)

Body:
In my experience it came VERY useful define the queue name as a combination of Environment Name and Project Queue Name

Using CloudFormation I create the queue like

QueueName:
  Type: AWS::SQS::Queue
  Properties:
    VisibilityTimeout: 120
    QueueName: !Join ['', [!Ref 'AWS::StackName', 'ProjectQueueName']]
    Tags:
      - Key: Stack
        Value: !Ref 'AWS::StackName'

In this way whenever you want to push something in a queue you'll just do

MyJob::dispatch($payload)->onQueue(env('APP_ENV').'ProjectQueueName');

or, if you want to define the queue name in the .env file too,

MyJob::dispatch($payload)->onQueue(env('APP_ENV').env('ProjectQueueName'));

And just to be a little more precise, in the queue.php you define the connection and the default queue, but no map alias, that would be quite useful, to be honest, but there is nothing like that yet, as far as I know


问:
CUDA runtime unknown error, maybe a driver problem? CUDA can't see my gpu
My code is very simple for now:

```<code>import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.cuda.current_device()

    ---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-20-3380d2c12118> in <module>
----> 1 torch.cuda.current_device()

~/.conda/envs/tensorflow/lib/python3.6/site-packages/torch/cuda/__init__.py in current_device()
    349 def current_device():
    350     r"""Returns the index of a currently selected device."""
--> 351     _lazy_init()
    352     return torch._C._cuda_getDevice()
    353

~/.conda/envs/tensorflow/lib/python3.6/site-packages/torch/cuda/__init__.py in _lazy_init()
    161             "Cannot re-initialize CUDA in forked subprocess. " + msg)
    162     _check_driver()
--> 163     torch._C._cuda_init()
    164     _cudart = _load_cudart()
    165     _cudart.cudaGetErrorName.restype = ctypes.c_char_p

RuntimeError: cuda runtime error (30) : unknown error at /opt/conda/conda-bld/pytorch_1556653099582/work/aten/src/THC/THCGeneral.cpp:51
</code>```

Looking in the internet it looks like it is a version problem, but I swear I tried all combinations of drivers from CUDA 10.0, 10.1, tensorflow-gpu 13, 12, etc. and nothing seems to work.

NVIDIA driver: nvidia-smi:

```<code>    +-----------------------------------------------------------------------------+
| NVIDIA-SMI 430.14       Driver Version: 430.14       CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce 930MX       Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   36C    P8    N/A /  N/A |    139MiB /  2004MiB |      4%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0       986      G   /usr/lib/xorg/Xorg                            64MiB |
|    0      1242      G   /usr/bin/gnome-shell                          72MiB |
+-----------------------------------------------------------------------------+
</code>```

CUDA VERSION nvcc --version :

```<code>nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2018 NVIDIA Corporation
Built on Sat_Aug_25_21:08:01_CDT_2018
Cuda compilation tools, release 10.0, V10.0.130
</code>```

tensorflow-gpu version: pip list | grep tensorflow:

```<code>tensorflow                         1.13.1
tensorflow-estimator               1.13.0
</code>```

pytorch version pip list | grep torch

```<code>pytorch-pretrained-bert            0.6.2
torch                              1.1.0
torchvision                        0.3.0
</code>```

Can anyone see a problem of compatibility and explain why and how I can fix it?

答:
Did you test your cuda installation ? If not you can use (which will take a while):

```<code> $ cd ~/NVIDIA_CUDA-10.0_Samples
 $ make
</code>```

And then:

```<code>$ cd ~/NVIDIA_CUDA-10.0_Samples/bin/x86_64/linux/release
$./deviceQuery
</code>```

You should get "Test passed!" as result.

Source

Body:
My code is very simple for now:

import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.cuda.current_device()

    ---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-20-3380d2c12118> in <module>
----> 1 torch.cuda.current_device()

~/.conda/envs/tensorflow/lib/python3.6/site-packages/torch/cuda/__init__.py in current_device()
    349 def current_device():
    350     r"""Returns the index of a currently selected device."""
--> 351     _lazy_init()
    352     return torch._C._cuda_getDevice()
    353

~/.conda/envs/tensorflow/lib/python3.6/site-packages/torch/cuda/__init__.py in _lazy_init()
    161             "Cannot re-initialize CUDA in forked subprocess. " + msg)
    162     _check_driver()
--> 163     torch._C._cuda_init()
    164     _cudart = _load_cudart()
    165     _cudart.cudaGetErrorName.restype = ctypes.c_char_p

RuntimeError: cuda runtime error (30) : unknown error at /opt/conda/conda-bld/pytorch_1556653099582/work/aten/src/THC/THCGeneral.cpp:51

Looking in the internet it looks like it is a version problem, but I swear I tried all combinations of drivers from CUDA 10.0, 10.1, tensorflow-gpu 13, 12, etc. and nothing seems to work.

NVIDIA driver: nvidia-smi:

    +-----------------------------------------------------------------------------+
| NVIDIA-SMI 430.14       Driver Version: 430.14       CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce 930MX       Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   36C    P8    N/A /  N/A |    139MiB /  2004MiB |      4%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0       986      G   /usr/lib/xorg/Xorg                            64MiB |
|    0      1242      G   /usr/bin/gnome-shell                          72MiB |
+-----------------------------------------------------------------------------+

CUDA VERSION nvcc --version :

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2018 NVIDIA Corporation
Built on Sat_Aug_25_21:08:01_CDT_2018
Cuda compilation tools, release 10.0, V10.0.130

tensorflow-gpu version: pip list | grep tensorflow:

tensorflow                         1.13.1
tensorflow-estimator               1.13.0

pytorch version pip list | grep torch

pytorch-pretrained-bert            0.6.2
torch                              1.1.0
torchvision                        0.3.0

Can anyone see a problem of compatibility and explain why and how I can fix it?

Body:
Did you test your cuda installation ? If not you can use (which will take a while):

 $ cd ~/NVIDIA_CUDA-10.0_Samples
 $ make

And then:

$ cd ~/NVIDIA_CUDA-10.0_Samples/bin/x86_64/linux/release
$./deviceQuery

You should get "Test passed!" as result.

Source


问:
How to make HTTP request in Swift?
I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes or do I just need to import default libraries? Or is it not possible to make an HTTP request based on native Swift code?</p>

答:
Using URLSession + Swift 5

Just adding to cezar's answer, if you want to make web request using Apple's URLSession class, there are multiple way to do the task

Simple GET Request with URL

Simple GET Request with URL and Parameters

Simple GET Request with URL with Error Handlings

Simple POST Request with URL, Parameters with Error Handlings

1. Simple GET Request with URL

```<code>func simpleGetUrlRequest()
    {
        let url = URL(string: "https://httpbin.org/get")!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            print("The response is : ",String(data: data, encoding: .utf8)!)
            //print(NSString(data: data, encoding: String.Encoding.utf8.rawValue) as Any)
        }
        task.resume()
    }
</code>```

Note : Make sure You must add "NSAppTransportSecurity" key in pList for http requests

```<code><key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</code>```

2. Simple GET Request with URL and Parameters

```<code>func simpleGetUrlWithParamRequest()
    {
        let url = URL(string: "https://www.google.com/search?q=peace")!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in

            if error != nil || data == nil {
                print("Client error!")
                return
            }
            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Server error!")
                return
            }
            print("The Response is : ",response)
        }
        task.resume()
    }
</code>```

3. Simple GET Request with URL with Error Handlings

```<code>func simpleGetUrlRequestWithErrorHandling()
    {
        let session = URLSession.shared
        let url = URL(string: "https://httpbin.org/get")!

        let task = session.dataTask(with: url) { data, response, error in

            if error != nil || data == nil {
                print("Client error!")
                return
            }

            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Server error!")
                return
            }

            guard let mime = response.mimeType, mime == "application/json" else {
                print("Wrong MIME type!")
                return
            }

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: [])
                print("The Response is : ",json)
            } catch {
                print("JSON error: \(error.localizedDescription)")
            }

        }
        task.resume()
    }
</code>```

4. Simple POST Request with URL, Parameters with Error Handlings.

```<code>func simplePostRequestWithParamsAndErrorHandling(){
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 30
        configuration.timeoutIntervalForResource = 30
        let session = URLSession(configuration: configuration)

        let url = URL(string: "https://httpbin.org/post")!

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let parameters = ["username": "foo", "password": "123456"]

        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
        } catch let error {
            print(error.localizedDescription)
        }

        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

            if error != nil || data == nil {
                print("Client error!")
                return
            }

            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Oops!! there is server error!")
                return
            }

            guard let mime = response.mimeType, mime == "application/json" else {
                print("response is not json")
                return
            }

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: [])
                print("The Response is : ",json)
            } catch {
                print("JSON error: \(error.localizedDescription)")
            }

        })

        task.resume()
    }
</code>```

Your suggestions are appreciated!!

Title: How to make HTTP request in Swift?

Body:
Using URLSession + Swift 5

Just adding to cezar's answer, if you want to make web request using Apple's URLSession class, there are multiple way to do the task

Simple GET Request with URL

Simple GET Request with URL and Parameters

Simple GET Request with URL with Error Handlings

Simple POST Request with URL, Parameters with Error Handlings

1. Simple GET Request with URL

func simpleGetUrlRequest()
    {
        let url = URL(string: "https://httpbin.org/get")!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
            guard let data = data else { return }
            print("The response is : ",String(data: data, encoding: .utf8)!)
            //print(NSString(data: data, encoding: String.Encoding.utf8.rawValue) as Any)
        }
        task.resume()
    }

Note : Make sure You must add "NSAppTransportSecurity" key in pList for http requests

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

2. Simple GET Request with URL and Parameters

func simpleGetUrlWithParamRequest()
    {
        let url = URL(string: "https://www.google.com/search?q=peace")!

        let task = URLSession.shared.dataTask(with: url) {(data, response, error) in

            if error != nil || data == nil {
                print("Client error!")
                return
            }
            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Server error!")
                return
            }
            print("The Response is : ",response)
        }
        task.resume()
    }

3. Simple GET Request with URL with Error Handlings

func simpleGetUrlRequestWithErrorHandling()
    {
        let session = URLSession.shared
        let url = URL(string: "https://httpbin.org/get")!

        let task = session.dataTask(with: url) { data, response, error in

            if error != nil || data == nil {
                print("Client error!")
                return
            }

            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Server error!")
                return
            }

            guard let mime = response.mimeType, mime == "application/json" else {
                print("Wrong MIME type!")
                return
            }

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: [])
                print("The Response is : ",json)
            } catch {
                print("JSON error: \(error.localizedDescription)")
            }

        }
        task.resume()
    }

4. Simple POST Request with URL, Parameters with Error Handlings.

func simplePostRequestWithParamsAndErrorHandling(){
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 30
        configuration.timeoutIntervalForResource = 30
        let session = URLSession(configuration: configuration)

        let url = URL(string: "https://httpbin.org/post")!

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let parameters = ["username": "foo", "password": "123456"]

        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
        } catch let error {
            print(error.localizedDescription)
        }

        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

            if error != nil || data == nil {
                print("Client error!")
                return
            }

            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Oops!! there is server error!")
                return
            }

            guard let mime = response.mimeType, mime == "application/json" else {
                print("response is not json")
                return
            }

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: [])
                print("The Response is : ",json)
            } catch {
                print("JSON error: \(error.localizedDescription)")
            }

        })

        task.resume()
    }

Your suggestions are appreciated!!


问:
How can I get consecutive nowrap spans to wrap as separate elements?
I have a block of text where I want to group words up as pairs so the two words do not break. There is an unintended consequence where when you have two  tags in a row he whole line turns into nowrap.

Example:
......

Code below is baseline: The result will wrap at any " "(space) or "-" that the container has.
(NOTE: This example is meant to be on a responsive web-page.)

```<code><div class="block-of-text" style="max-width: 550px">
  One-two Buckle-my-shoe, Three-four Shut-the-door,
  Five-six Pick-up-sticks, Seven-eight Lay-them-straight,
  Nine-ten Do-it-again.
</div>
</code>```

The Result of the Base line will look something like this.

```<code>|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four Shut- |
|  the-door, Five-six Pick-up-sticks, Seven-|
|  eight Lay-them-straight, Nine-ten Do-it- |
|  again.                                   |
|                                           |
|-------------------------------------------|
</code>```

I want to make sure any hyphenated word surrounded by ... stays on the same line.
Below is my attempt. (NOTE: I have One-two not surrounded by nowrap on purpose to show how it will not be included in the result.)

```<code><style>
  .nowrap {
    white-space: nowrap;
  }
</style>

<div class="block-of-text" style="max-width: 550px">
  One-two <span class="nowrap">Buckle-my-shoe, </span>
  <span class="nowrap">Three-four </span><span class="nowrap">Shut-the-door, </span>
  <span class="nowrap">Five-six </span><span class="nowrap">Pick-up-sticks, </span>
  <span class="nowrap">Seven-eight </span><span class="nowrap">Lay-them-straight, </span>
  <span class="nowrap">Nine-ten </span><span class="nowrap">Do-it-again.</span>
</div>
</code>```

My unintended result looks something like this and is NOT what I want. The  tags are acting as one giant nowrap.

```<code>|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two                                  |
|  Buckle-my-shoe, Three-four Shut-the-door, Five-six Pick-up-sticks, Seven-eight Lay-them-straight, Nine-ten Do-it-again.
|                                           |
|-------------------------------------------|
</code>```

What I want to have happen:

```<code>|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four       |
|  Shut-the-door, Five-six Pick-up-sticks,  |
|  Seven-eight Lay-them-straight, Nine-ten  |
|  Do-it-again.                             |
|                                           |
|-------------------------------------------|
</code>```

SOLUTION

Thanks to everyone and especially @Kravimir for helping find the solution:

It works when adding style display: inline-block;, while having all spans on the same line, and adding spacing with   inside the span.

```<code><style>
  .nowrap {
    white-space: nowrap;
    display: inline-block;
  }
</style>

<div class="block-of-text" style="max-width: 550px; border: solid 1px red">
  One-two <span class="nowrap">Buckle-my-shoe, </span><span class="nowrap">Three-four </span><span class="nowrap">Shut-the-door, </span><span class="nowrap">Five-six </span><span class="nowrap">Pick-up-sticks, </span><span class="nowrap">Seven-eight </span><span class="nowrap">Lay-them-straight, </span><span class="nowrap">Nine-ten </span><span class="nowrap">Do-it-again.</span>
</div>
</code>```

Additional info on solution: If you put " "(space) or   outside of the span it does not work as intended or you get 2 spaces between spans. Also the whitespace at the end of a line is not observed when the  tag is on a new line.

TLDR; Solution was edited in above.

答:
Use display: inline-block.

  span.nowrap {
    white-space: nowrap;
    display: inline-block;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="block-of-text" style="max-width: 550px">
  One-two <span class="nowrap">Buckle-my-shoe,</span>
  <span class="nowrap">Three-four</span> <span class="nowrap">Shut-the-door,</span>
  <span class="nowrap">Five-six</span> <span class="nowrap">Pick-up-sticks,</span>
  <span class="nowrap">Seven-eight</span> <span class="nowrap">Lay-them-straight,</span>
  <span class="nowrap">Nine-ten</span> <span class="nowrap">Do-it-again.</span>
</div></code>```

Body:
I have a block of text where I want to group words up as pairs so the two words do not break. There is an unintended consequence where when you have two  tags in a row he whole line turns into nowrap.

Example:
......

Code below is baseline: The result will wrap at any " "(space) or "-" that the container has.
(NOTE: This example is meant to be on a responsive web-page.)

  One-two Buckle-my-shoe, Three-four Shut-the-door,
  Five-six Pick-up-sticks, Seven-eight Lay-them-straight,
  Nine-ten Do-it-again.

The Result of the Base line will look something like this.

|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four Shut- |
|  the-door, Five-six Pick-up-sticks, Seven-|
|  eight Lay-them-straight, Nine-ten Do-it- |
|  again.                                   |
|                                           |
|-------------------------------------------|

I want to make sure any hyphenated word surrounded by ... stays on the same line.
Below is my attempt. (NOTE: I have One-two not surrounded by nowrap on purpose to show how it will not be included in the result.)

  One-two Buckle-my-shoe,
  Three-four Shut-the-door,
  Five-six Pick-up-sticks,
  Seven-eight Lay-them-straight,
  Nine-ten Do-it-again.

My unintended result looks something like this and is NOT what I want. The  tags are acting as one giant nowrap.

|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two                                  |
|  Buckle-my-shoe, Three-four Shut-the-door, Five-six Pick-up-sticks, Seven-eight Lay-them-straight, Nine-ten Do-it-again.
|                                           |
|-------------------------------------------|

What I want to have happen:

|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four       |
|  Shut-the-door, Five-six Pick-up-sticks,  |
|  Seven-eight Lay-them-straight, Nine-ten  |
|  Do-it-again.                             |
|                                           |
|-------------------------------------------|

SOLUTION

Thanks to everyone and especially @Kravimir for helping find the solution:

It works when adding style display: inline-block;, while having all spans on the same line, and adding spacing with   inside the span.

  One-two Buckle-my-shoe, Three-four Shut-the-door, Five-six Pick-up-sticks, Seven-eight Lay-them-straight, Nine-ten Do-it-again.

Additional info on solution: If you put " "(space) or   outside of the span it does not work as intended or you get 2 spaces between spans. Also the whitespace at the end of a line is not observed when the  tag is on a new line.

TLDR; Solution was edited in above.

Body:
Use display: inline-block.

  span.nowrap {
    white-space: nowrap;
    display: inline-block;
  }

<div class="block-of-text" style="max-width: 550px">
  One-two <span class="nowrap">Buckle-my-shoe,</span>
  <span class="nowrap">Three-four</span> <span class="nowrap">Shut-the-door,</span>
  <span class="nowrap">Five-six</span> <span class="nowrap">Pick-up-sticks,</span>
  <span class="nowrap">Seven-eight</span> <span class="nowrap">Lay-them-straight,</span>
  <span class="nowrap">Nine-ten</span> <span class="nowrap">Do-it-again.</span>
</div>


问:
Android Studio 3 can't build my project
I am using Android Studio 3 preview to code and build a android kotlin project but it does not seem to compile due to this error:

: java.lang.Exception: Unable to get response from daemon in 10000 ms

Could not perform incremental compilation: Could not connect to Kotlin
  compile daemon Could not connect to kotlin daemon. Using fallback
  strategy.

```<code>Error:Failed to complete Gradle execution.

Cause:
Gradle build daemon disappeared unexpectedly (it may have been killed or may have crashed)
</code>```

Here is my gradle build file

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.3-2'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha9'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

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

    apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.1'

    defaultConfig {
        applicationId "com.jr.app"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        buildConfigField "String", "DEMO_SERVER_URL", "https://demoserver.restlet.net/v1/"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.0.0'
    implementation 'com.android.support:design:26.0.0'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.android.support:support-v4:26.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.0'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.0'
}
</code>```

Thanks

答: Try to close android studio, delete .gradle and then open it. I had the same problem and it's fixed now.</p>

Title: Android Studio 3 can't build my project

Body:
I am using Android Studio 3 preview to code and build a android kotlin project but it does not seem to compile due to this error:

: java.lang.Exception: Unable to get response from daemon in 10000 ms

Could not perform incremental compilation: Could not connect to Kotlin
  compile daemon Could not connect to kotlin daemon. Using fallback
  strategy.

Error:Failed to complete Gradle execution.

Cause:
Gradle build daemon disappeared unexpectedly (it may have been killed or may have crashed)

Here is my gradle build file

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.3-2'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha9'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

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

    apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.1'

    defaultConfig {
        applicationId "com.jr.app"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        buildConfigField "String", "DEMO_SERVER_URL", "https://demoserver.restlet.net/v1/"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.0.0'
    implementation 'com.android.support:design:26.0.0'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.android.support:support-v4:26.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.0'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.0'
}

Thanks


问:
Looking for JSON parsing library
Is there a Javascript JSON parsing library out there that will parse a string like this?

```<code>‘{ param: “value” }’
</code>```

I know that JSON.parse(‘{ param: “value” }’) won’t. Because there are no quotes around param, it throws an error:

```<code>Unexpected token p in JSON at position 2
</code>```

But I can create Javascript objects with the standard JSON format without quotes around the property names:

```<code>const o = { param: ‘value’ };
</code>```

So I don’t see why a string like ‘{ param: “value” }’ wouldn’t be parsable. JSON.parse(…) won’t do it, but are there other JSON parsing libraries that will?

I’m programming in Angular 7.

答:
I'm going to assume that the fancy quotes in your question are a mistake, and that your real string looks like this:

```<code>{ param: "value" }
</code>```

You can parse it using eval:

```<code>result = eval("(" + str + ")");
</code>```

(If the fancy quotes are really there, you'll probably be tempted to replace them with replace or similar, but beware that doing so will also replace them inside strings.)

Live Example:

const str = '{ param: "value" }';
const result = eval("(" + str + ")");
console.log(`result.param = ${result.param}`);```

WARNING: Using eval in this way allows the supplier of the string to run arbitrary code within your code. So:

Never use eval on a string from User A in User B's session; doing so allows User A to run arbitrary code in User B's browser — a very bad idea.

Never use eval on a string supplied from a user on your server (because then your server is basically User B :-) )

Title: Looking for JSON parsing library

Body:
Is there a Javascript JSON parsing library out there that will parse a string like this?

‘{ param: “value” }’

I know that JSON.parse(‘{ param: “value” }’) won’t. Because there are no quotes around param, it throws an error:

Unexpected token p in JSON at position 2

But I can create Javascript objects with the standard JSON format without quotes around the property names:

const o = { param: ‘value’ };

So I don’t see why a string like ‘{ param: “value” }’ wouldn’t be parsable. JSON.parse(…) won’t do it, but are there other JSON parsing libraries that will?

I’m programming in Angular 7.

Body:
I'm going to assume that the fancy quotes in your question are a mistake, and that your real string looks like this:

{ param: "value" }

You can parse it using eval:

result = eval("(" + str + ")");

(If the fancy quotes are really there, you'll probably be tempted to replace them with replace or similar, but beware that doing so will also replace them inside strings.)

Live Example:

const str = '{ param: "value" }';
const result = eval("(" + str + ")");
console.log(`result.param = ${result.param}`);

WARNING: Using eval in this way allows the supplier of the string to run arbitrary code within your code. So:

Never use eval on a string from User A in User B's session; doing so allows User A to run arbitrary code in User B's browser — a very bad idea.

Never use eval on a string supplied from a user on your server (because then your server is basically User B :-) )


问:
Flyway not finding my migrations file in sbt
I'm trying to apply the migrations to stand up an H2 database in test, my folder structure is:

```<code>src
- test
-- resources
--- db
---- migration
----- V1_0__init_tables.sql
</code>```

I have my configuration set up to point at classpath:db/migration via

```<code>        Flyway
          .configure()
          .locations(migrateLocations)
          .dataSource(url, user, password)
          .load()
          .migrate()
</code>```

When I run my tests I get the following output

```<code>2018-11-29 16:14:14,351 DEBUG [ScalaTest-run] slf4j.Slf4jLog (Slf4jLog.java:45) - Scanning for classpath resources at 'classpath:db/migration' ...
2018-11-29 16:14:14,351 DEBUG [ScalaTest-run] slf4j.Slf4jLog (Slf4jLog.java:45) - Determining location urls for classpath:db/migration using ClassLoader sun.misc.Launcher$AppClassLoader@18b4aac2 ...
2018-11-29 16:14:14,420 WARN  [ScalaTest-run] slf4j.Slf4jLog (Slf4jLog.java:53) - Unable to resolve location classpath:db/migration
2018-11-29 16:14:14,421 DEBUG [ScalaTest-run] slf4j.Slf4jLog (Slf4jLog.java:45) - Scanning for classes at classpath:db/migration
</code>```

which leaves me confused as to why Flyway isn't able to find my file.  As far as I can tell I've done everything according to what the docs recommend.  My test eventually fails because my table was never migrated and thus can't be found by Slick.

It's possible there is an error in my migration file, but I would assume Flyway would have some sort of logging for this?  I don't see anything like that.

答: Spring Boot 2 sets spring.flyway.locations=classpath:db/migration as default and point to src/main/resources/db/migration folder regardless of you run unit testing. You can put your SQL files directory to filesystem then set spring.flyway.locations=filesystem:path/to/yourdir.

Body:
I'm trying to apply the migrations to stand up an H2 database in test, my folder structure is:

src
- test
-- resources
--- db
---- migration
----- V1_0__init_tables.sql

I have my configuration set up to point at classpath:db/migration via

        Flyway
          .configure()
          .locations(migrateLocations)
          .dataSource(url, user, password)
          .load()
          .migrate()

When I run my tests I get the following output

2018-11-29 16:14:14,351 DEBUG [ScalaTest-run] slf4j.Slf4jLog (Slf4jLog.java:45) - Scanning for classpath resources at 'classpath:db/migration' ...
2018-11-29 16:14:14,351 DEBUG [ScalaTest-run] slf4j.Slf4jLog (Slf4jLog.java:45) - Determining location urls for classpath:db/migration using ClassLoader sun.misc.Launcher$AppClassLoader@18b4aac2 ...
2018-11-29 16:14:14,420 WARN  [ScalaTest-run] slf4j.Slf4jLog (Slf4jLog.java:53) - Unable to resolve location classpath:db/migration
2018-11-29 16:14:14,421 DEBUG [ScalaTest-run] slf4j.Slf4jLog (Slf4jLog.java:45) - Scanning for classes at classpath:db/migration

which leaves me confused as to why Flyway isn't able to find my file.  As far as I can tell I've done everything according to what the docs recommend.  My test eventually fails because my table was never migrated and thus can't be found by Slick.

It's possible there is an error in my migration file, but I would assume Flyway would have some sort of logging for this?  I don't see anything like that.


问:
How can I select only some child nodes from an XML file in C#?
I have an XML file that I want to parse. It is longer than what I shall post here, but only this part interests me in this question:

```<code>       <Team>
        <TeamId>1187457</TeamId>
        <TeamName>Zanardi Redwings</TeamName>
        <Arena>
          <ArenaId>1184019</ArenaId>
          <ArenaName>Evolution</ArenaName>
        </Arena>
        <League>
          <LeagueId>37</LeagueId>
          <LeagueName>România</LeagueName>
        </League>
        <Country>
          <CountryId>36</CountryId>
          <CountryName>România</CountryName>
        </Country>
        <LeagueLevelUnit>
          <LeagueLevelUnitId>4109</LeagueLevelUnitId>
          <LeagueLevelUnitName>V.171</LeagueLevelUnitName>
        </LeagueLevelUnit>
        <Region>
          <RegionId>799</RegionId>
          <RegionName>Prahova</RegionName>
        </Region>
        <YouthTeam>
          <YouthTeamId>2337461</YouthTeamId>
          <YouthTeamName>Little Redwings</YouthTeamName>
          <YouthLeague>
            <YouthLeagueId>436902</YouthLeagueId>
            <YouthLeagueName>Normandie Ligue des jeunes</YouthLeagueName>
          </YouthLeague>
        </YouthTeam>
      </Team>
</code>```

From the part above, I only need to read the data from the TeamId and TeamName child nodes. To achieve this, I wrote the following code:

```<code>Nodes = Node.SelectNodes("Team");
foreach (XmlNode j in Nodes)
  {
    XmlNodeList TeamDetails = j.SelectNodes("*");
    foreach (XmlNode k in TeamDetails)
      {
         switch (k.Name)
           {
             case "TeamName":
               {
                  UserTeamNames[counter] = k.InnerXml;
                  break;
               }
             case "TeamId":
               {
                  if (!int.TryParse(k.InnerXml, out UserTeamIDs[counter]))
                   {
                      ShowErrorMessageBox("Parsing TeamID from XML file failed!"); //A function which sets some parameters for MessageBox.Show() then calls it
                   }
                  break;
                }
            }
       }
   }
</code>```

In the code above, counter is an int variable, which I need in other part of the code.

The code works perfectly, but I want to eliminate the useless looping and testing when the node I am working on is not either TeamName or TeamID.

I suspect the answer I am looking for has something to do with XPath expressions, but I am not sure.

How can I read the data from only the mentioned nodes, without any useless operations?

答:
Strictly in terms of xpath, the following expression should select your nodes:</p>

```<code>/Team/*[self::TeamId or self::TeamName]
</code>```

Body:
I have an XML file that I want to parse. It is longer than what I shall post here, but only this part interests me in this question:

       <Team>
        <TeamId>1187457</TeamId>
        <TeamName>Zanardi Redwings</TeamName>
        <Arena>
          <ArenaId>1184019</ArenaId>
          <ArenaName>Evolution</ArenaName>
        </Arena>
        <League>
          <LeagueId>37</LeagueId>
          <LeagueName>România</LeagueName>
        </League>
        <Country>
          <CountryId>36</CountryId>
          <CountryName>România</CountryName>
        </Country>
        <LeagueLevelUnit>
          <LeagueLevelUnitId>4109</LeagueLevelUnitId>
          <LeagueLevelUnitName>V.171</LeagueLevelUnitName>
        </LeagueLevelUnit>
        <Region>
          <RegionId>799</RegionId>
          <RegionName>Prahova</RegionName>
        </Region>
        <YouthTeam>
          <YouthTeamId>2337461</YouthTeamId>
          <YouthTeamName>Little Redwings</YouthTeamName>
          <YouthLeague>
            <YouthLeagueId>436902</YouthLeagueId>
            <YouthLeagueName>Normandie Ligue des jeunes</YouthLeagueName>
          </YouthLeague>
        </YouthTeam>
      </Team>

From the part above, I only need to read the data from the TeamId and TeamName child nodes. To achieve this, I wrote the following code:

Nodes = Node.SelectNodes("Team");
foreach (XmlNode j in Nodes)
  {
    XmlNodeList TeamDetails = j.SelectNodes("*");
    foreach (XmlNode k in TeamDetails)
      {
         switch (k.Name)
           {
             case "TeamName":
               {
                  UserTeamNames[counter] = k.InnerXml;
                  break;
               }
             case "TeamId":
               {
                  if (!int.TryParse(k.InnerXml, out UserTeamIDs[counter]))
                   {
                      ShowErrorMessageBox("Parsing TeamID from XML file failed!"); //A function which sets some parameters for MessageBox.Show() then calls it
                   }
                  break;
                }
            }
       }
   }

In the code above, counter is an int variable, which I need in other part of the code.

The code works perfectly, but I want to eliminate the useless looping and testing when the node I am working on is not either TeamName or TeamID.

I suspect the answer I am looking for has something to do with XPath expressions, but I am not sure.

How can I read the data from only the mentioned nodes, without any useless operations?

Body:
Strictly in terms of xpath, the following expression should select your nodes:

/Team/*[self::TeamId or self::TeamName]


问:
Converting a list to a "two or more objects" argument in R
I have to call a function in R that takes "2 or more objects" as an input, so the function definition is:

function(..., all = TRUE, <other named parameters>)

where ... is defined as 2 or more objects

The issue is I have is that my objects are in a list, and I am working with a different number of objects according to what I want to do. So if my list has 3 elements for example I would have to do:

function(list[[1]], list [[2]], list[[3]])

How can I do that generically, regardless of the number of element in my list ?

答:
An example would be helpful, but I'm pretty sure you're looking for do.call:

```<code>do.call(function, c(list, list(all=TRUE, <other named parameters>)))
</code>```

Body:
An example would be helpful, but I'm pretty sure you're looking for do.call:

do.call(function, c(list, list(all=TRUE, <other named parameters>)))


问:
How to set upstream proxies for each request in Titanium Web Proxy
We are using Titanium Web Proxy to crawl certain sites:

```<code>ProxyServer proxyServer = new ProxyServer();;
        proxyServer.BeforeRequest += OnRequest;
        proxyServer.BeforeResponse += OnResponse;
        proxyServer.ServerCertificateValidationCallback += OnCertificateValidation;
        proxyServer.ClientCertificateSelectionCallback += OnCertificateSelection;
        proxyServer.ConnectionTimeOutSeconds = 30;
        proxyServer.AddEndPoint(explicitEndPoint);
        proxyServer.UpStreamHttpProxy = new ExternalProxy()
         {
           \\ params here
         }
        proxyServer.Start();
</code>```

This lines sets up upstream proxy for all requests:

```<code>proxyServer.UpStreamHttpProxy = ...
</code>```

but I need to set up different UpStreamHttpProxy for each upstream request. I don't seem to be able to accomplish this. Any suggestions ?

答:
It is possible. Take a look here: How to use different ExternalProxy for each https request ?

This is the API:
GetCustomUpStreamProxyFunc
A callback to provide authentication credentials for up stream proxy this proxy is using for HTTP(S) requests. User should return the ExternalProxy object with valid credentials.

Declaration
public Func> GetCustomUpStreamProxyFunc { get; set; }
Property Value
Type    Description
Func>

Body:
We are using Titanium Web Proxy to crawl certain sites:

ProxyServer proxyServer = new ProxyServer();;
        proxyServer.BeforeRequest += OnRequest;
        proxyServer.BeforeResponse += OnResponse;
        proxyServer.ServerCertificateValidationCallback += OnCertificateValidation;
        proxyServer.ClientCertificateSelectionCallback += OnCertificateSelection;
        proxyServer.ConnectionTimeOutSeconds = 30;
        proxyServer.AddEndPoint(explicitEndPoint);
        proxyServer.UpStreamHttpProxy = new ExternalProxy()
         {
           \\ params here
         }
        proxyServer.Start();

This lines sets up upstream proxy for all requests:

proxyServer.UpStreamHttpProxy = ...

but I need to set up different UpStreamHttpProxy for each upstream request. I don't seem to be able to accomplish this. Any suggestions ?


问:
Questions on a modularity-based partitioning using networkx
given an edge list as seen in the code below:

```<code>import networkx as nx
from networkx.algorithms.community import greedy_modularity_communities
from networkx.algorithms.cuts import conductance

# Create a networkx graph object
my_graph = nx.Graph()

# Add edges to to the graph object
# Each tuple represents an edge between two nodes
my_graph.add_edges_from([
                        (1,2),
                        (1,3),
                        (3,4),
                        (1,5),
                        (3,5),
                        (4,2),
                        (2,3),
                        (3,0)])

# Draw the resulting graph
nx.draw(my_graph, with_labels=True, font_weight='bold')

# Modularity
c = list(greedy_modularity_communities(my_graph))
</code>```

We obtain as a cut:

```<code>[frozenset({0, 2, 3, 4}), frozenset({1, 5})]
</code>```

If we look at its corrensponding graph:

why are here node 1 and 5 removed or considered as a good split, and not node 0 removed from the rest of the graph instead?

Thank you in advance for any hints
Best regards

答:
Just from the name greedy_modularity_communities and from the documentation the algorithm will always return a approximation of an optimal partition.

For the partition you proposed, you can simply check the values:

from networkx.algorithms.community.quality import modularity

print(modularity(my_graph, [frozenset({0, 2, 3, 4}), frozenset({1, 5})]))
# 0.0546875
print(modularity(my_graph, [frozenset({1, 2, 3, 4, 5}), frozenset({0})]))
# -0.0078125
```

Body:
given an edge list as seen in the code below:

import networkx as nx
from networkx.algorithms.community import greedy_modularity_communities
from networkx.algorithms.cuts import conductance

# Create a networkx graph object
my_graph = nx.Graph()

# Add edges to to the graph object
# Each tuple represents an edge between two nodes
my_graph.add_edges_from([
                        (1,2),
                        (1,3),
                        (3,4),
                        (1,5),
                        (3,5),
                        (4,2),
                        (2,3),
                        (3,0)])

# Draw the resulting graph
nx.draw(my_graph, with_labels=True, font_weight='bold')

# Modularity
c = list(greedy_modularity_communities(my_graph))

We obtain as a cut:

[frozenset({0, 2, 3, 4}), frozenset({1, 5})]

If we look at its corrensponding graph:

why are here node 1 and 5 removed or considered as a good split, and not node 0 removed from the rest of the graph instead?

Thank you in advance for any hints
Best regards


问:
Unable to understand this JSON parse error
JSON parse error while paring the JSON string

I have this below JS code and it is giving error. I would like to print the engineCode and value?

Thanks.

```<code>//I have update the code. Sorry about the confusion ...
let a = '{ "car": "Honda", "specs": {"engineCode": 1001} }';
let b = JSON.parse(a);
console.log(b); //prints json
//JSON.parse(b.engineCode); //please ignore this .....
JSON.parse(b.specs); //error while parsing and how to fix??

"SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at bajahisowi.js:7:6
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"
</code>```

答:
You don't need to parse again, just use it using dot notation

let a = '{ "car": "Honda", "specs": {"engineCode": 1001} }';
let b = JSON.parse(a);
console.log(b.specs.engineCode); //prints json```

Body:
JSON parse error while paring the JSON string

I have this below JS code and it is giving error. I would like to print the engineCode and value?

Thanks.

//I have update the code. Sorry about the confusion ...
let a = '{ "car": "Honda", "specs": {"engineCode": 1001} }';
let b = JSON.parse(a);
console.log(b); //prints json
//JSON.parse(b.engineCode); //please ignore this .....
JSON.parse(b.specs); //error while parsing and how to fix??

"SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at bajahisowi.js:7:6
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"


问:
How to store system-created to-do list items?
In a to-do list where users have both system-created items and their own items, how would you store the items?

A to-do list can have a mix of items. The system-created items can be modified and deleted just like user-created items. There difference is the titles and description text for the system-created items are initially pulled from a configuration. Many users can have the same system-created items. E.g. if two users want to paint rooms in their houses, they'd both get "buy paint" items.

Option 1

Save the full system-created items (including the title & text) with the user-created items.

Pros: Flexibility for user modifications since the items belong to the user and are not dependent on a central item configuration.

Cons: Lots of redundancy because there will be many users all with the same items.

Option 2

Save references to a configuration for system-created items with the user-created items.

Pros: Flexibility for system modifications since if we want to say "buy X-brand paint" instead of "buy paint", the change is easily reflected for all users with this item.

Cons: System-created items have to persist forever in the configuration even if the item is no longer relevant for new to-do lists because otherwise the user's reference will be broken.

Other options?

Thank you!

答:
My initial thought is - what is your requirement? Your user-flows and project road-map might contain information to inform your design.

From your question "system-created items can be modified and deleted just like user-created items":

This indicates that you are going to have to have a way to track modifications to your 'system-created' templates per user or convert them to 'user-created' messages when they are edited.

This is more complexity than you seem to need

It seems much simpler to create messages from system templates, then have them be regular messages.

A bit of extra storage is not going to break the bank

You have not mentioned any case where you would need to operate over only system-created to-do's. But in this case, you could include created-by metadata.


问:
Deleted DB re Populate in MySql
I am In Deep Trouble..

I have lost my DB as by mistake Have deleted my DB from the Mysql Db,

So could someone help me in getting the Rollback of it.

Please help

答: The simplest solution would be to execute your most recent backup.</p>

Title: Deleted DB re Populate in MySql


问:
Flutter Reduce padding between DataRows in DataTable
How i want it to look like (before -> after) :

Is it possible to do it like in this image?

edit: Solved it like Hugo said, by copying the code of data_table.dart into a new file, changing the _dataRowHeight, and using that instead.

答:
It's not possible to do that in a simple way.

_dataRowHeight is an attribute (private, as you can see) defined inside DataTable. Since DataRow is not a Widget, you cannot force it to fit in a Container, as well.

The best option you got is copying the source code of DataTable in order to create your own DataTable, so you can modify the property _dataRowHeight.

Extending DataTable is also an option, but you would have to override the method build() and still copy a lot of content from DataTable.


问:
Import hooks into React Typescript
I am trying to implement hooks into a React (^16.6.0) application using TypeScript

```<code>import * as React, {useState}  from 'react';
</code>```

Any idea what is the right syntax for this import?

答:
I had the same error on "@types/react": "^16.8.17".  Looking at it's type def file, it was missing the useState function for some reason, though it was mentioned in the comments of other hooks like useReducer.

Upgrading to "@types/react": "^16.8.18" with npm i @types/react@latest fixed it.

Title: Import hooks into React Typescript

Body:
I am trying to implement hooks into a React (^16.6.0) application using TypeScript

import * as React, {useState}  from 'react';

Any idea what is the right syntax for this import?