问:
React-Native FlatList- Warning: Each child in an array or iterator should have a unique "key" prop, even after giving key={index}
I am building the photo-feed application, project-repo-here , in the comments section after clicking on show-comments, it shows comment page on a device, but in a terminal, it breaks with error as,

error is in comments.js file.

```<code>Warning: Each child in an array or iterator should have a unique "key" prop.%s%s See documentationOfREact/react-warning-keys for more information.%s,

Check the render method of `VirtualizedList`., ,
    in CellRenderer (at VirtualizedList.js:687)
    in VirtualizedList (at FlatList.js:662)
    in FlatList (at comments.js:212)
    in RCTView (at View.js:44)
    in comments (created by SceneView)
    in SceneView (at StackViewLayout.js:795)
    in RCTView (at View.js:44)
    in AnimatedComponent (at StackViewCard.js:69)
    in RCTView (at View.js:44)
    in AnimatedComponent (at screens.native.js:59)
    in Screen (at StackViewCard.js:57)
    in Card (at createPointerEventsContainer.js:27)
    in Container (at StackViewLayout.js:860)
    in RCTView (at View.js:44)
    in ScreenContainer (at StackViewLayout.js:311)
    in RCTView (at View.js:44)
    in AnimatedComponent (at StackViewLayout.js:307)
    in Handler (at StackViewLayout.js:300)
    in StackViewLayout (at withOrientation.js:30)
    in withOrientation (at StackView.js:79)
    in RCTView (at View.js:44)
    in Transitioner (at StackView.js:22)
    in StackView (created by Navigator)
    in Navigator (at createKeyboardAwareNavigator.js:12)
    in KeyboardAwareNavigator (at createAppContainer.js:388)
    in NavigationContainer (at App.js:70)
    in App (at withExpoRoot.js:22)
    in RootErrorBoundary (at withExpoRoot.js:21)
    in ExpoRootComponent (at renderApplication.js:34)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in AppContainer (at renderApplication.js:33)
- node_modules/react/cjs/react.development.js:217:39 in warningWithoutStack
- node_modules/react/cjs/react.development.js:617:32 in warning
- node_modules/react/cjs/react.development.js:1429:14 in validateExplicitKey
- node_modules/react/cjs/react.development.js:1451:28 in validateChildKeys
- node_modules/react/cjs/react.development.js:1619:22 in cloneElementWithValidation
- node_modules/react-native/Libraries/Lists/VirtualizedList.js:947:6 in render
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:10563:21 in finishClassComponent
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14091:21 in performUnitOfWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14129:41 in workLoop
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14226:15 in renderRoot
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:15193:17 in performWorkOnRoot
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:15090:24 in performWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:15047:14 in performSyncWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14925:19 in requestWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14711:16 in scheduleWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:7700:17 in enqueueSetState
- node_modules/react/cjs/react.development.js:364:31 in setState
* app/screens/comments.js:66:22 in <unknown>
- node_modules/promise/setimmediate/core.js:37:14 in tryCallOne
- node_modules/promise/setimmediate/core.js:123:25 in <unknown>
- ... 8 more stack frames from framework internals
</code>```

I am displaying comments-array using flatList and gave

keyExtractor={(item, index) => {
              item.id;
            }}

also, I tried giving key={index}, but same error.
I gave unique key as index to , but error occurs,

flatList component is

```<code>   <FlatList
        refreshing={this.state.refresh}
        data={this.state.comments_list}
        keyExtractor={(item, index) => {
          item.id;
        }}
        style={{ flex: 1, backgroundColor: "#eee" }}
        renderItem={({ item, index }) => (
          <View
            key={item.id}
            style={{
              width: "100%",
              overflow: "hidden",
              marginBottom: 5,
              justifyContent: "space-between",
              borderColor: "grey"
            }}
          >
            <View style={{ padding: 5 }}>
              <Text>time: {item.timestamp}</Text>
              <TouchableOpacity>
                <Text>{item.author}</Text>
              </TouchableOpacity>
            </View>

            <View>
              <Text>{item.comment}</Text>
            </View>
          </View>
        )}
      />
</code>```

firebase structure is this

答:
In my case:</p>

```<code>keyExtractor={(item, index) => item.id.toString() }
</code>```

Body:
I am building the photo-feed application, project-repo-here , in the comments section after clicking on show-comments, it shows comment page on a device, but in a terminal, it breaks with error as,

error is in comments.js file.

Warning: Each child in an array or iterator should have a unique "key" prop.%s%s See documentationOfREact/react-warning-keys for more information.%s,

Check the render method of `VirtualizedList`., ,
    in CellRenderer (at VirtualizedList.js:687)
    in VirtualizedList (at FlatList.js:662)
    in FlatList (at comments.js:212)
    in RCTView (at View.js:44)
    in comments (created by SceneView)
    in SceneView (at StackViewLayout.js:795)
    in RCTView (at View.js:44)
    in AnimatedComponent (at StackViewCard.js:69)
    in RCTView (at View.js:44)
    in AnimatedComponent (at screens.native.js:59)
    in Screen (at StackViewCard.js:57)
    in Card (at createPointerEventsContainer.js:27)
    in Container (at StackViewLayout.js:860)
    in RCTView (at View.js:44)
    in ScreenContainer (at StackViewLayout.js:311)
    in RCTView (at View.js:44)
    in AnimatedComponent (at StackViewLayout.js:307)
    in Handler (at StackViewLayout.js:300)
    in StackViewLayout (at withOrientation.js:30)
    in withOrientation (at StackView.js:79)
    in RCTView (at View.js:44)
    in Transitioner (at StackView.js:22)
    in StackView (created by Navigator)
    in Navigator (at createKeyboardAwareNavigator.js:12)
    in KeyboardAwareNavigator (at createAppContainer.js:388)
    in NavigationContainer (at App.js:70)
    in App (at withExpoRoot.js:22)
    in RootErrorBoundary (at withExpoRoot.js:21)
    in ExpoRootComponent (at renderApplication.js:34)
    in RCTView (at View.js:44)
    in RCTView (at View.js:44)
    in AppContainer (at renderApplication.js:33)
- node_modules/react/cjs/react.development.js:217:39 in warningWithoutStack
- node_modules/react/cjs/react.development.js:617:32 in warning
- node_modules/react/cjs/react.development.js:1429:14 in validateExplicitKey
- node_modules/react/cjs/react.development.js:1451:28 in validateChildKeys
- node_modules/react/cjs/react.development.js:1619:22 in cloneElementWithValidation
- node_modules/react-native/Libraries/Lists/VirtualizedList.js:947:6 in render
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:10563:21 in finishClassComponent
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14091:21 in performUnitOfWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14129:41 in workLoop
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14226:15 in renderRoot
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:15193:17 in performWorkOnRoot
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:15090:24 in performWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:15047:14 in performSyncWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14925:19 in requestWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:14711:16 in scheduleWork
- node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js:7700:17 in enqueueSetState
- node_modules/react/cjs/react.development.js:364:31 in setState
* app/screens/comments.js:66:22 in <unknown>
- node_modules/promise/setimmediate/core.js:37:14 in tryCallOne
- node_modules/promise/setimmediate/core.js:123:25 in <unknown>
- ... 8 more stack frames from framework internals

I am displaying comments-array using flatList and gave

keyExtractor={(item, index) => {
              item.id;
            }}

also, I tried giving key={index}, but same error.
I gave unique key as index to , but error occurs,

flatList component is

   <FlatList
        refreshing={this.state.refresh}
        data={this.state.comments_list}
        keyExtractor={(item, index) => {
          item.id;
        }}
        style={{ flex: 1, backgroundColor: "#eee" }}
        renderItem={({ item, index }) => (
          <View
            key={item.id}
            style={{
              width: "100%",
              overflow: "hidden",
              marginBottom: 5,
              justifyContent: "space-between",
              borderColor: "grey"
            }}
          >
            <View style={{ padding: 5 }}>
              <Text>time: {item.timestamp}</Text>
              <TouchableOpacity>
                <Text>{item.author}</Text>
              </TouchableOpacity>
            </View>

            <View>
              <Text>{item.comment}</Text>
            </View>
          </View>
        )}
      />

firebase structure is this

Body:
In my case:

keyExtractor={(item, index) => item.id.toString() }


来源: stackexchange

问:
how to create a button that links to textfile/excel sheet/url (EXTJS)?
I need to create a button that links to textfile/excel sheet/url.How to do the same in EXTJS ? Can anyone help me with the code ?</p>

答:
```<code>new Ext.Button({
  text: 'PRESS ME',
  handler: function() {
    window.open('http://textfiles.com/or/spreadsheet.xls', '_blank');
  }
});
</code>```

Or possibly window.location = http://somewhereelse.com/anotherfile.txt' in the handler if you don't want to open a new window.

ContentLicense: CC BY-SA 3.0

Body:
new Ext.Button({
  text: 'PRESS ME',
  handler: function() {
    window.open('http://textfiles.com/or/spreadsheet.xls', '_blank');
  }
});

Or possibly window.location = http://somewhereelse.com/anotherfile.txt' in the handler if you don't want to open a new window.


问:
How to use grep match as a variable (and not whole line)
This is the sample file

```<code>[user@linux]$ cat DeviceA
DeviceA#sh ver
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$
</code>```

Version 15.1(4)M10 will be highligted

```<code>[user@linux]$ egrep --color=auto 'Version (15.1\(4\)M7|15.1\(4\)M10|15.2\(1\)T4)' DeviceA
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$
</code>```

Using grep output as variable var

```<code>[user@linux]$ var=$(egrep --color=auto 'Version (15.1\(4\)M7|15.1\(4\)M10|15.2\(1\)T4)' DeviceA)
[user@linux]$
</code>```

Print variable var

```<code>[user@linux]$ echo $var
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$
</code>```

Instead of getting the whole line as var, can I just get Version 15.1(4)M10 when executing echo $var?

Desired Output

```<code>[user@linux]$ echo $var
Version 15.1(4)M10
[user@linux]$
</code>```

答:
try this:</p>

