问:
How can i return a generic List<T> from a generic method<T>()
Good morning,

I have a class Product{} that has a Dictionary:

```<code>Dictionary<Type, List<IPropertyItem>> extensions;
</code>```

I save my data with this method:

```<code>public void SaveItem<T>(T item)
    {
        Type currentType = typeof(T);

        if (!extensions.ContainsKey(currentType))
        {
            extensions.Add(currentType, new List<IPropertyItem>());
        }

        if (currentType == typeof(Discount))
        {
            Discount newDiscount = (Discount)Convert.ChangeType(item, typeof(Discount));
            extensions[currentType].Add(newDiscount);
        }
        else if(currentType == typeof(Tax))
        {
            Tax newTax = (Tax)Convert.ChangeType(item, typeof(Tax));
            extensions[currentType].Add(newTax);
        }
        else if(currentType == typeof(Size))
        {
            Size newSize = (Size)Convert.ChangeType(item, typeof(Size));
            extensions[currentType].Add(newSize);
        }
    }
</code>```

now i want to get a list of a certain value type stored in my Dictionary, i mean i want that the method returns me a List like this function:

```<code>public List<T> GetExtensionsDictionary<T>()
    {
        Type currentType = typeof(T);
        List<T> returnedList = new List<T>();

        if (!extensions.ContainsKey(currentType))
        {
            return null;
        }

        return extensions[T];
    }
</code>```

The method that is calling above is:

```<code>List<Discount> myDiscounts = myProduct.GetExtensionsDictionary<Discount>();
</code>```

thnks,

any help will be appreciated...

答:
I believe this is all you want:

```<code>public List<T> GetExtensionsDictionary<T>()
{
    Type currentType = typeof(T);
    List<T> returnedList = new List<T>();

    if (!extensions.ContainsKey(currentType))
    {
        return null;
    }

    return extensions[currentType].Cast<T>().ToList();
}
</code>```

You have to index into extensions with currentType not T because T is a generic parameter and you need the runtime type that you get with typeof.

You can use the linq methods Cast and ToList to turn the collection at currentType in the dictionary into a List<T>.  This is making a copy of the list, so be mindful of performance considerations.

Make sure you are using System.Linq;

Body:
Good morning,

I have a class Product{} that has a Dictionary:

Dictionary<Type, List<IPropertyItem>> extensions;

I save my data with this method:

public void SaveItem<T>(T item)
    {
        Type currentType = typeof(T);

        if (!extensions.ContainsKey(currentType))
        {
            extensions.Add(currentType, new List<IPropertyItem>());
        }

        if (currentType == typeof(Discount))
        {
            Discount newDiscount = (Discount)Convert.ChangeType(item, typeof(Discount));
            extensions[currentType].Add(newDiscount);
        }
        else if(currentType == typeof(Tax))
        {
            Tax newTax = (Tax)Convert.ChangeType(item, typeof(Tax));
            extensions[currentType].Add(newTax);
        }
        else if(currentType == typeof(Size))
        {
            Size newSize = (Size)Convert.ChangeType(item, typeof(Size));
            extensions[currentType].Add(newSize);
        }
    }

now i want to get a list of a certain value type stored in my Dictionary, i mean i want that the method returns me a List like this function:

public List<T> GetExtensionsDictionary<T>()
    {
        Type currentType = typeof(T);
        List<T> returnedList = new List<T>();

        if (!extensions.ContainsKey(currentType))
        {
            return null;
        }

        return extensions[T];
    }

The method that is calling above is:

List<Discount> myDiscounts = myProduct.GetExtensionsDictionary<Discount>();

thnks,

any help will be appreciated...

Body:
I believe this is all you want:

public List<T> GetExtensionsDictionary<T>()
{
    Type currentType = typeof(T);
    List<T> returnedList = new List<T>();

    if (!extensions.ContainsKey(currentType))
    {
        return null;
    }

    return extensions[currentType].Cast<T>().ToList();
}

You have to index into extensions with currentType not T because T is a generic parameter and you need the runtime type that you get with typeof.

You can use the linq methods Cast and ToList to turn the collection at currentType in the dictionary into a List<T>.  This is making a copy of the list, so be mindful of performance considerations.

Make sure you are using System.Linq;


来源: stackexchange

问:
Opening modal doubles the request every time user clicks - Rails
I'm adding https://github.com/kylefox/jquery-modal - Jquery Modal. To my project. I added it to my application.js

```<code>//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery.modal.min
//= require pickadate/picker
//= require pickadate/picker.date
</code>```

This I included the jquery.modal.min.js in my JS Directory. Added this to my link:

```<code><%= link_to "Sign In", new_user_session_path, class: "button", rel: "modal:open" %>
</code>```

The good news is, The modal opens but for some reason it's outside my container so it includes the topbar and the footer and it just looks awful. But weirder than that. It doubles the request to the server everytime I click the link? Does anybody know what I could be doing wrong?

答:
A few things I think you should watch for:

Turbolinks could be the one that makes the first call, you may try to disable Turbolink for the link tag.

I would want to believe the header and footer are being included because the other page being loaded into the modal renders the layout. You may try disabling the layout for the said page and see if that works.

ContentLicense: CC BY-SA 3.0

Body:
I'm adding https://github.com/kylefox/jquery-modal - Jquery Modal. To my project. I added it to my application.js

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery.modal.min
//= require pickadate/picker
//= require pickadate/picker.date

This I included the jquery.modal.min.js in my JS Directory. Added this to my link:

<%= link_to "Sign In", new_user_session_path, class: "button", rel: "modal:open" %>

The good news is, The modal opens but for some reason it's outside my container so it includes the topbar and the footer and it just looks awful. But weirder than that. It doubles the request to the server everytime I click the link? Does anybody know what I could be doing wrong?


问:
How to efficient perform column wise multiply?
I am trying to apply multiple multiplication columns wise in data.table. Example:

```<code>require(data.table)
DT <- data.table(a=1:5,b=2:6,c=3:7,
                 d=rep(1,5),e=rep(0,5),f=rep(-1,5))
</code>```

I want the results of a * d, b * e, and c * f, because I have 400 columns multiply another 400 column,
I wonder if there are some efficient solution. Thanks!

答:
yeah,it's quite easy,but I confused so long!</p>

```<code>DT[,paste0("a",1:3):= DT[,1:3]*DT[,4:6]]
</code>```

Body:
I am trying to apply multiple multiplication columns wise in data.table. Example:

require(data.table)
DT <- data.table(a=1:5,b=2:6,c=3:7,
                 d=rep(1,5),e=rep(0,5),f=rep(-1,5))

I want the results of a * d, b * e, and c * f, because I have 400 columns multiply another 400 column,
I wonder if there are some efficient solution. Thanks!

Body:
yeah,it's quite easy,but I confused so long!

DT[,paste0("a",1:3):= DT[,1:3]*DT[,4:6]]


问:
Bash Script that loops command line arguments
I want to write a bash script that continually runs a program over and over incrementing the first four digits by one each time until the output of the program changes from one thing to another.

For example:

./exampleProgram userName 0000-4567-4561-4564

output: Wrong

./exampleProgram userName 0001-4567-4561-4564

output: Wrong

./exampleProgram userName 0002-4567-4561-4564

output: Correct

-Loop terminates

The last three sets of four digits will stay constant, it's only the first four that change so the worst case scenario is about 10,000 loops.

答:
For example:

```<code>exampleProgram() {      #demo
        echo "Debug: $1 $2" >&2
        (($RANDOM % 10)) && { echo "Wrong"; return 1; } || { echo "Correct for $1 $2" ; return 0; }
}

for i in {0000..9999}
do
        res=$(exampleProgram JohnDoe "$i-4567-4561-4564")
        [[ "$res" =~ Correct ]] && break;
done
echo "Loop terminated at ($i) - result $res"
</code>```

prints

```<code>Debug: JohnDoe 0000-4567-4561-4564
Debug: JohnDoe 0001-4567-4561-4564
Debug: JohnDoe 0002-4567-4561-4564
Debug: JohnDoe 0003-4567-4561-4564
Loop terminated at (0003) - result Correct for JohnDoe 0003-4567-4561-4564
</code>```

If the exampleProgram has different exit status it is better to check it instead of the returned string, like:

```<code>    res=$(exampleProgram JohnDoe "$i-4567-4561-4564")
    (( $? )) || break;
</code>```

Body:
For example:

exampleProgram() {      #demo
        echo "Debug: $1 $2" >&2
        (($RANDOM % 10)) && { echo "Wrong"; return 1; } || { echo "Correct for $1 $2" ; return 0; }
}

for i in {0000..9999}
do
        res=$(exampleProgram JohnDoe "$i-4567-4561-4564")
        [[ "$res" =~ Correct ]] && break;
done
echo "Loop terminated at ($i) - result $res"

prints

Debug: JohnDoe 0000-4567-4561-4564
Debug: JohnDoe 0001-4567-4561-4564
Debug: JohnDoe 0002-4567-4561-4564
Debug: JohnDoe 0003-4567-4561-4564
Loop terminated at (0003) - result Correct for JohnDoe 0003-4567-4561-4564

If the exampleProgram has different exit status it is better to check it instead of the returned string, like:

    res=$(exampleProgram JohnDoe "$i-4567-4561-4564")
    (( $? )) || break;


问:
Get groups from Active Directory using C#
I am having issues getting the groups from Active Directory via System.DirectoryServices

Originally I started my application on a computer that was registered on the domain, but as it was a live domain I did not want to do any writes to AD what so ever, so I set up a machine with Windows XP as the host operating system, and installed windows server 2003 on a VM.

I've added another Ethernet port in the machine and set up a switch, the 1 Ethernet port is dedicated to the VM and the other port is used for the host.

After configuring the IP addresses to get them communicating I transferred my application onto the host machine and fired it up, but I was getting an DirectoryServicesCOMException.

