问:
Compare two list to sort the second list
I would like to compare two lists, if the value of the first list corresponds to the code of the second list, it would be necessary that the second list is sorted according to the values compared

First list :

```<code>      var List1 = [{id : "idValue2"}, {id : "idValue5"}]
</code>```

Second List (before sorting)

```<code>     var List2 = [
                  {code : "idValue1", label: "value1"},
                  {code : "idValue2", label: "value2"},
                  {code : "idValue3", label: "value3"},
                  {code : "idValue4", label: "value4"};
                  {code : "idValue5", label: "value5"}]
</code>```

After comparing list1 ids and list2 codes would get list2 sorted

Second List (after sorting)

```<code>     var List2 = [
                  {code : "idValue2", label: "value2"},
                  {code : "idValue5", label: "value5"}
                  {code : "idValue1", label: "value1"},
                  {code : "idValue3", label: "value3"},
                  {code : "idValue4", label: "value4"}]
</code>```

Here idValue2 and idValue5 take  the first places.

Do you have a solution ?

答:
Try like this. just a filter and some will get you the desired arrays finally concat both arrays

var List1 = [{id : "idValue2"}, {id : "idValue5"}]

var List2 = [
   {code : "idValue1", label: "value1"},
   {code : "idValue2", label: "value2"},
   {code : "idValue3", label: "value3"},
   {code : "idValue4", label: "value4"},
   {code : "idValue5", label: "value5"}
]

var a = List2.filter(x=> ( List1.some(y=> { return y.id == x.code }) ));

var b = List2.filter(x=> ( !List1.some(y=> { return y.id == x.code }) ))

var list3 = a.concat(b);

console.log(list3);```

Body:
I would like to compare two lists, if the value of the first list corresponds to the code of the second list, it would be necessary that the second list is sorted according to the values compared

First list :

      var List1 = [{id : "idValue2"}, {id : "idValue5"}]

Second List (before sorting)

     var List2 = [
                  {code : "idValue1", label: "value1"},
                  {code : "idValue2", label: "value2"},
                  {code : "idValue3", label: "value3"},
                  {code : "idValue4", label: "value4"};
                  {code : "idValue5", label: "value5"}]

After comparing list1 ids and list2 codes would get list2 sorted

Second List (after sorting)

     var List2 = [
                  {code : "idValue2", label: "value2"},
                  {code : "idValue5", label: "value5"}
                  {code : "idValue1", label: "value1"},
                  {code : "idValue3", label: "value3"},
                  {code : "idValue4", label: "value4"}]

Here idValue2 and idValue5 take  the first places.

Do you have a solution ?


来源: stackexchange

问:
Problems after upgrading to Xcode 10: Build input file cannot be found
I upgraded my Xcode SDK to version 10 last night and then find I cannot build.

I'm getting this error:

Build input file cannot be found:
  '/Users/call01/Library/Developer/Xcode/DerivedData/Comp-Lite-Apps-gytvmossqptokeafrddvvmnlzadk/Build/Products/Debug-iphoneos/SG11.app/SG11

which did not exist before my upgrade and I'm tempted to revert back but would like to stick with version 10 if I can resolve this issue.

答:
None of the above worked for me, but this did:

Open project in Finder, right click on your .xcodeproj file and show package contents

Open project.pbxproj in a text editor

Find the reference to your missing file

Edit path = "path/to/file.swift" to the actual location on disk and save the file.

Rebuild the project

ContentLicense: CC BY-SA 4.0


问:
How can I delete specific files in a folder but not the sub folders?
I have a huge folder structure and I want to delete some specific files only from main folders and leave sub folders intact.

Example:

```<code>Folder A/Sub-folderB/
</code>```

Now , I want to delete files from Folder A ONLY , and this should continue until the last folder N.

This is the code i have tried ,

```<code>Get-Childitem C:\serverfolders\users\* | Where-Object {-Not $_.PSIsContainer} | Foreach-Object {Remove-Item $_.FullName}
</code>```

Any help would be greatly appreciated.

答:
Just add "-File" option :)

```<code>  Get-Childitem C:\serverfolders\users -File | Remove-Item -force
</code>```

You can read more on Get-ChildItem help on MS

Body:
I have a huge folder structure and I want to delete some specific files only from main folders and leave sub folders intact.

Example:

Folder A/Sub-folderB/

Now , I want to delete files from Folder A ONLY , and this should continue until the last folder N.

This is the code i have tried ,

Get-Childitem C:\serverfolders\users\* | Where-Object {-Not $_.PSIsContainer} | Foreach-Object {Remove-Item $_.FullName}

Any help would be greatly appreciated.

Body:
Just add "-File" option :)

  Get-Childitem C:\serverfolders\users -File | Remove-Item -force

You can read more on Get-ChildItem help on MS


问:
Unity: Could not allocate memory: System out of memory! Memorylabel Texture
I know a lot of people get this issue but I have a hard time getting it fixed. Partly because this is my first Unity game.

So it is a 2d Android game using Unity 5.5.2f1 and I get the error when I try out my build. Note that this is my first build despite the game being 95% complete. I got stuck on building the APK for a while so I postponed fixing it. Building into an APK works fine but then when I run the game, after the intro screen the app crashes with the following debuglog (check note in the middle for where the crash occurs):

01-19 22:51:59.768: E/Unity(21604): Unable to find AudioPluginMsHRTF
  01-19 22:51:59.769: E/Unity(21604): Unable to find
  AudioPluginOculusSpatializer 01-19 22:51:59.848: D/Unity(21604):
  GL_AMD_compressed_ATC_texture GL_AMD_performance_monitor
  GL_AMD_program_binary_Z400 GL_EXT_debug_label GL_EXT_debug_marker
  GL_EXT_discard_framebuffer GL_EXT_robustness
  GL_EXT_texture_format_BGRA8888 GL_EXT_texture_type_2_10_10_10_REV
  GL_NV_fence GL_OES_compressed_ETC1_RGB8_texture GL_OES_depth_texture
  GL_OES_depth24 GL_OES_EGL_image GL_OES_EGL_sync
  GL_OES_EGL_image_external GL_OES_element_index_uint
  GL_OES_fbo_render_mipmap GL_OES_fragment_precision_high
  GL_OES_get_program_binary GL_OES_packed_depth_stencil
  GL_OES_depth_texture_cube_map GL_OES_rgb8_rgba8
  GL_OES_standard_derivatives GL_OES_texture_3D GL_OES_texture_float
  GL_OES_texture_half_float GL_OES_texture_half_float_linear
  GL_OES_texture_npot GL_OES_vertex_half_float
  GL_OES_vertex_type_10_10_10_2 GL_OES_vertex_array_object
  GL_QCOM_alpha_test GL_QCOM_binning_control GL_QCOM_driver_control
  GL_QCOM_perfmon_global_mode GL_QCOM_extended_get GL_QCOM_extended_get2
  GL_QCOM_tiled_rendering GL_QCOM_writeonly_rendering GL_EXT_sRGB
  GL_EXT_sRGB_write_control GL_EXT 01-19 22:51:59.848: D/Unity(21604):
  _texture_sRGB_decode GL_EXT_texture_filter_anisotropic GL_EXT_multisampled_render_to_texture GL_EXT_color_buffer_float
  GL_EXT_color_buffer_half_float GL_EXT_disjoint_timer_query 01-19
  22:52:00.564: W/Unity(21604): OnLevelWasLoaded was found on
  GameManager 01-19 22:52:00.564: W/Unity(21604): This message has been
  deprecated and will be removed in a later version of Unity. 01-19
  22:52:00.564: W/Unity(21604): Add a delegate to
  SceneManager.sceneLoaded instead to get notifications after scene
  loading has completed 01-19 22:52:00.564: W/Unity(21604):  01-19
  22:52:00.564: W/Unity(21604): (Filename: Line: 382)

when trying to transition from the scene 0 to scene 1

01-19 22:52:31.082: E/Unity(21604): Could not allocate memory: System
  out of memory! 01-19 22:52:31.082: E/Unity(21604): Trying to allocate:
  327716B with 16 alignment. MemoryLabel: Texture 01-19 22:52:31.082:
  E/Unity(21604): Allocation happend at: Line:464 in  01-19
  22:52:31.082: E/Unity(21604): Memory overview 01-19 22:52:31.082:
  E/Unity(21604): [ ALLOC_DEFAULT ] used: 10185997B | peak: 10217647B |
  reserved: 10604339B  01-19 22:52:31.082: E/Unity(21604): [
  ALLOC_TEMP_JOB ] used: 0B | peak: 0B | reserved: 524288B  01-19
  22:52:31.082: E/Unity(21604): [ ALLOC_GAMEOBJECT ] used: 665219B |
  peak: 665219B | reserved: 752068B  01-19 22:52:31.082: E/Unity(21604):
  [ ALLOC_GFX ] used: 48855042B | peak: 50558706B | reserved: 48861160B
  01-19 22:52:31.082: E/Unity(21604): [ ALLOC_PROFILER ] used: 0B |
  peak: 0B | reserved: 0B  01-19 22:52:31.082: E/Unity(21604): [
  ALLOC_TEMP_THREAD ] used: 110072B | peak: 0B | reserved: 2719744B
  01-19 22:52:31.082: E/Unity(21604):  01-19 22:52:31.082:
  E/Unity(21604): (Filename: Line: 996)

Now I have done the following:
-Made the intro screen as light as possible (at first I didn't even have one)
-Emptied the resource folder (cut my project size in half and increased build speed but that is about it)
-OpenGLES is set to 3 (someone advised this)

(note that there are no textures larger than 1000x1000)

As I said before, this is my first project in Unity. I am not the best programmer in the worl but over the last year I managed to put this little RPG together and I am quite ready to actually finish up and release! I would really appreciate any advise anyone can give!

Cheers,

Daan

答:
Go to File > Build Settings and make sure Scripts Only Build is unchecked.

This has fixed it for me in Unity 2018.3.7f1.

ContentLicense: CC BY-SA 3.0


问:
What does XmlReader.Parse() do?
edit: The project is an old project and the below code is one class in there that handles the xml.

There is a question to get the xsd from an old legacy application, but all it seems to be doing is: xmlReader.ParseXml(fileName,outputFile); in the ProcessXml() method.

```<code>using System;
using System.IO;
using System.Configuration;
using Utilities;
namespace JobProcessor
{

public class XmlJob : Job
{
    #region variables
    private string      ftpServer;
    private string      ftpUserName;
    private string      ftpPassWord;
    private string      ftpDestination;
    ///<summary>The xml reader used to get validation information from the xmp parsing</summary>
    protected XmlReader xmlReader   = new XmlReader();