```<code>tmp="${var%,*}"           # remove last part after ,
echo "${tmp##*,}"         # print last part after ,
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is the sample file

[user@linux]$ cat DeviceA
DeviceA#sh ver
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$

Version 15.1(4)M10 will be highligted

[user@linux]$ egrep --color=auto 'Version (15.1\(4\)M7|15.1\(4\)M10|15.2\(1\)T4)' DeviceA
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$

Using grep output as variable var

[user@linux]$ var=$(egrep --color=auto 'Version (15.1\(4\)M7|15.1\(4\)M10|15.2\(1\)T4)' DeviceA)
[user@linux]$

Print variable var

[user@linux]$ echo $var
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$

Instead of getting the whole line as var, can I just get Version 15.1(4)M10 when executing echo $var?

Desired Output

[user@linux]$ echo $var
Version 15.1(4)M10
[user@linux]$

Body:
try this:

tmp="${var%,*}"           # remove last part after ,
echo "${tmp##*,}"         # print last part after ,


问:
Gradient color in CSS with percentage
I have only basic knowledge on the CSS. I'm trying to give gradient color for one of my ITEM as per below guidelines and the gradient should be vertical.

I tried the below , but only the first color is coming all over the region. I dont understand that 30% and 50%. How to achieve this?

```<code> .myheader {
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);
  }
</code>```

Title: Gradient color in CSS with percentage

Body:
I have only basic knowledge on the CSS. I'm trying to give gradient color for one of my ITEM as per below guidelines and the gradient should be vertical.

I tried the below , but only the first color is coming all over the region. I dont understand that 30% and 50%. How to achieve this?

 .myheader {
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);
  }

Body:
This is an example , use your rgba colors.

.myheader {
  background: linear-gradient(to bottom, rgba(248,80,50,1) 0%, rgba(241,111,92,1) 50%, rgba(246,41,12,1) 51%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%
  }


问:
Saving data(octet-stream) from request as Excel file results in corrupted file
I'm returning an Excel file (which works fine) as octet stream from C# API using FileContentResult(byte[], MediaTypeNames.Application.Octet, "file.xlsx"

and then I'd want to open download file prompt from js and everything works fine except that the file is corrupted

I've been trying various solutions from these posts and Excel file always result in being corrupted

JavaScript: Create and save file

JavaScript blob filename without link

Create binary blob in JS

and also FileSaver.js

```<code>$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: 'application/json',
success: function (result)
{
    saveFile(result);
}
});
</code>```

I know that file is working fine because when I'm testing it via Swagger then it works fine

Any ideas?

答:
Workaround:

Returning base64 of that file and create a element on that page with href attribute that has value of

data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,

and then add your base64 to that value, so

'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'+base64

and then perform .click() on that link

Conversion of Base64 Encoded into XSLX

You can specify name of file by using download="" attribute

Body:
I'm returning an Excel file (which works fine) as octet stream from C# API using FileContentResult(byte[], MediaTypeNames.Application.Octet, "file.xlsx"

and then I'd want to open download file prompt from js and everything works fine except that the file is corrupted

I've been trying various solutions from these posts and Excel file always result in being corrupted

JavaScript: Create and save file

JavaScript blob filename without link

Create binary blob in JS

and also FileSaver.js

$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: 'application/json',
success: function (result)
{
    saveFile(result);
}
});

I know that file is working fine because when I'm testing it via Swagger then it works fine

Any ideas?


问:
How can i run .cmd file from http trigger azure function
I want to run .cmd file using azure function. I want to run this in background process instead of main process of azure function.

I have already saved the cmd file on azure function platform using Kudu Editor. I can run this locally but after deploying its not working at all (I am also not getting any error).

```<code>      string cmdFileLocation = @"D:\home\jobs.cmd";
       Process proc = new Process();
       ProcessStartInfo info = new ProcessStartInfo();
       try
       {
           info.FileName = cmdFileLocation;
           info.Arguments = name;
           info.WindowStyle = ProcessWindowStyle.Minimized;
           info.UseShellExecute = false;
           proc.StartInfo = info;
           info.RedirectStandardOutput = true;
           info.RedirectStandardError = true;
           proc.Start();
           proc.WaitForExit();
        }
        catch (Exception ex)
        {
            log.LogInformation("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
        }
</code>```

For testing there is curl command in cmd file. The curl will trigger on local machine using azure function as I can see the request coming (https://webhook.site) but after deplying nothing happens.

答:
Here is an easy way of getting any .exe/.cmd running as a web service. You just specify the input parameters to your exe/cmd in a configuration file. You can use binary files as inputs to the exe by specifying a URL to download it from.

Here's what the configuration file looks like

```<code>{
    "name": "consoleAppToFunctions",
    "input": {
        "command": "ffmpeg.exe -i {inputFile} {output1}",
        "arguments": {
            "inputFile": {
                "url": "https://1drv.ms/v/<link-to-file>"
                //binary file input
            },
            "output1": {
                "localfile": "out.mp3"
                //stored in a temp folder
            }
        }
    },
    "output": {
        "folder": "outputFolder",
        "binaryFile": {
            "returnFile": "*.mp3",
            "returnFileName": "yourFile.mp3"
        }
    }
}
</code>```

Here is the AZURE FUNCTION CODE for the same:

```<code>#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;
using System.IO;
using System.Diagnostics;

//Code from https://github.com/Azure-Samples/functions-dotnet-migrating-console-apps/edit/master/code/run.csx
//Written by Ambrose http://github.com/efficientHacks and Murali http://github.com/muralivp

public class ExeArg
{
    public string Name { get; set; }
    public string Type { get; set; }
    public string Value { get; set; }
}

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    string localPath = req.RequestUri.LocalPath;
    string functionName = localPath.Substring(localPath.LastIndexOf('/')+1);

    var json = File.ReadAllText(string.Format(@"D:\home\site\wwwroot\{0}\FunctionConfig.json",functionName));

    var config = JsonConvert.DeserializeObject<dynamic>(json);

    var functionArguments = config.input.arguments;
    var localOutputFolder = Path.Combine(@"d:\home\data", config.output.folder.Value, Path.GetFileNameWithoutExtension(Path.GetTempFileName()));
    Directory.CreateDirectory(localOutputFolder);
    var workingDirectory = Path.Combine(@"d:\home\site\wwwroot", functionName + "\\bin");
    Directory.SetCurrentDirectory(workingDirectory);//fun fact - the default working directory is d:\windows\system32

    var command = config.input.command.Value;

    var argList = new List<ExeArg>();

    //Parse the config file's arguments
    //handle file system, local file etc. and construct the input params for the actual calling of the .exe
    foreach (var arg in functionArguments)
    {
        var exeArg = new ExeArg();
        exeArg.Name = arg.Name;
        var value = (Newtonsoft.Json.Linq.JObject)arg.Value;
        var property = (Newtonsoft.Json.Linq.JProperty)value.First;
        exeArg.Type = property.Name;
        exeArg.Value = property.Value.ToString();

        var valueFromQueryString = await getValueFromQuery(req, exeArg.Name);

        log.Info("valueFromQueryString name=" + exeArg.Name);
        log.Info("valueFromQueryString val=" + valueFromQueryString);
        if(!string.IsNullOrEmpty(valueFromQueryString))
        {
            exeArg.Value = valueFromQueryString;
            log.Info(exeArg.Name + " " + valueFromQueryString);
        }

        if(exeArg.Type.ToLower() == "localfile" || exeArg.Type.ToLower() == "localfolder")
        {
            exeArg.Value = Path.Combine(localOutputFolder, exeArg.Value);
            exeArg.Type = "string";
        }
        if(string.IsNullOrEmpty(exeArg.Value))
        {
            //throw exception here
        }
        argList.Add(exeArg);
    }

    //call the exe
    Dictionary<string, string> paramList = ProcessParameters(argList, localOutputFolder);
    foreach (string parameter in paramList.Keys)
    {
        command = command.Replace(parameter, paramList[parameter]);
    }
    string commandName = command.Split(' ')[0];
    string arguments = command.Split(new char[] { ' ' }, 2)[1];
    log.Info("the command is " + command);
    log.Info("the working dir is " + workingDirectory);
    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = commandName;
    p.StartInfo.Arguments = arguments;
    p.Start();
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();
    File.WriteAllText(localOutputFolder+"\\out.txt",output);

    //handle return file
    log.Info("handling return file localOutputFolder=" + localOutputFolder);
    string outputFile = config.output.binaryFile.returnFile.Value;
    string outputFileName = config.output.binaryFile.returnFileName.Value;
    var path = Directory.GetFiles(localOutputFolder, outputFile)[0];

    log.Info("returning this file " + path);
    var result = new FileHttpResponseMessage(localOutputFolder);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = outputFileName
    };

    return result;
}

private static Dictionary<string, string> ProcessParameters(List<ExeArg> arguments, string outputFolder)
{
    Dictionary<string, string> paramList = new Dictionary<string, string>();
    foreach (var arg in arguments)
    {
        switch (arg.Type)
        {
            case "url":
                string downloadedFileName = ProcessUrlType((string)arg.Value, outputFolder);
                paramList.Add("{" + arg.Name + "}", downloadedFileName);
                break;
            case "string":
                paramList.Add("{" + arg.Name + "}", arg.Value.ToString());
                break;
            default:
                break;
        }
    }
    return paramList;
}

//you can modify this method to handle different URLs if necessary
private static string ProcessUrlType(string url, string outputFolder)
{
    Directory.CreateDirectory(outputFolder);
    string downloadedFile = Path.Combine(outputFolder, Path.GetFileName(Path.GetTempFileName()));
    //for oneDrive links
    HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    webRequest.AllowAutoRedirect = false;
    WebResponse webResp = webRequest.GetResponse();
    webRequest = (HttpWebRequest)HttpWebRequest.Create(webResp.Headers["Location"].Replace("redir", "download"));
    webResp = webRequest.GetResponse();
    string fileUrl = webResp.Headers["Content-Location"];

    WebClient webClient = new WebClient();
    webClient.DownloadFile(fileUrl, downloadedFile);
    return downloadedFile;
}

private async static Task<string> getValueFromQuery(HttpRequestMessage req, string name)
{
    // parse query parameter
    string value = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, name, true) == 0)
        .Value;

    //if not found in query string, look for it in the body (json)
    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    value = value ?? data?[name];
    return value;
}

//this is to delete the folder after the response
//thanks to: https://stackoverflow.com/a/30522890/2205372
public class FileHttpResponseMessage : HttpResponseMessage
{
    private string filePath;