With the message that the user name and password was invalid :( just to check that it was not active directory I created a 3rd virtual machine and installed Windows XP, which i added to the domain with the credentials tested in the APP, works a treat.

So I thought it must be because the machine where the application is running is not part of the domain.

Heres the block of code that was causing the issue:

```<code>public CredentialValidation(String Domain, String Username, String Password, Boolean Secure)
{
     //Validate the Domain!
     try
     {
         PrincipalContext Context = new PrincipalContext(ContextType.Domain, Domain); //Throws Exception
         _IsValidDomain = true;

         //Test the user login
         _IsValidLogin = Context.ValidateCredentials(Username, Password);

         //Check the Group Admin is within this user
         //******HERE
         var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);

         foreach(Principal Result in Results)
         {
             if (Result.SamAccountName == "Domain Admins")
             {
                 _IsAdminGroup = true;
                 break;
             }
         }
         Results.Dispose();
         Context.Dispose();
     }
     catch (PrincipalServerDownException)
     {
         _IsValidDomain = false;
     }
 }
</code>```

The information in the login dialogue is being entered like so:

```<code>Domain: test.internal
Username: testaccount
Password: Password01
</code>```

Hope someone can shed some light in this error.

Update:

After checking the Security Logs on the server i can see that my log in attempts was successful, but this is down to:

```<code>_IsValidLogin = Context.ValidateCredentials(Username, Password);
</code>```

The line after where im checking the groups is causing the error, so the main issue is that the lines of code below are not working correctly from a machine thats not joined to the network:

```<code>var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);
</code>```

答:
I used to do quite a bit of user management via C# .NET. I just dug up some methods you can try.

The following two methods will get a DirectoryEntry object for a given SAM account name. It takes a DirectoryEntry that is the root of the OU you want to start searching for the account at.

The other will give you a list of distinguished names of the groups the user is a member of. You can then use those DN's to search AD and get a DirectoryEntry object.

```<code>public List<string> GetMemberOf(DirectoryEntry de)
{
  List<string> memberof = new List<string>();

  foreach (object oMember in de.Properties["memberOf"])
  {
    memberof.Add(oMember.ToString());
  }

  return memberof;
}

public DirectoryEntry GetObjectBySAM(string sam, DirectoryEntry root)
{
  using (DirectorySearcher searcher = new DirectorySearcher(root, string.Format("(sAMAccountName={0})", sam)))
  {
    SearchResult sr = searcher.FindOne();

    if (!(sr == null)) return sr.GetDirectoryEntry();
    else
      return null;
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am having issues getting the groups from Active Directory via System.DirectoryServices

Originally I started my application on a computer that was registered on the domain, but as it was a live domain I did not want to do any writes to AD what so ever, so I set up a machine with Windows XP as the host operating system, and installed windows server 2003 on a VM.

I've added another Ethernet port in the machine and set up a switch, the 1 Ethernet port is dedicated to the VM and the other port is used for the host.

After configuring the IP addresses to get them communicating I transferred my application onto the host machine and fired it up, but I was getting an DirectoryServicesCOMException.

With the message that the user name and password was invalid :( just to check that it was not active directory I created a 3rd virtual machine and installed Windows XP, which i added to the domain with the credentials tested in the APP, works a treat.

So I thought it must be because the machine where the application is running is not part of the domain.

Heres the block of code that was causing the issue:

public CredentialValidation(String Domain, String Username, String Password, Boolean Secure)
{
     //Validate the Domain!
     try
     {
         PrincipalContext Context = new PrincipalContext(ContextType.Domain, Domain); //Throws Exception
         _IsValidDomain = true;

         //Test the user login
         _IsValidLogin = Context.ValidateCredentials(Username, Password);

         //Check the Group Admin is within this user
         //******HERE
         var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);

         foreach(Principal Result in Results)
         {
             if (Result.SamAccountName == "Domain Admins")
             {
                 _IsAdminGroup = true;
                 break;
             }
         }
         Results.Dispose();
         Context.Dispose();
     }
     catch (PrincipalServerDownException)
     {
         _IsValidDomain = false;
     }
 }

The information in the login dialogue is being entered like so:

Domain: test.internal
Username: testaccount
Password: Password01

Hope someone can shed some light in this error.

Update:

After checking the Security Logs on the server i can see that my log in attempts was successful, but this is down to:

_IsValidLogin = Context.ValidateCredentials(Username, Password);

The line after where im checking the groups is causing the error, so the main issue is that the lines of code below are not working correctly from a machine thats not joined to the network:

var Results = UserPrincipal.FindByIdentity(Context, Username).GetGroups(Context);

Body:
I used to do quite a bit of user management via C# .NET. I just dug up some methods you can try.

The following two methods will get a DirectoryEntry object for a given SAM account name. It takes a DirectoryEntry that is the root of the OU you want to start searching for the account at.

The other will give you a list of distinguished names of the groups the user is a member of. You can then use those DN's to search AD and get a DirectoryEntry object.

public List<string> GetMemberOf(DirectoryEntry de)
{
  List<string> memberof = new List<string>();

  foreach (object oMember in de.Properties["memberOf"])
  {
    memberof.Add(oMember.ToString());
  }

  return memberof;
}

public DirectoryEntry GetObjectBySAM(string sam, DirectoryEntry root)
{
  using (DirectorySearcher searcher = new DirectorySearcher(root, string.Format("(sAMAccountName={0})", sam)))
  {
    SearchResult sr = searcher.FindOne();

    if (!(sr == null)) return sr.GetDirectoryEntry();
    else
      return null;
  }
}


问:
Javascript addEventListener function gets invoked without the Event being triggered
I may be overlooking something obvious but this just doesn't seem to go right.

I have this little code block in which an addEventListener method should trigger a function and meanwhile pass a parameter through so I can work with different functions while creating all EventListeners with one loop.
It does work, but the function gets invoked immediately when the site finishes loading.

Why doesn't the function wait until it gets triggered, but runs immediately?

```<code>var html = document.getElementsByTagName('html');
var pics = document.getElementsByClassName('pics');
var functions = [];

for(h=0;h<pics.length;h++){
    array[h] = show(h);
}

for(p=0;p<pics.length;p++){
    pics[p].addEventListener('click',array[p]);
}

function show(index){
    html[0].style.backgroundColor = "black";
}
</code>```

答:
array[h] = show(h); is being invoked on page load. Here is working code.

```<code>var html = document.getElementsByTagName('html');
var pics = document.getElementsByClassName('pics');
var functions = [];
var array = [];

for(h=0;h<pics.length;h++){
  array[h] = function () { show(h) };
}

for(p=0;p<pics.length;p++){
  pics[p].addEventListener('click',array[p]);
}

function show(index){
  html[0].style.backgroundColor = "black";
}
</code>```

Body:
I may be overlooking something obvious but this just doesn't seem to go right.

I have this little code block in which an addEventListener method should trigger a function and meanwhile pass a parameter through so I can work with different functions while creating all EventListeners with one loop.
It does work, but the function gets invoked immediately when the site finishes loading.

Why doesn't the function wait until it gets triggered, but runs immediately?

var html = document.getElementsByTagName('html');
var pics = document.getElementsByClassName('pics');
var functions = [];

for(h=0;h<pics.length;h++){
    array[h] = show(h);
}

for(p=0;p<pics.length;p++){
    pics[p].addEventListener('click',array[p]);
}

function show(index){
    html[0].style.backgroundColor = "black";
}

Body:
array[h] = show(h); is being invoked on page load. Here is working code.

var html = document.getElementsByTagName('html');
var pics = document.getElementsByClassName('pics');
var functions = [];
var array = [];

for(h=0;h<pics.length;h++){
  array[h] = function () { show(h) };
}

for(p=0;p<pics.length;p++){
  pics[p].addEventListener('click',array[p]);
}

function show(index){
  html[0].style.backgroundColor = "black";
}


问:
Online service for storing key/value pairs?
I am developing an android application. It does http communication with a web server. As of now, the web server IP address is hard coded. In the future, if I change to a different server with some other IP address, then I have to change the code. I know that probably having domain name/static address will solve this issue. But since my native app is specific for small devices, I need to find alternative easy solution.

As a solution, I am thinking of storing the key/value pairs in an online store service. So the app can query the online service for server ip and use the configured value. If IP changes, then I need to do modification in online service and need not change the app code. Is there any service which suits to my purpose?

Also are there any other better solutions to my requirement?

答:
You can use keyvalue.xyz. It is cloud key/value store service with REST API.

Disclaimer: I have developed the system.


问:
AngularJS/Karma/Jasmine - Service call not returning value
I'm attempting to make a call to a Github API using a service injected into a component - and yes, I am using AngularJS 1.5.3.

In the unit test, I am not receiving back a value (the function does work when I run it in the browser). I'm not sure what I'm doing wrong and hopefully someone could point me in the right direction.

Here's the error:

main.component.js

```<code>(function(){
    angular.module("app").component("mainComponent", {
        templateUrl: "/templates/main.component.html",
        controllerAs: "vm",
        controller: function(APIFactory, UserFactory, $state){
            const vm = this;

            vm.searchGithub = function(){
                APIFactory.getAPI(vm.searchText).then(function(res){
                    res.status !== 200 ? $state.go("404", {errorData: res.data }) : (
                        vm.User = new UserFactory.User(res.data),
                        $state.go("profile", {userData: vm.User})
                    );
                })
                .catch(function(err){
                    $state.go("fourOFour");
                });
            };
        }
    });
})();
</code>```

main.component.spec.js

```<code>describe("Main Component", function(){
    var mainComponent, APIFactory, UserFactory, $httpBackend, $q, $state, $rootScope;

    const addy = "https://api.github.com/users/";

    beforeEach(angular.mock.module("app"));

    beforeEach(inject(function(_APIFactory_, _UserFactory_, _$httpBackend_, _$state_, _$q_, _$rootScope_, _$componentController_){
        APIFactory = _APIFactory_;
        UserFactory = _UserFactory_;
        $httpBackend = _$httpBackend_;
        $state = _$state_;
        $q = _$q_;
        $rootScope = _$rootScope_;
        $rootScope.$new();
        mainComponent = _$componentController_("mainComponent", { $scope : {} });
    }));

    describe("Checking if the searchGithub() worked correctly", function(){
        var result;

        beforeEach(function(){
            spyOn(mainComponent, "searchGithub").and.callThrough();
            spyOn(APIFactory, "getAPI").and.callThrough();
            result = {};
        });

        it("should make a call to UserFactory", function(){
            mainComponent.searchText = "someName";
            expect(mainComponent.searchText).toBeDefined();

            // RESPONSE_SUCCESS does exist, I've omitted it.
            $httpBackend.whenGET(addy + mainComponent.searchText).respond(200, $q.when(RESPONSE_SUCCESS));

            // This is where I expect something to work

            APIFactory.getAPI(mainComponent.searchText).then(function(res){
                result = res;
            });

            $httpBackend.flush();

            expect(APIFactory.getAPI).toHaveBeenCalledWith(mainComponent.searchText);
            expect(mainComponent.User).toBeDefined();
        });
    });

});
</code>```

答:
So this is what I came up with for a solution. If anybody wants to give me a better solution, I am up for ideas.

First I made two mocks and then I injected them into mainComponent, as well as a spy for my mocked APIFactoryMock.getAPI function:

```<code>const APIFactoryMock = {
    getAPI: function(){}
};

const UserFactoryMock = {
    User: function(data){
        return {
            login: data.login,
            id: data.id,
            avatar_url: data.avatar_url,
            html_url: data.html_url,
            followers: data.followers,
            following: data.following,
            public_repos: data.public_repos,
            public_gists: data.public_gists,
            created_at: data.created_at,
            updated_at: data.updated_at,
            name: data.name,
            company: data.company,
            blog: data.blog,
            location: data.location,
            bio: data.bio,
            hireable: data.hireable,
            email: data.email,
            links: {
                followers_url: data.followers_url,
                following_url: data.following_url,
                subscriptions_url: data.subscriptions_url,
                repos_url: data.repos_url,
                organizations_url: data.organizations_url
            }
        }
    }
};

beforeEach(inject(function(_APIFactory_, _UserFactory_, _$httpBackend_, _$state_, _$q_, _$rootScope_, _$componentController_){
    APIFactory = _APIFactory_;
    UserFactory = _UserFactory_;
    $httpBackend = _$httpBackend_;
    $state = _$state_;
    $q = _$q_;
    $rootScope = _$rootScope_;
    $rootScope.$new();
    spyOn(APIFactoryMock, "getAPI").and.returnValue(RESPONSE_SUCCESS);
    bindings = { APIFactory: APIFactoryMock, UserFactory: UserFactoryMock, $state: $state };
    mainComponent = _$componentController_("mainComponent", { $scope : {} }, bindings);
}));
</code>```

And then I wrote tests for the mocks:

```<code>it("should make a call to UserFactory", function(){
        mainComponent.searchText = "someName";
        expect(mainComponent.searchText).toBeDefined();

        mainComponent.searchGithub(mainComponent.searchText);
        $httpBackend.whenGET(addy + mainComponent.searchText).respond(200, $q.when(RESPONSE_SUCCESS));

        $httpBackend.flush();

        mainComponent.User = UserFactoryMock.User(RESPONSE_SUCCESS.data);

        expect(mainComponent.searchGithub).toHaveBeenCalledWith(mainComponent.searchText);
        expect(mainComponent.User).toBeDefined();
        expect(mainComponent.User.id).toEqual(666);
    });
</code>```

Body:
I'm attempting to make a call to a Github API using a service injected into a component - and yes, I am using AngularJS 1.5.3.

In the unit test, I am not receiving back a value (the function does work when I run it in the browser). I'm not sure what I'm doing wrong and hopefully someone could point me in the right direction.

Here's the error:

main.component.js

(function(){
    angular.module("app").component("mainComponent", {
        templateUrl: "/templates/main.component.html",
        controllerAs: "vm",
        controller: function(APIFactory, UserFactory, $state){
            const vm = this;

            vm.searchGithub = function(){
                APIFactory.getAPI(vm.searchText).then(function(res){
                    res.status !== 200 ? $state.go("404", {errorData: res.data }) : (
                        vm.User = new UserFactory.User(res.data),
                        $state.go("profile", {userData: vm.User})
                    );
                })
                .catch(function(err){
                    $state.go("fourOFour");
                });
            };
        }
    });
})();

main.component.spec.js

describe("Main Component", function(){
    var mainComponent, APIFactory, UserFactory, $httpBackend, $q, $state, $rootScope;

    const addy = "https://api.github.com/users/";

    beforeEach(angular.mock.module("app"));

    beforeEach(inject(function(_APIFactory_, _UserFactory_, _$httpBackend_, _$state_, _$q_, _$rootScope_, _$componentController_){
        APIFactory = _APIFactory_;
        UserFactory = _UserFactory_;
        $httpBackend = _$httpBackend_;
        $state = _$state_;
        $q = _$q_;
        $rootScope = _$rootScope_;
        $rootScope.$new();
        mainComponent = _$componentController_("mainComponent", { $scope : {} });
    }));

    describe("Checking if the searchGithub() worked correctly", function(){
        var result;

        beforeEach(function(){
            spyOn(mainComponent, "searchGithub").and.callThrough();
            spyOn(APIFactory, "getAPI").and.callThrough();
            result = {};
        });

        it("should make a call to UserFactory", function(){
            mainComponent.searchText = "someName";
            expect(mainComponent.searchText).toBeDefined();

            // RESPONSE_SUCCESS does exist, I've omitted it.
            $httpBackend.whenGET(addy + mainComponent.searchText).respond(200, $q.when(RESPONSE_SUCCESS));

            // This is where I expect something to work

            APIFactory.getAPI(mainComponent.searchText).then(function(res){
                result = res;
            });

            $httpBackend.flush();

            expect(APIFactory.getAPI).toHaveBeenCalledWith(mainComponent.searchText);
            expect(mainComponent.User).toBeDefined();
        });
    });

});

Body:
So this is what I came up with for a solution. If anybody wants to give me a better solution, I am up for ideas.

First I made two mocks and then I injected them into mainComponent, as well as a spy for my mocked APIFactoryMock.getAPI function:

const APIFactoryMock = {
    getAPI: function(){}
};

const UserFactoryMock = {
    User: function(data){
        return {
            login: data.login,
            id: data.id,
            avatar_url: data.avatar_url,
            html_url: data.html_url,
            followers: data.followers,
            following: data.following,
            public_repos: data.public_repos,
            public_gists: data.public_gists,
            created_at: data.created_at,
            updated_at: data.updated_at,
            name: data.name,
            company: data.company,
            blog: data.blog,
            location: data.location,
            bio: data.bio,
            hireable: data.hireable,
            email: data.email,
            links: {
                followers_url: data.followers_url,
                following_url: data.following_url,
                subscriptions_url: data.subscriptions_url,
                repos_url: data.repos_url,
                organizations_url: data.organizations_url
            }
        }
    }
};

beforeEach(inject(function(_APIFactory_, _UserFactory_, _$httpBackend_, _$state_, _$q_, _$rootScope_, _$componentController_){
    APIFactory = _APIFactory_;
    UserFactory = _UserFactory_;
    $httpBackend = _$httpBackend_;
    $state = _$state_;
    $q = _$q_;
    $rootScope = _$rootScope_;
    $rootScope.$new();
    spyOn(APIFactoryMock, "getAPI").and.returnValue(RESPONSE_SUCCESS);
    bindings = { APIFactory: APIFactoryMock, UserFactory: UserFactoryMock, $state: $state };
    mainComponent = _$componentController_("mainComponent", { $scope : {} }, bindings);
}));

And then I wrote tests for the mocks:

it("should make a call to UserFactory", function(){
        mainComponent.searchText = "someName";
        expect(mainComponent.searchText).toBeDefined();

        mainComponent.searchGithub(mainComponent.searchText);
        $httpBackend.whenGET(addy + mainComponent.searchText).respond(200, $q.when(RESPONSE_SUCCESS));

        $httpBackend.flush();

        mainComponent.User = UserFactoryMock.User(RESPONSE_SUCCESS.data);

        expect(mainComponent.searchGithub).toHaveBeenCalledWith(mainComponent.searchText);
        expect(mainComponent.User).toBeDefined();
        expect(mainComponent.User.id).toEqual(666);
    });


问:
mysql: can I send debug messages to log file using mysql commands?
I would like to debug my stored procedures properly, the easiest way i can think of is to be able to send debug messages to the log file of mysql. is that possible ?!</p>

答:
As I have not heard of anything like that I will recommend you this http://benjisimon.blogspot.com/2007/02/debugging-mysql-stored-procedures.html

or read this topic How do you debug MySQL stored procedures?


问:
Change layout direction of flexed boxes reliably
I'm trying to achieve the following layout changes with css3 only. My main problem here is, that I don't want to add sizes explicitly. I'd prefer to let the layout flow freely. I'm using the css flexbox. And after an automatic wrap the layout direction of the small items should change.

I made this behavior almost work with @media(orientation: portrait). But then I still have restrictions on the size of the red box. You find that there's a third state with the yellow items being displayed horizontally next to the red box.

div {
  min-width: 50px;
  min-height: 50px;
  margin: 8px;
  justify-content: flex-end;
}

#body {
  background: lightgray;
  padding: 8px;
  display: flex;
  flex-wrap: wrap;
}

#box {
  background: lightpink;
  min-width: 150px;
  height: 220px;
  flex-grow: 1;
}

.item {
  background: lightyellow;
}

#wrap {
  margin: 0;
}

@media(orientation: portrait) {
  #wrap {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><title>Example</title>
<div id="body">
  <div id="box"></div>
  <div id="wrap">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
</div></code>```

Please not that all sizes are purely superficial.

I was wondering if it's possible to force the item box to wrap when the landscape mode is active. Or maybe have a selector for the red box filling the complete horizontal viewport.

答:
you can use a display:block on the div with id body and add this in your media rule

```<code>@media(orientation: portrait) {
#wrap { display: flex; flex-wrap: wrap; justify-content: flex-end;border:solid red;}
#body{display:block;}
}
</code>```

fiddle here with resizable window else

snippet

<!DOCTYPE html>
<meta charset="utf-8">

<title>Example</title>

```

Body:
I'm trying to achieve the following layout changes with css3 only. My main problem here is, that I don't want to add sizes explicitly. I'd prefer to let the layout flow freely. I'm using the css flexbox. And after an automatic wrap the layout direction of the small items should change.

I made this behavior almost work with @media(orientation: portrait). But then I still have restrictions on the size of the red box. You find that there's a third state with the yellow items being displayed horizontally next to the red box.

div {
  min-width: 50px;
  min-height: 50px;
  margin: 8px;
  justify-content: flex-end;
}

#body {
  background: lightgray;
  padding: 8px;
  display: flex;
  flex-wrap: wrap;
}

#box {
  background: lightpink;
  min-width: 150px;
  height: 220px;
  flex-grow: 1;
}

.item {
  background: lightyellow;
}

#wrap {
  margin: 0;
}

@media(orientation: portrait) {
  #wrap {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
  }
}

<title>Example</title>

Please not that all sizes are purely superficial.

I was wondering if it's possible to force the item box to wrap when the landscape mode is active. Or maybe have a selector for the red box filling the complete horizontal viewport.

Body:
you can use a display:block on the div with id body and add this in your media rule

@media(orientation: portrait) {
#wrap { display: flex; flex-wrap: wrap; justify-content: flex-end;border:solid red;}
#body{display:block;}
}

fiddle here with resizable window else

snippet

<!DOCTYPE html>
<meta charset="utf-8">
<style type="text/css">
div { min-width: 50px; min-height: 50px; margin: 8px; justify-content: flex-end; }
#body { background: lightgray; padding: 8px; display: flex; flex-wrap: wrap; }
#box { background: lightpink; min-width: 150px; height: 220px; flex-grow: 1; }
.item { background: lightyellow; }
#wrap { margin: 0;border:solid green; }
#break{}
@media(orientation: portrait) {
#wrap { display: flex; flex-wrap: wrap; justify-content: flex-end;border:solid red;}
#body{display:block;}
}
</style>
<title>Example</title>
<div id="body">
<div id="box"></div>
<div id="wrap">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div></div>


问:
How to add the data in the same row but in diffrent columns according to the hotel names
My db is storing hotel_names in 1-7 rows but counts are stored in 8-14 rows.i want to store counts according to hotel_name.
Actually i am stuck at one point. i want to display like this:

```<code> Hotel_id   Hotel_name| Is_pool |   Pool_count
1   cAnberra hotel  1   1.4
2   Hayat hotel     1   1.2
3   grand           1    1.0
4   New one hotel   1   1.99
5   7 hotels        1   0.98
6   New light       1   0.78
7   Lime light hotel1   0.1
</code>```

but my code is dislaying :

```<code>Hotel_id    Hotel_name  Is_pool Pool_count
  1    cAnberra hotel        1
  2     Hayat hotel          1
  3     grand                1
  4     New one hotel        1
  5     7 hotels             1
  6      New light           1
  7     Lime light hotel     1
  8                                1.4
  9                                1.2
  10                               1.0
  11                               1.99
  12                               0.98
  13                               0.78
  14                               0.1
</code>```

This is my code:

```<code>for hotel in myarrayUrl[ind_pos]:
    print("The myarrayUrl converted to a list")
    print(hotel)

    c.execute("INSERT INTO hotels (hotel_name, is_pool) VALUES (?,?)" , [hotel,1])

for count in myarray[ind_pos]:

    print("The myarray converted to a list")
    print(count)

    c.execute("INSERT INTO hotels (pool_count)  VALUES (?)" , [count])
</code>```

help me.thanks in advance.

答:
Each INSERT statement creates a new row.

To change some value in an existing row, you would need to do an UPDATE.

However, in this case, you should just insert all values into the same row at once:

```<code>for hotel, count in zip(myarrayUrl[ind_pos], myarray[ind_pos]):
    c.execute('INSERT INTO hotels(hotel_name, is_pool, pool_count) VALUES (?, ?, ?)',
              [hotel, 1, count])
</code>```

Body:
My db is storing hotel_names in 1-7 rows but counts are stored in 8-14 rows.i want to store counts according to hotel_name.
Actually i am stuck at one point. i want to display like this:

 Hotel_id   Hotel_name| Is_pool |   Pool_count
1   cAnberra hotel  1   1.4
2   Hayat hotel     1   1.2
3   grand           1    1.0
4   New one hotel   1   1.99
5   7 hotels        1   0.98
6   New light       1   0.78
7   Lime light hotel1   0.1

but my code is dislaying :

Hotel_id    Hotel_name  Is_pool Pool_count
  1    cAnberra hotel        1
  2     Hayat hotel          1
  3     grand                1
  4     New one hotel        1
  5     7 hotels             1
  6      New light           1
  7     Lime light hotel     1
  8                                1.4
  9                                1.2
  10                               1.0
  11                               1.99
  12                               0.98
  13                               0.78
  14                               0.1

This is my code:

for hotel in myarrayUrl[ind_pos]:
    print("The myarrayUrl converted to a list")
    print(hotel)

    c.execute("INSERT INTO hotels (hotel_name, is_pool) VALUES (?,?)" , [hotel,1])

for count in myarray[ind_pos]:

    print("The myarray converted to a list")
    print(count)

    c.execute("INSERT INTO hotels (pool_count)  VALUES (?)" , [count])

help me.thanks in advance.

Body:
Each INSERT statement creates a new row.

To change some value in an existing row, you would need to do an UPDATE.

However, in this case, you should just insert all values into the same row at once:

for hotel, count in zip(myarrayUrl[ind_pos], myarray[ind_pos]):
    c.execute('INSERT INTO hotels(hotel_name, is_pool, pool_count) VALUES (?, ?, ?)',
              [hotel, 1, count])


问:
Jasper reports are missing in Eclipse metadata folder
I am working on dynamic web project using Eclipse. I have created a report using Jaspersoft Studio. Now I am trying to access the same from my jsp. But i am getting below error:

java.io.FileNotFoundException: /home/kavi/dev/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/inqc/Blank_A4_Landscape.jasper

Please snap shows my report location. But as per above error, those files are missing in above path. So please someone help to resolve this error.

答:
How are you trying to access the file? Using java.io.File?

Try using the absolute path, something like /home/kavi/dev/workspace/inqc/Blank_A4_Landscape.jasper as opposed to navigating via the .metadata folder and see if it works.

Update:

A sample jsp file that reads text from a .txt file and prints it.

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.io.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%
        String s = null;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File("C:/Eclipse/workspace/Temp/sample.txt")));
            s = reader.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
    %>

    <p>String is <%=s %></p>

</body>
</html>
</code>```

Body:
How are you trying to access the file? Using java.io.File?

Try using the absolute path, something like /home/kavi/dev/workspace/inqc/Blank_A4_Landscape.jasper as opposed to navigating via the .metadata folder and see if it works.

Update:

A sample jsp file that reads text from a .txt file and prints it.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.io.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%
        String s = null;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File("C:/Eclipse/workspace/Temp/sample.txt")));
            s = reader.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
    %>

    <p>String is <%=s %></p>