    private string      outputFile;

    public XmlJob(string fileName, string type) : base(fileName, type){
        ftpServer       = ConfigurationManager.AppSettings[type + "-ftp"];
        ftpUserName     = ConfigurationManager.AppSettings[type + "-ftpUser"];
        ftpPassWord     = ConfigurationManager.AppSettings[type + "-ftpPass"];
        ftpDestination  = ConfigurationManager.AppSettings[type + "-ftpDest"];
    }

    protected bool ConfigureXmlReader(){
        int    recType    = 0;

        try{
            //set up the record types (i.e. the elements that trigger a new record in the output
            while(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")] != null){
                xmlReader.AddRecordType(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")],recType.ToString("00"));
                recType++;
            }
            //store the number of types
            xmlReader.SetNoRecordTypes(recType);
        }catch(Exception e){
            HandleError("Error loading record types\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }

        try{
            //set up the fields which make up each record type
            for(int i=0;i<recType;i++){
                xmlReader.AddFieldsList(i,ConfigurationManager.AppSettings[type + "-" + i.ToString("00") + "Fields"]);
            }
        }catch(Exception e){
            HandleError("Error loading field list\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    public override void RunJob(){
        outputFile = Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(fileName) + ".flat");

        if(!ConfigureXmlReader()){
            return;
        }

        if(!CheckInputFile()){
            return;
        }

        if(!ProcessXml()){
            return;
        }

        if(!Validate()){
            return;
        }

        if(ftpServer!=null && ftpUserName!=null && ftpPassWord!=null && ftpDestination!=null){
            if(!FtpFile()){
                return;
            }
        }

        MoveOriginalFile();
    }

    protected virtual bool Validate(){
        return(true);
    }

    protected bool ProcessXml(){
        /*
         * Process the xml file into a delimited format
         */

        try{
            xmlReader.ParseXml(fileName,outputFile);
        }catch(Exception e){
            HandleError("Error parsing XML file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }
    protected bool FtpFile(){
        try{
            FtpMethods.UploadFile(ftpServer,ftpUserName,ftpPassWord,outputFile,ftpDestination);
        }catch(Exception e){
            HandleError("Error FTPing file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    #endregion
}
</code>```

}

What exactly does this command do? F1 doesn't find anything and searching google gets me to a lot of xmlTextReaders.

答:
Edit: After looking at the code it Looks Like XmlReader is a custom class (Given that no using statements for System.Xml exists) which most likely wraps around XDocument as explained below

It could be incorrectly named , the only Parse method I know that works with Xml is all the XmlElements in the System.Xml.Linq namespace. I.e.

```<code>XDocument.Parse(xmlString);
</code>```

This will parse the xml, it will check that it is a valid xmlDocument and if it is it will load it as an XDocument (or whatever element)

Title: What does XmlReader.Parse() do?

Body:
edit: The project is an old project and the below code is one class in there that handles the xml.

There is a question to get the xsd from an old legacy application, but all it seems to be doing is: xmlReader.ParseXml(fileName,outputFile); in the ProcessXml() method.

using System;
using System.IO;
using System.Configuration;
using Utilities;
namespace JobProcessor
{

public class XmlJob : Job
{
    #region variables
    private string      ftpServer;
    private string      ftpUserName;
    private string      ftpPassWord;
    private string      ftpDestination;
    ///The xml reader used to get validation information from the xmp parsing
    protected XmlReader xmlReader   = new XmlReader();

    private string      outputFile;

    public XmlJob(string fileName, string type) : base(fileName, type){
        ftpServer       = ConfigurationManager.AppSettings[type + "-ftp"];
        ftpUserName     = ConfigurationManager.AppSettings[type + "-ftpUser"];
        ftpPassWord     = ConfigurationManager.AppSettings[type + "-ftpPass"];
        ftpDestination  = ConfigurationManager.AppSettings[type + "-ftpDest"];
    }

    protected bool ConfigureXmlReader(){
        int    recType    = 0;

        try{
            //set up the record types (i.e. the elements that trigger a new record in the output
            while(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")] != null){
                xmlReader.AddRecordType(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")],recType.ToString("00"));
                recType++;
            }
            //store the number of types
            xmlReader.SetNoRecordTypes(recType);
        }catch(Exception e){
            HandleError("Error loading record types\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }

        try{
            //set up the fields which make up each record type
            for(int i=0;i<recType;i++){
                xmlReader.AddFieldsList(i,ConfigurationManager.AppSettings[type + "-" + i.ToString("00") + "Fields"]);
            }
        }catch(Exception e){
            HandleError("Error loading field list\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    public override void RunJob(){
        outputFile = Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(fileName) + ".flat");

        if(!ConfigureXmlReader()){
            return;
        }

        if(!CheckInputFile()){
            return;
        }

        if(!ProcessXml()){
            return;
        }

        if(!Validate()){
            return;
        }

        if(ftpServer!=null && ftpUserName!=null && ftpPassWord!=null && ftpDestination!=null){
            if(!FtpFile()){
                return;
            }
        }

        MoveOriginalFile();
    }

    protected virtual bool Validate(){
        return(true);
    }

    protected bool ProcessXml(){
        /*
         * Process the xml file into a delimited format
         */

        try{
            xmlReader.ParseXml(fileName,outputFile);
        }catch(Exception e){
            HandleError("Error parsing XML file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }
    protected bool FtpFile(){
        try{
            FtpMethods.UploadFile(ftpServer,ftpUserName,ftpPassWord,outputFile,ftpDestination);
        }catch(Exception e){
            HandleError("Error FTPing file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    #endregion
}

}

What exactly does this command do? F1 doesn't find anything and searching google gets me to a lot of xmlTextReaders.

Body:
Edit: After looking at the code it Looks Like XmlReader is a custom class (Given that no using statements for System.Xml exists) which most likely wraps around XDocument as explained below

It could be incorrectly named , the only Parse method I know that works with Xml is all the XmlElements in the System.Xml.Linq namespace. I.e.

XDocument.Parse(xmlString);

This will parse the xml, it will check that it is a valid xmlDocument and if it is it will load it as an XDocument (or whatever element)


问:
Angular inside existing .NET Core MVC solution not working
I got an existing solution in .NET Core MVC that I wanted to use Angular in a specific view, but not everywhere.

Therefore I used the command line to create a new Angular application inside the solution in a folder called Angular.

The structure is:

SelfService (Project)

Angular

src (all other angular structure here also in this level)

Views

Dashboard

Dashboard.cshtml

There is a feature switch to let it be eased in by pilots trying it out.

I use the feature of proxy because Angular development server is running port 4200, and my applications port is running port 44323. So using proxy to fix that on my local machine.

I have set it up, which works very well when running the development server and going to "http://localhost:4200", but when I go to /dashboard in the existing solution it loads the same view, but the clicks and updates doesn't work. It simply does nothing

Startup.cs (Part of)

```<code>public IServiceProvider ConfigureServices(IServiceCollection services)
        {

// In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "Angular/dist";
            });
}

public void Configure
{
app.UseStaticFiles();

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Default}/{action=Index}/{id?}");
            });

app.UseSpa(spa =>
                {
                    spa.Options.SourcePath = "Angular";

                    if (env.IsDevelopment())
                    {
                        spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
                    }
                    // Doesn't work so using a bat-file running ng serve and then works
                    //if (env.IsDevelopment())
                    //{
                    //    spa.UseAngularCliServer(npmScript: "start");
                    //}
                });
}
</code>```

Dashboard.cshtml

```<code>@if (ViewBag.IsAngularDasboardFeaturesEnabled)
                        {
                            <app-root>app-root is loading ...</app-root>
                        }

.....

@section EndContent {
    @if (ViewBag.IsAngularDasboardFeaturesEnabled)
    {
        @if (hostingEnv.IsDevelopment())
        {
            <script type="text/javascript" src="http://localhost:4200/runtime.js"></script>
            <script type="text/javascript" src="http://localhost:4200/polyfills.js"></script>
            <script type="text/javascript" src="http://localhost:4200/styles.js"></script>
            <script type="text/javascript" src="http://localhost:4200/vendor.js"></script>
            <script type="text/javascript" src="http://localhost:4200/main.js"></script>
        }
        else
        {
            <script type="text/javascript" src="~/scripts/AngularOutput/main.js" asp-append-version="true"></script>
            <script type="text/javascript" src="~/scripts/AngularOutput/polyfills.js" asp-append-version="true"></script>
            <script type="text/javascript" src="~/scripts/AngularOutput/runtime.js" asp-append-version="true"></script>
            <script type="text/javascript" src="~/scripts/AngularOutput/styles.js" asp-append-version="true"></script>
            <script type="text/javascript" src="~/scripts/AngularOutput/vendor.js" asp-append-version="true"></script>
        }
    }
</code>```

app.component.html

```<code><div (click)="clickHandler()">
  {{title}}
</div>
</code>```

app.component.ts

```<code>export class AppComponent {
  counter: number = 1;
  title = 'Angular LAWE (You are the BOSSmann)' + this.counter;

  constructor() {
    setTimeout(() => {
      console.log("hello");
      this.title = "something else";
    }, 5000);
  }

  clickHandler(): any {
    console.log("Change click", ++this.counter);
    this.title = "hi" + this.counter;
  }
}
</code>```

I would expect that when it works in with the development server for http://localhost:4200, then it would also work for https://localhost:44323/dashboard/ but it doesn't.

?? Can it be the problem of https vs http?

UPDATE 1: I have used in Angular application folder in package.json "start": "ng serve --ssl true", which removed the WDS-error, but now gives GET https://localhost/runtime.js net::ERR_CONNECTION_REFUSED

?? When my development server from VS in Startup.cs doesn't work, could that be the reason why the clicks and everything doesn't work? It renders the component, and writes logs from init, and I can call the clickMethod that logs clicked, but clicking the div doesn't work.

UPDATE 2: Changed the port to be the local developments port instead of 4200, but gave a 500 response instead.

答:
I found out that if I copied the markup to another controller and another view everything worked out fine.
It was the combination of Knockout mixed with Angular that made it not work.

```<code><!-- ko if: selectedAreaTabFound() === 1 -->
<app-root>app-root is loading ...</app-root>
<!-- /ko -->
</code>```

So the click events was working if it wasn't combined with Knockout, and routing and all events could fire if it was in a new page.
Eventually I scraped everything away and it came down to removing all the knockout comments around it for it to work.
So now I have to think about another way to make it work where I wanted it, but I found the problem.

Body:
I got an existing solution in .NET Core MVC that I wanted to use Angular in a specific view, but not everywhere.

Therefore I used the command line to create a new Angular application inside the solution in a folder called Angular.

The structure is:

SelfService (Project)

Angular

src (all other angular structure here also in this level)

Views

Dashboard

Dashboard.cshtml

There is a feature switch to let it be eased in by pilots trying it out.

I use the feature of proxy because Angular development server is running port 4200, and my applications port is running port 44323. So using proxy to fix that on my local machine.

I have set it up, which works very well when running the development server and going to "http://localhost:4200", but when I go to /dashboard in the existing solution it loads the same view, but the clicks and updates doesn't work. It simply does nothing

Startup.cs (Part of)

public IServiceProvider ConfigureServices(IServiceCollection services)
        {

// In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "Angular/dist";
            });
}

public void Configure
{
app.UseStaticFiles();

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Default}/{action=Index}/{id?}");
            });

app.UseSpa(spa =>
                {
                    spa.Options.SourcePath = "Angular";

                    if (env.IsDevelopment())
                    {
                        spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
                    }
                    // Doesn't work so using a bat-file running ng serve and then works
                    //if (env.IsDevelopment())
                    //{
                    //    spa.UseAngularCliServer(npmScript: "start");
                    //}
                });
}

Dashboard.cshtml

@if (ViewBag.IsAngularDasboardFeaturesEnabled)
                        {
                            <app-root>app-root is loading ...</app-root>
                        }

.....

@section EndContent {
    @if (ViewBag.IsAngularDasboardFeaturesEnabled)
    {
        @if (hostingEnv.IsDevelopment())
        {

        }
        else
        {

        }
    }

app.component.html

  {{title}}

app.component.ts

export class AppComponent {
  counter: number = 1;
  title = 'Angular LAWE (You are the BOSSmann)' + this.counter;

  constructor() {
    setTimeout(() => {
      console.log("hello");
      this.title = "something else";
    }, 5000);
  }

  clickHandler(): any {
    console.log("Change click", ++this.counter);
    this.title = "hi" + this.counter;
  }
}

I would expect that when it works in with the development server for http://localhost:4200, then it would also work for https://localhost:44323/dashboard/ but it doesn't.

?? Can it be the problem of https vs http?

UPDATE 1: I have used in Angular application folder in package.json "start": "ng serve --ssl true", which removed the WDS-error, but now gives GET https://localhost/runtime.js net::ERR_CONNECTION_REFUSED

?? When my development server from VS in Startup.cs doesn't work, could that be the reason why the clicks and everything doesn't work? It renders the component, and writes logs from init, and I can call the clickMethod that logs clicked, but clicking the div doesn't work.

UPDATE 2: Changed the port to be the local developments port instead of 4200, but gave a 500 response instead.

Body:
I found out that if I copied the markup to another controller and another view everything worked out fine.
It was the combination of Knockout mixed with Angular that made it not work.

<!-- ko if: selectedAreaTabFound() === 1 -->
<app-root>app-root is loading ...</app-root>
<!-- /ko -->

So the click events was working if it wasn't combined with Knockout, and routing and all events could fire if it was in a new page.
Eventually I scraped everything away and it came down to removing all the knockout comments around it for it to work.
So now I have to think about another way to make it work where I wanted it, but I found the problem.


问:
Install/test problem with full Nativescript CLI install
I've done an apparently clean install of the Nativescript CLI on MacOS X, yet when I run tns doctor it fails: </p>

```<code>bash-3.2$ /usr/local/lib/node_modules/nativescript/bin/tns doctor

/usr/local/lib/node_modules/nativescript/lib/common/verify-node-    version.js:32
            console.warn((`${os.EOL}${nodeWarning.message}${os.EOL}`).yellow.bold)
                  ^
SyntaxError: Unexpected token ILLEGAL
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous>     (/usr/local/lib/node_modules/nativescript/bin/tns:8:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
</code>```

答:
The problem is that you are using very old Node.js version. NativeScript CLI requires at least Node.js 6, but I recommend you to use current LTS - Node.js 10.
Node.js 0.10.29 (which is your current version) does not support the syntax used in NativeScript CLI's codebase.</p>

Body:
I've done an apparently clean install of the Nativescript CLI on MacOS X, yet when I run tns doctor it fails:

bash-3.2$ /usr/local/lib/node_modules/nativescript/bin/tns doctor

/usr/local/lib/node_modules/nativescript/lib/common/verify-node-    version.js:32
            console.warn((`${os.EOL}${nodeWarning.message}${os.EOL}`).yellow.bold)
                  ^
SyntaxError: Unexpected token ILLEGAL
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous>     (/usr/local/lib/node_modules/nativescript/bin/tns:8:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)


问:
Date being sent in Selenium Webdriver (java) comes out wrong
I have a small script that sends a date to an Inputfield with ID=bla.

```<code>@Then("^I fill in the date \"([^\"]*)\"$")
public void fill_date(String date) throws Throwable {

  waitForElementPresent(By.id(bla));
  driver.findElement(By.id(bla)).click();
  driver.findElement(By.id(bla)).clear();
  driver.findElement(By.id(bla)).sendKeys(date);
  driver.findElement(By.id(Submitbutton).click();
  }
</code>```

Now, every time I run it with, for example, date=28-06-1985, it completely messes up the date and actually sends "28-61-8590" instead of "28-06-1985". Needless to say, my test fails because the date does not exists... I also removed the Click and Clear before sending the date, but nothing seems to be working. Also, removing the stripes in the data (so sending 28061985) doesn't do anything.

What am I doing wrong here? Is there a better way to fill an input field with a date?

答:
Entering text letter by letter helps me in such cases:</p>

```<code>public void enterTextOneByOne(WebElement inputElement, String text){
  for (char letter : text.toCharArray()) {
    inputElement.sendKeys(CharBuffer.wrap(new char[]{letter}));
  }
}
</code>```

Body:
I have a small script that sends a date to an Inputfield with ID=bla.

@Then("^I fill in the date \"([^\"]*)\"$")
public void fill_date(String date) throws Throwable {

  waitForElementPresent(By.id(bla));
  driver.findElement(By.id(bla)).click();
  driver.findElement(By.id(bla)).clear();
  driver.findElement(By.id(bla)).sendKeys(date);
  driver.findElement(By.id(Submitbutton).click();
  }

Now, every time I run it with, for example, date=28-06-1985, it completely messes up the date and actually sends "28-61-8590" instead of "28-06-1985". Needless to say, my test fails because the date does not exists... I also removed the Click and Clear before sending the date, but nothing seems to be working. Also, removing the stripes in the data (so sending 28061985) doesn't do anything.

What am I doing wrong here? Is there a better way to fill an input field with a date?

Body:
Entering text letter by letter helps me in such cases:

public void enterTextOneByOne(WebElement inputElement, String text){
  for (char letter : text.toCharArray()) {
    inputElement.sendKeys(CharBuffer.wrap(new char[]{letter}));
  }
}


问:
Istio VirtualServie with DaemonSet on hostPort
I have a DaemonSet exposed via hostPort. Is it possible to create a istio VirtualService that points to hostIP:hostPort?</p>

答:
Istio VirtualService is a set of traffic routing rules.

Based on the matching criteria, traffic is sent to destination service but NOT hostIP

So, with VirtualService you can set a combination of service name and NodePort

```<code>- destination:
        host: my-service.default.svc.cluster.local
        port:
          number: 9080
</code>```

What is the background of your request? Probably it can be achieved in some other way.

Body:
Istio VirtualService is a set of traffic routing rules.

Based on the matching criteria, traffic is sent to destination service but NOT hostIP

So, with VirtualService you can set a combination of service name and NodePort

- destination:
        host: my-service.default.svc.cluster.local
        port:
          number: 9080

What is the background of your request? Probably it can be achieved in some other way.


问:
How to send POSTFIELDS to cURL correctly
I need to send POST data via cURL as shown in the picture.

image with POST data

i have this code

```<code> $data = [
            'action' => 'order_cost',
            'address' => 'http://91.211.117.3:720'
        ];

  $query = http_build_query($data);

   $url = "https://ap4.taxi/api/TaxiAPI.php";
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvJFySHvqeKppEN9W',
            )
        );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        $output = curl_exec($ch);

        curl_close($ch);

        var_dump($output);
</code>```

but I get an error

image with error

I have already tried many options. Postman sends POST normally and I receive the answer.

Please tell me I can not even imagine how this can be done.

答:
As I see from your code you are sending just two fields by POST method (action and address)
Please show us a code of https://ap4.taxi/api/TaxiAPI.php where you process received data.</p>

Body:
I need to send POST data via cURL as shown in the picture.

image with POST data

i have this code

 $data = [
            'action' => 'order_cost',
            'address' => 'http://91.211.117.3:720'
        ];

  $query = http_build_query($data);

   $url = "https://ap4.taxi/api/TaxiAPI.php";
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvJFySHvqeKppEN9W',
            )
        );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        $output = curl_exec($ch);

        curl_close($ch);

        var_dump($output);

but I get an error

image with error

I have already tried many options. Postman sends POST normally and I receive the answer.

Please tell me I can not even imagine how this can be done.


问:
How can I Split the String Correctly?
I am getting a result of "kjhvkjkasdfkjh@grouping@group_group.12018-08-20".

I am looking to split the string in java to only get the "2018-08-20".

Any suggestions? The part I want is always at the end.

答:
```<code>String sample = "kjhvkjkasdfkjh@grouping@group_group.12018-08-20"
int SubstringStart = sample.length() - 10;
String outputsample = sample.substring(SubstringStart);
</code>```

will break if string has length shorter than 10

Title: How can I Split the String Correctly?

Body:
String sample = "kjhvkjkasdfkjh@grouping@group_group.12018-08-20"
int SubstringStart = sample.length() - 10;
String outputsample = sample.substring(SubstringStart);

will break if string has length shorter than 10


问:
whitelist domain names on Azure AD with App Registration
The authentication process for O365 requires adding the redirect URL in a whitelist on the app’s dashboard on Azure.

However, this whitelist doesn't work with domain names. It requires to add the entire URL for every page which is not possible if you have a huge number of URLs, plus some of the URLs are dynamically generated by the backend.
Is it possible to whitelist the domain with all its sub-directories/URLs in one go?

答:
No, it is not (unless you want to use wildcards, which you shouldn't).

In general when you need dynamic redirects,
you should store the location you want to redirect to locally in a cookie/session/local storage/session storage.
Then use a single redirect URL, and when you get the redirect there, get that stored "local redirect URL" from where you stored it, and redirect the user there.

I touched upon this on a recent article: https://joonasw.net/view/avoiding-wildcard-reply-urls-with-msal-js


问:
how to format my text dataset for training?
I'm new to python and machine learning,
I'm working on training a chatbot

I collected (or wrote) large number of possible inputs in an excel file (.xlsx), I will train my dataset using LSTM and IOBES lableing, I will do the same as here :
https://www.depends-on-the-definition.com/guide-sequence-tagging-neural-networks-python/

In the link you can see a snapshot of the dataset, I want to make my dataset like it.

my questions are :

1- Is there a way to split a sentence into words so I can do the tagging for words ? (there is a tool in Excel, I tried it but it is very exhausted).
2- I tried to convert my file to .cvs, but I've faced a lot of problems (it is with utf-8, because my dataset is not in english) , is there another extension ?

I really appreciate your help and advice.
Thank you

答:
You can use the pandas method pd.read_excel('your_file.xlsx',sep=',') to avoid converting your file into csv.

To split a sentence into words you need to use a Natural Language Processing (NLP) python package like nltk with an English vocabulary. This will take into account punctuation, quotes etc..


问:
Unable to resolve view exception with Spring Boot WebFlux when deploying as WAR
Facing below exception while deploying Spring WebFlux application as war file in tomcat.Extended with  AbstractAnnotationConfigDispatcherHandlerInitializer and implemented getConfigClasses method as below.

Application

```<code>@SpringBootApplication
public class TestSpringApplication extends AbstractAnnotationConfigDispatcherHandlerInitializer {

    public static void main(String[] args) {
        SpringApplication.run(TestSpringApplication.class, args);
    }
    @Override
    protected Class<?>[] getConfigClasses() {
        return new Class[]{
            WebConfig.class
        };
    }
</code>```

Controller

```<code>@Controller
public class TestSpringController {

    @RequestMapping("/test")
    public Mono<String> hello(Model model){

         return Mono.just("account");
    }
}
</code>```

Note : account.html is placed under resources/templates

Exception

```<code>java.lang.IllegalStateException: Could not resolve view with name 'account'.
    at org.springframework.web.reactive.result.view.ViewResolutionResultHandler.lambda$resolveViews$3(ViewResolutionResultHandler.java:276) ~[spring-webflux-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:107) [reactor-core-3.1.1.RELEASE.jar:3.1.1.RELEASE]
</code>```

答:
Use @RestController instead of @Controller annotation of TestSpringController class

Alternatively, you can add the @ResponseBody annotations to controller methods annotated with @Controller which return a response body.

Body:
Facing below exception while deploying Spring WebFlux application as war file in tomcat.Extended with  AbstractAnnotationConfigDispatcherHandlerInitializer and implemented getConfigClasses method as below.

Application

@SpringBootApplication
public class TestSpringApplication extends AbstractAnnotationConfigDispatcherHandlerInitializer {

    public static void main(String[] args) {
        SpringApplication.run(TestSpringApplication.class, args);
    }
    @Override
    protected Class<?>[] getConfigClasses() {
        return new Class[]{
            WebConfig.class
        };
    }

Controller

@Controller
public class TestSpringController {

    @RequestMapping("/test")
    public Mono<String> hello(Model model){

         return Mono.just("account");
    }
}

Note : account.html is placed under resources/templates

Exception

java.lang.IllegalStateException: Could not resolve view with name 'account'.
    at org.springframework.web.reactive.result.view.ViewResolutionResultHandler.lambda$resolveViews$3(ViewResolutionResultHandler.java:276) ~[spring-webflux-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:107) [reactor-core-3.1.1.RELEASE.jar:3.1.1.RELEASE]


问:
Throttling in multithread console application
My console application opens 100 threads which do exactly the same - sends some date to host in internal network. The host is very responsive, I have checked that it can handle much bigger number of requests in every second. The console application also is quite primitive and responsive (it doesn't use database or something) - it only sends requests to host. Increasing the number of threads doesn't improve the speed. It seems something is throttling the speed of communication the app with the host. Moreover I have run three instances of the same console application in the same time, and they have made 3x time more, so it seems the limitation is one the level of application.

I have already increased DefaultConnectionLimit but with no effect.

```<code>class Program
{
    static void Main(string[] args)
    {
        System.Net.ServicePointManager.DefaultConnectionLimit = 200;

        for (var i = 1; i <= 100; i++)
        {
            int threadId = i;
            Thread thread = new Thread(() =>
            {
                Testing(threadId);
            });
            thread.Start();
        }
    }

    private static void Testing(int threadId)
    {
        //just communicate with host
    }
}
</code>```

答:
Creation of a new Thread everytime is very expensive. You shouldn't create threads explicitly. Use task api instead to run this on threadpool:

```<code>var tasks = new Task[100];
for (var i = 0; i < 100; i++)
{
    int threadId = i;
    tasks[i] = Task.Run(() => Testing(threadId));
}
Task.WhenAll(tasks).GetAwaiter().GetResult();
</code>```

Body:
My console application opens 100 threads which do exactly the same - sends some date to host in internal network. The host is very responsive, I have checked that it can handle much bigger number of requests in every second. The console application also is quite primitive and responsive (it doesn't use database or something) - it only sends requests to host. Increasing the number of threads doesn't improve the speed. It seems something is throttling the speed of communication the app with the host. Moreover I have run three instances of the same console application in the same time, and they have made 3x time more, so it seems the limitation is one the level of application.

I have already increased DefaultConnectionLimit but with no effect.

class Program
{
    static void Main(string[] args)
    {
        System.Net.ServicePointManager.DefaultConnectionLimit = 200;

        for (var i = 1; i <= 100; i++)
        {
            int threadId = i;
            Thread thread = new Thread(() =>
            {
                Testing(threadId);
            });
            thread.Start();
        }
    }

    private static void Testing(int threadId)
    {
        //just communicate with host
    }
}

Body:
Creation of a new Thread everytime is very expensive. You shouldn't create threads explicitly. Use task api instead to run this on threadpool:

var tasks = new Task[100];
for (var i = 0; i < 100; i++)
{
    int threadId = i;
    tasks[i] = Task.Run(() => Testing(threadId));
}
Task.WhenAll(tasks).GetAwaiter().GetResult();


问:
How can I identify uppercase and lowercase characters in a string with swift?
This is what I have so far (for testing purpose):

```<code>let string = "The quick BroWn fOX jumpS Over tHe lazY DOg"

for chr in string {
    if isupper(String(chr)) {
        print(String(chr).lowercaseString)
        continue
    }
    print(chr)
}
</code>```

how can I test for uppercase and lowercase characters?

I know I can call C functions from swift, but this does not seems to be correct for me.  How can I do this with swift only?

答:
Simple extension accepts any CharacterSet to check:

```<code>extension String {
    func hasCharacter(in characterSet: CharacterSet) -> Bool {
        return rangeOfCharacter(from: characterSet) != nil
    }
}
</code>```

usage:

```<code>"aBc".hasCharacter(in: .lowercaseLetters)
"aBc".hasCharacter(in: .uppercaseLetters)
"aBc".hasCharacter(in: <#AnyOtherCharacterSetYouWant#>)
</code>```

Body:
This is what I have so far (for testing purpose):

let string = "The quick BroWn fOX jumpS Over tHe lazY DOg"

for chr in string {
    if isupper(String(chr)) {
        print(String(chr).lowercaseString)
        continue
    }
    print(chr)
}

how can I test for uppercase and lowercase characters?

I know I can call C functions from swift, but this does not seems to be correct for me.  How can I do this with swift only?

Body:
Simple extension accepts any CharacterSet to check:

extension String {
    func hasCharacter(in characterSet: CharacterSet) -> Bool {
        return rangeOfCharacter(from: characterSet) != nil
    }
}

usage:

"aBc".hasCharacter(in: .lowercaseLetters)
"aBc".hasCharacter(in: .uppercaseLetters)
"aBc".hasCharacter(in: <#AnyOtherCharacterSetYouWant#>)


问:
Is it possible to generate small executables with MINGW g++?
I understand that MINGW-g++ compiles larger executables because it statically links many things. On the other hand MSVC++ links dynamically against DLLs from the VCRedist package, and that is why it produces way smaller executables.

However, is it possible to compile with g++ in a similar manner on windows? Not necessarily MINGW-g++ but something that I can use with Qt Creator (I didn't add Qt as a tag because it's irrelevant to the question).

答: You can use cygwin (www.cygwin.com). They use a runtime DLL much like MSVCRT . Then your program depends on the cygwin runtime, of course (kind of a tautology, sorry).</p>


问:
How can i send the keys ` and ´ with Selenium in C#?
I want to send the Keys ` and ´ to an Input-Element with the sendKeys method. But the characters are not shown in the input.

The documentation says nothing about these keys.
https://seleniumhq.github.io/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Keys.htm

```<code>WebElement element = driver.FindElement(By.id("UserName"));

element.SendKeys("´ `");
</code>```

答:
When it comes to desktop browsers the easiest is to go for driver.ExecuteScript() method in order to set the <input> element value by means of JavaScript

Reference code:

```<code>IWebElement element = driver.FindElement(By.Id("UserName"));
driver.ExecuteScript("arguments[0].value=\"´ `\";", element);
</code>```

Be aware that the approach might not work for Appium device automation as certain mobile platforms/browsers cannot execute JavaScript like desktop browsers do.

Body:
I want to send the Keys ` and ´ to an Input-Element with the sendKeys method. But the characters are not shown in the input.

The documentation says nothing about these keys.
https://seleniumhq.github.io/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Keys.htm

WebElement element = driver.FindElement(By.id("UserName"));

element.SendKeys("´ `");

Body:
When it comes to desktop browsers the easiest is to go for driver.ExecuteScript() method in order to set the <input> element value by means of JavaScript

Reference code:

IWebElement element = driver.FindElement(By.Id("UserName"));
driver.ExecuteScript("arguments[0].value=\"´ `\";", element);

Be aware that the approach might not work for Appium device automation as certain mobile platforms/browsers cannot execute JavaScript like desktop browsers do.


问:
How to convert a codepoint to utf-8?
I have some code that reads in an a unicode codepoint (as escaped in a string 0xF00).

Since im using boost, I'm speculating if the following is best (and correct) approach:

```<code>unsigned int codepoint{0xF00};
boost::locale::conv::utf_to_utf<char>(&codepoint, &codepoint+1);
</code>```

?

答:
You can do this with the standard library using std::wstring_convert to convert UTF-32 (code points) to UTF-8:

```<code>#include <locale>
#include <codecvt>

std::string codepoint_to_utf8(char32_t codepoint) {
    std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;
    return convert.to_bytes(&codepoint, &codepoint + 1);
}
</code>```

This returns a std::string whose size is 1, 2, 3 or 4 depending on how large codepoint is. It will throw a std::range_error if the code point is too large (> 0x10FFFF, the max unicode code point).

Your version with boost seems to be doing the same thing. The documentation says that the utf_to_utf function converts a UTF encoding to another one, in this case 32 to 8. If you use char32_t, it will be a "correct" approach, that will work on systems where unsigned int isn't the same size as char32_t.

```<code>// The function also converts the unsigned int to char32_t
std::string codepoint_to_utf8(char32_t codepoint) {
    return boost::locale::conv::utf_to_utf<char>(&codepoint, &codepoint + 1);
}
</code>```

Title: How to convert a codepoint to utf-8?

Body:
I have some code that reads in an a unicode codepoint (as escaped in a string 0xF00).

Since im using boost, I'm speculating if the following is best (and correct) approach:

unsigned int codepoint{0xF00};
boost::locale::conv::utf_to_utf<char>(&codepoint, &codepoint+1);

?

Body:
You can do this with the standard library using std::wstring_convert to convert UTF-32 (code points) to UTF-8:

#include <locale>
#include <codecvt>

std::string codepoint_to_utf8(char32_t codepoint) {
    std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;
    return convert.to_bytes(&codepoint, &codepoint + 1);
}

This returns a std::string whose size is 1, 2, 3 or 4 depending on how large codepoint is. It will throw a std::range_error if the code point is too large (> 0x10FFFF, the max unicode code point).

Your version with boost seems to be doing the same thing. The documentation says that the utf_to_utf function converts a UTF encoding to another one, in this case 32 to 8. If you use char32_t, it will be a "correct" approach, that will work on systems where unsigned int isn't the same size as char32_t.

// The function also converts the unsigned int to char32_t
std::string codepoint_to_utf8(char32_t codepoint) {
    return boost::locale::conv::utf_to_utf<char>(&codepoint, &codepoint + 1);
}


答:
The thing is that craeting more threads than you have cores in your processors is pointless.

For example you have 4 cores and create 100 threads: where do you expect 96 threads to run? They have to wait and decrease of performance is due to creating and managing unnecessary threads.

You should use ThreadPool, which will optimize number of threads created and scheduled to work.

Title: Throttling in multithread console application


问:
Adding trust cert inside a docker container
I have a keycloak running inside a docker and I want to add a trusted certificate, so I ssh in to the container and copy the cert file and imported the certificate via the keytool

```<code>${JAVA_JDK}/jre/bin/keytool \
    -import -trustcacerts \
    -alias "efactory-nimble_salzburgresearch_at.crt" -file efac.crt \
    -keystore ${JAVA_JDK}/jre/lib/security/cacerts \
    -storepass changeit \
    -noprompt
</code>```

The response from the key tool was,

```<code>Picked up _JAVA_OPTIONS: -Xmx256m -Xms50m
Certificate was added to keystore
</code>```

After successfully importing the certificate also Im getting this error in keycloak.

```<code>Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

So my question is does the jvm needs to be restarted after adding the certificate inside a docker container & does any one else also came across this issue ?

答:
Yes, the JVM needs restart after adding the certificate to the keystore - look here: Imported certificate to Java keystore, JVM ignores the new cert.

Other than that, you should probably have a more "persistent" way how to update the keystore since it'll be gone after the container is removed.

Body:
I have a keycloak running inside a docker and I want to add a trusted certificate, so I ssh in to the container and copy the cert file and imported the certificate via the keytool

${JAVA_JDK}/jre/bin/keytool \
    -import -trustcacerts \
    -alias "efactory-nimble_salzburgresearch_at.crt" -file efac.crt \
    -keystore ${JAVA_JDK}/jre/lib/security/cacerts \
    -storepass changeit \
    -noprompt

The response from the key tool was,

Picked up _JAVA_OPTIONS: -Xmx256m -Xms50m
Certificate was added to keystore

After successfully importing the certificate also Im getting this error in keycloak.

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

So my question is does the jvm needs to be restarted after adding the certificate inside a docker container & does any one else also came across this issue ?


问:
Align footer at the bottom of the content, push to right of the sidebar
I wanted to place the footer at the bottom of the content, but not spread across the whole width of the page. The footer should always be bottom if the content is not place i.e. as shown in figure 1. The sidebar can be toggled by the button place at the navbar.

I was only able to get as shown below:

The sidebar should push the footer to the right, but it is always at the top. As, when the sidebar is hidden or collapsed the footer should occupy the width of the page as occupied buy the content.

HTML implementation is in the following structure:

```<code><div class="wrapper">
   <!-- Navbar -->
   <nav class="navbar navbar-expand-sm fixed-top navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
      <div class="container-fluid">
      </div>
   </nav>
   <!-- Sidebar -->
   <div id="sidebar" class="shadow-sm"></div>
   <!-- Page Content -->
   <div id="content">
      <div class="container-fluid">
         <div class="card">
            <div class="card-body">
               <h1>
                  Collapsing Menu
                  <small class="text-muted">Version 2.1</small>
               </h1>
            </div>
         </div>
      </div>
   </div>
</div>
<footer id="page-footer" class="py-3 bg-dark text-light">
   <div class="container">

   </div>
</footer>
</code>```

CSS for the footer and sidebar:

```<code>footer {
    bottom: 0;
    left: 0;
    position: fixed;
    width: 100%;
}
#sidebar {
    margin-top: 54px;
    width: 250px;
    position: fixed;
    top: 0;
    left: 0;
    height: calc(100vh - 55px);
    z-index: 999;
    padding: 10px;
    -webkit-transition: right .5s ease,left .5s ease;
    -moz-transition: right .5s ease,left .5s ease;
    -o-transition: right .5s ease,left .5s ease;
    transition: right .5s ease,left .5s ease;
}
</code>```

答:
I'd recommend putting the footer in the div with the id "content," or the one with class "container-fluid."

See how that works.

Long Version: Your footer is currently being spaced according to its parent context. In the current version, the context that you're placing your footer in is not in the scope of what you posted- this means that, in terms of processing, the footer is not aware of the content container. The quickest solution here would be to place the footer in the context of the container that holds your content. This way, the footer is contained by the same div that the content is presented in. Whether or not it touches the bottom of the screen is up to your css.

Hope that helps.

Body:
I wanted to place the footer at the bottom of the content, but not spread across the whole width of the page. The footer should always be bottom if the content is not place i.e. as shown in figure 1. The sidebar can be toggled by the button place at the navbar.

I was only able to get as shown below:

The sidebar should push the footer to the right, but it is always at the top. As, when the sidebar is hidden or collapsed the footer should occupy the width of the page as occupied buy the content.

HTML implementation is in the following structure:

                  Collapsing Menu
                  Version 2.1

CSS for the footer and sidebar:

footer {
    bottom: 0;
    left: 0;
    position: fixed;
    width: 100%;
}
#sidebar {
    margin-top: 54px;
    width: 250px;
    position: fixed;
    top: 0;
    left: 0;
    height: calc(100vh - 55px);
    z-index: 999;
    padding: 10px;
    -webkit-transition: right .5s ease,left .5s ease;
    -moz-transition: right .5s ease,left .5s ease;
    -o-transition: right .5s ease,left .5s ease;
    transition: right .5s ease,left .5s ease;
}


问:
How to create default tasks?
I found how to create tasks for a project but these tasks are not saved from a project to another.

So my question is: Is there a way to create default tasks that would be accessible to every new project ?

答:
There is an unresolved feature request for allowing tasks to be shared across projects:

Shared configuration (tasks/settings) (#1435)

In the meantime, it's possible to work around this by creating a custom extension using the task provider API:

Extension API - Task Provider - Build Task example

Can extensions contribute a custom task in VS Code?

Title: How to create default tasks?


问:
(Unity) Enabling App Bundle (Google Play) option when building with the BuildPipeline?
Does anyone know how I can enable the App Bundle (Google Play) option when building with the Unity BuildPipeline? Trying to get this to work with our CI server, this is the code currently used to create an APK:

```<code>BuildPlayerOptions prodBuildPlayerOptions = new BuildPlayerOptions();
 prodBuildPlayerOptions.scenes = scenes;
 prodBuildPlayerOptions.locationPathName = $"PSS.Prod.{baseBuildFileName}.apk";
 prodBuildPlayerOptions.target = BuildTarget.Android;
 prodBuildPlayerOptions.options = BuildOptions.None;
 BuildPipeline.BuildPlayer(prodBuildPlayerOptions);
</code>```

Any help would be greatly appreciated!
Cheers, Thomas

答:
According to the document, just do:

```<code>EditorUserBuildSettings.buildAppBundle = true;
</code>```

If Unity version is lower than 2018, also need to set:

```<code>EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
</code>```

Body:
Does anyone know how I can enable the App Bundle (Google Play) option when building with the Unity BuildPipeline? Trying to get this to work with our CI server, this is the code currently used to create an APK:

BuildPlayerOptions prodBuildPlayerOptions = new BuildPlayerOptions();
 prodBuildPlayerOptions.scenes = scenes;
 prodBuildPlayerOptions.locationPathName = $"PSS.Prod.{baseBuildFileName}.apk";
 prodBuildPlayerOptions.target = BuildTarget.Android;
 prodBuildPlayerOptions.options = BuildOptions.None;
 BuildPipeline.BuildPlayer(prodBuildPlayerOptions);

Any help would be greatly appreciated!
Cheers, Thomas

Body:
According to the document, just do:

EditorUserBuildSettings.buildAppBundle = true;

If Unity version is lower than 2018, also need to set:

EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;


问:
can't use a property name as argument when expecting keyof typeof class
I have a class with a static property:

export class names{
    public static readonly rootNames= {
        a: 'a',
        b: 'b',
        c: 'c',
        d: 'd',
        e: 'e',
    };
}
```

<p>I want to define a function that takes an argument that can only be one of those values:</p>

<pre class="lang-js prettyprint-override"><code>private getSubFolderByName(name: keyof typeof names.rootNames) {}
// name has type 'a' | 'b'... as expected
</code>```

but when calling the function with e.g. names.rootNames.a I get the error that Argument of type 'string' is not assignable to parameter of type '"a" | "b" | "c" | "d" | "e"', because these properties ('a', 'b', etc.) have type string.

I tried:

private getSubFolderByName(name: typeof names.rootNames[keyof typeof names.rootNames]) {}
```

But that is just string, again. I need to prevent the types of these properties from widening to string.

答:
First, the function signature needs to be the second version:

private getSubFolderByName(name: typeof names.rootNames[keyof typeof names.rootNames]) {}
```

<p>This creates a union type where the members are the <em>values</em> of the <code>names.rootNames</code> property. The first version created a union of the names of the <em>keys</em> in <code>names.rootNames</code>, even if they were coincidentally the same.</p>

<p>Second, to prevent type-widening, declare <code>rootNames as const</code>:</p>

<pre class="lang-js prettyprint-override"><code>export class names{
    public static readonly rootNames= {
        a: 'a',
        b: 'b',
        c: 'c',
        d: 'd',
        e: 'e',
    } as const;
}
</code>```

This makes the property of e.g. e be of type 'e' rather than type string.

Body:
I have a class with a static property:

export class names{
    public static readonly rootNames= {
        a: 'a',
        b: 'b',
        c: 'c',
        d: 'd',
        e: 'e',
    };
}

I want to define a function that takes an argument that can only be one of those values:

private getSubFolderByName(name: keyof typeof names.rootNames) {}
// name has type 'a' | 'b'... as expected

but when calling the function with e.g. names.rootNames.a I get the error that Argument of type 'string' is not assignable to parameter of type '"a" | "b" | "c" | "d" | "e"', because these properties ('a', 'b', etc.) have type string.

I tried:

private getSubFolderByName(name: typeof names.rootNames[keyof typeof names.rootNames]) {}

But that is just string, again. I need to prevent the types of these properties from widening to string.

Body:
First, the function signature needs to be the second version:

private getSubFolderByName(name: typeof names.rootNames[keyof typeof names.rootNames]) {}

This creates a union type where the members are the values of the names.rootNames property. The first version created a union of the names of the keys in names.rootNames, even if they were coincidentally the same.

Second, to prevent type-widening, declare rootNames as const:

export class names{
    public static readonly rootNames= {
        a: 'a',
        b: 'b',
        c: 'c',
        d: 'd',
        e: 'e',
    } as const;
}

This makes the property of e.g. e be of type 'e' rather than type string.


问:
how to send mail using handler?
i want to send mail so i wrote one method in handler.ashx but i got error as

The "SendUsing" configuration value is invalid. what does it mean pls help me

public bool Sendmail()
    {
        bool strResult = false;
        try
        {

```<code>        email.Subject = " Registration";

        email.To = "ravivarma_07d@yahoo.com";
        email.From = "giribhushan.svg@gmail.com";
        email.Cc = "ravivarma_07d@yahoo.com";
        email.Bcc = "ravivarma_07d@yahoo.com";
        email.BodyFormat = MailFormat.Html;

        email.Body = "<html>" +
                       "<body>" +
                      "<b>Hi ravi</b>"+
                       "</body>" +
                       "</html>";
        email.Priority = MailPriority.Normal;

       SmtpMail.Send(email);
        strResult = true;
    }
    catch (Exception ex)
    {
        //FTEHelper.SendEmail("ticketupload@whohastwo.com", "Ticket Upload Batch Error",
        //   ex.ToString());

        strResult = false;

    }

    return strResult;

}
</code>```

答:
You should specify an SMTP server.

```<code>SmtpMail.SmtpServer = "yourservername";
</code>```

Also you should consider using System.Net.Mail namespace instead of System.Web.Mail. (If you aren't forced to use .NET 1, of course.)

Title: how to send mail using handler?

Body:
i want to send mail so i wrote one method in handler.ashx but i got error as

The "SendUsing" configuration value is invalid. what does it mean pls help me

public bool Sendmail()
    {
        bool strResult = false;
        try
        {

        email.Subject = " Registration";

        email.To = "ravivarma_07d@yahoo.com";
        email.From = "giribhushan.svg@gmail.com";
        email.Cc = "ravivarma_07d@yahoo.com";
        email.Bcc = "ravivarma_07d@yahoo.com";
        email.BodyFormat = MailFormat.Html;

        email.Body = "" +
                       "" +
                      "Hi ravi"+
                       "" +
                       "";
        email.Priority = MailPriority.Normal;

       SmtpMail.Send(email);
        strResult = true;
    }
    catch (Exception ex)
    {
        //FTEHelper.SendEmail("ticketupload@whohastwo.com", "Ticket Upload Batch Error",
        //   ex.ToString());

        strResult = false;

    }

    return strResult;

}

Body:
You should specify an SMTP server.

SmtpMail.SmtpServer = "yourservername";

Also you should consider using System.Net.Mail namespace instead of System.Web.Mail. (If you aren't forced to use .NET 1, of course.)


问:
Initilizing a dictionary issues
Instead of just initilizing

```<code>Screens (Dictionary<GameObject, string> Screens) values
</code>```

this code creates a new gameObject screens with these associated values.

The problem is here:

```<code>Screens[new GameObject(cont.Key)] = cont.Value;
</code>```

This is the result for screens : "Screens are created again with the associated values
RightOuterPad=, LeftOuterPad=, LeftScreen=, RightOuterPad=,OPENPAD1-video-2 ,LeftOuterPad=OPENPAD1-video-1, LeftScreen=MAINBOARD1-video-2

```<code>Dictionary<string, string> content = new Dictionary<string, string>();

content = ReadConfigFile(path);

Dictionary<GameObject, string> Screens = config.Screens;

List<string> ScreensNames = new List<string>();

foreach (var screen in Screens)
{
    ScreensNames.Add(screen.Key.name);
}

foreach (KeyValuePair<string, string> cont in content)
{
    if (ScreensNames.Contains(cont.Key))
    {
        Debug.Log(Screens);
        Screens[new GameObject(cont.Key)]= cont.Value;
    }
}
</code>```

答:
It sounds like what you are trying to do is

```<code>using System.Linq;

...

var keyObjectReference = Screens.keys.FirstOrDefault(o => string.Equals(o.name, cont.Key));
config.Screens[keyObjectReference] = cont.Value;
</code>```

this instead retrieves the first GameObject that has a matching name with cont.Key and uses that reference instead for accessing the correct entry in the config.Screens dictionary.

Title: Initilizing a dictionary issues

Body:
Instead of just initilizing

Screens (Dictionary<GameObject, string> Screens) values

this code creates a new gameObject screens with these associated values.

The problem is here:

Screens[new GameObject(cont.Key)] = cont.Value;

This is the result for screens : "Screens are created again with the associated values
RightOuterPad=, LeftOuterPad=, LeftScreen=, RightOuterPad=,OPENPAD1-video-2 ,LeftOuterPad=OPENPAD1-video-1, LeftScreen=MAINBOARD1-video-2

Dictionary<string, string> content = new Dictionary<string, string>();

content = ReadConfigFile(path);

Dictionary<GameObject, string> Screens = config.Screens;

List<string> ScreensNames = new List<string>();

foreach (var screen in Screens)
{
    ScreensNames.Add(screen.Key.name);
}

foreach (KeyValuePair<string, string> cont in content)
{
    if (ScreensNames.Contains(cont.Key))
    {
        Debug.Log(Screens);
        Screens[new GameObject(cont.Key)]= cont.Value;
    }
}

Body:
It sounds like what you are trying to do is

using System.Linq;

...

var keyObjectReference = Screens.keys.FirstOrDefault(o => string.Equals(o.name, cont.Key));
config.Screens[keyObjectReference] = cont.Value;

this instead retrieves the first GameObject that has a matching name with cont.Key and uses that reference instead for accessing the correct entry in the config.Screens dictionary.


问:
Dynamic Dropdown using semantic ui
Got a problem with semantic-ui dropdown. I've been using Semantic-Ui, and wanted to change the dropdown item dynamically. That is, when i choose the value from the first dropdown, the second dropdown's item is not getting reflected.

Here is the code snippet:

$(document).ready(function() {
  $("#programmetype").dropdown({
    onChange: function() {

      $('#servicetype').html(
        '
'+'
Choose..
'+''+'
'+

        '
ACP
' +
        '
 ART
'+'
 '+'
'
      );
      $('#servicetype').dropdown();
    }

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.1.1.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>

<div id="programmetype" class="ui selection dropdown select-
        language">
  <input type="hidden" name="programmetype">
  <div class="text">Choose..</div>
  <i class="dropdown icon"></i>
  <div class="menu">
    <div class="item" data-value="val1">Car</div>
    <div class="item" data-value="val2">Tank</div>
    <div class="item" data-value="val3">Plane</div>
  </div>
</div>

<div id="servicetype"></div></code>```

答:
Syntax Errors

You are making line breaks inside your strings, break the lines properly with a + operator and your script won't find a syntax error, thus your code should run.

Second Dropdown

About the second dropdown. you're missing something. Look at the first dropdown DOM structure. the parent element #programmetype has the classes ui selection dropdown select-language for the CSS to get applied.

But for your #servicetype, you don't have those classes and you never added them, so in the onChange of your first dropdown, add these classes, (check the script)

Also, you need a hidden input to hold the data which you missed. But it's there for the first dropdown. Check the snippet, I've added them.

Hope this helps.

Check the snippet bellow:

$(document).ready(function() {
  $("#programmetype").dropdown({
    onChange: function() {

      $('#servicetype').addClass('ui selection dropdown select-language'); // add these classes for the UI.
      $('#servicetype').html(
        '<input type="hidden" name="servicetype">' // you need a hidden input and the rest is fine
        +'
Choose..
'
        +''
        +'
'
        +'
ACP
'
        +'
 ART
'
        +'
'
        +'
'
      );
      $('#servicetype').dropdown();
    }

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.1.1.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>

<div id="programmetype" class="ui selection dropdown select-language">
  <input type="hidden" name="programmetype">
  <div class="text">Choose..</div>
  <i class="dropdown icon"></i>
  <div class="menu">
    <div class="item" data-value="val1">Car</div>
    <div class="item" data-value="val2">Tank</div>
    <div class="item" data-value="val3">Plane</div>
  </div>
</div>

<div id="servicetype"></div></code>```

Title: Dynamic Dropdown using semantic ui

Body:
Got a problem with semantic-ui dropdown. I've been using Semantic-Ui, and wanted to change the dropdown item dynamically. That is, when i choose the value from the first dropdown, the second dropdown's item is not getting reflected.

Here is the code snippet:

$(document).ready(function() {
  $("#programmetype").dropdown({
    onChange: function() {

      $('#servicetype').html(
        '
'+'
Choose..
'+''+'
'+

        '
ACP
' +
        '
 ART
'+'
 '+'
'
      );
      $('#servicetype').dropdown();
    }

  });
});

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">

  <input type="hidden" name="programmetype">

Choose..

Car

Tank

Plane

Body:
Syntax Errors

You are making line breaks inside your strings, break the lines properly with a + operator and your script won't find a syntax error, thus your code should run.

Second Dropdown

About the second dropdown. you're missing something. Look at the first dropdown DOM structure. the parent element #programmetype has the classes ui selection dropdown select-language for the CSS to get applied.

But for your #servicetype, you don't have those classes and you never added them, so in the onChange of your first dropdown, add these classes, (check the script)

Also, you need a hidden input to hold the data which you missed. But it's there for the first dropdown. Check the snippet, I've added them.

Hope this helps.

Check the snippet bellow:

$(document).ready(function() {
  $("#programmetype").dropdown({
    onChange: function() {

      $('#servicetype').addClass('ui selection dropdown select-language'); // add these classes for the UI.
      $('#servicetype').html(
        '<input type="hidden" name="servicetype">' // you need a hidden input and the rest is fine
        +'<div class="text">Choose..</div>'
        +'<i class="dropdown icon "></i>'
        +'<div class="menu">'
        +'<div class="item" data-value="acp">ACP</div>'
        +'<div class="item" data-value="art"> ART</div>'
        +'</div>'
        +'</div>'
      );
      $('#servicetype').dropdown();
    }

  });
});

<script src="https://code.jquery.com/jquery-3.1.1.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>

<div id="programmetype" class="ui selection dropdown select-language">
  <input type="hidden" name="programmetype">
  <div class="text">Choose..</div>
  <i class="dropdown icon"></i>
  <div class="menu">
    <div class="item" data-value="val1">Car</div>
    <div class="item" data-value="val2">Tank</div>
    <div class="item" data-value="val3">Plane</div>
  </div>
</div>

<div id="servicetype"></div>


问:
Find next greater number with zeros in sql number
I'm looking for a way to find next greater number starting by 1 and followed by zeros in Microsoft SQL. Numbers could vary in digits. ie:

Query: 9856, Result after procedure: 10000
Query: 98999, Result after procedure: 100000

Thanks.

EDIT: There is no chance of having negative numbers. This is a calculation for a energy meter. For example, numbers can go up to 99999 or 999999 or 9999999. When energy overcome that number, it will start again at 0. So I can't read what energy has been used in that period. To know it, I need to calculate the number as asked, then perform some basic maths.

There is no need for knowing what is going on on 10, 100, etc, because of the nature of the operation. It will only be used when the above escenario happend.

答:
You can do this with just arithmetic operations:</p>

```<code>select power(10, floor(log(v.n - 0.1, 10)) + 1)
from (values (1), (10), (8), (9982), (124)) v(n)
</code>```

Body:
You can do this with just arithmetic operations:

select power(10, floor(log(v.n - 0.1, 10)) + 1)
from (values (1), (10), (8), (9982), (124)) v(n)


问:
IndentationError: expected an indented block, but it seems correct
In the code I provided there is an

```<code>>IndentationError in line 10, or at the END of:

> while ((while_bolian == "") and (correct_count >= 0) and (total_count != 0)) or ((while_bolian == True) and (correct_count >= 0) and (total_count != 0)):
</code>```

However all my indentations seem correct, I am using pycharm and if I put my cursor just after the above line of code it says Indent Expected.

I have done research about this error however nothing seems to be helping with the problem.

```<code>    total_count = int(input("how many questions do you want to be in the quizz \n10.\n50.\n100.\n:"))
    try:
        while ((while_bolian == "") and (correct_count >= 0) and (total_count != 0)) or ((while_bolian == True) and (correct_count >= 0) and (total_count != 0)):
    except ValueError:
        print("please enter a question limit")

>     line 10
        except ValueError:
        ^
IndentationError: expected an indented block

> Process finished with exit code 1
</code>```

答:
The while need an instruction like pass, with an extra indentation.

Right now the while tries to run the except!

See for example Python syntax for an empty while loop

Body:
In the code I provided there is an

>IndentationError in line 10, or at the END of:

> while ((while_bolian == "") and (correct_count >= 0) and (total_count != 0)) or ((while_bolian == True) and (correct_count >= 0) and (total_count != 0)):

However all my indentations seem correct, I am using pycharm and if I put my cursor just after the above line of code it says Indent Expected.

I have done research about this error however nothing seems to be helping with the problem.

    total_count = int(input("how many questions do you want to be in the quizz \n10.\n50.\n100.\n:"))
    try:
        while ((while_bolian == "") and (correct_count >= 0) and (total_count != 0)) or ((while_bolian == True) and (correct_count >= 0) and (total_count != 0)):
    except ValueError:
        print("please enter a question limit")

>     line 10
        except ValueError:
        ^
IndentationError: expected an indented block

> Process finished with exit code 1


问:
JBehave RunningStoriesFailed exception ; org.jbehave.core.embedder.Embedder$RunningStoriesFailed
getting this error while executing the project :-

```<code>java.lang.RuntimeException: org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in running stories:
sample/test.story: org.jbehave.core.embedder.StoryManager$StoryExecutionFailed: sample/test.story
    at net.serenitybdd.jbehave.runners.SerenityReportingRunner.run(SerenityReportingRunner.java:169)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in running stories:
sample/test.story: org.jbehave.core.embedder.StoryManager$StoryExecutionFailed: sample/test.story
    at org.jbehave.core.embedder.Embedder$ThrowingRunningStoriesFailed.handleFailures(Embedder.java:553)
    at org.jbehave.core.embedder.Embedder.handleFailures(Embedder.java:238)
    at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:216)
    at net.serenitybdd.jbehave.embedders.ExtendedEmbedder.runStoriesAsPaths(ExtendedEmbedder.java:60)
    at net.serenitybdd.jbehave.runners.SerenityReportingRunner.run(SerenityReportingRunner.java:167)
    ... 5 more
</code>```

```<code>test.story :-
Meta:

Narrative:
As a user
I want to perform an action
So that I can achieve a business goal

Scenario: scenario description

Given a variable <var>

When save the variable <var>

Then display the variable

Examples:
|var|
|test|
</code>```

```<code>package sample;

import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;

import net.thucydides.core.annotations.Steps;

public class SampleScenario {

  @Steps
  private SampleBehaviour sampleBehaviour;

  @Given("a variable <var>")
  public void checkVar(String var){
    sampleBehaviour.checkVariable(var);
  }

  @When("save the variable <var>")
  public void setVar(String var){
    sampleBehaviour.setVariable(var);
  }

  @Then("display the variable")
  public void printVar(){
    sampleBehaviour.printVar();
  }

}

-----------------------------------------------------------------

package sample;

import net.thucydides.core.annotations.Step;
import net.thucydides.core.steps.ScenarioSteps;

public class SampleBehaviour extends ScenarioSteps {

  private String variable;

  @Step public void checkVariable(String var) {
    if (var == null) {
      System.out.println("var is not valid");
    }
  }

  @Step public void setVariable(String var) {
    variable = var;
  }

  @Step public void printVar() {
    System.out.println("var = " + variable);
  }
}

------------------------------------------------------------------

package testsuite;

import java.util.ArrayList;
import java.util.List;
import org.jbehave.core.annotations.BeforeStories;
import com.gdn.qa.util.restassured.HttpHeaderManager;
import com.gdn.qa.util.restassured.UserDefinedVariables;

import net.serenitybdd.jbehave.SerenityStories;

public class AcceptanceTestSuite extends SerenityStories {

  @BeforeStories
  public void initApi(){
    UserDefinedVariables.initDataUserDefinedVariables();
    HttpHeaderManager.addHeader("Content-Type","application/json");
    HttpHeaderManager.addHeader("Charset","UTF-8");
  }

  @Override
  public List<String> storyPaths(){
    List<String> testLink = new ArrayList<>();
    testLink.add("sample/test.story");
    return testLink;
  }
}
</code>```

答:
I had a similar issue after update my jbehave-core dependency from an old version 3.10 to 4.5.1 without update the jbehave-junit-runner.

Before the update I have two main dependencies:

```<code>    <dependency>
        <groupId>org.jbehave</groupId>
        <artifactId>jbehave-core</artifactId>
        <version>3.10</version>
    </dependency>
    <dependency>
        <groupId>de.codecentric</groupId>
        <artifactId>jbehave-junit-runner</artifactId>
        <version>1.2.0</version>
    </dependency>
</code>```

After update only the jbeave-core the tests broken:

```<code>    <dependency>
        <groupId>org.jbehave</groupId>
        <artifactId>jbehave-core</artifactId>
        <version>4.5.1</version>
    </dependency>
    <dependency>
        <groupId>de.codecentric</groupId>
        <artifactId>jbehave-junit-runner</artifactId>
        <version>1.2.0</version>
    </dependency>
</code>```

I had to update to a new version of jbehave-junit-runner as follow:

```<code>    <dependency>
        <groupId>org.jbehave</groupId>
        <artifactId>jbehave-core</artifactId>
        <version>4.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.github.valfirst</groupId>
        <artifactId>jbehave-junit-runner</artifactId>
        <version>2.3.0</version>
    </dependency>
</code>```

This fixed the issue.

Body:
getting this error while executing the project :-

java.lang.RuntimeException: org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in running stories:
sample/test.story: org.jbehave.core.embedder.StoryManager$StoryExecutionFailed: sample/test.story
    at net.serenitybdd.jbehave.runners.SerenityReportingRunner.run(SerenityReportingRunner.java:169)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.jbehave.core.embedder.Embedder$RunningStoriesFailed: Failures in running stories:
sample/test.story: org.jbehave.core.embedder.StoryManager$StoryExecutionFailed: sample/test.story
    at org.jbehave.core.embedder.Embedder$ThrowingRunningStoriesFailed.handleFailures(Embedder.java:553)
    at org.jbehave.core.embedder.Embedder.handleFailures(Embedder.java:238)
    at org.jbehave.core.embedder.Embedder.runStoriesAsPaths(Embedder.java:216)
    at net.serenitybdd.jbehave.embedders.ExtendedEmbedder.runStoriesAsPaths(ExtendedEmbedder.java:60)
    at net.serenitybdd.jbehave.runners.SerenityReportingRunner.run(SerenityReportingRunner.java:167)
    ... 5 more

test.story :-
Meta:

Narrative:
As a user
I want to perform an action
So that I can achieve a business goal

Scenario: scenario description

Given a variable <var>

When save the variable <var>

Then display the variable

Examples:
|var|
|test|

package sample;

import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;

import net.thucydides.core.annotations.Steps;

public class SampleScenario {

  @Steps
  private SampleBehaviour sampleBehaviour;

  @Given("a variable <var>")
  public void checkVar(String var){
    sampleBehaviour.checkVariable(var);
  }

  @When("save the variable <var>")
  public void setVar(String var){
    sampleBehaviour.setVariable(var);
  }

  @Then("display the variable")
  public void printVar(){
    sampleBehaviour.printVar();
  }

}

-----------------------------------------------------------------

package sample;

import net.thucydides.core.annotations.Step;
import net.thucydides.core.steps.ScenarioSteps;

public class SampleBehaviour extends ScenarioSteps {

  private String variable;

  @Step public void checkVariable(String var) {
    if (var == null) {
      System.out.println("var is not valid");
    }
  }

  @Step public void setVariable(String var) {
    variable = var;
  }

  @Step public void printVar() {
    System.out.println("var = " + variable);
  }
}

------------------------------------------------------------------

package testsuite;

import java.util.ArrayList;
import java.util.List;
import org.jbehave.core.annotations.BeforeStories;
import com.gdn.qa.util.restassured.HttpHeaderManager;
import com.gdn.qa.util.restassured.UserDefinedVariables;

import net.serenitybdd.jbehave.SerenityStories;

public class AcceptanceTestSuite extends SerenityStories {

  @BeforeStories
  public void initApi(){
    UserDefinedVariables.initDataUserDefinedVariables();
    HttpHeaderManager.addHeader("Content-Type","application/json");
    HttpHeaderManager.addHeader("Charset","UTF-8");
  }

  @Override
  public List<String> storyPaths(){
    List<String> testLink = new ArrayList<>();
    testLink.add("sample/test.story");
    return testLink;
  }
}

Body:
I had a similar issue after update my jbehave-core dependency from an old version 3.10 to 4.5.1 without update the jbehave-junit-runner.

Before the update I have two main dependencies:

    <dependency>
        <groupId>org.jbehave</groupId>
        <artifactId>jbehave-core</artifactId>
        <version>3.10</version>
    </dependency>
    <dependency>
        <groupId>de.codecentric</groupId>
        <artifactId>jbehave-junit-runner</artifactId>
        <version>1.2.0</version>
    </dependency>

After update only the jbeave-core the tests broken:

    <dependency>
        <groupId>org.jbehave</groupId>
        <artifactId>jbehave-core</artifactId>
        <version>4.5.1</version>
    </dependency>
    <dependency>
        <groupId>de.codecentric</groupId>
        <artifactId>jbehave-junit-runner</artifactId>
        <version>1.2.0</version>
    </dependency>

I had to update to a new version of jbehave-junit-runner as follow:

    <dependency>
        <groupId>org.jbehave</groupId>
        <artifactId>jbehave-core</artifactId>
        <version>4.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.github.valfirst</groupId>
        <artifactId>jbehave-junit-runner</artifactId>
        <version>2.3.0</version>
    </dependency>

This fixed the issue.


问:
Filtering data with spatie query builder using trait
I put logic from my function index() of UserController in trait taht i created:

```<code>public function index()
{
    $this->authorize('view', Auth::user());
    $users = QueryBuilder::for(User::class)
        ->allowedIncludes('kids','roles','articles','recordings')
        ->allowedFilters('first_name', 'last_name', 'email')
        ->get();
    return UserResource::collection($users);
}
</code>```

and this is my trait :

```<code><?php
namespace App\Http\Traits;

use App\Models\User;
use Spatie\QueryBuilder\QueryBuilder;

trait Filterable
{
  public function filter()
  {
    $users = QueryBuilder::for(User::class)
            ->allowedIncludes('kids','roles','articles','recordings')
            ->allowedFilters('first_name', 'last_name', 'email')
            ->get();
            return $users;
  }
}
</code>```

So now my function index() looks like this:

```<code>use Filterable;

    public function index()
    {
        $this->authorize('view', Auth::user());
        $users = $this->filter();
        return UserResource::collection($users);
</code>```

Now when i do this in my postman
{{url}}/api/users?filter[first_name]=anna
it works and it returns anna from my database but when I try
{{url}}/api/users?include=roles
it return every user from database but does not include roles.
Can somebody help me with this?

答:
This is taken straight from the github page: https://github.com/spatie/laravel-query-builder#custom-filters

Custom filters

```<code>use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;

class FiltersUserPermission implements Filter
{
    public function __invoke(Builder $query, $value, string $property) : Builder
    {
        return $query->whereHas('permissions', function (Builder $query) use ($value) {
            $query->where('name', $value);
        });
    }
}

use Spatie\QueryBuilder\Filter;

// GET /users?filter[permission]=createPosts
$users = QueryBuilder::for(User::class)
    ->allowedFilters(Filter::custom('permission', FiltersUserPermission::class))
    ->get();
// $users will contain all users that have the `createPosts` permission
</code>```

Body:
I put logic from my function index() of UserController in trait taht i created:

public function index()
{
    $this->authorize('view', Auth::user());
    $users = QueryBuilder::for(User::class)
        ->allowedIncludes('kids','roles','articles','recordings')
        ->allowedFilters('first_name', 'last_name', 'email')
        ->get();
    return UserResource::collection($users);
}

and this is my trait :

<?php
namespace App\Http\Traits;

use App\Models\User;
use Spatie\QueryBuilder\QueryBuilder;

trait Filterable
{
  public function filter()
  {
    $users = QueryBuilder::for(User::class)
            ->allowedIncludes('kids','roles','articles','recordings')
            ->allowedFilters('first_name', 'last_name', 'email')
            ->get();
            return $users;
  }
}

So now my function index() looks like this:

use Filterable;

    public function index()
    {
        $this->authorize('view', Auth::user());
        $users = $this->filter();
        return UserResource::collection($users);

Now when i do this in my postman
{{url}}/api/users?filter[first_name]=anna
it works and it returns anna from my database but when I try
{{url}}/api/users?include=roles
it return every user from database but does not include roles.
Can somebody help me with this?

Body:
This is taken straight from the github page: https://github.com/spatie/laravel-query-builder#custom-filters

Custom filters

use Spatie\QueryBuilder\Filters\Filter;
use Illuminate\Database\Eloquent\Builder;

class FiltersUserPermission implements Filter
{
    public function __invoke(Builder $query, $value, string $property) : Builder
    {
        return $query->whereHas('permissions', function (Builder $query) use ($value) {
            $query->where('name', $value);
        });
    }
}

use Spatie\QueryBuilder\Filter;

// GET /users?filter[permission]=createPosts
$users = QueryBuilder::for(User::class)
    ->allowedFilters(Filter::custom('permission', FiltersUserPermission::class))
    ->get();
// $users will contain all users that have the `createPosts` permission


问:
Custom ocmod modification not working in opencart version 3.0.2.0
I have successfully uploaded my customised .ocmod folder(.ocmode.zip) in the extension installer and got success message too. But this is not loading in the extensions.
I'm using opencart Version 3.0.3.2.

My files are in the structure:
 - upload
     - admin
     - catalog

Is there an alternative way to approach this?
Please help.

Thanks in advance.

答:
The issue is solved. It was a silly mistake. The folder structure was wrong.
The image folder was missing inside the admin folder, it is mandatory to keep the image folder even though there is no image inside it.  </p>


问:
Python: Waiting for all threads to be at a specific point in code to continue
I want to run a process on multiple threads, but after each iteration the processes should wait for a global process to finish. More specifically:

I have a list of "ants", which all construct a tour on a graph (this I want to do concurrently). This happens many times over many iterations. After each ant completed their iteration, I want to update the graph. How can I best do this? some code I have:

ants = [Ant() for _ in range(50)] # 50 ants in a list

with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex:
    # start threads on slices of ants
    f1 = ex.submit(solve_aco, ants[:n_ants//4], epochs)
    f2 = ex.submit(solve_aco, ants[n_ants//4:n_ants // 2], epochs)
    f3 = ex.submit(solve_aco, ants[n_ants // 2:n_ants // 2 + n_ants // 4], epochs)
    f4 = ex.submit(solve_aco, ants[n_ants // 2 + n_ants // 4:], epochs)

    # while not finished: if all ants are waiting, update graph

def solve_aco(ants, epochs):
    for _ in range(epochs):
        # Construct route through graph
        # Wait until graph update, then continue next epoch
```

I have tried some things with threading.Condition() but I can't seem to figure out where and how to wait / notify threads properly.

Thank you in advance!

答:
With concurrent.futures.wait() (https://docs.python.org/3/library/concurrent.futures.html#module-functions) you can wait for the work in your worker threads to complete before continuing.

BTW: Due to the global interpreter lock, if the work you're doing in solve_aco all happens in pure Python code, multithreading will not give you a performance boost. You can use the ProcessPoolExecutor instead, though it comes with more overhead. Basically, if executing solve_aco() takes a long time (many milliseconds), use a ProcessPoolExecutor. If not, you're probably better off just working in a single thread.

Body:
I want to run a process on multiple threads, but after each iteration the processes should wait for a global process to finish. More specifically:

I have a list of "ants", which all construct a tour on a graph (this I want to do concurrently). This happens many times over many iterations. After each ant completed their iteration, I want to update the graph. How can I best do this? some code I have:

ants = [Ant() for _ in range(50)] # 50 ants in a list

with concurrent.futures.ThreadPoolExecutor(max_workers=4) as ex:
    # start threads on slices of ants
    f1 = ex.submit(solve_aco, ants[:n_ants//4], epochs)
    f2 = ex.submit(solve_aco, ants[n_ants//4:n_ants // 2], epochs)
    f3 = ex.submit(solve_aco, ants[n_ants // 2:n_ants // 2 + n_ants // 4], epochs)
    f4 = ex.submit(solve_aco, ants[n_ants // 2 + n_ants // 4:], epochs)

    # while not finished: if all ants are waiting, update graph

def solve_aco(ants, epochs):
    for _ in range(epochs):
        # Construct route through graph
        # Wait until graph update, then continue next epoch

I have tried some things with threading.Condition() but I can't seem to figure out where and how to wait / notify threads properly.

Thank you in advance!