    public FileHttpResponseMessage(string filePath)
    {
        this.filePath = filePath;
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        Content.Dispose();
        Directory.Delete(filePath,true);
    }
}
</code>```

Here you can find more on this. Hope it helps.

Body:
I want to run .cmd file using azure function. I want to run this in background process instead of main process of azure function.

I have already saved the cmd file on azure function platform using Kudu Editor. I can run this locally but after deploying its not working at all (I am also not getting any error).

      string cmdFileLocation = @"D:\home\jobs.cmd";
       Process proc = new Process();
       ProcessStartInfo info = new ProcessStartInfo();
       try
       {
           info.FileName = cmdFileLocation;
           info.Arguments = name;
           info.WindowStyle = ProcessWindowStyle.Minimized;
           info.UseShellExecute = false;
           proc.StartInfo = info;
           info.RedirectStandardOutput = true;
           info.RedirectStandardError = true;
           proc.Start();
           proc.WaitForExit();
        }
        catch (Exception ex)
        {
            log.LogInformation("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
        }

For testing there is curl command in cmd file. The curl will trigger on local machine using azure function as I can see the request coming (https://webhook.site) but after deplying nothing happens.

Body:
Here is an easy way of getting any .exe/.cmd running as a web service. You just specify the input parameters to your exe/cmd in a configuration file. You can use binary files as inputs to the exe by specifying a URL to download it from.

Here's what the configuration file looks like

{
    "name": "consoleAppToFunctions",
    "input": {
        "command": "ffmpeg.exe -i {inputFile} {output1}",
        "arguments": {
            "inputFile": {
                "url": "https://1drv.ms/v/<link-to-file>"
                //binary file input
            },
            "output1": {
                "localfile": "out.mp3"
                //stored in a temp folder
            }
        }
    },
    "output": {
        "folder": "outputFolder",
        "binaryFile": {
            "returnFile": "*.mp3",
            "returnFileName": "yourFile.mp3"
        }
    }
}

Here is the AZURE FUNCTION CODE for the same:

#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;
using System.IO;
using System.Diagnostics;

//Code from https://github.com/Azure-Samples/functions-dotnet-migrating-console-apps/edit/master/code/run.csx
//Written by Ambrose http://github.com/efficientHacks and Murali http://github.com/muralivp

public class ExeArg
{
    public string Name { get; set; }
    public string Type { get; set; }
    public string Value { get; set; }
}

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    string localPath = req.RequestUri.LocalPath;
    string functionName = localPath.Substring(localPath.LastIndexOf('/')+1);

    var json = File.ReadAllText(string.Format(@"D:\home\site\wwwroot\{0}\FunctionConfig.json",functionName));

    var config = JsonConvert.DeserializeObject<dynamic>(json);

    var functionArguments = config.input.arguments;
    var localOutputFolder = Path.Combine(@"d:\home\data", config.output.folder.Value, Path.GetFileNameWithoutExtension(Path.GetTempFileName()));
    Directory.CreateDirectory(localOutputFolder);
    var workingDirectory = Path.Combine(@"d:\home\site\wwwroot", functionName + "\\bin");
    Directory.SetCurrentDirectory(workingDirectory);//fun fact - the default working directory is d:\windows\system32

    var command = config.input.command.Value;

    var argList = new List<ExeArg>();

    //Parse the config file's arguments
    //handle file system, local file etc. and construct the input params for the actual calling of the .exe
    foreach (var arg in functionArguments)
    {
        var exeArg = new ExeArg();
        exeArg.Name = arg.Name;
        var value = (Newtonsoft.Json.Linq.JObject)arg.Value;
        var property = (Newtonsoft.Json.Linq.JProperty)value.First;
        exeArg.Type = property.Name;
        exeArg.Value = property.Value.ToString();

        var valueFromQueryString = await getValueFromQuery(req, exeArg.Name);

        log.Info("valueFromQueryString name=" + exeArg.Name);
        log.Info("valueFromQueryString val=" + valueFromQueryString);
        if(!string.IsNullOrEmpty(valueFromQueryString))
        {
            exeArg.Value = valueFromQueryString;
            log.Info(exeArg.Name + " " + valueFromQueryString);
        }

        if(exeArg.Type.ToLower() == "localfile" || exeArg.Type.ToLower() == "localfolder")
        {
            exeArg.Value = Path.Combine(localOutputFolder, exeArg.Value);
            exeArg.Type = "string";
        }
        if(string.IsNullOrEmpty(exeArg.Value))
        {
            //throw exception here
        }
        argList.Add(exeArg);
    }

    //call the exe
    Dictionary<string, string> paramList = ProcessParameters(argList, localOutputFolder);
    foreach (string parameter in paramList.Keys)
    {
        command = command.Replace(parameter, paramList[parameter]);
    }
    string commandName = command.Split(' ')[0];
    string arguments = command.Split(new char[] { ' ' }, 2)[1];
    log.Info("the command is " + command);
    log.Info("the working dir is " + workingDirectory);
    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = commandName;
    p.StartInfo.Arguments = arguments;
    p.Start();
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();
    File.WriteAllText(localOutputFolder+"\\out.txt",output);

    //handle return file
    log.Info("handling return file localOutputFolder=" + localOutputFolder);
    string outputFile = config.output.binaryFile.returnFile.Value;
    string outputFileName = config.output.binaryFile.returnFileName.Value;
    var path = Directory.GetFiles(localOutputFolder, outputFile)[0];

    log.Info("returning this file " + path);
    var result = new FileHttpResponseMessage(localOutputFolder);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = outputFileName
    };

    return result;
}

private static Dictionary<string, string> ProcessParameters(List<ExeArg> arguments, string outputFolder)
{
    Dictionary<string, string> paramList = new Dictionary<string, string>();
    foreach (var arg in arguments)
    {
        switch (arg.Type)
        {
            case "url":
                string downloadedFileName = ProcessUrlType((string)arg.Value, outputFolder);
                paramList.Add("{" + arg.Name + "}", downloadedFileName);
                break;
            case "string":
                paramList.Add("{" + arg.Name + "}", arg.Value.ToString());
                break;
            default:
                break;
        }
    }
    return paramList;
}

//you can modify this method to handle different URLs if necessary
private static string ProcessUrlType(string url, string outputFolder)
{
    Directory.CreateDirectory(outputFolder);
    string downloadedFile = Path.Combine(outputFolder, Path.GetFileName(Path.GetTempFileName()));
    //for oneDrive links
    HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    webRequest.AllowAutoRedirect = false;
    WebResponse webResp = webRequest.GetResponse();
    webRequest = (HttpWebRequest)HttpWebRequest.Create(webResp.Headers["Location"].Replace("redir", "download"));
    webResp = webRequest.GetResponse();
    string fileUrl = webResp.Headers["Content-Location"];

    WebClient webClient = new WebClient();
    webClient.DownloadFile(fileUrl, downloadedFile);
    return downloadedFile;
}

private async static Task<string> getValueFromQuery(HttpRequestMessage req, string name)
{
    // parse query parameter
    string value = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, name, true) == 0)
        .Value;

    //if not found in query string, look for it in the body (json)
    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    value = value ?? data?[name];
    return value;
}

//this is to delete the folder after the response
//thanks to: https://stackoverflow.com/a/30522890/2205372
public class FileHttpResponseMessage : HttpResponseMessage
{
    private string filePath;

    public FileHttpResponseMessage(string filePath)
    {
        this.filePath = filePath;
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        Content.Dispose();
        Directory.Delete(filePath,true);
    }
}

Here you can find more on this. Hope it helps.


问:
ListView showing only the last item in the first position of ListView
I want to show some items in a list view. The problem is that the list view only shows the last item in the first position of the list view. It shows the the no. of items correctly but the remaining positions remain blank.

Can't understand where I am doing wrong. Any help please? I am attaching a screenshot here

MainActivit.java

ListView topicList;
ArrayList<Topics> topics;
ArrayList<Topics> topicsArrayList;
TopicAdapter topicAdapter;

//Inside onCreat method
topicList = findViewById(R.id.lv_list);

        //Array list to show items in the list view
        topics = new ArrayList<>();
        topicAdapter = new TopicAdapter(this, R.layout.list_item_row, topics);
        topicList.setAdapter(topicAdapter);

        //Array list to add the list items
        topicsArrayList = new ArrayList<>();

        Topics vumika = new Topics();
        vumika.setTopicName("Vumika");
        topicsArrayList.add(vumika);

        Topics prachin_yug = new Topics();
        vumika.setTopicName("Prachin Yug");
        topicsArrayList.add(prachin_yug);

        Topics madhya_yug = new Topics();
        vumika.setTopicName("Madhya Yug");
        topicsArrayList.add(madhya_yug);

        Topics adhunik_yug = new Topics();
        vumika.setTopicName("Adhunik Yug");
        topicsArrayList.add(adhunik_yug);

        //Add all the topics to the topic list
        if (topicsArrayList != null || topicsArrayList.size() > 0) {
            topics.addAll(topicsArrayList);
            topicAdapter.notifyDataSetChanged();
        }
```

<p><code>TopicAdapter.java</code> class</p>

<pre class="lang-java prettyprint-override"><code>public class TopicAdapter extends BaseAdapter {

    private Context context;
    private int layout;
    private ArrayList<Topics> topics;
    private ViewHolder viewHolder;

    public TopicAdapter(Context context, int layout, ArrayList<Topics> topics) {
        this.context = context;
        this.layout = layout;
        this.topics = topics;
    }

    public TopicAdapter(Context context, int layout, ArrayList<Topics> topics, ViewHolder viewHolder) {
        this.context = context;
        this.layout = layout;
        this.topics = topics;
        this.viewHolder = viewHolder;
    }

    @Override
    public int getCount() {
        return topics.size();
    }

    @Override
    public Object getItem(int position) {
        return topics.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        viewHolder = new ViewHolder();

        if (row == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (inflater != null) {
                row = inflater.inflate(layout, null);
                viewHolder.topicName = row.findViewById(R.id.tv_topic_name);
                row.setTag(viewHolder);

            }
        } else {
            viewHolder = (ViewHolder) row.getTag();
        }

        Topics topic = topics.get(position);
        viewHolder.topicName.setText(topic.getTopicName());

        return row;
    }

    private class ViewHolder {
        TextView topicName;
    }
}
</code>```

答:
It shows the last item because you are repeatedly using the vumika.setTopicName() setter method. you have to set the name to each every new Topics object.

The correct one is

```<code>Topics vumika = new Topics();
vumika.setTopicName("Vumika");
topicsArrayList.add(vumika);