</body>
</html>


问:
MUC/Sub Remove user subscription automatically
I am trying to develop a chat app using Ejabberd 16.09, the only way i find to unsubscribe a user is

```<code><iq from='hag66@shakespeare.example'
to='coven@muc.shakespeare.example'
type='set'
id='E6E10350-76CF-40C6-B91B-1EA08C332FC7'>
</code>```

There is any way to automatically unsubscribe the user when he leave the room?

Or anyway to someone else to remove his subscription?

答:
There is any way to automatically unsubscribe the user when he leave
  the room?

No.It can not be done.
The purpose of introducing MUC/Sub is that even if user is not part of room, one can get notification/messages via subscription which won't happen in case of normal muc behavior(xep-0045).

If you want to unsubscribe when user leaves room, then i don't see any reason why you are using MUC/SUB.Normal MUC will properly suit for your behavior.

Body:
I am trying to develop a chat app using Ejabberd 16.09, the only way i find to unsubscribe a user is

<iq from='hag66@shakespeare.example'
to='coven@muc.shakespeare.example'
type='set'
id='E6E10350-76CF-40C6-B91B-1EA08C332FC7'>

There is any way to automatically unsubscribe the user when he leave the room?

Or anyway to someone else to remove his subscription?


问:
Setting divider location on a JSplitPane
I'd like to have 3 resizable horizontally JPanels. It works fine but I can not set the position of the first JSlitPane: sp.setDividerLocation(.3); doesn't work.

```<code>public class JSplitPanelProva extends JFrame {

        public JSplitPanelProva() {
            this.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel();
            leftPanel.setBackground(Color.BLUE);
            JPanel centerPanel = new JPanel();
            centerPanel.setBackground(Color.CYAN);
            JPanel rightPanel = new JPanel();
            rightPanel.setBackground(Color.GREEN);

            JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, centerPanel);
            JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp, rightPanel);

            sp.setOneTouchExpandable(true);
            sp2.setOneTouchExpandable(true);

            this.add(sp2, BorderLayout.CENTER);

            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            this.setSize(1000, 600);
            this.setVisible(true);

            sp.setDividerLocation(.3);
            sp2.setDividerLocation(.6);
        }

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            new JSplitPanelProva();

        }

    }
</code>```

I get this:

Can someone help me?
Thanks.

答:
It looks like 3 things need to happen:

The divider location can't be set until the frame is visible

Setting the location of the second split pane needs to be done first

Setting the location of the first split pane needs to be added to the end of on the Event Dispatch Thread (EDT)

The following code will accomplish all 3:

```<code>this.setVisible(true);

sp2.setDividerLocation(.6);

SwingUtilities.invokeLater(new Runnable()
{
    public void run()
    {
        sp.setDividerLocation(.3);
    }
});
</code>```

Note: all Swing components should be create on the EDT. So you should also be using the following to create the frame:

```<code>EventQueue.invokeLater(new Runnable()
{
    public void run()
    {
        new JSplitPaneProva();
    }
});
</code>```

Body:
I'd like to have 3 resizable horizontally JPanels. It works fine but I can not set the position of the first JSlitPane: sp.setDividerLocation(.3); doesn't work.

public class JSplitPanelProva extends JFrame {

        public JSplitPanelProva() {
            this.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel();
            leftPanel.setBackground(Color.BLUE);
            JPanel centerPanel = new JPanel();
            centerPanel.setBackground(Color.CYAN);
            JPanel rightPanel = new JPanel();
            rightPanel.setBackground(Color.GREEN);

            JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, centerPanel);
            JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp, rightPanel);

            sp.setOneTouchExpandable(true);
            sp2.setOneTouchExpandable(true);

            this.add(sp2, BorderLayout.CENTER);

            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            this.setSize(1000, 600);
            this.setVisible(true);

            sp.setDividerLocation(.3);
            sp2.setDividerLocation(.6);
        }

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            new JSplitPanelProva();

        }

    }

I get this:

Can someone help me?
Thanks.

Body:
It looks like 3 things need to happen:

The divider location can't be set until the frame is visible

Setting the location of the second split pane needs to be done first

Setting the location of the first split pane needs to be added to the end of on the Event Dispatch Thread (EDT)

The following code will accomplish all 3:

this.setVisible(true);

sp2.setDividerLocation(.6);

SwingUtilities.invokeLater(new Runnable()
{
    public void run()
    {
        sp.setDividerLocation(.3);
    }
});

Note: all Swing components should be create on the EDT. So you should also be using the following to create the frame:

EventQueue.invokeLater(new Runnable()
{
    public void run()
    {
        new JSplitPaneProva();
    }
});


问:
PostgreSQL, trigrams and similarity
Just testing PostgreSQL 9.6.2 on my Mac and playing with Ngrams.
Assuming there is a GIN trigram index on winery field.

The limit for similarity (I know this is deprecated):

```<code>SELECT set_limit(0.5);
</code>```

I'm building a trigram search on 2,3M row table.

My select code:

```<code>SELECT winery, similarity(winery, 'chateau chevla blanc') AS similarity
FROM usr_wines
WHERE status=1 AND winery % 'chateau chevla blanc'
ORDER BY similarity DESC;
</code>```

My results (329 ms on my mac):

```<code>Chateau ChevL Blanc 0,85
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc,  0,736842
Chateau Blanc   0,736842
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc (7)    0,666667
Chateau Cheval Blanc Cbo    0,64
Chateau Du Cheval Blanc 0,64
Chateau Du Cheval Blanc 0,64
</code>```

Well, I don't understand how can "Chateau blanc" have a similarity > to "Chateau Cheval Blanc" in this case ? I understand that the 2 words are the exact same "chateau" and "blanc", but there is no other word "cheval".

Also why "Chateau ChevL Blanc" is first ? A letter "a" is missing !

Well, my goal is to match all possible duplicates when I give a winery name, even if it's mispelled. What did I miss ?

答:
The concept of trigram similarity relies on having any sentence divided into "trigrams" (sequences of three consecutive letters), and treating the result as a SET (i.e.: the order doesn't matter, and you don't have repeated values). Before the sentence is considered, two blank spaces are added at the beginning, and one at the end, and single spaces are replaced by double ones.

Trigrams are a special case of N-grams.

The trigram set corresponding to "Chateau blanc" is found by finding all sequences of three letters that appear on it:

  chateau  blanc
---                 => '  c'
 ---                => ' ch'
  ---               => 'cha'
   ---              => 'hat'
    ---             => 'ate'
     ---            => 'tea'
      ---           => 'eau'
       ---          => 'au '
        ---         => 'u  '
         ---        => '  b'
          ---       => ' bl'
           ---      => 'bla'
            ---     => 'lan'
             ---    => 'anc'
              ---   => 'nc '
```

<p>Sorting them, and taking out repetitions gets you:</p>

```'  b'
'  c'
' bl'
' ch'
'anc'
'ate'
'au '
'bla'
'cha'
'eau'
'hat'
'lan'
'nc '
'tea'
```

<p>This can be computed by PostgreSQL by means of the function <code>show_trgm</code>:</p>

```SELECT show_trgm('Chateau blanc') AS A

A = [  b,  c, bl, ch,anc,ate,au ,bla,cha,eau,hat,lan,nc ,tea]
```

<p>... which has 14 trigrams.  (Check pg_trgm).</p>

<p>And the trigram set corresponding to "Chateau Cheval Blanc" is:</p>

```SELECT show_trgm('Chateau Cheval Blanc') AS B

B = [  b,  c, bl, ch,anc,ate,au ,bla,cha,che,eau,evl,hat,hev,la ,lan,nc ,tea,vla]
```

<p>... which has 19 trigrams</p>

<p>If you count how many trigrams have both sets in common, you find that they have the following ones:</p>

```A intersect B =
    [  b,  c, bl, ch,anc,ate,au ,bla,cha,eau,hat,lan,nc ,tea]