Topics prachin_yug = new Topics();
prachin_yug.setTopicName("Prachin Yug");
topicsArrayList.add(prachin_yug);

Topics madhya_yug = new Topics();
madhya_yug.setTopicName("Madhya Yug");
topicsArrayList.add(madhya_yug);

Topics adhunik_yug = new Topics();
adhunik_yug.setTopicName("Adhunik Yug");
topicsArrayList.add(adhunik_yug);
</code>```

Body:
I want to show some items in a list view. The problem is that the list view only shows the last item in the first position of the list view. It shows the the no. of items correctly but the remaining positions remain blank.

Can't understand where I am doing wrong. Any help please? I am attaching a screenshot here

MainActivit.java

ListView topicList;
ArrayList<Topics> topics;
ArrayList<Topics> topicsArrayList;
TopicAdapter topicAdapter;

//Inside onCreat method
topicList = findViewById(R.id.lv_list);

        //Array list to show items in the list view
        topics = new ArrayList<>();
        topicAdapter = new TopicAdapter(this, R.layout.list_item_row, topics);
        topicList.setAdapter(topicAdapter);

        //Array list to add the list items
        topicsArrayList = new ArrayList<>();

        Topics vumika = new Topics();
        vumika.setTopicName("Vumika");
        topicsArrayList.add(vumika);

        Topics prachin_yug = new Topics();
        vumika.setTopicName("Prachin Yug");
        topicsArrayList.add(prachin_yug);

        Topics madhya_yug = new Topics();
        vumika.setTopicName("Madhya Yug");
        topicsArrayList.add(madhya_yug);

        Topics adhunik_yug = new Topics();
        vumika.setTopicName("Adhunik Yug");
        topicsArrayList.add(adhunik_yug);

        //Add all the topics to the topic list
        if (topicsArrayList != null || topicsArrayList.size() > 0) {
            topics.addAll(topicsArrayList);
            topicAdapter.notifyDataSetChanged();
        }

TopicAdapter.java class

public class TopicAdapter extends BaseAdapter {

    private Context context;
    private int layout;
    private ArrayList<Topics> topics;
    private ViewHolder viewHolder;

    public TopicAdapter(Context context, int layout, ArrayList<Topics> topics) {
        this.context = context;
        this.layout = layout;
        this.topics = topics;
    }

    public TopicAdapter(Context context, int layout, ArrayList<Topics> topics, ViewHolder viewHolder) {
        this.context = context;
        this.layout = layout;
        this.topics = topics;
        this.viewHolder = viewHolder;
    }

    @Override
    public int getCount() {
        return topics.size();
    }

    @Override
    public Object getItem(int position) {
        return topics.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        viewHolder = new ViewHolder();

        if (row == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (inflater != null) {
                row = inflater.inflate(layout, null);
                viewHolder.topicName = row.findViewById(R.id.tv_topic_name);
                row.setTag(viewHolder);

            }
        } else {
            viewHolder = (ViewHolder) row.getTag();
        }

        Topics topic = topics.get(position);
        viewHolder.topicName.setText(topic.getTopicName());

        return row;
    }

    private class ViewHolder {
        TextView topicName;
    }
}

Body:
It shows the last item because you are repeatedly using the vumika.setTopicName() setter method. you have to set the name to each every new Topics object.

The correct one is

Topics vumika = new Topics();
vumika.setTopicName("Vumika");
topicsArrayList.add(vumika);

Topics prachin_yug = new Topics();
prachin_yug.setTopicName("Prachin Yug");
topicsArrayList.add(prachin_yug);

Topics madhya_yug = new Topics();
madhya_yug.setTopicName("Madhya Yug");
topicsArrayList.add(madhya_yug);

Topics adhunik_yug = new Topics();
adhunik_yug.setTopicName("Adhunik Yug");
topicsArrayList.add(adhunik_yug);


问:
Self signed certificate in Android application of RAD
I have REST service over SSL with self-signed certificate. I can call it from regular delphi application through TRESTClient. But When I use it inside Android application it raises the following exception during call.

Exception class EJNIException with message
  'java.security.cert.CertificateException:
  java.security.cert.CertPathValidatorException: Trust anchor for
  certification path not found.

I found, that network security must be configured via adding android:networkSecurityConfig="@xml/network_security_config" into application section of AndroidManifest.template.xml file.

```<code><application android:networkSecurityConfig="@xml/network_security_config"
    android:persistent="%persistent%"
    android:restoreAnyVersion="%restoreAnyVersion%"
    android:label="%label%"
    android:debuggable="%debuggable%"
    android:largeHeap="%largeHeap%"
    android:icon="%icon%"
    android:theme="%theme%"
    android:hardwareAccelerated="%hardwareAccelerated%"
    android:resizeableActivity="false">
</code>```

Then I had to create res\xml\network_security_config.xml file with the similar contents:

```<code><?xml version="1.0" encoding="utf-8"?> <network-security-config>
    <domain-config>
        <domain includeSubdomains="true">example.com</domain>
        <trust-anchors>
            <certificates src="@raw/my_ca"/>
        </trust-anchors>
    </domain-config> </network-security-config>
</code>```

But where to place network_security_config.xml file. When I placed it in res folder inside Debug it was deleted during build. So it can not be found and app raises exception during packaging stage.

Error: E2312
  C:\Users\User\Documents\Embarcadero\Studio\Projects\Andr\Android\Debug\TabbedApplication\AndroidManifest.xml:19:
  error: Error: No resource found that matches the given name (at
  'networkSecurityConfig' with value '@xml/network_security_config').

I don't know, where to place it and give RAD Studio know, that it must grab this file on compile time.

答:
You cannot directly use Debug and Release folders to specify files you need to deploy with your application as they are temporary folders cleared on each rebuild.

For deployment you should use Project -> Deployment dialog.

There you can specify which local files (placed outside build folders) you want to deploy, in which configuration (Debug, Release or both) and their destination path.

Body:
I have REST service over SSL with self-signed certificate. I can call it from regular delphi application through TRESTClient. But When I use it inside Android application it raises the following exception during call.

Exception class EJNIException with message
  'java.security.cert.CertificateException:
  java.security.cert.CertPathValidatorException: Trust anchor for
  certification path not found.

I found, that network security must be configured via adding android:networkSecurityConfig="@xml/network_security_config" into application section of AndroidManifest.template.xml file.

<application android:networkSecurityConfig="@xml/network_security_config"
    android:persistent="%persistent%"
    android:restoreAnyVersion="%restoreAnyVersion%"
    android:label="%label%"
    android:debuggable="%debuggable%"
    android:largeHeap="%largeHeap%"
    android:icon="%icon%"
    android:theme="%theme%"
    android:hardwareAccelerated="%hardwareAccelerated%"
    android:resizeableActivity="false">

Then I had to create res\xml\network_security_config.xml file with the similar contents:

<?xml version="1.0" encoding="utf-8"?> <network-security-config>
    <domain-config>
        <domain includeSubdomains="true">example.com</domain>
        <trust-anchors>
            <certificates src="@raw/my_ca"/>
        </trust-anchors>
    </domain-config> </network-security-config>

But where to place network_security_config.xml file. When I placed it in res folder inside Debug it was deleted during build. So it can not be found and app raises exception during packaging stage.

Error: E2312
  C:\Users\User\Documents\Embarcadero\Studio\Projects\Andr\Android\Debug\TabbedApplication\AndroidManifest.xml:19:
  error: Error: No resource found that matches the given name (at
  'networkSecurityConfig' with value '@xml/network_security_config').

I don't know, where to place it and give RAD Studio know, that it must grab this file on compile time.


答:
The first topic Topics vumika = new Topics(); is added every time to the topicsArrayList, by changing its name. So the last name is reflected. So, use the following :-

vumika.setTopicName("Adhunik Yug"); is the last name which is written to vumika

```<code>  Topics vumika = new Topics();
  vumika.setTopicName("Vumika");
  topicsArrayList.add(vumika);

  Topics prachin_yug = new Topics();
  prachin_yug.setTopicName("Prachin Yug");
  topicsArrayList.add(prachin_yug);

  Topics madhya_yug = new Topics();
  madhya_yug.setTopicName("Madhya Yug");
  topicsArrayList.add(madhya_yug);

  Topics adhunik_yug = new Topics();
  adhunik_yug.setTopicName("Adhunik Yug");
  topicsArrayList.add(adhunik_yug);
</code>```

Title: ListView showing only the last item in the first position of ListView

Body:
The first topic Topics vumika = new Topics(); is added every time to the topicsArrayList, by changing its name. So the last name is reflected. So, use the following :-

vumika.setTopicName("Adhunik Yug"); is the last name which is written to vumika

  Topics vumika = new Topics();
  vumika.setTopicName("Vumika");
  topicsArrayList.add(vumika);

  Topics prachin_yug = new Topics();
  prachin_yug.setTopicName("Prachin Yug");
  topicsArrayList.add(prachin_yug);

  Topics madhya_yug = new Topics();
  madhya_yug.setTopicName("Madhya Yug");
  topicsArrayList.add(madhya_yug);

  Topics adhunik_yug = new Topics();
  adhunik_yug.setTopicName("Adhunik Yug");
  topicsArrayList.add(adhunik_yug);


问:
ML Engine Runtime version and Python version not supported
I am trying to run Google clound ml-engine following this tutorial, when executing this command :

```<code>$ gcloud ml-engine jobs submit training `whoami`_object_detection_`date +%s` \
    --job-dir=gs://${YOUR_GCS_BUCKET}/train\
    --packages dist/object_detection-0.1.tar.gz,slim/dist/slim-0.1.tar.gz,/tmp/pycocotools/pycocotools-2.0.tar.gz\
    --module-name object_detection.model_tpu_main \
    --runtime-version 1.10\
    --scale-tier BASIC_TPU\
    --region us-central1\
    --
    --model_dir=gs://${YOUR_GCS_BUCKET}/train
    --tpu_zone us-central1
    --pipeline_config_path=gs://${YOUR_GCS_BUCKET}/data/pipeline.config