```

<p>and the ones they have in total are:</p>

```A union B =
    [  b,  c, bl, ch,anc,ate,au ,bla,cha,che,eau,evl,hat,hev,la ,lan,nc ,tea,vla]
```

<p>That is, both sentences have 14 trigrams in common, and 19 in total.<br>
The similarity is computed as:</p>

<pre class="lang-none prettyprint-override"><code> similarity = 14 / 19
</code>```

You can check it with:

```<code>SELECT
    cast(14.0/19.0 as real) AS computed_result,
    similarity('Chateau blanc', 'chateau cheval blanc') AS function_in_pg
</code>```

and you'll see that you get: 0.736842

... which explains how similarity is computed, and why you get the values you get.

NOTE: You can compute the intersection and union by means of:

```<code>SELECT
   array_agg(t) AS in_common
FROM
(
    SELECT unnest(show_trgm('Chateau blanc')) AS t
    INTERSECT
    SELECT unnest(show_trgm('chateau chevla blanc')) AS t
    ORDER BY t
) AS trigrams_in_common ;

SELECT
   array_agg(t) AS in_total
FROM
(
    SELECT unnest(show_trgm('Chateau blanc')) AS t
    UNION
    SELECT unnest(show_trgm('chateau chevla blanc')) AS t
) AS trigrams_in_total ;
</code>```

And this is a way to explore the similarity of different pair of sentences:

```<code>WITH p AS
(
    SELECT
      'This is just a sentence I''ve invented'::text AS f1,
      'This is just a sentence I''ve also invented'::text AS f2
),
t1 AS
(
    SELECT unnest(show_trgm(f1)) FROM p
),
t2 AS
(
    SELECT unnest(show_trgm(f2)) FROM p
),
x AS
(
    SELECT
        (SELECT count(*) FROM
            (SELECT * FROM t1 INTERSECT SELECT * FROM t2) AS s0)::integer AS same,
        (SELECT count(*) FROM
            (SELECT * FROM t1 UNION     SELECT * FROM t2) AS s0)::integer AS total,
        similarity(f1, f2) AS sim_2
FROM
    p
)
SELECT
    same, total, same::real/total::real AS sim_1, sim_2
FROM
    x ;
</code>```

You can check it at Rextester

Title: PostgreSQL, trigrams and similarity

Body:
Just testing PostgreSQL 9.6.2 on my Mac and playing with Ngrams.
Assuming there is a GIN trigram index on winery field.

The limit for similarity (I know this is deprecated):

SELECT set_limit(0.5);

I'm building a trigram search on 2,3M row table.

My select code:

SELECT winery, similarity(winery, 'chateau chevla blanc') AS similarity
FROM usr_wines
WHERE status=1 AND winery % 'chateau chevla blanc'
ORDER BY similarity DESC;

My results (329 ms on my mac):

Chateau ChevL Blanc 0,85
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc   0,736842
Chateau Blanc,  0,736842
Chateau Blanc   0,736842
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc    0,727273
Chateau Cheval Blanc (7)    0,666667
Chateau Cheval Blanc Cbo    0,64
Chateau Du Cheval Blanc 0,64
Chateau Du Cheval Blanc 0,64

Well, I don't understand how can "Chateau blanc" have a similarity > to "Chateau Cheval Blanc" in this case ? I understand that the 2 words are the exact same "chateau" and "blanc", but there is no other word "cheval".

Also why "Chateau ChevL Blanc" is first ? A letter "a" is missing !

Well, my goal is to match all possible duplicates when I give a winery name, even if it's mispelled. What did I miss ?

Body:
The concept of trigram similarity relies on having any sentence divided into "trigrams" (sequences of three consecutive letters), and treating the result as a SET (i.e.: the order doesn't matter, and you don't have repeated values). Before the sentence is considered, two blank spaces are added at the beginning, and one at the end, and single spaces are replaced by double ones.

Trigrams are a special case of N-grams.

The trigram set corresponding to "Chateau blanc" is found by finding all sequences of three letters that appear on it:

  chateau  blanc
---                 => '  c'
 ---                => ' ch'
  ---               => 'cha'
   ---              => 'hat'
    ---             => 'ate'
     ---            => 'tea'
      ---           => 'eau'
       ---          => 'au '
        ---         => 'u  '
         ---        => '  b'
          ---       => ' bl'
           ---      => 'bla'
            ---     => 'lan'
             ---    => 'anc'
              ---   => 'nc '

Sorting them, and taking out repetitions gets you:

'  b'
'  c'
' bl'
' ch'
'anc'
'ate'
'au '
'bla'
'cha'
'eau'
'hat'
'lan'
'nc '
'tea'

This can be computed by PostgreSQL by means of the function show_trgm:

SELECT show_trgm('Chateau blanc') AS A

A = [  b,  c, bl, ch,anc,ate,au ,bla,cha,eau,hat,lan,nc ,tea]

... which has 14 trigrams.  (Check pg_trgm).

And the trigram set corresponding to "Chateau Cheval Blanc" is:

SELECT show_trgm('Chateau Cheval Blanc') AS B

B = [  b,  c, bl, ch,anc,ate,au ,bla,cha,che,eau,evl,hat,hev,la ,lan,nc ,tea,vla]

... which has 19 trigrams

If you count how many trigrams have both sets in common, you find that they have the following ones:

A intersect B =
    [  b,  c, bl, ch,anc,ate,au ,bla,cha,eau,hat,lan,nc ,tea]

and the ones they have in total are:

A union B =
    [  b,  c, bl, ch,anc,ate,au ,bla,cha,che,eau,evl,hat,hev,la ,lan,nc ,tea,vla]

That is, both sentences have 14 trigrams in common, and 19 in total.

The similarity is computed as:

 similarity = 14 / 19

You can check it with:

SELECT
    cast(14.0/19.0 as real) AS computed_result,
    similarity('Chateau blanc', 'chateau cheval blanc') AS function_in_pg

and you'll see that you get: 0.736842

... which explains how similarity is computed, and why you get the values you get.

NOTE: You can compute the intersection and union by means of:

SELECT
   array_agg(t) AS in_common
FROM
(
    SELECT unnest(show_trgm('Chateau blanc')) AS t
    INTERSECT
    SELECT unnest(show_trgm('chateau chevla blanc')) AS t
    ORDER BY t
) AS trigrams_in_common ;

SELECT
   array_agg(t) AS in_total
FROM
(
    SELECT unnest(show_trgm('Chateau blanc')) AS t
    UNION
    SELECT unnest(show_trgm('chateau chevla blanc')) AS t
) AS trigrams_in_total ;

And this is a way to explore the similarity of different pair of sentences:

WITH p AS
(
    SELECT
      'This is just a sentence I''ve invented'::text AS f1,
      'This is just a sentence I''ve also invented'::text AS f2
),
t1 AS
(
    SELECT unnest(show_trgm(f1)) FROM p
),
t2 AS
(
    SELECT unnest(show_trgm(f2)) FROM p
),
x AS
(
    SELECT
        (SELECT count(*) FROM
            (SELECT * FROM t1 INTERSECT SELECT * FROM t2) AS s0)::integer AS same,
        (SELECT count(*) FROM
            (SELECT * FROM t1 UNION     SELECT * FROM t2) AS s0)::integer AS total,
        similarity(f1, f2) AS sim_2
FROM
    p
)
SELECT
    same, total, same::real/total::real AS sim_1, sim_2
FROM
    x ;

You can check it at Rextester

ContentLicense: CC BY-SA 4.0


问:
VB6 Run time error 424
I am getting error 424 on this line, can anyone help me please.

```<code>lblprvbal.Text = Val(NewItem.SubItems(11))
</code>```

```<code>Private Sub cmdShow_Click()
'lblTotPur/lblTotPayRet/lblBalance
Dim strShow, mSlNo
Dim rsShow As New ADODB.Recordset
Dim NewItem As Variant
If Trim(txtCustomer.Text) = "" Then
    MsgBox "Please select customer to proceed...", vbCritical, POPUP_COMP
    Exit Sub
End If

Dim recCnt
pgrPartyLedger.Min = 0
recCnt = 0
'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser CASH PURCHASE RETURN
strShow = "select Count(*) as mCnt from VOUCHMST A,VOUCHDAT B, Prevbal C  "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
'strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn
recCnt = rsShow("mCnt")
rsShow.Close
pgrPartyLedger.Max = recCnt + 1

'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser
strShow = "select A.Id,A.cmnt,A.ADV,A.VNO,A.DATED,B.IDNO,B.IDNAME,B.AMOUNT,B.DR_CR,B.VNARRATION,A.REMARKS,B.CQ_TYPE, B.BANKNAME, B.BANKBRANCH, B.CQ_NO, C.amnt from VOUCHMST A,VOUCHDAT B, Prevbal C "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn

Dim mPur, mPayRet, mAnyAdv, mTempVNO
mPur = 0
mPayRet = 0
mAnyAdv = 0

mSlNo = 1
ShowPaymentHeader
Do While Not rsShow.EOF
    mTempVNO = rsShow("VNO")

    Set NewItem = listViewPayment.ListItems.Add(, "C" & mSlNo, Format(rsShow("DATED"), "dd/MM/yyyy"))
    NewItem.SubItems(1) = mTempVNO
    NewItem.SubItems(2) = IIf(IsNull(rsShow("IDNAME")), "", CommaFilterText(rsShow("IDNAME"), 1))
    NewItem.SubItems(11) = rsShow("amnt")
    If Trim(rsShow("REMARKS")) = "CASH SALE" Then
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
    ElseIf Trim(rsShow("REMARKS")) = "CREDIT SALE" Then
        mAnyAdv = ShowPartialAdvance(rsShow("VNO"))
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT") + Val(mAnyAdv))

        If Val(mAnyAdv) > 0 Then
            NewItem.SubItems(4) = FormatTakaPaisa(mAnyAdv)

        Else
            NewItem.SubItems(4) = ""

        End If
    Else
        NewItem.SubItems(3) = ""
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(7) = rsShow("CQ_TYPE")
        NewItem.SubItems(8) = rsShow("BANKNAME")
        NewItem.SubItems(9) = rsShow("BANKBRANCH")
        NewItem.SubItems(10) = rsShow("CQ_NO")

        NewItem.SubItems(13) = "" & rsShow("cmnt")

    End If
    NewItem.SubItems(6) = rsShow("IDNO")

    mPur = mPur + Val(NewItem.SubItems(3))
    mPayRet = mPayRet + Val(NewItem.SubItems(4))

    NewItem.SubItems(5) = rsShow("REMARKS")

    NewItem.SubItems(12) = GetVoucherRefNo(mTempVNO)

    pgrPartyLedger.Value = mSlNo

    mSlNo = mSlNo + 1
    rsShow.MoveNext
Loop
rsShow.Close

lblprvbal.Text = Val(NewItem.SubItems(11))
lblTotPur.Caption = FormatTakaPaisa(mPur) + Val(lblprvbal.Text)
lblTotPayRet.Caption = FormatTakaPaisa(mPayRet)
lblBalance.Caption = FormatTakaPaisa(mPur - mPayRet) + Val(lblprvbal.Text)

pgrPartyLedger.Value = 0
End Sub
</code>```

答: Check if not NewItem is Nothing.</p>

Title: VB6 Run time error 424

Body:
I am getting error 424 on this line, can anyone help me please.

lblprvbal.Text = Val(NewItem.SubItems(11))

Private Sub cmdShow_Click()
'lblTotPur/lblTotPayRet/lblBalance
Dim strShow, mSlNo
Dim rsShow As New ADODB.Recordset
Dim NewItem As Variant
If Trim(txtCustomer.Text) = "" Then
    MsgBox "Please select customer to proceed...", vbCritical, POPUP_COMP
    Exit Sub
End If

Dim recCnt
pgrPartyLedger.Min = 0
recCnt = 0
'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser CASH PURCHASE RETURN
strShow = "select Count(*) as mCnt from VOUCHMST A,VOUCHDAT B, Prevbal C  "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
'strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn
recCnt = rsShow("mCnt")
rsShow.Close
pgrPartyLedger.Max = recCnt + 1

'VOUCHMST_P//VNO,DATED,VTYPE,REMARKS,byUser
strShow = "select A.Id,A.cmnt,A.ADV,A.VNO,A.DATED,B.IDNO,B.IDNAME,B.AMOUNT,B.DR_CR,B.VNARRATION,A.REMARKS,B.CQ_TYPE, B.BANKNAME, B.BANKBRANCH, B.CQ_NO, C.amnt from VOUCHMST A,VOUCHDAT B, Prevbal C "
strShow = strShow & " where A.VNO=B.VNO and B.IDNO=C.obd and (A.REMARKS='CASH SALE RETURN' OR A.REMARKS='CREDIT SALE RETURN' OR A.REMARKS='CREDIT SALE' OR A.REMARKS='CASH SALE' OR A.REMARKS='RECEIPT' OR A.REMARKS='CREDIT NOTE') "
strShow = strShow & " and A.DATED between #" & Format(dtFrom.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and #" & Format(dtTo.Value, "MM/dd/yyyy") & "# "
strShow = strShow & " and B.IDNO = '" & Trim(txtCustomerId.Text) & "' "
strShow = strShow & " order by A.ID,A.DATED,A.VNO"
rsShow.Open strShow, cn

Dim mPur, mPayRet, mAnyAdv, mTempVNO
mPur = 0
mPayRet = 0
mAnyAdv = 0

mSlNo = 1
ShowPaymentHeader
Do While Not rsShow.EOF
    mTempVNO = rsShow("VNO")

    Set NewItem = listViewPayment.ListItems.Add(, "C" & mSlNo, Format(rsShow("DATED"), "dd/MM/yyyy"))
    NewItem.SubItems(1) = mTempVNO
    NewItem.SubItems(2) = IIf(IsNull(rsShow("IDNAME")), "", CommaFilterText(rsShow("IDNAME"), 1))
    NewItem.SubItems(11) = rsShow("amnt")
    If Trim(rsShow("REMARKS")) = "CASH SALE" Then
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
    ElseIf Trim(rsShow("REMARKS")) = "CREDIT SALE" Then
        mAnyAdv = ShowPartialAdvance(rsShow("VNO"))
        NewItem.SubItems(3) = FormatTakaPaisa(rsShow("AMOUNT") + Val(mAnyAdv))

        If Val(mAnyAdv) > 0 Then
            NewItem.SubItems(4) = FormatTakaPaisa(mAnyAdv)

        Else
            NewItem.SubItems(4) = ""

        End If
    Else
        NewItem.SubItems(3) = ""
        NewItem.SubItems(4) = FormatTakaPaisa(rsShow("AMOUNT"))
        NewItem.SubItems(7) = rsShow("CQ_TYPE")
        NewItem.SubItems(8) = rsShow("BANKNAME")
        NewItem.SubItems(9) = rsShow("BANKBRANCH")
        NewItem.SubItems(10) = rsShow("CQ_NO")

        NewItem.SubItems(13) = "" & rsShow("cmnt")

    End If
    NewItem.SubItems(6) = rsShow("IDNO")

    mPur = mPur + Val(NewItem.SubItems(3))
    mPayRet = mPayRet + Val(NewItem.SubItems(4))

    NewItem.SubItems(5) = rsShow("REMARKS")

    NewItem.SubItems(12) = GetVoucherRefNo(mTempVNO)

    pgrPartyLedger.Value = mSlNo

    mSlNo = mSlNo + 1
    rsShow.MoveNext
Loop
rsShow.Close

lblprvbal.Text = Val(NewItem.SubItems(11))
lblTotPur.Caption = FormatTakaPaisa(mPur) + Val(lblprvbal.Text)
lblTotPayRet.Caption = FormatTakaPaisa(mPayRet)
lblBalance.Caption = FormatTakaPaisa(mPur - mPayRet) + Val(lblprvbal.Text)

pgrPartyLedger.Value = 0
End Sub

Body: Check if not NewItem is Nothing.


问:
How do I display an array inside a string in javascript?
This is the code :

```<code>list = ["Alex","John","Kit","Lenny"];
for(var i = 0; i < 4; i++) {
  $("body").append("<p> list[i] </p>');
};
</code>```

Look at the for loop(yes this is using jquery),i want to add the list items inside the paragraph headers.How do i do it ?

答:
list[i] is not a string, it's a variable. To include it into the appended element, close the quotation marks in following way:

var list = ["Alex","John","Kit","Lenny"];
for(var i = 0; i < 4; i++) {
  $("body").append("
" + list[i] + "
")
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
This is the code :

list = ["Alex","John","Kit","Lenny"];
for(var i = 0; i < 4; i++) {
  $("body").append("
 list[i]
');
};

Look at the for loop(yes this is using jquery),i want to add the list items inside the paragraph headers.How do i do it ?

Body:
list[i] is not a string, it's a variable. To include it into the appended element, close the quotation marks in following way:

var list = ["Alex","John","Kit","Lenny"];
for(var i = 0; i < 4; i++) {
  $("body").append("<p>" + list[i] + "</p>")
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
C++ object leak
I am currently learning C++, and I'm experiencing with local scope of objects.

If I understand correctly, with this code :

```<code>void stepOne() {
TestClass t1;
t1.thisIsAInt = 2;}
</code>```

Once we exit the scope of the stepOne method, the t1 object should be cleared out of memory.

Now, I wanted to test this, so with a debugger I got the address of the object, and once I got back into main, I made a pointer on the address that I got from the debugger.

I was surprised to find that the pointer was still pointing to the same object I created earlier.

Normally, it is my understanding that the object would have been cleared of memory since we left the scope.

Now,

Do I not understand it properly?

Did getting the address of it made it not leave the scope?

Is it free memory for the OS, and just not cleared yet? (Filled with zeroes)

If I passed the pointer to a function from stepOne, would it still have  been cleared once I left the scope? ( I understand I could have used a smart pointer, to make sure it only survives the local scope)

答:
Once an object has gone out of scope and is destructed (add a breakpoint in the destructor to make sure it is) you should not reference the memory that was owned by that object.

Just because the object is destructed doesn't mean the memory it occupied will just "disappear". The memory still exists, and until it is reused by another object will not change its contents. Clearing memory takes (a little) time, doing it perhaps thousands of times each second will suddenly become very expensive.

Title: C++ object leak

Body:
I am currently learning C++, and I'm experiencing with local scope of objects.

If I understand correctly, with this code :

void stepOne() {
TestClass t1;
t1.thisIsAInt = 2;}

Once we exit the scope of the stepOne method, the t1 object should be cleared out of memory.

Now, I wanted to test this, so with a debugger I got the address of the object, and once I got back into main, I made a pointer on the address that I got from the debugger.

I was surprised to find that the pointer was still pointing to the same object I created earlier.

Normally, it is my understanding that the object would have been cleared of memory since we left the scope.

Now,

Do I not understand it properly?

Did getting the address of it made it not leave the scope?

Is it free memory for the OS, and just not cleared yet? (Filled with zeroes)

If I passed the pointer to a function from stepOne, would it still have  been cleared once I left the scope? ( I understand I could have used a smart pointer, to make sure it only survives the local scope)


问:
Creating/Using Files with Python 3.6
I am trying to make something that would generate several random files and based on those files it determines the outcome of what happens (text based adventure game) and yes I want to use files due to the fact the game is supposed to be 'hack-able/mod-able.' For some reason trying to create the files in another directory gives me the error

FileNotFoundError: [Errno 2] No such file or directory: 'file0599265.txt'

```<code>import os
import os.path
import random as rand
os.chdir("C:\Program Files (x86)\File Stuff")
f = open('file' + str(rand.randint(1,1000000)) + '.txt', 'w')
f.write('Test')
f.close
</code>```

What must I do so that it will create that file? I really cannot nail the who change directory thing to make it where I want, but I will stick for this for now (The "C:\Program Files (x86)\File Stuff" was only made for testing purposes).

答:
4 issues:

You aren't importing random which will cuase errors

You should use the with keyword as it is pretty standard to use in this situation

You must have the directory C:\\Program Files (x86)\\File Stuff already created.

You need to change the \'s to \\'s.  \ is an escape character, so if you don't escape the escape, then it can run into conflicts (i.e. \n).

Without further ado, here's the new code:

```<code>import os, os.path, random
os.chdir("C:\\Program Files (x86)\\File Stuff")
with open('file' + str(random.randint(1,1000000)) + '.txt', 'w') as f:
    f.write('Test')
</code>```

Title: Creating/Using Files with Python 3.6

Body:
I am trying to make something that would generate several random files and based on those files it determines the outcome of what happens (text based adventure game) and yes I want to use files due to the fact the game is supposed to be 'hack-able/mod-able.' For some reason trying to create the files in another directory gives me the error

FileNotFoundError: [Errno 2] No such file or directory: 'file0599265.txt'

import os
import os.path
import random as rand
os.chdir("C:\Program Files (x86)\File Stuff")
f = open('file' + str(rand.randint(1,1000000)) + '.txt', 'w')
f.write('Test')
f.close

What must I do so that it will create that file? I really cannot nail the who change directory thing to make it where I want, but I will stick for this for now (The "C:\Program Files (x86)\File Stuff" was only made for testing purposes).

Body:
4 issues:

You aren't importing random which will cuase errors

You should use the with keyword as it is pretty standard to use in this situation

You must have the directory C:\\Program Files (x86)\\File Stuff already created.

You need to change the \'s to \\'s.  \ is an escape character, so if you don't escape the escape, then it can run into conflicts (i.e. \n).

Without further ado, here's the new code:

import os, os.path, random
os.chdir("C:\\Program Files (x86)\\File Stuff")
with open('file' + str(random.randint(1,1000000)) + '.txt', 'w') as f:
    f.write('Test')


问:
Javascript - remove split method
I am trying to create the select application using Javascipt only. I got to know about this code on internet and it uses the split method to return value and .innerHTML. Now say if I do not want to use the split method and just return with .innerHTML into html element with no value, how to do that using for loop as used in this code ?</p>

```<code>   <!DOCTYPE html>
<html>
<head>
    <title>Select Options</title>
</head>
<body>

<h2>Choose your car</h2>
<hr>

Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Hyundai">Hyundai</option>
    <option value="Honda">Honda</option>
    <option value="Maruti">Maruti</option>
</select>

<hr>

Choose Car Model
<select id="slct2" ></select>

</body>

<script type="text/javascript">
    function populate(s1,s2){
        var s1 = document.getElementById(s1);
        var s2 = document.getElementById(s2);
        s2.innerHTML = "";

        if(s1.value == "Hyundai") {
            var optionArray = ["|", "i10|i10","i20|i20", "Verna|Verna"]
        }
        for(var option in optionArray){
            var pair = optionArray[option].split("|");
            var newOption = document.createElement('option');
            newOption.value = pair[0];
            newOption.innerHTML = pair[1];
            s2.options.add(newOption);
        }
    }
</script>

</html>
</code>```

答:
Removing or simply commenting (may be you would require it in future) few lines should do what you want:

```<code><script type="text/javascript">
    function populate(s1,s2){
        var s1 = document.getElementById(s1);
        var s2 = document.getElementById(s2);
        s2.innerHTML = "";

        if(s1.value == "Hyundai") {
            var optionArray = ["|", "i10|i10","i20|i20", "Verna|Verna"]
        }
        for(var option in optionArray){
            var pair = optionArray[option]; //.split("|");
            var newOption = document.createElement('option');
            newOption.value = pair; //[0];
            newOption.innerHTML = pair; //[1];
            s2.options.add(newOption);
        }
    }
</script>
</code>```

With above code, you are no using .split() and just assigning the whole object to the new element.

Title: Javascript - remove split method

Body:
I am trying to create the select application using Javascipt only. I got to know about this code on internet and it uses the split method to return value and .innerHTML. Now say if I do not want to use the split method and just return with .innerHTML into html element with no value, how to do that using for loop as used in this code ?

   <!DOCTYPE html>

    <title>Select Options</title>

Choose your car

Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Hyundai">Hyundai</option>
    <option value="Honda">Honda</option>
    <option value="Maruti">Maruti</option>
</select>

Choose Car Model
<select id="slct2" ></select>

Body:
Removing or simply commenting (may be you would require it in future) few lines should do what you want:

<script type="text/javascript">
    function populate(s1,s2){
        var s1 = document.getElementById(s1);
        var s2 = document.getElementById(s2);
        s2.innerHTML = "";

        if(s1.value == "Hyundai") {
            var optionArray = ["|", "i10|i10","i20|i20", "Verna|Verna"]
        }
        for(var option in optionArray){
            var pair = optionArray[option]; //.split("|");
            var newOption = document.createElement('option');
            newOption.value = pair; //[0];
            newOption.innerHTML = pair; //[1];
            s2.options.add(newOption);
        }
    }
</script>

With above code, you are no using .split() and just assigning the whole object to the new element.


问:
Error in loading model in Sample Reflective Editor
I can open my .model file in Exeed Editor. But when I want to open it in Sample Reflective Editor it has below errors. What should I do?

答: That is because the metamodel is registered both through a plugin and manually.</p>


问:
Lagging System or a possible bug in TensorFlow?
I am currently working on RnD in TensorFlow (CPU Version), but unable to decide on the basic requirement for my system for training on large datasets or may be I stumbled upon a possible bug in TensorFlow library.

The Official TensorFlow documentation, nowhere suggests any specific requirement for the system to be building and running TensorFlow programs on. From what I can understand, if that can be run over Windows, Linux, Mac along with Android, iOS and also over embedded systems like RaspberryPi, I suppose there should not be any such hardware requirement for the same.

However, while in the process of initial research, I tried running the TensorFlow Seq2Seq model (translating English to French https://www.tensorflow.org/tutorials/seq2seq), where the training and test datasets end up taking around 7-8 GB of diskspace initially and 20-22Gb on a whole. Once the translate.py python script is executed, it ends up choking the memory and pushing disk utilization to 98% and 100% respectively.

My current system runs Windows 8.1 64 bit OS, Core i5 5200U clocking at 2.2 GHz, 8GB RAM and around 70GB free space on HDD (specifically allotted for TensorFlow usage). But even after allowing my system to run over 7-8 hours (with no other application running) it got stuck multiple times and usually after the memory utilization peeks to around 100% after tokenizing the datasets.

Though I am not sure, but I suppose the TensorFlow learning graph is being created inside the RAM and once it expands to around all the memory space, the program ends up in un-ending loop waiting for memory to get cleared and then increase the learning graph.

So the whole drills down to 3 questions:

Does TensorFlow uses RAM for building and saving Learning Graph? If so, is it possible to get choked in a similar fashion?

From a business perspective, is there a minimum hardware requirement for training such a system?

If it is not the system requirement, can this be a possible bug in TensorFlow library which pushes it into an unending loop waiting for memory to get cleared?

Update

After running the python script for over 30 hours continuously, the process seems to have stuck at the same place for past 14 hours while "Reading development and training data". Refer image below for further investigation:

答:
As soon as I was about to shut down the program, the same started responding again and I waited for another 15-20 minutes and finally I got the answer from the OS itself. It was indeed low RAM that was causing the problem. Attaching the screen grab of the Windows Alert of system running low on memory for reference, incase anyone gets caught in same situation.

UPDATE

I tried taking a VM instance on Google Cloud Platform. This machine had 2 x Intel Xeon (R) each running at 2.23 GHZ, with 13GB RAM and 50GB storage. But the result was same in this situation also even though the application was utilising more than 10.5 GB RAM. Seems like this tutorial script needs a very intense system probably a Super Computer with atleast 32 GB RAM to run and execute completely. I might look to write/arrange my own dataset now. However, this must be taken as future enhancement to use Persistent Storage (HDD/SSD) to create the Graph instead of RAM so as to avoid chocking of Memory.


问:
Substract 3D text to a Geometry in Three.js
I want to transform my 3D text to Geometry so I can use it with CSG (I used a Three.js CSG wrapper also) to substract it from another object like in this question.

My 3D text :

```<code>loader.load('optimer_regular.typeface.json', function (font){
    var text = new THREE.TextGeometry('Tayst', {
        font: font,
        size: 4,
        height: 3
    });
    var textMat = new THREE.MeshBasicMaterial({color: 0xffffff});
    var textGeo = new THREE.Mesh(text, textMat);
    textGeo.position.x = -7;
    textGeo.position.z = 6;
    scene.add(textGeo);
});
</code>```

My substract thing I want to do for the 3D text (but here it's from circles):

```<code>var dots = new THREE.Geometry();
    for(var i = 0; i < coordinates.length; i++){
        var coords  = coordinates[i];

        sphereMesh.position.x   = coords[0];
        sphereMesh.position.y   = coords[1];
        sphereMesh.position.z   = coords[2];

        sphereMesh.updateMatrix();
        dots.merge(sphereMesh.geometry, sphereMesh.matrix);
    }

var sphereCsg = THREE.CSG.toCSG(dots);

var resultGeo = THREE.CSG.fromCSG(resultCsg.subtract(sphereCsg));

cube = new THREE.Mesh(resultGeo, material);
</code>```

But the thing is, I think, I need to convert my text to a real Geometry so I can substract it?

答:
Well i found out using the library I already got, but instead I didn't had to do the "merge" for example.

Here is the working code (in case someone needs it) :

```<code>var loader = new THREE.FontLoader();
loader.load('helvetiker_regular.typeface.json', function (font){
    var text = new THREE.TextGeometry('Test', {
        font: font,
        size: 4,
        height: 0.5
    });
    var textGeo = new THREE.Mesh(text);
    textGeo.position.x = -5;
    textGeo.position.z = 7.5;

    var txtCsg = THREE.CSG.toCSG(textGeo);

    var resultGeo = THREE.CSG.fromCSG(resultCsg.subtract(txtCsg));

    cube = new THREE.Mesh(resultGeo, material);
    scene.add(cube);
});
</code>```

Body:
I want to transform my 3D text to Geometry so I can use it with CSG (I used a Three.js CSG wrapper also) to substract it from another object like in this question.

My 3D text :

loader.load('optimer_regular.typeface.json', function (font){
    var text = new THREE.TextGeometry('Tayst', {
        font: font,
        size: 4,
        height: 3
    });
    var textMat = new THREE.MeshBasicMaterial({color: 0xffffff});
    var textGeo = new THREE.Mesh(text, textMat);
    textGeo.position.x = -7;
    textGeo.position.z = 6;
    scene.add(textGeo);
});

My substract thing I want to do for the 3D text (but here it's from circles):

var dots = new THREE.Geometry();
    for(var i = 0; i < coordinates.length; i++){
        var coords  = coordinates[i];

        sphereMesh.position.x   = coords[0];
        sphereMesh.position.y   = coords[1];
        sphereMesh.position.z   = coords[2];

        sphereMesh.updateMatrix();
        dots.merge(sphereMesh.geometry, sphereMesh.matrix);
    }

var sphereCsg = THREE.CSG.toCSG(dots);

var resultGeo = THREE.CSG.fromCSG(resultCsg.subtract(sphereCsg));

cube = new THREE.Mesh(resultGeo, material);

But the thing is, I think, I need to convert my text to a real Geometry so I can substract it?

Body:
Well i found out using the library I already got, but instead I didn't had to do the "merge" for example.

Here is the working code (in case someone needs it) :

var loader = new THREE.FontLoader();
loader.load('helvetiker_regular.typeface.json', function (font){
    var text = new THREE.TextGeometry('Test', {
        font: font,
        size: 4,
        height: 0.5
    });
    var textGeo = new THREE.Mesh(text);
    textGeo.position.x = -5;
    textGeo.position.z = 7.5;

    var txtCsg = THREE.CSG.toCSG(textGeo);

    var resultGeo = THREE.CSG.fromCSG(resultCsg.subtract(txtCsg));

    cube = new THREE.Mesh(resultGeo, material);
    scene.add(cube);
});


问:
ORACLE SQL PASSWORD FUNCTION
Need to create a function that verifies a password (more than 5 characters, different from the previous one, it isn't neither "password" nor "123456")
I tried this but i get errors</p>

```<code>CREATE OR REPLACE FUNCTION my_verification_function (
    username VARCHAR2,
    password VARCHAR2,
    old_password VARCHAR2)
RETURN BOOLEAN IS
BEGIN
    IF LENGTH(password) < 6 THEN RETURN FALSE;
    ELSE IF (password = "password" OR password = '123' OR password = old_password) THEN RETURN FALSE
    ELSE RETURN TRUE;
    END IF;
END my_verification_function;$
</code>```

答:
```<code>CREATE OR REPLACE FUNCTION my_verification_function (
    username VARCHAR2,
    pass VARCHAR2,
    old_password VARCHAR2)
RETURN varchar2   IS
BEGIN
    IF LENGTH(pass) < 6 THEN RETURN 'FALSE';
    ELSIF (pass = 'password' OR pass = '123456' OR pass = old_password) THEN RETURN 'FALSE';
    ELSE RETURN 'TRUE';
    END IF;
END;
</code>```

Several notes:

1) You should use ELSIF instead of ELSE IF

2) If you need call this function in "pure" SQL, BOOLEAN type will give you error, so you can use VARCHAR2 instead.

3) Don't use reserved words like PASSWORD

Title: ORACLE SQL PASSWORD FUNCTION

Body:
Need to create a function that verifies a password (more than 5 characters, different from the previous one, it isn't neither "password" nor "123456")
I tried this but i get errors

CREATE OR REPLACE FUNCTION my_verification_function (
    username VARCHAR2,
    password VARCHAR2,
    old_password VARCHAR2)
RETURN BOOLEAN IS
BEGIN
    IF LENGTH(password) < 6 THEN RETURN FALSE;
    ELSE IF (password = "password" OR password = '123' OR password = old_password) THEN RETURN FALSE
    ELSE RETURN TRUE;
    END IF;
END my_verification_function;$

Body:
CREATE OR REPLACE FUNCTION my_verification_function (
    username VARCHAR2,
    pass VARCHAR2,
    old_password VARCHAR2)
RETURN varchar2   IS
BEGIN
    IF LENGTH(pass) < 6 THEN RETURN 'FALSE';
    ELSIF (pass = 'password' OR pass = '123456' OR pass = old_password) THEN RETURN 'FALSE';
    ELSE RETURN 'TRUE';
    END IF;
END;

Several notes:

1) You should use ELSIF instead of ELSE IF

2) If you need call this function in "pure" SQL, BOOLEAN type will give you error, so you can use VARCHAR2 instead.

3) Don't use reserved words like PASSWORD


问:
i want to remove string after colon in sql server
-- i need data like this F11.20,F13.20,F14.10 in sql server</p>

```<code>declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';
select left(@S, charindex(':', @S, charindex(':', @S)+2)-2);
</code>```

答:
Any Split/Parse Function would do the trick, but you would have to perform secondary logic to clean the parsed string.  That said, I modified a parse function to accept any two non-like delimiters (start/end).  In this case a , and :

Also, being a Table-Valued-Function, it is easy to incorporate into a CROSS APPLY or as a stand-alone as illustrated below.

Example

```<code>Select NewString = Stuff((Select ',' +RetVal
 From  [dbo].[udf-Str-Extract](@S,',',':')
 For XML Path ('')),1,1,'')
</code>```

Returns

```<code>F11.20,F13.20,F14.10
</code>```

The UDF if Interested

```<code>CREATE FUNCTION [dbo].[udf-Str-Extract] (@String varchar(max),@Delimiter1 varchar(100),@Delimiter2 varchar(100))
Returns Table
As
Return (

with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
       cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 N1,cte1 N2,cte1 N3,cte1 N4,cte1 N5,cte1 N6) A ),
       cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter1) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter1)) = @Delimiter1),
       cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter1,@String,s.N),0)-S.N,8000) From cte3 S)

Select RetSeq = Row_Number() over (Order By N)
      ,RetPos = N
      ,RetVal = left(RetVal,charindex(@Delimiter2,RetVal)-1)
 From  (Select *,RetVal = Substring(@String, N, L) From cte4) A
 Where charindex(@Delimiter2,RetVal)>1

/*
Max Length of String 1MM characters

Declare @String varchar(max) = 'Dear [[FirstName]] [[LastName]], ...'
Select * From [dbo].[udf-Str-Extract] (@String,'[[',']]')
*/
</code>```

EDIT Just to Help with the Visualization

If you executed the TVF alone:

```<code>declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';

Select * From [dbo].[udf-Str-Extract](@S,',',':')
</code>```

Returns

```<code>RetSeq  RetPos  RetVal
1       2       F11.20
2       10      F13.20
3       38      F14.10
</code>```

EDIT 2 - Execute via Cross Apply

```<code>Declare @YourTable table (ID int,SomeString varchar(200))
Insert Into @YourTable values
(1,',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom'),
(2,',Z99.55:,Z25.10:Someother text')

Select A.ID
      ,B.*
 From  @YourTable A
 Cross Apply (
                Select NewString = Stuff((Select ',' +RetVal
                                           From  [dbo].[udf-Str-Extract](A.SomeString,',',':')
                                           For XML Path ('')),1,1,'')
             ) B
</code>```

Returns

```<code>ID  NewString
1   F11.20,F13.20,F14.10
2   Z99.55,Z25.10
</code>```

Body:
-- i need data like this F11.20,F13.20,F14.10 in sql server

declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';
select left(@S, charindex(':', @S, charindex(':', @S)+2)-2);

Body:
Any Split/Parse Function would do the trick, but you would have to perform secondary logic to clean the parsed string.  That said, I modified a parse function to accept any two non-like delimiters (start/end).  In this case a , and :

Also, being a Table-Valued-Function, it is easy to incorporate into a CROSS APPLY or as a stand-alone as illustrated below.

Example

Select NewString = Stuff((Select ',' +RetVal
 From  [dbo].[udf-Str-Extract](@S,',',':')
 For XML Path ('')),1,1,'')

Returns

F11.20,F13.20,F14.10

The UDF if Interested

CREATE FUNCTION [dbo].[udf-Str-Extract] (@String varchar(max),@Delimiter1 varchar(100),@Delimiter2 varchar(100))
Returns Table
As
Return (

with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
       cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 N1,cte1 N2,cte1 N3,cte1 N4,cte1 N5,cte1 N6) A ),
       cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter1) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter1)) = @Delimiter1),
       cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter1,@String,s.N),0)-S.N,8000) From cte3 S)