</code>```

commands which answers me :

```<code>  ERROR: (gcloud.ml-engine.jobs.submit.training) INVALID_ARGUMENT: Field: runtime_version Error: The specified runtime version '1.10' with the Python version '' is not supported for TPU training.  Please specify a different runtime version. See https://cloud.google.com/ml/docs/concepts/runtime-version-list for a list of supported versions
- '@type': type.googleapis.com/google.rpc.BadRequest
  fieldViolations:
  - description: The specified runtime version '1.10' with the Python version '' is
  not supported for TPU training.  Please specify a different runtime version.
  See https://cloud.google.com/ml/docs/concepts/runtime-version-list for a list
  of supported versions
field: runtime_version
</code>```

Because no version of python is detected, I added a --config=config.yaml argument to the command line:

config.yaml:

```<code>trainingInput:
  pythonVersion: "3.5"
</code>```

but the problem barely changed :

```<code>...
 - description: The specified runtime version '1.10' with the Python version '3.5'
...
</code>```

the runtime version list specify that runtime-version 1.10 is compatible with python 3.5, I also tried different runtime environement / python version which are required to work but my command keeps failling.

答:
For information the current supported  versions are now 1.11 or 1.12
runtime-version-list

Body:
I am trying to run Google clound ml-engine following this tutorial, when executing this command :

$ gcloud ml-engine jobs submit training `whoami`_object_detection_`date +%s` \
    --job-dir=gs://${YOUR_GCS_BUCKET}/train\
    --packages dist/object_detection-0.1.tar.gz,slim/dist/slim-0.1.tar.gz,/tmp/pycocotools/pycocotools-2.0.tar.gz\
    --module-name object_detection.model_tpu_main \
    --runtime-version 1.10\
    --scale-tier BASIC_TPU\
    --region us-central1\
    --
    --model_dir=gs://${YOUR_GCS_BUCKET}/train
    --tpu_zone us-central1
    --pipeline_config_path=gs://${YOUR_GCS_BUCKET}/data/pipeline.config

commands which answers me :

  ERROR: (gcloud.ml-engine.jobs.submit.training) INVALID_ARGUMENT: Field: runtime_version Error: The specified runtime version '1.10' with the Python version '' is not supported for TPU training.  Please specify a different runtime version. See https://cloud.google.com/ml/docs/concepts/runtime-version-list for a list of supported versions
- '@type': type.googleapis.com/google.rpc.BadRequest
  fieldViolations:
  - description: The specified runtime version '1.10' with the Python version '' is
  not supported for TPU training.  Please specify a different runtime version.
  See https://cloud.google.com/ml/docs/concepts/runtime-version-list for a list
  of supported versions
field: runtime_version

Because no version of python is detected, I added a --config=config.yaml argument to the command line:

config.yaml:

trainingInput:
  pythonVersion: "3.5"

but the problem barely changed :

...
 - description: The specified runtime version '1.10' with the Python version '3.5'
...

the runtime version list specify that runtime-version 1.10 is compatible with python 3.5, I also tried different runtime environement / python version which are required to work but my command keeps failling.


答:
There is copy paste mistake, only vumika is changing, Change like following

```<code> topics = new ArrayList<>();
        topicAdapter = new TopicAdapter(this, R.layout.list_item_row, topics);
        topicList.setAdapter(topicAdapter);

        //Array list to add the list items
        topicsArrayList = new ArrayList<>();

        Topics vumika = new Topics();
        vumika.setTopicName("Vumika");
        topicsArrayList.add(vumika);

        Topics prachin_yug = new Topics();
        prachin_yug.setTopicName("Prachin Yug");
        topicsArrayList.add(prachin_yug);

        Topics madhya_yug = new Topics();
        madhya_yug.setTopicName("Madhya Yug");
        topicsArrayList.add(madhya_yug);

        Topics adhunik_yug = new Topics();
        adhunik_yug.setTopicName("Adhunik Yug");
        topicsArrayList.add(adhunik_yug);
</code>```

Body:
There is copy paste mistake, only vumika is changing, Change like following

 topics = new ArrayList<>();
        topicAdapter = new TopicAdapter(this, R.layout.list_item_row, topics);
        topicList.setAdapter(topicAdapter);

        //Array list to add the list items
        topicsArrayList = new ArrayList<>();

        Topics vumika = new Topics();
        vumika.setTopicName("Vumika");
        topicsArrayList.add(vumika);

        Topics prachin_yug = new Topics();
        prachin_yug.setTopicName("Prachin Yug");
        topicsArrayList.add(prachin_yug);

        Topics madhya_yug = new Topics();
        madhya_yug.setTopicName("Madhya Yug");
        topicsArrayList.add(madhya_yug);

        Topics adhunik_yug = new Topics();
        adhunik_yug.setTopicName("Adhunik Yug");
        topicsArrayList.add(adhunik_yug);


问:
Angular 8: "could not find implementation for builder" when running ng serve
I just installed Angular 8. When I try to run a project with "ng serve --open" it gives me the following error:

```<code>
Could not find the implementation for builder @angular-devkit/build-angular:dev-server
Error: Could not  find the implementation for builder @angular-devkit/build-angular:dev-server
    at WorkspaceNodeModulesArchitectHost.resolveBuilder (C:\Users\manus\project\space-estate\webshop\frontend\client\node_modules\@angular\cli\node_modules\@angular-devkit\architect\node\node-modules-architect-host.js:49:19)
    at ServeCommand.initialize (C:\Users\manus\project\space-estate\webshop\frontend\client\node_modules\@angular\cli\models\architect-command.js:72:63)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:11)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)

</code>```

when I check the versions it gives me the following:

```<code>Angular CLI: 8.0.1
Node: 10.13.0
OS: win32 x64
Angular: 8.0.0
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.13.9
@angular-devkit/build-angular     0.13.9
@angular-devkit/build-optimizer   0.13.9
@angular-devkit/build-webpack     0.13.9
@angular-devkit/core              8.0.1
@angular-devkit/schematics        8.0.1 (cli-only)
@ngtools/webpack                  7.3.9
@schematics/angular               8.0.1 (cli-only)
@schematics/update                0.800.1 (cli-only)
rxjs                              6.5.2
typescript                        3.4.5
webpack                           4.29.0
</code>```

答:
If you are using Angular 8, you should ensure your Angular packages are safely updated to the current stable version by running the following command

```<code>ng update
</code>```

Otherwise, you can try to manually update the @angular/cli and core framework package manually.

```<code>ng update @angular/cli @angular/core
</code>```

Body:
I just installed Angular 8. When I try to run a project with "ng serve --open" it gives me the following error:

Could not find the implementation for builder @angular-devkit/build-angular:dev-server
Error: Could not  find the implementation for builder @angular-devkit/build-angular:dev-server
    at WorkspaceNodeModulesArchitectHost.resolveBuilder (C:\Users\manus\project\space-estate\webshop\frontend\client\node_modules\@angular\cli\node_modules\@angular-devkit\architect\node\node-modules-architect-host.js:49:19)
    at ServeCommand.initialize (C:\Users\manus\project\space-estate\webshop\frontend\client\node_modules\@angular\cli\models\architect-command.js:72:63)
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:11)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)

when I check the versions it gives me the following:

Angular CLI: 8.0.1
Node: 10.13.0
OS: win32 x64
Angular: 8.0.0
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.13.9
@angular-devkit/build-angular     0.13.9
@angular-devkit/build-optimizer   0.13.9
@angular-devkit/build-webpack     0.13.9
@angular-devkit/core              8.0.1
@angular-devkit/schematics        8.0.1 (cli-only)
@ngtools/webpack                  7.3.9
@schematics/angular               8.0.1 (cli-only)
@schematics/update                0.800.1 (cli-only)
rxjs                              6.5.2
typescript                        3.4.5
webpack                           4.29.0

Body:
If you are using Angular 8, you should ensure your Angular packages are safely updated to the current stable version by running the following command

ng update

Otherwise, you can try to manually update the @angular/cli and core framework package manually.

ng update @angular/cli @angular/core


问:
Bootstrap modal is not showing while clicking on update button using jquery
I am using jquery to update the data using bootstrap modal its not showing the modal i don't know why

This is my code for the modal

```<code><div id="updateModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
            </div>

            <div class="modal-body">
                    <div class="form-group">
                        <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" />
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="email" name="email" placeholder="Enter email" />
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="mob" name="mob" placeholder="Enter Mobile" />
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="city" name="city" placeholder="Enter City" />
                    </div>

                <a href="#" id="save" class="btn btn-success pull-right">Update</a>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
            </div>
        </div>
    </div>
</code>```

This is the jquery code :

```<code>    $(document).ready(function(){
       $(document).on('click','a[data-role=update]',function(){
          var id = $(this).data(id);
           var name = $('#'+id).children('td[data-target=name]').text();
           var email = $('#'+id).children('td[data-target=email]').text();
           var mob = $('#'+id).children('td[data-target=mob]').text();
           var city = $('#'+id).children('td[data-target=city]').text();

           $('#name').val(name);
           $('#email').val(email);
           $('#mob').val(mob);
           $('#city').val(city);
           $('#updateModal').modal('toggle');
       });
    });
</code>```

And this is the code for persons list to be updated :

```<code><div class="table">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Sr. No.</th>
                <th>Name</th>
                <th>Email</th>
                <th>Mobile</th>
                <th>City</th>
                <th>Action</th>
            </tr>
        </thead>

        <tbody>
            <?php while($row = mysqli_fetch_array($query)): $count++;?>
            <tr id="<?php echo $row['id'];?>">
                <td><?php echo $count;?></td>
                <td data-target="name"><?php echo $row['name'];?></td>
                <td data-target="email"><?php echo $row['email'];?></td>
                <td data-target="mob"><?php echo $row['mob'];?></td>
                <td data-target="city"><?php echo $row['city'];?></td>
                <td><a href="#" class="btn btn-success btn-sm" data-role="update" data-id="<?php echo $row['id'];?>">Update</a></td>
            </tr>
            <?php endwhile;?>
        </tbody>

    </table>