Select RetSeq = Row_Number() over (Order By N)
      ,RetPos = N
      ,RetVal = left(RetVal,charindex(@Delimiter2,RetVal)-1)
 From  (Select *,RetVal = Substring(@String, N, L) From cte4) A
 Where charindex(@Delimiter2,RetVal)>1

/*
Max Length of String 1MM characters

Declare @String varchar(max) = 'Dear [[FirstName]] [[LastName]], ...'
Select * From [dbo].[udf-Str-Extract] (@String,'[[',']]')
*/

EDIT Just to Help with the Visualization

If you executed the TVF alone:

declare @S varchar(200) = ',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom';

Select * From [dbo].[udf-Str-Extract](@S,',',':')

Returns

RetSeq  RetPos  RetVal
1       2       F11.20
2       10      F13.20
3       38      F14.10

EDIT 2 - Execute via Cross Apply

Declare @YourTable table (ID int,SomeString varchar(200))
Insert Into @YourTable values
(1,',F11.20:,F13.20:Sedative, hypnotic o,F14.10:Cocaine abuse, uncom'),
(2,',Z99.55:,Z25.10:Someother text')

Select A.ID
      ,B.*
 From  @YourTable A
 Cross Apply (
                Select NewString = Stuff((Select ',' +RetVal
                                           From  [dbo].[udf-Str-Extract](A.SomeString,',',':')
                                           For XML Path ('')),1,1,'')
             ) B

Returns

ID  NewString
1   F11.20,F13.20,F14.10
2   Z99.55,Z25.10


问:
How to convert sql limit query to linq lambda?
Here's an example that I want to convert to lambda query:</p>

```<code>SELECT TOP(5) Pbschedules.s_id, Pbschedules.date, Pbworth2.worth, Pbschedules.pb_id
FROM Pbschedules INNER JOIN Pbworth2 ON Pbschedules.pb_id = Pbworth2.pb_id
ORDER BY s_id desc
</code>```

答:
```<code>var query = database.Pbschedules// your starting point - table in the "from" statement
  .Join(database.Pbworth2, // the source table of the inner join
  pbs=> pbs.pb_id,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
  worth=> worth.pb_id,   // Select the foreign key (the second part of the "on" clause)
  (pbs, worth) => new { PbsID = pbs.s_id, Worth = worth.worth /*other columns*/ }) // selection
  .OrderByDescending(x => x.s_id)
  .Take(5);
</code>```

Body:
Here's an example that I want to convert to lambda query:

SELECT TOP(5) Pbschedules.s_id, Pbschedules.date, Pbworth2.worth, Pbschedules.pb_id
FROM Pbschedules INNER JOIN Pbworth2 ON Pbschedules.pb_id = Pbworth2.pb_id
ORDER BY s_id desc


问:
What is the error in using fopen instead of fopen_s as suggested by Visual Studio?
I started working on the OpenGL code for Amusement Park. but I'm getting the following error:

```<code>"error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details."
</code>```

even if I try to change it frm fopen to fopen_s, there more errors.

This is the code part:

```<code>GLuint LoadBMP(const char *fileName)
{
    FILE *file;
    unsigned char header[54], *data;
    unsigned int dataPos, size, width, height;
    file = fopen(fileName, "rb");
    fread(header, 1, 54, file);             //Windows BMP begin with 54 byte header
    dataPos = *(int*)&(header[0x0A]);   //dec10, Actual BMP data
    size = *(int*)&(header[0x22]);  //dec34, BMP Size
    width = *(int*)&(header[0x12]); //dec18, Image Width
    height = *(int*)&(header[0x16]);    //dec22, Image Height
    if (size == NULL)
        size = width * height * 3;
    if (dataPos == NULL)
        dataPos = 54;
    data = new unsigned char[size];
    fread(data, 1, size, file);
    fclose(file);
    GLuint texture;
    glGenTextures(1, &texture);             //Generate (allocate) 1 texture name
    glBindTexture(GL_TEXTURE_2D, texture);  //Bind the 2D texture

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);  //MAG filter
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);  //MIN filter

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, data); //target, level, internalFormat, width, height,border, format, type, data
    return texture;
}
</code>```

I'm getting error in the file = fopen statement.

Help me to find the error in this.

答:
fopen_s is the secure version of fopen so if you don't want to use fopen_s consider using _CRT_SECURE_NO_WARNINGS to get rid of that error, since you are using Visual Studio.

Now if you want to use fopen_s to correct the error, you have to look at the documentation of fopen_s

Example of use:

```<code>errno_t returnValue = fopen_s(&file, fileName, "r");
</code>```

Body:
I started working on the OpenGL code for Amusement Park. but I'm getting the following error:

"error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details."

even if I try to change it frm fopen to fopen_s, there more errors.

This is the code part:

GLuint LoadBMP(const char *fileName)
{
    FILE *file;
    unsigned char header[54], *data;
    unsigned int dataPos, size, width, height;
    file = fopen(fileName, "rb");
    fread(header, 1, 54, file);             //Windows BMP begin with 54 byte header
    dataPos = *(int*)&(header[0x0A]);   //dec10, Actual BMP data
    size = *(int*)&(header[0x22]);  //dec34, BMP Size
    width = *(int*)&(header[0x12]); //dec18, Image Width
    height = *(int*)&(header[0x16]);    //dec22, Image Height
    if (size == NULL)
        size = width * height * 3;
    if (dataPos == NULL)
        dataPos = 54;
    data = new unsigned char[size];
    fread(data, 1, size, file);
    fclose(file);
    GLuint texture;
    glGenTextures(1, &texture);             //Generate (allocate) 1 texture name
    glBindTexture(GL_TEXTURE_2D, texture);  //Bind the 2D texture

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);  //MAG filter
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);  //MIN filter

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, data); //target, level, internalFormat, width, height,border, format, type, data
    return texture;
}

I'm getting error in the file = fopen statement.

Help me to find the error in this.

Body:
fopen_s is the secure version of fopen so if you don't want to use fopen_s consider using _CRT_SECURE_NO_WARNINGS to get rid of that error, since you are using Visual Studio.

Now if you want to use fopen_s to correct the error, you have to look at the documentation of fopen_s

Example of use:

errno_t returnValue = fopen_s(&file, fileName, "r");