</div>
</code>```

By writing upto this i expect that the modal should pop-up and displays the information in the input fields but while I'm clicking on the update button the modal doesn't pop-ups.

Any help should be appreciated.

答:
You have a mistake in your script.You just missed a quote

please replace the below line

```<code>var id = $(this).data('id');
</code>```

Body:
I am using jquery to update the data using bootstrap modal its not showing the modal i don't know why

This is my code for the modal

                <button type="button" class="close" data-dismiss="modal">×</button>

                        <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" />

                        <input type="text" class="form-control" id="email" name="email" placeholder="Enter email" />

                        <input type="text" class="form-control" id="mob" name="mob" placeholder="Enter Mobile" />

                        <input type="text" class="form-control" id="city" name="city" placeholder="Enter City" />

                Update

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

This is the jquery code :

    $(document).ready(function(){
       $(document).on('click','a[data-role=update]',function(){
          var id = $(this).data(id);
           var name = $('#'+id).children('td[data-target=name]').text();
           var email = $('#'+id).children('td[data-target=email]').text();
           var mob = $('#'+id).children('td[data-target=mob]').text();
           var city = $('#'+id).children('td[data-target=city]').text();

           $('#name').val(name);
           $('#email').val(email);
           $('#mob').val(mob);
           $('#city').val(city);
           $('#updateModal').modal('toggle');
       });
    });

And this is the code for persons list to be updated :

                Sr. No.
                Name
                Email
                Mobile
                City
                Action

            <?php while($row = mysqli_fetch_array($query)): $count++;?>
            <tr id="<?php echo $row['id'];?>">
                <?php echo $count;?>
                <?php echo $row['name'];?>
                <?php echo $row['email'];?>
                <?php echo $row['mob'];?>
                <?php echo $row['city'];?>
                <a href="#" class="btn btn-success btn-sm" data-role="update" data-id="<?php echo $row['id'];?>">Update

            <?php endwhile;?>

By writing upto this i expect that the modal should pop-up and displays the information in the input fields but while I'm clicking on the update button the modal doesn't pop-ups.

Any help should be appreciated.

Body:
You have a mistake in your script.You just missed a quote

please replace the below line

var id = $(this).data('id');


问:
parse parenthesized numbers to negative numbers
How can i Parse parenthesized numbers in a list of strings  to negative numbers (or strings with negative sign).

example

```<code>input
list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']

output
['abcd',-1234,'Level-2 (2):','-31%', 'others','-3102.2%']
</code>```

strings only with numbers inside parenthesis or numbers with comma/dot inside parenthesis followed by a percentage(%) sign, should be parsed . other strings such as 'Level-2 (2):' should not be parsed.

I have tried

```<code>translator = str.maketrans(dict.fromkeys('(),'))
['-'+(x.translate(translator)) for x in list1]
</code>```

but the output is (every element has a - appended)

```<code>['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']
</code>```

Body:
How can i Parse parenthesized numbers in a list of strings  to negative numbers (or strings with negative sign).

example

input
list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']

output
['abcd',-1234,'Level-2 (2):','-31%', 'others','-3102.2%']

strings only with numbers inside parenthesis or numbers with comma/dot inside parenthesis followed by a percentage(%) sign, should be parsed . other strings such as 'Level-2 (2):' should not be parsed.

I have tried

translator = str.maketrans(dict.fromkeys('(),'))
['-'+(x.translate(translator)) for x in list1]

but the output is (every element has a - appended)

['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']

Body:
for item in list1:
    idx = list1.index(item)
    list1[idx] = '-' + list1[idx].replace('(','').replace(')','').replace(',','')

print (list1)

output:

['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']

or just:

list1= ['abcd','(1,234)','Level-2 (2):','(31)%', 'others','(3,102.2)%']

print (['-' + item.replace('(','').replace(')','').replace(',','') for item in list1])

output:

['-abcd', '-1234', '-Level-2 2:', '-31%', '-others', '-3102.2%']


问:
Spring request scope bean
How can I set up a bean which will created once per request.

I Tried to do like this :

```<code>   @Component
   @Scope(value = "request")
   public class TestBean {
        @PostConstruct
        public void init() {
             System.out.println("start request");
        }

        @PreDestroy
        public void onDestroy() {
             System.out.println("ends request");
        }
   }
</code>```

Thanks.

答:
You can set your bean to request scope by xml configuration as

```<code> <bean id="testBean" class="com.test.TestBean" scope="request">
    <aop:scoped-proxy/>
  </bean>
</code>```

Tag aop:scoped-proxy  will be used to inject your bean using proxy. This is xml based way to set your bean to request scope.

Title: Spring request scope bean

Body:
How can I set up a bean which will created once per request.

I Tried to do like this :

   @Component
   @Scope(value = "request")
   public class TestBean {
        @PostConstruct
        public void init() {
             System.out.println("start request");
        }

        @PreDestroy
        public void onDestroy() {
             System.out.println("ends request");
        }
   }

Thanks.

Body:
You can set your bean to request scope by xml configuration as

 <bean id="testBean" class="com.test.TestBean" scope="request">
    <aop:scoped-proxy/>
  </bean>

Tag aop:scoped-proxy  will be used to inject your bean using proxy. This is xml based way to set your bean to request scope.


问:
Set selected item of spinner programmatically
I am working on an android project and I am using a spinner which uses an array adapter which is populated from the database.

I can't find out how I can set the selected item programmatically from the list. For example if, in the spinner I have the following items:

Category 1

Category 2

Category 3

How would I programmatically make Category 2 the selected item when the screen is created. I was thinking it might be similar to c# I.E Spinner.SelectedText = "Category 2" but there doesn't seem to be any method similar to this for Android.

答:
I had the same issue since yesterday.Unfortunately the first item in the array list is shown by default in spinner widget.A turnaround would be to find the previous selected item with each element in the array list and swap its position with the first element.Here is the code.</p>

```<code>OnResume()
{
int before_index = ShowLastSelectedElement();
if (isFound){
      Collections.swap(yourArrayList,before_index,0);
   }
adapter = new ArrayAdapter<String>(CurrentActivity.this,
                            android.R.layout.simple_spinner_item, yourArrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item;                    yourListView.setAdapter(adapter);
}
...
private int ShowLastSelectedElement() {
        String strName = "";
        int swap_index = 0;
        for (int i=0;i<societies.size();i++){
            strName = yourArrayList.get(i);
            if (strName.trim().toLowerCase().equals(lastselectedelement.trim().toLowerCase())){
                swap_index = i;
                isFound = true;
            }
        }
        return swap_index;
    }
</code>```

Body:
I had the same issue since yesterday.Unfortunately the first item in the array list is shown by default in spinner widget.A turnaround would be to find the previous selected item with each element in the array list and swap its position with the first element.Here is the code.

OnResume()
{
int before_index = ShowLastSelectedElement();
if (isFound){
      Collections.swap(yourArrayList,before_index,0);
   }
adapter = new ArrayAdapter<String>(CurrentActivity.this,
                            android.R.layout.simple_spinner_item, yourArrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item;                    yourListView.setAdapter(adapter);
}
...
private int ShowLastSelectedElement() {
        String strName = "";
        int swap_index = 0;
        for (int i=0;i<societies.size();i++){
            strName = yourArrayList.get(i);
            if (strName.trim().toLowerCase().equals(lastselectedelement.trim().toLowerCase())){
                swap_index = i;
                isFound = true;
            }
        }
        return swap_index;
    }


问:
Decimal numbers get round up while formatting python
Here is what I have tried:

```<code>>>> pi = 3.14159265
>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.1f') #print 3.1
'3.1'
>>> format(pi, '.10f') #print 3.1415926500, more precision than the original
'3.1415926500'
>>> format(pi, '.5f') #print 3.14159, more precision than the original
'3.14159'
>>> format(pi, '.4f')
'3.1416'
</code>```

The concern part is this:

```<code>>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.4f')
'3.1416'
</code>```

Where I was expecting to have 3.1415, I am getting 3.1416. Please suggest me.

The SO is showing these 2 links:

http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate

http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary

But these are not the one I am looking for.

答:
It's because it is rounding it, so it is just like the round function.

To fix it:

```<code>>>> l = str(pi).split('.')
>>> l[0] + '.' + l[1][:4]
'3.1415'
>>> float(l[0] + '.' + l[1][:4])
3.1415
</code>```

A function version of it:

```<code>def first_n(a, b):
    l = str(a).split('.')
    return int(l[0] + '.' + l[1][:b])
</code>```

And now:

```<code>print(first_n(pi, 4))
</code>```

Gives:

```<code>3.1415
</code>```

Body:
Here is what I have tried:

>>> pi = 3.14159265
>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.1f') #print 3.1
'3.1'
>>> format(pi, '.10f') #print 3.1415926500, more precision than the original
'3.1415926500'
>>> format(pi, '.5f') #print 3.14159, more precision than the original
'3.14159'
>>> format(pi, '.4f')
'3.1416'

The concern part is this:

>>> format(pi, '.3f') #print 3.142 # 3 precision after the decimal point
'3.142'
>>> format(pi, '.4f')
'3.1416'

Where I was expecting to have 3.1415, I am getting 3.1416. Please suggest me.

The SO is showing these 2 links:

http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate

http://stackoverflow.com/questions/1089018/why-cant-decimal-numbers-be-represented-exactly-in-binary

But these are not the one I am looking for.

Body:
It's because it is rounding it, so it is just like the round function.

To fix it:

>>> l = str(pi).split('.')
>>> l[0] + '.' + l[1][:4]
'3.1415'
>>> float(l[0] + '.' + l[1][:4])
3.1415

A function version of it:

def first_n(a, b):
    l = str(a).split('.')
    return int(l[0] + '.' + l[1][:b])

And now:

print(first_n(pi, 4))

Gives:

3.1415


问:
Selenium ChromeDriver - the HTTP request to the remote WebDriver server for URL timed out after 60 seconds
I am using the ChromeDriver in an nunit test to test whether a complex page loads:

```<code>public ChromeDriver Driver { get; private set; }

 [OneTimeSetUp]
    public void Setup()
    {
        ChromeOptions co = new ChromeOptions{};
        co.AddArgument("no-sandbox");
        Driver = new ChromeDriver( co) ;
        Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(120);
        Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(120);
        Driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(120);
        Driver.Manage().Window.Maximize();
    }
</code>```

As you can see I have tried to increase timeouts to 2 miutes everywhere yet when I run

```<code>Driver.Navigate().GoToUrl(url);
</code>```

against the page I get

```<code>OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL timed out after 60 seconds.
</code>```

The page does take longer than 60 seconds to load,  So how do I increase the 60 seconds ?

答:
You need to increase the DefaultCommandTimeout in RemoteWebDriver. You can do it by using the ChromeDriver(ChromeDriverService, ChromeOptions, TimeSpan) or ChromeDriver(string, ChromeOptions, TimeSpan) overloads

```<code>ChromeOptions co = new ChromeOptions{};

Driver = new ChromeDriver("path to ChromeDriver.exe", co, TimeSpan.FromSeconds(120));
// or
Driver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), co, TimeSpan.FromSeconds(120));
</code>```

Body:
I am using the ChromeDriver in an nunit test to test whether a complex page loads:

public ChromeDriver Driver { get; private set; }

 [OneTimeSetUp]
    public void Setup()
    {
        ChromeOptions co = new ChromeOptions{};
        co.AddArgument("no-sandbox");
        Driver = new ChromeDriver( co) ;
        Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(120);
        Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(120);
        Driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(120);
        Driver.Manage().Window.Maximize();
    }

As you can see I have tried to increase timeouts to 2 miutes everywhere yet when I run

Driver.Navigate().GoToUrl(url);

against the page I get

OpenQA.Selenium.WebDriverException : The HTTP request to the remote WebDriver server for URL timed out after 60 seconds.

The page does take longer than 60 seconds to load,  So how do I increase the 60 seconds ?

Body:
You need to increase the DefaultCommandTimeout in RemoteWebDriver. You can do it by using the ChromeDriver(ChromeDriverService, ChromeOptions, TimeSpan) or ChromeDriver(string, ChromeOptions, TimeSpan) overloads

ChromeOptions co = new ChromeOptions{};

Driver = new ChromeDriver("path to ChromeDriver.exe", co, TimeSpan.FromSeconds(120));
// or
Driver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), co, TimeSpan.FromSeconds(120));


问:
Displaying action sheet when tableview cell is tapped
Then I am trying to call action sheet when cell is tapped, and this is what I did

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let alertController = UIAlertController(title: "Action Sheet", message: "What do you like to do", preferredStyle: .alert)

        let okButton = UIAlertAction(title: "Done", style: .default, handler: { (action) -> Void in
            print("Ok button tapped")
        })

        let deleteButton = UIAlertAction(title: "Skip", style: .destructive, handler: { (action) -> Void in
            print("Delete button tapped")
        })

    alertController.addAction(okButton)
}
</code>```

When i am tapping cell, alert controller is not showing up. What am I missing?

答:
We create a function didSelectContact, and use func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) to handle selected Cell in tableview. If each cell tapped this action sheet will open.

```<code>func didSelectContact(){

    let alert = UIAlertController(title: "Choose Once", message: "What you want do with contact", preferredStyle: UIAlertControllerStyle.actionSheet)
    let call = UIAlertAction(title: "Call", style: UIAlertActionStyle.default) { (UIAlertAction) in
    }
    let sms = UIAlertAction(title: "SMS", style: UIAlertActionStyle.default) { (UIAlertAction) in

    }
    let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)

    alert.addAction(call)
    alert.addAction(sms)
    alert.addAction(cancel)

    self.present(alert, animated: true, completion: nil)
}

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
  IndexPath) {

    self.didSelectContact()
}
</code>```

Body:
Then I am trying to call action sheet when cell is tapped, and this is what I did

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let alertController = UIAlertController(title: "Action Sheet", message: "What do you like to do", preferredStyle: .alert)

        let okButton = UIAlertAction(title: "Done", style: .default, handler: { (action) -> Void in
            print("Ok button tapped")
        })

        let deleteButton = UIAlertAction(title: "Skip", style: .destructive, handler: { (action) -> Void in
            print("Delete button tapped")
        })

    alertController.addAction(okButton)
}

When i am tapping cell, alert controller is not showing up. What am I missing?

Body:
We create a function didSelectContact, and use func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) to handle selected Cell in tableview. If each cell tapped this action sheet will open.

func didSelectContact(){

    let alert = UIAlertController(title: "Choose Once", message: "What you want do with contact", preferredStyle: UIAlertControllerStyle.actionSheet)
    let call = UIAlertAction(title: "Call", style: UIAlertActionStyle.default) { (UIAlertAction) in
    }
    let sms = UIAlertAction(title: "SMS", style: UIAlertActionStyle.default) { (UIAlertAction) in

    }
    let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)

    alert.addAction(call)
    alert.addAction(sms)
    alert.addAction(cancel)

    self.present(alert, animated: true, completion: nil)
}

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
  IndexPath) {

    self.didSelectContact()
}


问:
Question about linq2sql
I have some legacy code with linq2sql classes. DataContext class has following definition for stored procedure:

```<code> [Function(Name="dbo.sp_Goods_SelectBySection")]
        public ISingleResult<sp_Goods_SelectBySectionResult> sp_Goods_SelectBySection([Parameter(Name="SectionId", DbType="Int")] System.Nullable<int> sectionId)
        {
            IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), sectionId);
            return ((ISingleResult<sp_Goods_SelectBySectionResult>)(result.ReturnValue));
        }
</code>```

But when i am trying create same procedure in my own project, designer creating procedure with different implementation:

```<code>[Function(Name="dbo.sp_Goods_SelectBySection")]
        public int sp_Goods_SelectBySection([Parameter(Name="SectionId", DbType="Int")] System.Nullable<int> sectionId)
        {
            IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), sectionId);
            return ((int)(result.ReturnValue));
        }
</code>```

And i cannt change type in method properties.

Here is code of stored procedure.

```<code>ALTER PROCEDURE [dbo].[sp_Goods_SelectBySection]
(
    @SectionId INT
)
AS
BEGIN

    SET NOCOUNT ON;

    SELECT
        Goods.Id,
        Goods.[Name],
        TypeId,
        Makerid,
        Price,
        [Description],
        Term,
        Types.Name AS TypeName,
        Makers.Name AS MakerName,
        GoodsImage.SmallImageUrl AS MainImageUrl,
        Goods.IsDeleted,
        Goods.Rang
    FROM Goods
         INNER JOIN Types ON (Types.Id = Goods.TypeId)
         INNER JOIN Makers ON (Makers.Id = Goods.MakerId)
         LEFT JOIN GoodsImage ON ( GoodsImage.GoodId = Goods.Id AND GoodsImage.IsMain = 1 AND GoodsImage.IsDeleted = 0 )
    WHERE
        Types.SectionId = @SectionId
        AND Goods.IsDeleted  = 0
    ORDER BY Rang ASC
END
</code>```

Why? And how i can create procedure which returning ISingleResult instead of int?

Note i have many such procedures and modify by hand each of them is not good idea i think.

I guess it's designer problem. Because i created new test project and it work ok. Thanks to all who helped me. Especially to Andras Zoltan.

答:
Sorry, slightly misunderstood your question but I'll keep my initial comments

Remember that stored procedures return a result set, not a value; unless you count the value returned in a return statement.  Therefore you need a type to wrap around the columns and rows that are returned.

You can change the return type to a table if you know the SP returns a rowset that maps to one of your table types.  But you are not going to be able to just return 'an int'.

See this link: http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/1667a989-08a0-402c-9358-e4637406a75f (sorry it's over on MSDN forums - not SO :$) and the linked topic from that http://msdn.microsoft.com/en-us/library/bb386975.aspx

Update

L2S uses the equivalent of SQL reflection to figure what an SP returns in order to auto-generate the result.

If the SP doesn't SELECT, or if it only has a RETURN in it, you will get a basic int return type for your mapped function.  This kind of thing can happen legitimately or erroneously if the SP uses IF statements to fork and return different results accordingly; L2S cannot possibly figure out a single return type that can satisfy all possible outcomes, and so it just plumps for one of them.

As @JohnOpincar mentions in his comments, there is a question mark over whether the SP you've posted here is actually the one you've mapped - since the names are not the same?  My guess is that you've dragged on the wrong SP - and that's only got a RETURN in it, or it returns multiple things and L2S has borked.

Update 2

Okay - so you've changed the names in the source.  My recommendation is to delete the SP from the L2S designer (and any other manual attempt you may have for this SP), and drag it back on again from the Server Explorer, making sure it's the same server/db you drag it from.  With the SQL you've posted, L2S will most definitely be able to figure out what the result set is as it's very simple.

Title: Question about linq2sql

Body:
I have some legacy code with linq2sql classes. DataContext class has following definition for stored procedure:

 [Function(Name="dbo.sp_Goods_SelectBySection")]
        public ISingleResult<sp_Goods_SelectBySectionResult> sp_Goods_SelectBySection([Parameter(Name="SectionId", DbType="Int")] System.Nullable<int> sectionId)
        {
            IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), sectionId);
            return ((ISingleResult<sp_Goods_SelectBySectionResult>)(result.ReturnValue));
        }

But when i am trying create same procedure in my own project, designer creating procedure with different implementation:

[Function(Name="dbo.sp_Goods_SelectBySection")]
        public int sp_Goods_SelectBySection([Parameter(Name="SectionId", DbType="Int")] System.Nullable<int> sectionId)
        {
            IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), sectionId);
            return ((int)(result.ReturnValue));
        }

And i cannt change type in method properties.

Here is code of stored procedure.

ALTER PROCEDURE [dbo].[sp_Goods_SelectBySection]
(
    @SectionId INT
)
AS
BEGIN

    SET NOCOUNT ON;

    SELECT
        Goods.Id,
        Goods.[Name],
        TypeId,
        Makerid,
        Price,
        [Description],
        Term,
        Types.Name AS TypeName,
        Makers.Name AS MakerName,
        GoodsImage.SmallImageUrl AS MainImageUrl,
        Goods.IsDeleted,
        Goods.Rang
    FROM Goods
         INNER JOIN Types ON (Types.Id = Goods.TypeId)
         INNER JOIN Makers ON (Makers.Id = Goods.MakerId)
         LEFT JOIN GoodsImage ON ( GoodsImage.GoodId = Goods.Id AND GoodsImage.IsMain = 1 AND GoodsImage.IsDeleted = 0 )
    WHERE
        Types.SectionId = @SectionId
        AND Goods.IsDeleted  = 0
    ORDER BY Rang ASC
END

Why? And how i can create procedure which returning ISingleResult instead of int?

Note i have many such procedures and modify by hand each of them is not good idea i think.

I guess it's designer problem. Because i created new test project and it work ok. Thanks to all who helped me. Especially to Andras Zoltan.


问:
Building .net-core apps with 3rd party libraries
I have a dot net core console app that I want to package up as a .exe and distribute to colleagues.

As all the users of the product are on Windows 10 I build the project using

```<code>dotnet build -r win10-x64
</code>```

This is great in that it gives a small deployment package. Now that I have introduced 3rd party libraries (via nuget) I have a problem in that they are not included in the build output.

Is there a way to build a dot net core project as a .exe, including 3rd party libraries but not all the dot net libraries?

Solution Found

Following @turobo's lead from below, I ended up with the following:

```<code>dotnet publish  -r win10-x64  -c Release --self-contained false
</code>```

答:
You are almost there. You need to use "dotnet publish" command to create a dotnet package. In dotnet core, the build command is not supposed to create a package that is distributable.

Excerpt from dotnet build reference:

If the project has third-party dependencies, such as libraries from
  NuGet, they're resolved from the NuGet cache and aren't available with
  the project's built output. With that in mind, the product of dotnet
  build isn't ready to be transferred to another machine to run. This is
  in contrast to the behavior of the .NET Framework in which building an
  executable project (an application) produces output that's runnable on
  any machine where the .NET Framework is installed. To have a similar
  experience with .NET Core, you need to use the dotnet publish command.
  For more information, see .NET Core Application Deployment.

What you are looking for is Framework-dependent executables (FDE). Excerpt from here:

Framework-dependent executables. Produces an executable that runs on a
  target platform. Similar to FDDs, framework-dependent executables
  (FDE) are platform-specific and aren't self-contained. These
  deployments still rely on the presence of a shared system-wide version
  of .NET Core to run. Unlike an SCD, your app only contains your code
  and any third-party dependencies that are outside of the .NET Core
  libraries. FDEs produce an executable that runs on the target
  platform.

This should work:

```<code>dotnet publish -r win10-x64
</code>```

Body:
I have a dot net core console app that I want to package up as a .exe and distribute to colleagues.

As all the users of the product are on Windows 10 I build the project using

dotnet build -r win10-x64

This is great in that it gives a small deployment package. Now that I have introduced 3rd party libraries (via nuget) I have a problem in that they are not included in the build output.

Is there a way to build a dot net core project as a .exe, including 3rd party libraries but not all the dot net libraries?

Solution Found

Following @turobo's lead from below, I ended up with the following:

dotnet publish  -r win10-x64  -c Release --self-contained false

Body:
You are almost there. You need to use "dotnet publish" command to create a dotnet package. In dotnet core, the build command is not supposed to create a package that is distributable.

Excerpt from dotnet build reference:

If the project has third-party dependencies, such as libraries from
  NuGet, they're resolved from the NuGet cache and aren't available with
  the project's built output. With that in mind, the product of dotnet
  build isn't ready to be transferred to another machine to run. This is
  in contrast to the behavior of the .NET Framework in which building an
  executable project (an application) produces output that's runnable on
  any machine where the .NET Framework is installed. To have a similar
  experience with .NET Core, you need to use the dotnet publish command.
  For more information, see .NET Core Application Deployment.

What you are looking for is Framework-dependent executables (FDE). Excerpt from here:

Framework-dependent executables. Produces an executable that runs on a
  target platform. Similar to FDDs, framework-dependent executables
  (FDE) are platform-specific and aren't self-contained. These
  deployments still rely on the presence of a shared system-wide version
  of .NET Core to run. Unlike an SCD, your app only contains your code
  and any third-party dependencies that are outside of the .NET Core
  libraries. FDEs produce an executable that runs on the target
  platform.

This should work:

dotnet publish -r win10-x64


问:
How to install an application to SD card of the Android emulator rather than its internal memory?
I can't find a way to install my app to SD card, nor move it post-installation through the emulator's Android settings UI. I do have installLocation=auto in the manifest, also tried preferExternal. Is this at all doable?

There's this old question, but the accepted answer no longer works:

```<code>adb install -s .\app-debug.apk
Performing Streamed Install
adb: failed to install .\app-debug.apk:
Exception occurred while executing:
java.lang.IllegalArgumentException: New installs into ASEC containers no longer supported
</code>```

This is with Android 9 Google Services x86_64 image.

答:
According to the link you could use

```<code>set-install-location location
</code>```

Where location is

0: Auto: Let system decide the best location.

1: Internal: install on    internal device storage.

2: External: on external media.

Body:
I can't find a way to install my app to SD card, nor move it post-installation through the emulator's Android settings UI. I do have installLocation=auto in the manifest, also tried preferExternal. Is this at all doable?

There's this old question, but the accepted answer no longer works:

adb install -s .\app-debug.apk
Performing Streamed Install
adb: failed to install .\app-debug.apk:
Exception occurred while executing:
java.lang.IllegalArgumentException: New installs into ASEC containers no longer supported

This is with Android 9 Google Services x86_64 image.

Body:
According to the link you could use

set-install-location location

Where location is

0: Auto: Let system decide the best location.

1: Internal: install on    internal device storage.

2: External: on external media.


问:
Gradient color in CSS with percentage
I have only basic knowledge on the CSS. I'm trying to give gradient color for one of my ITEM as per below guidelines and the gradient should be vertical.

I tried the below , but only the first color is coming all over the region. I dont understand that 30% and 50%. How to achieve this?

```<code> .myheader {
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);
  }
</code>```

答:
 .myheader {
  width: 100px;
  height: 100px;
  background: linear-gradient(to bottom, blue 15%, purple 45%, red 90%);
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myheader"></div></code>```

The to bottom direction tells you that your gradient is going from top to bottom. So if the first color is 85%, that means that it goes down to 85% of the height of the container.

By inverting the percentage (85% -> 15%), you can achieve the result you want.

Title: Gradient color in CSS with percentage

Body:
I have only basic knowledge on the CSS. I'm trying to give gradient color for one of my ITEM as per below guidelines and the gradient should be vertical.

I tried the below , but only the first color is coming all over the region. I dont understand that 30% and 50%. How to achieve this?

 .myheader {
  background: linear-gradient(to bottom, #mycolor1 85%, #mycolor2 45%, #mycolor3 10%);
  }

Body:
 .myheader {
  width: 100px;
  height: 100px;
  background: linear-gradient(to bottom, blue 15%, purple 45%, red 90%);
 }

<div class="myheader"></div>

The to bottom direction tells you that your gradient is going from top to bottom. So if the first color is 85%, that means that it goes down to 85% of the height of the container.

By inverting the percentage (85% -> 15%), you can achieve the result you want.


问:
Is there any way to add extension on Project Explorer to create new wizard project?

Is it possible to add my specific project wizard under "Create a project..." part?

I added for right click "new" like this

```<code><extension point="org.eclipse.ui.navigator.navigatorContent">
  <commonWizard
          type="new"
          wizardId="com.XXX.projectWizard">
          <enablement></enablement>
  </commonWizard>
  </extension>
</code>```

答:
The view will add 'Create new xxxx' lines at the start of this list for new project wizards which are declared as a newWizardShortcut for the current perspective using the org.eclipse.ui.perspectiveExtensions extension point.

```<code><extension point="org.eclipse.ui.perspectiveExtensions">
    <perspectiveExtension
        targetID="org.eclipse.ui.resourcePerspective">
        <newWizardShortcut id="org.eclipse.jdt.ui.wizards.NewProjectCreationWizard"/>
</code>```

The new wizard must be a project wizard.

This also adds the wizard to the top level of the 'New' menu in the projects section.

Body:
Is it possible to add my specific project wizard under "Create a project..." part?

I added for right click "new" like this

<extension point="org.eclipse.ui.navigator.navigatorContent">
  <commonWizard
          type="new"
          wizardId="com.XXX.projectWizard">
          <enablement></enablement>
  </commonWizard>
  </extension>

Body:
The view will add 'Create new xxxx' lines at the start of this list for new project wizards which are declared as a newWizardShortcut for the current perspective using the org.eclipse.ui.perspectiveExtensions extension point.

<extension point="org.eclipse.ui.perspectiveExtensions">
    <perspectiveExtension
        targetID="org.eclipse.ui.resourcePerspective">
        <newWizardShortcut id="org.eclipse.jdt.ui.wizards.NewProjectCreationWizard"/>

The new wizard must be a project wizard.

This also adds the wizard to the top level of the 'New' menu in the projects section.


问:
When I open the Excel it runs the macro and change the date saved
Am doing a macro in a check box (Form Control), the main idea is when I check the check box in the next cell it saves the date of the day I marked the checkbox. But instead if I save the check box with the mark it gets updated when I open the document, erasing the saved date and updating today's date.

I've tried 2 ifs and Errors GoTo Err and doesn't work

this is the code I have:

```<code>If ActiveSheet.Shapes("Check Box 2").ControlFormat.Value = 1 Then

cells(6, 5).Value = Date

Else

 Range("E6").ClearContents

End If
</code>```

I need to put some code that stops the actualization. Or it tells the macro that when the check box is mark doesn't have to update the date.

答:
If the intent is to store the date of last marking the checkbox you could simply make a value copy, a very basic example:</p>

```<code>Sub CheckBox1_Click()

'cell A1 = linked cell to check box
'Cell A2 contains formula today()
'cell A3 target cell overwritten on marking check box

Select Case Sheets("Sheet1").Range("A1")

Case True

Sheets("Sheet1").Range("A2").Copy
Sheets("Sheet1").Range("A3").PasteSpecial Paste:=xlPasteValues

End Select

End Sub
</code>```

Body:
Am doing a macro in a check box (Form Control), the main idea is when I check the check box in the next cell it saves the date of the day I marked the checkbox. But instead if I save the check box with the mark it gets updated when I open the document, erasing the saved date and updating today's date.

I've tried 2 ifs and Errors GoTo Err and doesn't work

this is the code I have:

If ActiveSheet.Shapes("Check Box 2").ControlFormat.Value = 1 Then

cells(6, 5).Value = Date

Else

 Range("E6").ClearContents

End If

I need to put some code that stops the actualization. Or it tells the macro that when the check box is mark doesn't have to update the date.

Body:
If the intent is to store the date of last marking the checkbox you could simply make a value copy, a very basic example:

Sub CheckBox1_Click()

'cell A1 = linked cell to check box
'Cell A2 contains formula today()
'cell A3 target cell overwritten on marking check box

Select Case Sheets("Sheet1").Range("A1")

Case True

Sheets("Sheet1").Range("A2").Copy
Sheets("Sheet1").Range("A3").PasteSpecial Paste:=xlPasteValues

End Select

End Sub