问:
How to get the dependency tree in a Maven 3 plugin?
In a Maven 2 mojo you can use something like this to get the dependency tree:

```<code>DependencyNode rootNode;
try {
  rootNode = treeBuilder.buildDependencyTree(project, localRepository,
      artifactFactory, artifactMetadataSource, null, artifactCollector);
} catch (DependencyTreeBuilderException e) {
  throw new MojoExecutionException("Failed to create dependency tree.", e);
}
final CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
rootNode.accept(visitor);
final List<DependencyNode> nodes = visitor.getNodes();
</code>```

What's the Maven 3 equivalent? Many involved classes have become deprecated in the meantime (ArtifactCollector, ArtifactMetadataSource, etc.).

答:
I haven't found any working solution online, so I looked into the Maven source code and worked out a solution myself. Most of the following code was copied from maven source code, I have tested it with Maven 3.5.4 and it worked perfectly.

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.DefaultDependencyResolutionRequest;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectDependenciesResolver;
import org.eclipse.aether.graph.DependencyFilter;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.util.filter.AndDependencyFilter;
import org.eclipse.aether.util.filter.ScopeDependencyFilter;

import javax.inject.Inject;
import java.util.*;

@Mojo( name = "test-mojo", requiresDependencyResolution = ResolutionScope.RUNTIME)
public class TestMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true, required = true)
    private MavenProject project;
    @Parameter(defaultValue = "${session}", readonly = true, required = true)
    private MavenSession session;
    @Inject
    private ProjectDependenciesResolver dependenciesResolver;

    public void execute() throws MojoExecutionException {
        try {
            Collection<String> scopesToResolve = new HashSet<>();
            scopesToResolve.add("compile");
            scopesToResolve.add("provided");
            scopesToResolve.add("runtime");
            scopesToResolve.add("system");
            scopesToResolve.add("test");
            Collection<String> scopesToCollect = new HashSet<>();
            scopesToCollect.add("compile");
            scopesToCollect.add("provided");
            scopesToCollect.add("runtime");
            scopesToCollect.add("system");
            scopesToCollect.add("test");
            Collection<Artifact> projectArtifacts = new HashSet<>();
            projectArtifacts.add(project.getArtifact());
            DependencyFilter collectionFilter = new ScopeDependencyFilter( null, negate( scopesToCollect ) );
            DependencyFilter resolutionFilter = new ScopeDependencyFilter( null, negate( scopesToResolve ) );
            resolutionFilter = AndDependencyFilter.newInstance( collectionFilter, resolutionFilter );
            resolutionFilter = AndDependencyFilter.newInstance( resolutionFilter, new ReactorDependencyFilter( projectArtifacts ) );
            DefaultDependencyResolutionRequest request =
                    new DefaultDependencyResolutionRequest( project, session.getRepositorySession() );
            request.setResolutionFilter( resolutionFilter );
            DependencyResolutionResult result = dependenciesResolver.resolve( request );

            // Here is your dependency gragh, you can do whatever you want with it.
            List<DependencyNode> children = result.getDependencyGraph().getChildren();
            List<DependencyNode> grandChildren = children.get(0).getChildren();
        } catch (Exception e) {
            e.printStackTrace();
            throw new MojoExecutionException(e.getMessage());
        }
    }

    private Collection<String> negate( Collection<String> scopes )
    {
        Collection<String> result = new HashSet<>();
        Collections.addAll( result, "system", "compile", "provided", "runtime", "test" );

        for ( String scope : scopes )
        {
            if ( "compile".equals( scope ) )
            {
                result.remove( "compile" );
                result.remove( "system" );
                result.remove( "provided" );
            }
            else if ( "runtime".equals( scope ) )
            {
                result.remove( "compile" );
                result.remove( "runtime" );
            }
            else if ( "compile+runtime".equals( scope ) )
            {
                result.remove( "compile" );
                result.remove( "system" );
                result.remove( "provided" );
                result.remove( "runtime" );
            }
            else if ( "runtime+system".equals( scope ) )
            {
                result.remove( "compile" );
                result.remove( "system" );
                result.remove( "runtime" );
            }
            else if ( "test".equals( scope ) )
            {
                result.clear();
            }
        }

        return result;
    }
    private static class ReactorDependencyFilter
            implements DependencyFilter
    {

        private Set<String> keys = new HashSet<>();

        ReactorDependencyFilter( Collection<Artifact> artifacts )
        {
            for ( Artifact artifact : artifacts )
            {
                String key = ArtifactUtils.key( artifact );
                keys.add( key );
            }
        }

        public boolean accept(DependencyNode node, List<DependencyNode> parents )
        {
            org.eclipse.aether.graph.Dependency dependency = node.getDependency();
            if ( dependency != null )
            {
                org.eclipse.aether.artifact.Artifact a = dependency.getArtifact();
                String key = ArtifactUtils.key( a.getGroupId(), a.getArtifactId(), a.getVersion() );
                return !keys.contains( key );
            }
            return false;
        }

    }
}

```

<p>Also, notice that you need to add some dependencies to make it work. Here is mine.</p>

```<dependencies>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-plugin-api</artifactId>
        <version>3.6.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven.plugin-tools</groupId>
        <artifactId>maven-plugin-annotations</artifactId>
        <version>3.6.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-project</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven.shared</groupId>
        <artifactId>maven-common-artifact-filters</artifactId>
        <version>3.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-core</artifactId>
        <version>3.5.4</version>
    </dependency>
</dependencies>
```

Body:
In a Maven 2 mojo you can use something like this to get the dependency tree:

DependencyNode rootNode;
try {
  rootNode = treeBuilder.buildDependencyTree(project, localRepository,
      artifactFactory, artifactMetadataSource, null, artifactCollector);
} catch (DependencyTreeBuilderException e) {
  throw new MojoExecutionException("Failed to create dependency tree.", e);
}
final CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
rootNode.accept(visitor);
final List<DependencyNode> nodes = visitor.getNodes();

What's the Maven 3 equivalent? Many involved classes have become deprecated in the meantime (ArtifactCollector, ArtifactMetadataSource, etc.).

Body:
I haven't found any working solution online, so I looked into the Maven source code and worked out a solution myself. Most of the following code was copied from maven source code, I have tested it with Maven 3.5.4 and it worked perfectly.

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.DefaultDependencyResolutionRequest;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectDependenciesResolver;
import org.eclipse.aether.graph.DependencyFilter;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.util.filter.AndDependencyFilter;
import org.eclipse.aether.util.filter.ScopeDependencyFilter;

import javax.inject.Inject;
import java.util.*;

@Mojo( name = "test-mojo", requiresDependencyResolution = ResolutionScope.RUNTIME)
public class TestMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project}", readonly = true, required = true)
    private MavenProject project;
    @Parameter(defaultValue = "${session}", readonly = true, required = true)
    private MavenSession session;
    @Inject
    private ProjectDependenciesResolver dependenciesResolver;

    public void execute() throws MojoExecutionException {
        try {
            Collection<String> scopesToResolve = new HashSet<>();
            scopesToResolve.add("compile");
            scopesToResolve.add("provided");
            scopesToResolve.add("runtime");
            scopesToResolve.add("system");
            scopesToResolve.add("test");
            Collection<String> scopesToCollect = new HashSet<>();
            scopesToCollect.add("compile");
            scopesToCollect.add("provided");
            scopesToCollect.add("runtime");
            scopesToCollect.add("system");
            scopesToCollect.add("test");
            Collection<Artifact> projectArtifacts = new HashSet<>();
            projectArtifacts.add(project.getArtifact());
            DependencyFilter collectionFilter = new ScopeDependencyFilter( null, negate( scopesToCollect ) );
            DependencyFilter resolutionFilter = new ScopeDependencyFilter( null, negate( scopesToResolve ) );
            resolutionFilter = AndDependencyFilter.newInstance( collectionFilter, resolutionFilter );
            resolutionFilter = AndDependencyFilter.newInstance( resolutionFilter, new ReactorDependencyFilter( projectArtifacts ) );
            DefaultDependencyResolutionRequest request =
                    new DefaultDependencyResolutionRequest( project, session.getRepositorySession() );
            request.setResolutionFilter( resolutionFilter );
            DependencyResolutionResult result = dependenciesResolver.resolve( request );

            // Here is your dependency gragh, you can do whatever you want with it.
            List<DependencyNode> children = result.getDependencyGraph().getChildren();
            List<DependencyNode> grandChildren = children.get(0).getChildren();
        } catch (Exception e) {
            e.printStackTrace();
            throw new MojoExecutionException(e.getMessage());
        }
    }

    private Collection<String> negate( Collection<String> scopes )
    {
        Collection<String> result = new HashSet<>();
        Collections.addAll( result, "system", "compile", "provided", "runtime", "test" );

        for ( String scope : scopes )
        {
            if ( "compile".equals( scope ) )
            {
                result.remove( "compile" );
                result.remove( "system" );
                result.remove( "provided" );
            }
            else if ( "runtime".equals( scope ) )
            {
                result.remove( "compile" );
                result.remove( "runtime" );
            }
            else if ( "compile+runtime".equals( scope ) )
            {
                result.remove( "compile" );
                result.remove( "system" );
                result.remove( "provided" );
                result.remove( "runtime" );
            }
            else if ( "runtime+system".equals( scope ) )
            {
                result.remove( "compile" );
                result.remove( "system" );
                result.remove( "runtime" );
            }
            else if ( "test".equals( scope ) )
            {
                result.clear();
            }
        }

        return result;
    }
    private static class ReactorDependencyFilter
            implements DependencyFilter
    {

        private Set<String> keys = new HashSet<>();

        ReactorDependencyFilter( Collection<Artifact> artifacts )
        {
            for ( Artifact artifact : artifacts )
            {
                String key = ArtifactUtils.key( artifact );
                keys.add( key );
            }
        }

        public boolean accept(DependencyNode node, List<DependencyNode> parents )
        {
            org.eclipse.aether.graph.Dependency dependency = node.getDependency();
            if ( dependency != null )
            {
                org.eclipse.aether.artifact.Artifact a = dependency.getArtifact();
                String key = ArtifactUtils.key( a.getGroupId(), a.getArtifactId(), a.getVersion() );
                return !keys.contains( key );
            }
            return false;
        }

    }
}

Also, notice that you need to add some dependencies to make it work. Here is mine.

<dependencies>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-plugin-api</artifactId>
        <version>3.6.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven.plugin-tools</groupId>
        <artifactId>maven-plugin-annotations</artifactId>
        <version>3.6.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-project</artifactId>
        <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven.shared</groupId>
        <artifactId>maven-common-artifact-filters</artifactId>
        <version>3.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-core</artifactId>
        <version>3.5.4</version>
    </dependency>
</dependencies>


来源: stackexchange

问:
Unable to get focus on Textbox when bootstrap modal popup opens
Hii I want to get focus on input textbox when the bootstrap modal popup opens

```<code><div class="modal fade nopading" id="myModalpop" role="dialog">
    <div class="model-area">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-head">
                <a class="navbar-brand" href="index.html"><img src="~/Content/images/logo.png" alt="Ova" style="float: left; padding-top: 10px;"></a>
                <form class="form-inline md-form form-sm mt-0" style="text-align: center;" method="get" action="@Url.Action("Review", "Product")">
                    <a href"#"><i class="fa fa-search" aria-hidden="true"></i></a>
                    <input name="id" class="form-contro form-control-sm ml-3 w-75 wow fadeInRight animated" id="txtsearch"  type="text" placeholder="Search" aria-label="Search">
                </form>
                <button type="button" class="close" data-dismiss="modal">×</button>

            </div>
            <div class="modal-body" style="padding: 0px;">
                @*<p class="links_p wow fadeInRight animated">QUICK LINKS</p>*@

            </div>

        </div>
    </div>

</div><!-- end navbar-cell -->
</code>```

I have applied javascript

```<code><script type="text/javascript">
$(document).ready(function () {

    $('#myModalpop').on('show.bs.modal', function () {

        $('#txtsearch').focus;
        //$(this).find('#txtsearch').focus();
     });
});
</script>
</code>```

Focus on textbox

答:
You have two solutions to solve this issue

first one is using setTimeout function to set focus your textbox within 'show.bs.modal' event because this event is fired before model shown as following

```<code>$(function () {
    $('#myModalpop').on('show.bs.modal', function () {
          setTimeout(function(){ $('#txtsearch').focus(); }, 300);
     });
});
</code>```

second solution is using 'shown.bs.modal' event which fired after modal shown but you should remove class fade from you model as following:

```<code>$(function () {
    $('#myModalpop').on('shown.bs.modal', function () {
        $('#txtsearch').focus();
     });
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hii I want to get focus on input textbox when the bootstrap modal popup opens

                <form class="form-inline md-form form-sm mt-0" style="text-align: center;" method="get" action="@Url.Action("Review", "Product")">

                    <input name="id" class="form-contro form-control-sm ml-3 w-75 wow fadeInRight animated" id="txtsearch"  type="text" placeholder="Search" aria-label="Search">
                </form>
                <button type="button" class="close" data-dismiss="modal">×</button>

                @*
QUICK LINKS
*@

I have applied javascript

Focus on textbox

Body:
You have two solutions to solve this issue

first one is using setTimeout function to set focus your textbox within 'show.bs.modal' event because this event is fired before model shown as following

$(function () {
    $('#myModalpop').on('show.bs.modal', function () {
          setTimeout(function(){ $('#txtsearch').focus(); }, 300);
     });
});

second solution is using 'shown.bs.modal' event which fired after modal shown but you should remove class fade from you model as following:

$(function () {
    $('#myModalpop').on('shown.bs.modal', function () {
        $('#txtsearch').focus();
     });
});


问:
Email body containing dot (.) in the URL gets replaced by two dots
I have written code to send emails from my .NET application. Application sends emails successfully. The emails contain number of hyperlinks each inside anchor tags. However, if I try to open emails in the outlook client, it is converting single dot to two dots in the URL. I analyzed the pattern and I could see it happening only when the dot character in URL is the first character of a new line in outlook email. Outlook sets lines automatically, so I do not have control over it.

While forming the body contents, I am setting the "BodyEncoding" property of MailMessage object to System.Text.Encoding.UTF8, but that doesn't make difference in the output.

Could anyone please help what could be the reason, and how to resolve this issue?

答:
I have been facing similar issue when i was trying to save mail in Directory using web.config file.

```<code><system.net>
    <mailSettings>
      <smtp deliveryMethod="SpecifiedPickupDirectory">
        <specifiedPickupDirectory pickupDirectoryLocation="c:\TestMails\"/>
      </smtp>
    </mailSettings>
  </system.net>
</code>```

This issue has been resolved, when sent mail directly to Mail address.

ContentLicense: CC BY-SA 3.0

Body:
I have been facing similar issue when i was trying to save mail in Directory using web.config file.

<system.net>
    <mailSettings>
      <smtp deliveryMethod="SpecifiedPickupDirectory">
        <specifiedPickupDirectory pickupDirectoryLocation="c:\TestMails\"/>
      </smtp>
    </mailSettings>
  </system.net>

This issue has been resolved, when sent mail directly to Mail address.


问:
Syntax error or access violation: 1064 You have an error in your SQL syntax in alter table
I am trying to alter the auto_increment by laravel stament function and it is giving the error.

The complete error message displaying is SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1 (SQL: alter table bills AUTO_INCREMENT=9)

```<code>if($quantity[$i]>$qtny)
{
    Bills::where('id','=',$invoice_no)->delete();
    DB::enableQueryLog();
        DB::statement('alter table `bills` AUTO_INCREMENT=?',array('invoice_no'=>$invoice_no));
    dd(DB::getQueryLog());
    //return "<script>alert('Quantity is not available for product ".$item_name[$i]."');location.href='/create';</script>";
}
</code>```

答:
Variable Placeholder is not allowed here.
So. I have done by this way,</p>

```<code>DB::statement('alter table `bills` AUTO_INCREMENT = '.$invoice_no);
</code>```

Body:
I am trying to alter the auto_increment by laravel stament function and it is giving the error.

The complete error message displaying is SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1 (SQL: alter table bills AUTO_INCREMENT=9)

if($quantity[$i]>$qtny)
{
    Bills::where('id','=',$invoice_no)->delete();
    DB::enableQueryLog();
        DB::statement('alter table `bills` AUTO_INCREMENT=?',array('invoice_no'=>$invoice_no));
    dd(DB::getQueryLog());
    //return "";
}

Body:
Variable Placeholder is not allowed here.
So. I have done by this way,

DB::statement('alter table `bills` AUTO_INCREMENT = '.$invoice_no);


问:
Clustering Weblogic JMS
I have 8 instances of Weblogic, dispatched on 4 machines. Those 8 instances are grouped in a cluster.

Those 8 instances are great for EJB containers, but I have also 8 instances of Weblogic JMS server. In consequence, all my JMS messages are dispatched on those 8 instances...

My volume is too low to need so many JMS servers. I'd like to have only one JMS Weblogic instance by machine.

Is it possible to disable JMS Messaging on some instance?

答:
You target JMS servers to individual managed servers.  What you can do is to target the JMS servers to only one of the managed servers running on each of your machines.

However, you need to be careful about targeting your applications and MDBs, for example, to make sure they can bind to the JNDI names of the required queues.  Otherwise you're going to get errors in your stdout and log files that will clutter them up.

Title: Clustering Weblogic JMS


问:
Git: How to make a multiple commit revertible?
I usually try to squash all commits that belong to the same feature addition on one commit. One of the reasons of doing this is to make easy to me (and my team) to revert my feature quickly and cleanly if necessary.

But this prevents me to divide the new additions in multiple commits when it has more sense for creating a coherent git history.

How can I add 2 commits to my history but make them revertible in one shot?

I was thinking that the merge commits may have some use here but I don't know how.

答:
You could pass range to git revert. For example:

```<code>git revert commit1..commit2
</code>```

Would insert N revert commits, each for the each commit in commit1..commit2 range. It's a „one shot” command that will introduce several revert commits.

Body:
You could pass range to git revert. For example:

git revert commit1..commit2

Would insert N revert commits, each for the each commit in commit1..commit2 range. It's a „one shot” command that will introduce several revert commits.


问:
How do I check if sum of any N numbers of items in a list equals or greater than a value in Kotlin
Is it possible to check if any combination of n numbers of Items in a list is greater than or equal to a number? and how?</p>

答:
What I would do is:

Sort the list in descending order

Check if the sum of the first N items is >= target. If that is not true then any other combination won't be >= target for sure.

An example is:

```<code>val numbers = listOf(5, 2, 8, 12, 4, 9, 0)

val target = 29
val n = 3

val result = numbers.sortedDescending().take(n).sum() >= target
println(result) // true if target is <= 29, false otherwise
</code>```

Note that this approach takes O(n * log(n)), i.e. the slowest operation is sorting. Also, this approach would work even if numbers contains less than n elements

Body:
What I would do is:

Sort the list in descending order

Check if the sum of the first N items is >= target. If that is not true then any other combination won't be >= target for sure.

An example is:

val numbers = listOf(5, 2, 8, 12, 4, 9, 0)

val target = 29
val n = 3

val result = numbers.sortedDescending().take(n).sum() >= target
println(result) // true if target is <= 29, false otherwise

Note that this approach takes O(n * log(n)), i.e. the slowest operation is sorting. Also, this approach would work even if numbers contains less than n elements


问:
Efficient way to order a dictionary by value and stringify it
I have a dictionary with string keys and int values

```<code>for word in coocc[query]:
    resp[word]=coocc[query][word]
</code>```

{"share": 1, "pizza": 3, "eating": 1,...}

I need to sort by value and return a json string.

The following works:

```<code>sortedList=sorted(resp.items(), key=operator.itemgetter(1), reverse=True)
sortedDict=collections.OrderedDict(sortedList)
return json.dumps(sortedDict)
</code>```

'{"cheese": 4, "pizza": 3, "table": 3,..}

but it doesn't seems very efficient to me

答:
Python 3 solution:

```<code>d = {"share": 1, "pizza": 3, "eating": 1,"table": 5, "cheese": 4 }
sorted = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted)
print (json.dumps(sorted))
</code>```

output:

```<code>{'share': 1, 'eating': 1, 'pizza': 3, 'cheese': 4, 'table': 5}
{"share": 1, "eating": 1, "pizza": 3, "cheese": 4, "table": 5}
</code>```

EDIT:

```<code>import json
d = {"share": 1, "pizza": 3, "eating": 1,"table": 5, "cheese": 4 }
sorted = dict(sorted(d.items(), key=lambda x: x[1], reverse = True))
print(sorted)
print (json.dumps(sorted))
</code>```

output:

```<code>{'table': 5, 'cheese': 4, 'pizza': 3, 'share': 1, 'eating': 1}
{"table": 5, "cheese": 4, "pizza": 3, "share": 1, "eating": 1}
</code>```

Body:
I have a dictionary with string keys and int values

for word in coocc[query]:
    resp[word]=coocc[query][word]

{"share": 1, "pizza": 3, "eating": 1,...}

I need to sort by value and return a json string.

The following works:

sortedList=sorted(resp.items(), key=operator.itemgetter(1), reverse=True)
sortedDict=collections.OrderedDict(sortedList)
return json.dumps(sortedDict)

'{"cheese": 4, "pizza": 3, "table": 3,..}

but it doesn't seems very efficient to me

Body:
Python 3 solution:

d = {"share": 1, "pizza": 3, "eating": 1,"table": 5, "cheese": 4 }
sorted = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted)
print (json.dumps(sorted))

output:

{'share': 1, 'eating': 1, 'pizza': 3, 'cheese': 4, 'table': 5}
{"share": 1, "eating": 1, "pizza": 3, "cheese": 4, "table": 5}

EDIT:

import json
d = {"share": 1, "pizza": 3, "eating": 1,"table": 5, "cheese": 4 }
sorted = dict(sorted(d.items(), key=lambda x: x[1], reverse = True))
print(sorted)
print (json.dumps(sorted))

output:

{'table': 5, 'cheese': 4, 'pizza': 3, 'share': 1, 'eating': 1}
{"table": 5, "cheese": 4, "pizza": 3, "share": 1, "eating": 1}


问:
How to render html content in Vaadin TextField
What i'm trying to do is really simple: render html tag in TextField or TextArea.

But after googling for a long time i'm surprised to find out that Vaadin seems not to support it.Vaadin ComboBox or ListBox provides .setRender() method to render content in whatever the way i want. But TextField or TextArea do not have functions like that.I wonder is there any way to do this?

Vaadin TextField supports custom theme , but it didn't work when rendering.

textArea.addThemeVariants(TextAreaVariant.MATERIAL_ALWAYS_FLOAT_LABEL);
```

答:
TextField and TextArea are fields to edit plain text.

If you want to display html content, there is Html component in Flow to do that.

If you want to edit html content there is separate RichTextEditor for doing that.

Also if you allow user to input the html, remember to sanitize the html before displaying it with e.g. Jsoup in order to avoid xss i.e. JavaScript injection issues.


问:
Disable sudo password for specific user login
I have a bash script that executes some PostgreSQL as

sudo -i -u postgres psql <<EOF > /dev/null
--SQL CODE
EOF
```

The sudo asks me for a password for the current user and I'd like to disable that. I don't want to provide a password inside the script through sudo -S. I know I can disable the password for sudo using visudo, however I need to specify the command for which to disable it (I don't want to disable it globally). How do I disable the sudo password for sudo -i -u postgres ?

答:
You probably like a line in the sudoers file as follows:

```<code>script_user ALL = (postgres) NOPASSWD: /usr/bin/psql
</code>```

The individual items in the line are as follows:

script_user: the (standard) user which uses the bash script (i.e., your user account)

ALL: special variable, here at the position where it indicates all hosts. You could try and limit this to e.g. localhost if you want

(postgres): user to run the command(s) as. That is, the user specified by the -u option

NOPASSWD: special variable indicating that the following command does not require a password (for this combination of user, sudo user and host, of course)

/usr/bin/psql: the specific command allowed. This could also be a comma-separated lists of commands, or ALL. (Obviously the path may be different on your machine.)

Related questions and answers on StackOverflow are a bit scattered and don't appear to fully answer your specific question, but I've come across an overall nice write-up on this topic by Abhijit Menon-Sen, which I found clearer to read than the various man pages on sudo & friends.

Body:
I have a bash script that executes some PostgreSQL as

sudo -i -u postgres psql <<EOF > /dev/null
--SQL CODE
EOF

The sudo asks me for a password for the current user and I'd like to disable that. I don't want to provide a password inside the script through sudo -S. I know I can disable the password for sudo using visudo, however I need to specify the command for which to disable it (I don't want to disable it globally). How do I disable the sudo password for sudo -i -u postgres ?

Body:
You probably like a line in the sudoers file as follows:

script_user ALL = (postgres) NOPASSWD: /usr/bin/psql

The individual items in the line are as follows:

script_user: the (standard) user which uses the bash script (i.e., your user account)

ALL: special variable, here at the position where it indicates all hosts. You could try and limit this to e.g. localhost if you want

(postgres): user to run the command(s) as. That is, the user specified by the -u option

NOPASSWD: special variable indicating that the following command does not require a password (for this combination of user, sudo user and host, of course)

/usr/bin/psql: the specific command allowed. This could also be a comma-separated lists of commands, or ALL. (Obviously the path may be different on your machine.)

Related questions and answers on StackOverflow are a bit scattered and don't appear to fully answer your specific question, but I've come across an overall nice write-up on this topic by Abhijit Menon-Sen, which I found clearer to read than the various man pages on sudo & friends.


问:
show full version of thumbnail on rollover with jQuery?
WordPress creates a new image at a reduced size when I specify the dimensions I want it to display, so when I choose 300 x 230 it produces this file as the image source:

http://example.com/myphoto-300x230.jpg

from this full-size version:

http://example.com/myphoto.jpg

I'm using a plugin to expand the 300x230 on rollover. The expanded view is the 300x230 blown up, which is blurry. Is there a way to show the full-size version on rollover, so that it's myphoto-300x230.jpg by default but myphoto.jpg on rollover? Would I need to regex the filename to get rid of the numbers for the dimensions?

答:
Rather than regex you could store the path to the original image in another attribute of the image tag such as fullsize:

```
<img src="http://example.com/myphoto-300x230.jpg" fullsize="http://example.com/myphoto.jpg" />
```

Then just get the value of this attribute in your hover function.

Body:
Rather than regex you could store the path to the original image in another attribute of the image tag such as fullsize:

<img src="http://example.com/myphoto-300x230.jpg" fullsize="http://example.com/myphoto.jpg" />

Then just get the value of this attribute in your hover function.


问:
Looking for a Product Guarantee registration form (Wordpress Plugin)
I want to create a form where users can register their product guarantees on our website.

Does anyone know of a good wordpress plugin that might be able to accommodate this? This is a standalone website without WooCommerce and essentially acts as a contact form where users enter information about the products they wish to register.

The objective is for us to be able to retrieve and retain the information sent in that we can access via the wordpress dashboard.

This also needs to notify us via email when a registration has been sent in and needs to notify users of their registration via an automated email that gets sent when they click 'submit'.

I have set up a new page that I want this to sit on but is there a way to create such a form?

Thanks

答: For the record.   ER Forms seems to do the trick. I do have a separate query however as I want the end user to be able to click a button to add more text fields to the form so they can register as many products as they wish but i'll flag this up in a separate question</p>


问:
How to allocate the right amount of memory (c)
I'm currently experimenting on C, memory allocation and shared memory. I need help, the code is this:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include <sys/stat.h>
#include <sys/sem.h>
#include <sys/shm.h>

#include "shared_memory.h"
#include "semaphore.h"
#include "errExit.h"

struct Node {
    int ID;
    char password[10];
    struct Node *next;
};

key_t shmKeyServer = 131;
size_t size = (sizeof(struct Node)) * 100;

int main (int argc, char *argv[]) {
    int shmidServer = alloc_shared_memory(shmKeyServer, size);
    struct Node *node = (struct Node *)get_shared_memory(shmidServer, 0);

    //fill all the structs

    for(int i=0;i<100;i++){
       node->ID = i;
       sprintf(node->password, "%s%i", "campo num:", i);
       node->next = node + sizeof(struct Node);
       printf("you are on %i cicle \n", i);
       node = node->next;
    }

    return 0;
}
</code>```

The function alloc_shared_memory is here:

```<code>int alloc_shared_memory(key_t shmKey, size_t size) {
   // get, or create, a shared memory segment
   int shmid = shmget(shmKey, size, IPC_CREAT | S_IRUSR | S_IWUSR);
   if (shmid == -1)
       errExit("shmget failed");

   return shmid;
}
</code>```

get_shared_memory:

```<code>void *get_shared_memory(int shmid, int shmflg) {
    // attach the shared memory
    void *ptr_sh = shmat(shmid, NULL, shmflg);
    if (ptr_sh == (void *)-1)
        errExit("shmat failed");

    return ptr_sh;
}
</code>```

The problem is that after the 8th cicle. I get segmentation error.
I think the problem is the memory allocation or the size declaration.

答:
The problem is the line:

```<code>node->next = node + sizeof(struct Node);
</code>```

As typeof(node) is struct Node * this statement increments the node pointer by sizeof(struct Node) * sizeof(struct Node) bytes (see pointer arithmetic in C). You want to increment the node pointer by sizeof(struct Node) bytes, not by sizeof(struct Node) nodes.

You want:

```<code>node->next = (char*)node + sizeof(struct Node);
// or better:
node->next = (void*)((uintptr_t)(void*)node + sizeof(struct Node));
node->next = (void*)((char*)(void*)node + sizeof(struct Node));
// or
node->next = node + 1;
node->next = &node[1];
</code>```

Which fixes the seg fault.

In the line:

```<code>sprintf(node->password, "%s%i", "campo num:", i);
</code>```

undefined behavior happens. The "%s%i", "campo num:", i is printing 12 bytes into node->password pointer, which has only 10 bytes of memory:

```<code>campo num:1
</code>```

is 11 character + 1 byte for string terminating zero byte. Also for numbers greater then 10 sprintf will write 13 bytes. It's best to use snprintf as in snprintf(node->password, sizeof(node->password) to protect against buffer overflows. Also you can sprintf return value int ret = sprintf(..);  if (ret > sizeof(node->password)) { err(1, "Overflowed"); }

Body:
I'm currently experimenting on C, memory allocation and shared memory. I need help, the code is this:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include <sys/stat.h>
#include <sys/sem.h>
#include <sys/shm.h>

#include "shared_memory.h"
#include "semaphore.h"
#include "errExit.h"

struct Node {
    int ID;
    char password[10];
    struct Node *next;
};

key_t shmKeyServer = 131;
size_t size = (sizeof(struct Node)) * 100;

int main (int argc, char *argv[]) {
    int shmidServer = alloc_shared_memory(shmKeyServer, size);
    struct Node *node = (struct Node *)get_shared_memory(shmidServer, 0);

    //fill all the structs

    for(int i=0;i<100;i++){
       node->ID = i;
       sprintf(node->password, "%s%i", "campo num:", i);
       node->next = node + sizeof(struct Node);
       printf("you are on %i cicle \n", i);
       node = node->next;
    }

    return 0;
}

The function alloc_shared_memory is here:

int alloc_shared_memory(key_t shmKey, size_t size) {
   // get, or create, a shared memory segment
   int shmid = shmget(shmKey, size, IPC_CREAT | S_IRUSR | S_IWUSR);
   if (shmid == -1)
       errExit("shmget failed");

   return shmid;
}

get_shared_memory:

void *get_shared_memory(int shmid, int shmflg) {
    // attach the shared memory
    void *ptr_sh = shmat(shmid, NULL, shmflg);
    if (ptr_sh == (void *)-1)
        errExit("shmat failed");

    return ptr_sh;
}

The problem is that after the 8th cicle. I get segmentation error.
I think the problem is the memory allocation or the size declaration.

Body:
The problem is the line:

node->next = node + sizeof(struct Node);

As typeof(node) is struct Node * this statement increments the node pointer by sizeof(struct Node) * sizeof(struct Node) bytes (see pointer arithmetic in C). You want to increment the node pointer by sizeof(struct Node) bytes, not by sizeof(struct Node) nodes.

You want:

node->next = (char*)node + sizeof(struct Node);
// or better:
node->next = (void*)((uintptr_t)(void*)node + sizeof(struct Node));
node->next = (void*)((char*)(void*)node + sizeof(struct Node));
// or
node->next = node + 1;
node->next = &node[1];

Which fixes the seg fault.

In the line:

sprintf(node->password, "%s%i", "campo num:", i);

undefined behavior happens. The "%s%i", "campo num:", i is printing 12 bytes into node->password pointer, which has only 10 bytes of memory:

campo num:1

is 11 character + 1 byte for string terminating zero byte. Also for numbers greater then 10 sprintf will write 13 bytes. It's best to use snprintf as in snprintf(node->password, sizeof(node->password) to protect against buffer overflows. Also you can sprintf return value int ret = sprintf(..);  if (ret > sizeof(node->password)) { err(1, "Overflowed"); }


问:
how do i remove array of elements in mongodb
I'm trying to remove array of elements but it's not working at all..

in schema

```<code>var connectedUsers = Schema({
  fruits: { type: Array },
  vegetables: { type: Array }
})
var connectedusers = mongoose.model("connectedusers", connectedUsers)
</code>```

Node js routing file

```<code>router.post('/connectedusers', function(req,res) {
connection.connectedusers.update(
        { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
        { multi: true }
    )
    connection.connectedusers.find({}, function (err, docs) {
        if (err) throw err;
        res.json({
            docs: docs
        })
    })
});
</code>```

In mongodb collection

```<code>{
    "_id": {
        "$oid": "5cef68f690a42ba057760e98"
    },
    "__v": 0,
    "connectArray": [
        "vinay",
        "vinay1"
    ],
    "fruits": [
        "apples",
        "pears",
        "oranges",
        "grapes",
        "bananas"
    ],
    "vegetables": [
        "carrots",
        "celery",
        "squash",
        "carrots"
    ]
}
</code>```

Array of elements are not removing.. its showing all collection details.
how do i remove elements from mongodb using $Pull or any other.

答:
Try as below:

```<code>router.post('/connectedusers', function(req,res) {
connection.connectedusers.update(
        {},                   //  Missing query part
        {
           $pull: {
                 fruits: { $in: [ "apples", "oranges" ] },
                 vegetables: "carrots"
           }
        },
        { multi: true }
    )
    connection.connectedusers.find({}, function (err, docs) {
        if (err) throw err;
        res.json({
            docs: docs
        })
    })
});
</code>```

Your query is working fine I tried it at my end. You were missing query part from MongoDB update function

Body:
I'm trying to remove array of elements but it's not working at all..

in schema

var connectedUsers = Schema({
  fruits: { type: Array },
  vegetables: { type: Array }
})
var connectedusers = mongoose.model("connectedusers", connectedUsers)

Node js routing file

router.post('/connectedusers', function(req,res) {
connection.connectedusers.update(
        { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
        { multi: true }
    )
    connection.connectedusers.find({}, function (err, docs) {
        if (err) throw err;
        res.json({
            docs: docs
        })
    })
});

In mongodb collection

{
    "_id": {
        "$oid": "5cef68f690a42ba057760e98"
    },
    "__v": 0,
    "connectArray": [
        "vinay",
        "vinay1"
    ],
    "fruits": [
        "apples",
        "pears",
        "oranges",
        "grapes",
        "bananas"
    ],
    "vegetables": [
        "carrots",
        "celery",
        "squash",
        "carrots"
    ]
}

Array of elements are not removing.. its showing all collection details.
how do i remove elements from mongodb using $Pull or any other.

Body:
Try as below:

router.post('/connectedusers', function(req,res) {
connection.connectedusers.update(
        {},                   //  Missing query part
        {
           $pull: {
                 fruits: { $in: [ "apples", "oranges" ] },
                 vegetables: "carrots"
           }
        },
        { multi: true }
    )
    connection.connectedusers.find({}, function (err, docs) {
        if (err) throw err;
        res.json({
            docs: docs
        })
    })
});

Your query is working fine I tried it at my end. You were missing query part from MongoDB update function


问:
Subscribing a variable in rxjs
In my component, I subscribe to a variable like this:

```<code>import { Subject, of } from 'rxjs'

....
distance: number
constructor() {
    this.distance = 0;
    this.getDistance().subscribe(
      (newDistanceValue) => {
        console.log('newDistanceValue', newDistanceValue)
      }
    )
    ....
}

getDistance(): Observable<number> {
   return of(this.distance);
}
</code>```

I get the following output, for the initial value of the variable.

```<code>newDistanceValue 0
</code>```

...but when I change the value in other methods of the component, subscriber doesn't output the new value of distance.

What am I missing?

答:
It's rxjs not rsjx :)

you're generating a new Observable every time you call getDistance, and it only emits one value which is the current value of distance, you should make it a BehaviorSubject instead

import { BehaviorSubject } from 'rxjs'

....
distance$ = new BehaviorSubject(0)
constructor() {
    this.distance$.subscribe(
      (newDistanceValue) => {
        console.log('newDistanceValue', newDistanceValue)
      }
    )
    // or get value of distance synchronously
    console.log(this.distance$.getValue())
    ....
}

foo() {
    this.distance$.next(1)
}
```

Title: Subscribing a variable in rxjs

Body:
In my component, I subscribe to a variable like this:

import { Subject, of } from 'rxjs'

....
distance: number
constructor() {
    this.distance = 0;
    this.getDistance().subscribe(
      (newDistanceValue) => {
        console.log('newDistanceValue', newDistanceValue)
      }
    )
    ....
}

getDistance(): Observable<number> {
   return of(this.distance);
}

I get the following output, for the initial value of the variable.

newDistanceValue 0

...but when I change the value in other methods of the component, subscriber doesn't output the new value of distance.

What am I missing?


问:
WCF CORs Globel.asax VS web.config
Hey all I have the following in my Global.asax file:

```<code>protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");

    if (HttpContext.Current.Request.HttpMethod == "OPTIONS") {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Pragma, Cache-Control");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}
</code>```

I run the WCF and test it out using the following:

```<code>function ajaxGetData() {
    $.ajax({
        url: 'http://localhost:62755/TutorialService.svc/Tutorial',
        type: 'GET',
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {
            console.log(data);
        },
            failure: function (response) {
            alert(response.d);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("error: ", jqXHR);
        }
    });
}

function ajaxPostData() {
    $.ajax({
        url: 'http://localhost:62755/TutorialService.svc/Tutorial/1',
        type: 'POST',
        data: JSON.stringify({"Tutorialid": 1}),
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data, textStatus, jqXHR) {
            console.log(data);
        },
            failure: function (response) {
            alert(response.d);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("error: ", jqXHR);
        }
    });
}
</code>```

That works just fine for both GET and POST. However, if I comment all that out above and use the Web.config and structure it just like the Global.asax file like so:

```<code><httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Max-Age" value="1728000" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization, Pragma, Cache-Control" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>
</code>```

It works for get GET but not the POST. Post error in the console saying:

Access to XMLHttpRequest at 'http://localhost:62755/TutorialService.svc/Tutorial/1' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

What am I missing?

答:
In my case , I solved my problem with configuring cors in web.config by adding the following code to global.asax to ensure every option method will have a 200 status code.</p>

```<code>protected void Application_EndRequest(object sender, EventArgs e)
    {

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.StatusCode = 200;
        }

    }
</code>```

Title: WCF CORs Globel.asax VS web.config

Body:
Hey all I have the following in my Global.asax file:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");

    if (HttpContext.Current.Request.HttpMethod == "OPTIONS") {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Pragma, Cache-Control");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}

I run the WCF and test it out using the following:

function ajaxGetData() {
    $.ajax({
        url: 'http://localhost:62755/TutorialService.svc/Tutorial',
        type: 'GET',
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {
            console.log(data);
        },
            failure: function (response) {
            alert(response.d);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("error: ", jqXHR);
        }
    });
}

function ajaxPostData() {
    $.ajax({
        url: 'http://localhost:62755/TutorialService.svc/Tutorial/1',
        type: 'POST',
        data: JSON.stringify({"Tutorialid": 1}),
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (data, textStatus, jqXHR) {
            console.log(data);
        },
            failure: function (response) {
            alert(response.d);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("error: ", jqXHR);
        }
    });
}

That works just fine for both GET and POST. However, if I comment all that out above and use the Web.config and structure it just like the Global.asax file like so:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Max-Age" value="1728000" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization, Pragma, Cache-Control" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

It works for get GET but not the POST. Post error in the console saying:

Access to XMLHttpRequest at 'http://localhost:62755/TutorialService.svc/Tutorial/1' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

What am I missing?

Body:
In my case , I solved my problem with configuring cors in web.config by adding the following code to global.asax to ensure every option method will have a 200 status code.

protected void Application_EndRequest(object sender, EventArgs e)
    {

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.StatusCode = 200;
        }

    }


问:
Aspnet Core MVC application with spotify authentication callback url redirecting to 127.0.0.1
I'm building an aspnet core web application and want to allow my users to authenticate using their Spotify accounts. I've managed to get the auth flow working as expected when running locally but when I deploy and am using my domain the callback url is: http://127.0.0.1/callback.

Heres the configuration for external auth:

```<code>        services.AddAuthentication()
        .AddSpotify(options =>
        {
            options.ClientId = "blahblah";
            options.ClientSecret = "blahblah";
            options.CallbackPath = "/callback";
            options.Scope.Add("user-follow-read");
</code>```

As you can see, options.CallbackPath is /callback so i'm assuming this is appended to the hosted domain from the server?

My configuration looks like this:

Ubuntu 18.04 LTS VM

Application running in a Docker container, listening on port 80 (no https)

Nginx server configured as a reverse proxy for my domain

Lets encrypt issuing SSL certificates for nginx

Spotify redirect url set to https://example.com/callback and http//:localhost:5001/callback

I have tried:

Setting .UseUrls("https://example.com") in program.cs

Various different combinations of redirect urls in spotify's app configuration

Is there a way I can specify the host within the spotify authentication options or maybe theres some magic I can do within nginx to help with the callback?

Thanks

答:
I've use a slightly different component in the past but the same should apply...

For the callback path you should just set it to:

On Spotify
- http://[yourlocaldomain]:[port]/signin-spotify
- http://yourlocaldomain.com/signin-spotify

The component you're using will set /signin-spotify as default for CallbackPath so you don't need to set it in your services.AddAuthentication().AddSpotify(options =>... setup.

Then in your controller your 'ExternalLogin' should look something like this...

```<code>[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
    // Request a redirect to the external login provider
    return new ChallengeResult(provider, Url.Action("externallogincallback", "account", new { ReturnUrl = returnUrl }));
}
</code>```

where provider = Spotify and returnUrl = the local path location you want to go after the sign up is complete (e.g. '/home/welcome').

The user will be returned to account/externallogincallback in this example after logging in to Spotify. The  externallogincallback does the sign up stuff then pushes the user on to the url specified in returnUrl.

Body:
I'm building an aspnet core web application and want to allow my users to authenticate using their Spotify accounts. I've managed to get the auth flow working as expected when running locally but when I deploy and am using my domain the callback url is: http://127.0.0.1/callback.

Heres the configuration for external auth:

        services.AddAuthentication()
        .AddSpotify(options =>
        {
            options.ClientId = "blahblah";
            options.ClientSecret = "blahblah";
            options.CallbackPath = "/callback";
            options.Scope.Add("user-follow-read");

As you can see, options.CallbackPath is /callback so i'm assuming this is appended to the hosted domain from the server?

My configuration looks like this:

Ubuntu 18.04 LTS VM

Application running in a Docker container, listening on port 80 (no https)

Nginx server configured as a reverse proxy for my domain

Lets encrypt issuing SSL certificates for nginx

Spotify redirect url set to https://example.com/callback and http//:localhost:5001/callback

I have tried:

Setting .UseUrls("https://example.com") in program.cs

Various different combinations of redirect urls in spotify's app configuration

Is there a way I can specify the host within the spotify authentication options or maybe theres some magic I can do within nginx to help with the callback?

Thanks

Body:
I've use a slightly different component in the past but the same should apply...

For the callback path you should just set it to:

On Spotify
- http://[yourlocaldomain]:[port]/signin-spotify
- http://yourlocaldomain.com/signin-spotify

The component you're using will set /signin-spotify as default for CallbackPath so you don't need to set it in your services.AddAuthentication().AddSpotify(options =>... setup.

Then in your controller your 'ExternalLogin' should look something like this...

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
    // Request a redirect to the external login provider
    return new ChallengeResult(provider, Url.Action("externallogincallback", "account", new { ReturnUrl = returnUrl }));
}

where provider = Spotify and returnUrl = the local path location you want to go after the sign up is complete (e.g. '/home/welcome').

The user will be returned to account/externallogincallback in this example after logging in to Spotify. The  externallogincallback does the sign up stuff then pushes the user on to the url specified in returnUrl.


问:
Custom "Repair" and "Uninstall" functions for MSI installers (when called from the Control Panel)
The Add/Remove Programs (or Programs and Features) Control Panel applet usually allows to uninstall or repair a program.

For a non-MSI installation it's easy to define what should happen, when a user clicks the "Change" or "Uninstall" button. Just set the appropriate keys in the Registry (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\<AppName>).

My question is how to make the "Change", "Repair", and "Uninstall" buttons to work my way (e.g. to start a custom program) if an MSI-installation is used?

答:
If you're using an MSI, do it the MSI way.

If you want to do something different, then don't use an MSI. You'll give yourself many, many headaches and lose the benefits of using MSI in the first place.

If you need to run your own EXE during uninstall, see my answer to this question and simply just negate the conditions.

One thing you have to remember with an MSI installation is that the user interface is optional, you can't count on it being displayed either during install or uninstall. A user might remove an application with MSIEXEC /X rather than clicking a button in ARP

If you really want to "do it your way" then I'd suggest creating a bootstrapper for the MSI, having the MSI install hide itself from Add/Remove Programs, and then manually add an ARP entry for your custom installer using the registry keys you have specified above.

OwnerDisplayName: Toro

LastEditorDisplayName: Jeffrey Hantin

OwnerDisplayName: sascha

ContentLicense: CC BY-SA 2.5


问:
What's the best design for this problem with IoC and Circular Reference
I'll try to explain in the simple way.

I have a solution (c# 4.0) that contain 4 projects

Framework

DAL

Domain

WebApplication

So my question is:

Framework is the right place to configure my Unity IoC? I want to configure via code and not with xml, so Framework need to know reference of DAL but DAL already knows Framework.

All my projects will know Framework, so where i configure my IoC?

答:
Applications should be configured in the Composition Root, which is as close to the entry point as possible. In your case, that would be the WebApplication. That's the only project which should have a reference to Unity. None of the other projects should have any reference to Unity at all.

In the composition root, you should follow the Register Resolve Release pattern.

See also this answer - it talks about Ninject instead of Unity, but the concept (and hence the answer) is the same.


问:
Is there a way to read data from many files, each column of each file to be saved in a separate array
I read the names and details of each file and then I preview them for a test in MessageBox.
Is there a way for each column of all files to be recorded in a separate array?

Meteorological charts

```<code>       var pathFiles = Directory.EnumerateFiles(@"C:\Meteo", "*.dat");

        List<string> lines = Directory.EnumerateFiles(@"C:\Meteo", "*.dat").SelectMany(file => File.ReadLines(file)).ToList();

        //Display only filenames.
        //foreach (string file in Directory.EnumerateFiles(@"C:\Meteo", "*.dat"))
        //{
        //    MessageBox.Show(file);
        //}

        foreach (string file in Directory.EnumerateFiles(@"C:\Meteo", "*.dat"))
        {
            // read each line
            foreach (string line in File.ReadLines(file))
            {
                // and show file name and line in a message box
                MessageBox.Show(line, file);
            }
        }
</code>```

I see the data being visualized, but I want to sort them in 11 separate arrays.

PIC (too many .*dat files with the same structure):

答:
First, we have to determine what is the column separator; it seems it's either tabulation or / and space:

```<code>var data = Directory
  .EnumerateFiles(@"C:\Meteo", "*.dat")
  .SelectMany(file => File.ReadLines(file))
  .Select(line => line.Split(new char[] {'\t', ' '}, StringSplitOptions.RemoveEmptyEntries))
  .ToList();
</code>```

Now it's time to pivot the data:

```<code>var result = Enumerable
  .Range(0, data.Any() ? data[0].Length : 11)
  .Select(column => data
     .Select(line => line[column])
     .ToArray())
  .ToArray();
</code>```

So you'll have array of 11 arrays (columns):

```<code>string demo = result[1][3]; // 1st column - (dates), 3d record
</code>```

However, I doubt if you really want to pivot the data. I suggest turning each line into a class, e.g.

```<code>var result = Directory
  .EnumerateFiles(@"C:\Meteo", "*.dat")
  .SelectMany(file => File.ReadLines(file))
  .Select(line => line.Split(new char[] {'\t', ' '}, StringSplitOptions.RemoveEmptyEntries))
  .Select(items => new {
     id = items[0],
     date = DateTime.ParseExact(items[1], "dd-MM-yyyy", CultureInfo.InvariantCulture),
     /* etc. */
   })
  .ToList();
</code>```

then when you want to work with, say, date you can have an array as

```<code> var dates = result
   .Select(item => item.date)
   .ToArray();
</code>```

Edit: or, if you want to see items (say, date and id) in a message box (see comment below) all you need is foreach:

```<code> foreach (var item in result)) {
   MessageBox.Show($"{item.date} and {item.id}");
 }
</code>```

Body:
I read the names and details of each file and then I preview them for a test in MessageBox.
Is there a way for each column of all files to be recorded in a separate array?

Meteorological charts

       var pathFiles = Directory.EnumerateFiles(@"C:\Meteo", "*.dat");

        List<string> lines = Directory.EnumerateFiles(@"C:\Meteo", "*.dat").SelectMany(file => File.ReadLines(file)).ToList();

        //Display only filenames.
        //foreach (string file in Directory.EnumerateFiles(@"C:\Meteo", "*.dat"))
        //{
        //    MessageBox.Show(file);
        //}

        foreach (string file in Directory.EnumerateFiles(@"C:\Meteo", "*.dat"))
        {
            // read each line
            foreach (string line in File.ReadLines(file))
            {
                // and show file name and line in a message box
                MessageBox.Show(line, file);
            }
        }

I see the data being visualized, but I want to sort them in 11 separate arrays.

PIC (too many .*dat files with the same structure):

Body:
First, we have to determine what is the column separator; it seems it's either tabulation or / and space:

var data = Directory
  .EnumerateFiles(@"C:\Meteo", "*.dat")
  .SelectMany(file => File.ReadLines(file))
  .Select(line => line.Split(new char[] {'\t', ' '}, StringSplitOptions.RemoveEmptyEntries))
  .ToList();

Now it's time to pivot the data:

var result = Enumerable
  .Range(0, data.Any() ? data[0].Length : 11)
  .Select(column => data
     .Select(line => line[column])
     .ToArray())
  .ToArray();

So you'll have array of 11 arrays (columns):

string demo = result[1][3]; // 1st column - (dates), 3d record

However, I doubt if you really want to pivot the data. I suggest turning each line into a class, e.g.

var result = Directory
  .EnumerateFiles(@"C:\Meteo", "*.dat")
  .SelectMany(file => File.ReadLines(file))
  .Select(line => line.Split(new char[] {'\t', ' '}, StringSplitOptions.RemoveEmptyEntries))
  .Select(items => new {
     id = items[0],
     date = DateTime.ParseExact(items[1], "dd-MM-yyyy", CultureInfo.InvariantCulture),
     /* etc. */
   })
  .ToList();

then when you want to work with, say, date you can have an array as

 var dates = result
   .Select(item => item.date)
   .ToArray();

Edit: or, if you want to see items (say, date and id) in a message box (see comment below) all you need is foreach:

 foreach (var item in result)) {
   MessageBox.Show($"{item.date} and {item.id}");
 }


问:
Angular 2 : Change an ng Smart table row into a routerlink
I'm working on ng2 Smart Table, and I want to change a row (or even a cell data) into a link (routerlink), I'm currently using this method in order to get some data of my row :

```<code>onUserRowSelect(event)
{
    console.log('user row select: ', event);
    this.selected = event.selected;
    console.log('selected list: ', this.selected);
    this.router.navigate(["/dashboard"]);
    console.log("this is a test ");
}
</code>```

Of course the event is coming from the HTML file,
I'm using this.router.navigate to navigate to my other page, the problem is that an error is always occurring telling me

TypeError: this.router is undefined
    Stack trace:
    [1215]/SmartTables.prototype.onUserRowSelect@http:

can anyone tell me 1) what's the problem here, and 2) how can I extract the data coming from the event (it's returning an Object). Many thanks

答:
In your settings configure like this in the column

```<code>objektelinks: {
title: 'Objektelink',
type: 'custom',
renderComponent: LinkViewComponent,
},
</code>```

create a render component like this

```<code>import { Component, OnInit, Input, Output, EventEmitter } from
'@angular/core';
import { ViewCell } from 'ng2-smart-table';

@component({
selector: 'ngx-link-view',
template: <a [routerLink]= "['/auth/register']"> Objekte </a>,
})
export class LinkViewComponent implements ViewCell, OnInit {
renderValue: string;

@input() value: string | number;
@input() rowData: any;

@output() save: EventEmitter = new EventEmitter();

ngOnInit() {
enter code here
}

}
</code>```

Body:
I'm working on ng2 Smart Table, and I want to change a row (or even a cell data) into a link (routerlink), I'm currently using this method in order to get some data of my row :

onUserRowSelect(event)
{
    console.log('user row select: ', event);
    this.selected = event.selected;
    console.log('selected list: ', this.selected);
    this.router.navigate(["/dashboard"]);
    console.log("this is a test ");
}

Of course the event is coming from the HTML file,
I'm using this.router.navigate to navigate to my other page, the problem is that an error is always occurring telling me

TypeError: this.router is undefined
    Stack trace:
    [1215]/SmartTables.prototype.onUserRowSelect@http:

can anyone tell me 1) what's the problem here, and 2) how can I extract the data coming from the event (it's returning an Object). Many thanks

Body:
In your settings configure like this in the column

objektelinks: {
title: 'Objektelink',
type: 'custom',
renderComponent: LinkViewComponent,
},

create a render component like this

import { Component, OnInit, Input, Output, EventEmitter } from
'@angular/core';
import { ViewCell } from 'ng2-smart-table';

@component({
selector: 'ngx-link-view',
template: <a [routerLink]= "['/auth/register']"> Objekte </a>,
})
export class LinkViewComponent implements ViewCell, OnInit {
renderValue: string;

@input() value: string | number;
@input() rowData: any;

@output() save: EventEmitter = new EventEmitter();

ngOnInit() {
enter code here
}

}


问:
How do I give a newly created role permissions to join a newly created voice chat with the JDA library?
I am attempting to make roles that users can assign themselves and then create hidden voice chats that only that role can see. So far I have created a role and created a hidden voice chat with the code below. But now I don't know how to add permissions to the newly created role to join the newly created voice chat.

event.getGuild().getController().createCopyOfRole(event.getGuild().getRoleById("582333645948452874")).setMentionable(true).setName(messageSent[1]).queue();

event.getGuild().getController().createCopyOfChannel(event.getGuild().getVoiceChannelById("583088218145292298")).setName(messageSent[1]).queue();
```

答:
You can use addPermissionOverride on the ChannelAction that is returned by createCopyOfChannel.

EnumSet<Permission> permissions = EnumSet.of(Permission.VIEW_CHANNEL);
Role role = event.getGuild().getRoleById(582333645948452874L);
VoiceChannel channel = event.getGuild().getVoiceChannelById(583088218145292298L);
GuildController controller = event.getGuild().getController();
controller.createCopyOfRole(role)
          .setMentionable(true)
          .setName(messageSent[1])
          .queue((r) -> {
              controller.createCopyOfChannel(channel)
                        .setName(messageSent[1])
                        // allow the new role to view the channel
                        .addPermissionOverride(r, permissions, null)
                        // Don't allow the everyone role to view the channel
                        .addPermissionOverride(guild.getPublicRole(), null, permissions)
                        .queue();
          });
```

The new role that was created is available in the callback of queue. In my case I named it r. You can then use that role r to add a permission override to the channel before creating it. To deny others access you simply use the public role (@everyone) and deny view access from it.

Body:
You can use addPermissionOverride on the ChannelAction that is returned by createCopyOfChannel.

EnumSet<Permission> permissions = EnumSet.of(Permission.VIEW_CHANNEL);
Role role = event.getGuild().getRoleById(582333645948452874L);
VoiceChannel channel = event.getGuild().getVoiceChannelById(583088218145292298L);
GuildController controller = event.getGuild().getController();
controller.createCopyOfRole(role)
          .setMentionable(true)
          .setName(messageSent[1])
          .queue((r) -> {
              controller.createCopyOfChannel(channel)
                        .setName(messageSent[1])
                        // allow the new role to view the channel
                        .addPermissionOverride(r, permissions, null)
                        // Don't allow the everyone role to view the channel
                        .addPermissionOverride(guild.getPublicRole(), null, permissions)
                        .queue();
          });

The new role that was created is available in the callback of queue. In my case I named it r. You can then use that role r to add a permission override to the channel before creating it. To deny others access you simply use the public role (@everyone) and deny view access from it.


问:
Semantic-UI React Checkbox state not working
I've got a parent container that calls a class-based react component child (since the semantic-ui react docs are all written with class-based components). The child component has a Form.Field:

```<code><Form.Field
    control={Checkbox}
    label={{children: 'cardreader'}}
    checked = {this.state.cardReaderChecked}
    onChange={this.cardReaderToggleHandler}
/>
</code>```

I've got a state:

```<code>state = {
    cardReaderChecked: false,
}
</code>```

and a cardReaderToggleHandler:

```<code>cardReaderToggleHandler = () => {
    console.log(this.state.cardReaderChecked);
    this.setState((prevState, props) => ({
        cardReaderChecked : !prevState.cardReaderChecked
    }))
console.log(this.state.cardReaderChecked);
}
</code>```

I've tried toggling on this.state.cardReaderChecked but I found a lot of references and docs recommending this approach with the prevState to avoid the delay in state updating.

However, there must a logical fault because it doesn't work. If I refresh the page, the checkbox is clear as this.state.cardReaderChecked.

The first time I click the checkbox it renders with the tick, and my this.state.cardReaderChecked updates to true (according to my trusty React tools in Chrome). However, both console.log printouts give me a false and if I pass my state back to the parent form, it also shows that the checkbox is false.

Every subsequent click toggles but a ticked checkbox shows a true state but passes on a false to the parent form (that's where the console.log is currently) and vice versa an unticked checkbox passes back a true.

I'm almost tempted to remove the not from the prev.state in the setState, but I would prefer to understand why this happens.

Bonus Question: How can I query the checkbox state checked in a functional component?

答:
Pass the function to a child as prop</p>

```<code>class Parent extends Component {

  state = {
    cardReaderChecked: false,
  }

  cardReaderToggleHandler = () => {

    this.setState((prevState, props) => ({
      cardReaderChecked : !prevState.cardReaderChecked
    }), () => console.log(this.state.cardReaderChecked))
  }
  ....

  render () {
    return (
     ....
     <Form.Field
       control={Checkbox}
       label={{children: 'cardreader'}}
       checked = {this.state.cardReaderChecked}
       onChange={this.cardReaderToggleHandler}
     />
    )
  }
</code>```

Body:
I've got a parent container that calls a class-based react component child (since the semantic-ui react docs are all written with class-based components). The child component has a Form.Field:

<Form.Field
    control={Checkbox}
    label={{children: 'cardreader'}}
    checked = {this.state.cardReaderChecked}
    onChange={this.cardReaderToggleHandler}
/>

I've got a state:

state = {
    cardReaderChecked: false,
}

and a cardReaderToggleHandler:

cardReaderToggleHandler = () => {
    console.log(this.state.cardReaderChecked);
    this.setState((prevState, props) => ({
        cardReaderChecked : !prevState.cardReaderChecked
    }))
console.log(this.state.cardReaderChecked);
}

I've tried toggling on this.state.cardReaderChecked but I found a lot of references and docs recommending this approach with the prevState to avoid the delay in state updating.

However, there must a logical fault because it doesn't work. If I refresh the page, the checkbox is clear as this.state.cardReaderChecked.

The first time I click the checkbox it renders with the tick, and my this.state.cardReaderChecked updates to true (according to my trusty React tools in Chrome). However, both console.log printouts give me a false and if I pass my state back to the parent form, it also shows that the checkbox is false.

Every subsequent click toggles but a ticked checkbox shows a true state but passes on a false to the parent form (that's where the console.log is currently) and vice versa an unticked checkbox passes back a true.

I'm almost tempted to remove the not from the prev.state in the setState, but I would prefer to understand why this happens.

Bonus Question: How can I query the checkbox state checked in a functional component?

Body:
Pass the function to a child as prop

class Parent extends Component {

  state = {
    cardReaderChecked: false,
  }

  cardReaderToggleHandler = () => {

    this.setState((prevState, props) => ({
      cardReaderChecked : !prevState.cardReaderChecked
    }), () => console.log(this.state.cardReaderChecked))
  }
  ....

  render () {
    return (
     ....
     <Form.Field
       control={Checkbox}
       label={{children: 'cardreader'}}
       checked = {this.state.cardReaderChecked}
       onChange={this.cardReaderToggleHandler}
     />
    )
  }


问:
Error when checking model target: the list of Numpy arrays that you are passing to your model is not the size the model expected
I'm trying to predict 3 material properties based on 4 inputs.
inputs: Heat-rate, temp, pressure, time
outputs: density, grain size, hardness

I already tried to use np.array(), tf.reshape(), and np.ndarray() nothing worked

```<code> def build_model():
        model = keras.Sequential([
            layers.Dense(4, activation = tf.nn.relu, input_shape = [len(train_dataset.keys())]),
            layers.Dense(64, activation = tf.nn.sigmoid),
            layers.Dense(64, activation = tf.nn.relu),
            layers.Dense(64, activation = tf.nn.relu),
            layers.Dense(3)
        ])

    optimizer = keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0)

    model.compile(loss = 'mean_squared_error',
                 optimizer = optimizer,
                 metrics = ['mean_absolute_error', 'mean_squared_error'])
    return model

model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_35 (Dense)             (None, 4)                 20
_________________________________________________________________
dense_36 (Dense)             (None, 64)                320
_________________________________________________________________
dense_37 (Dense)             (None, 64)                4160
_________________________________________________________________
dense_38 (Dense)             (None, 64)                4160
_________________________________________________________________
dense_39 (Dense)             (None, 3)                 195
=================================================================
Total params: 8,855
Trainable params: 8,855
Non-trainable params: 0
_________________________________________________________________

 print(np.array(normed_train_data))
    print(train_labels)

[[0.78865053 0.75882112 0.66666667 1.        ]
 [0.78865053 0.92764634 1.         0.33333333]
 [1.         0.84323373 1.         0.33333333]
 [1.         0.95176422 1.         0.33333333]
 [0.78865053 0.95176422 1.         0.        ]
 [0.78865053 0.95176422 1.         0.33333333]
 [0.78865053 0.92764634 1.         0.66666667]
 [1.         0.92764634 1.         0.33333333]
 [1.         0.87941056 1.         0.33333333]
 [0.78865053 0.97588211 1.         0.2       ]
 [0.78865053 0.90352845 0.66666667 1.        ]
 [1.         0.80705689 1.         0.33333333]
 [0.78865053 1.         0.66666667 0.66666667]
 [1.         0.83117478 1.         0.33333333]
 [0.78865053 0.97588211 1.         0.2       ]
 [0.78865053 1.         1.         0.2       ]
 [0.78865053 0.71058534 0.66666667 1.        ]
 [0.78865053 0.90352845 1.         0.33333333]
 [0.78865053 0.95176422 0.66666667 1.        ]
 [0.78865053 0.85046909 0.66666667 1.        ]
 [1.         0.80705689 1.         0.33333333]]
[[2      66.5
28     96.8
13     96.4
10     99.0
26     98.2
24    100.0
27     97.6
11     99.0
17     96.2
22    100.0
5      81.8
16     71.4
8      96.0
14     91.9
23    100.0
20    100.0
1      65.8
29     90.3
6      94.4
4      71.8
18     91.9
Name: density, dtype: float64], [2      4.000
28     0.688
13     0.474
10     0.564
26     0.688
24     0.811
27     0.688
11     0.564
17     0.082
22    25.000
5      4.000
16     0.564
8      4.000
14     0.444
23     0.877
20    51.000
1      4.000
29     0.688
6      4.000
4      4.000
18     0.074
Name: grain size, dtype: float64], [2       400000000
28    29400000000
13    31800000000
10    31800000000
26    32300000000
24    35600000000
27    31800000000
11    31800000000
17    31800000000
22    30700000000
5      6700000000
16    31800000000
8     33300000000
14    31800000000
23    34200000000
20    28500000000
1       200000000
29    22800000000
6     32000000000
4      2400000000
18    31800000000
Name: hardness, dtype: int64]]

class PrintDot(keras.callbacks.Callback):
    def on_epoch_end(self,epoch,logs):
        if epoch % 100 == 0: print('')
        print('.',end='')

EPOCH=1000

history = model.fit(normed_train_data, train_labels,
epochs=EPOCH, validation_split = 0.2, verbose=0,
callbacks=[PrintDot()])
</code>```

ValueError: Error when checking model target: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 1 array(s), but instead got the following list of 3 arrays

I'm expecting to train the machine to give me those 3 outputs and plot them with the corresponding real value and get the error.

答:
I presume you are trying to pass an array of shape [rows, columns] as input, where you have mentioned columns = 4. If that is the case the below code should work for you.

The None in the input shape corresponds to the length of the data (or rows).

```<code>model = keras.Sequential([
            layers.Dense(64, activation = tf.nn.sigmoid, input_shape = [None, 4]),
            layers.Dense(64, activation = tf.nn.relu),
            layers.Dense(64, activation = tf.nn.relu),
            layers.Dense(3)
        ])
</code>```

The above model takes an input each of size 4 and passes it along 3 hidden layers of 64 neurons and outputs a vector of size 3.

Body:
I'm trying to predict 3 material properties based on 4 inputs.
inputs: Heat-rate, temp, pressure, time
outputs: density, grain size, hardness

I already tried to use np.array(), tf.reshape(), and np.ndarray() nothing worked

 def build_model():
        model = keras.Sequential([
            layers.Dense(4, activation = tf.nn.relu, input_shape = [len(train_dataset.keys())]),
            layers.Dense(64, activation = tf.nn.sigmoid),
            layers.Dense(64, activation = tf.nn.relu),
            layers.Dense(64, activation = tf.nn.relu),
            layers.Dense(3)
        ])

    optimizer = keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0)

    model.compile(loss = 'mean_squared_error',
                 optimizer = optimizer,
                 metrics = ['mean_absolute_error', 'mean_squared_error'])
    return model

model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_35 (Dense)             (None, 4)                 20
_________________________________________________________________
dense_36 (Dense)             (None, 64)                320
_________________________________________________________________
dense_37 (Dense)             (None, 64)                4160
_________________________________________________________________
dense_38 (Dense)             (None, 64)                4160
_________________________________________________________________
dense_39 (Dense)             (None, 3)                 195
=================================================================
Total params: 8,855
Trainable params: 8,855
Non-trainable params: 0
_________________________________________________________________

 print(np.array(normed_train_data))
    print(train_labels)

[[0.78865053 0.75882112 0.66666667 1.        ]
 [0.78865053 0.92764634 1.         0.33333333]
 [1.         0.84323373 1.         0.33333333]
 [1.         0.95176422 1.         0.33333333]
 [0.78865053 0.95176422 1.         0.        ]
 [0.78865053 0.95176422 1.         0.33333333]
 [0.78865053 0.92764634 1.         0.66666667]
 [1.         0.92764634 1.         0.33333333]
 [1.         0.87941056 1.         0.33333333]
 [0.78865053 0.97588211 1.         0.2       ]
 [0.78865053 0.90352845 0.66666667 1.        ]
 [1.         0.80705689 1.         0.33333333]
 [0.78865053 1.         0.66666667 0.66666667]
 [1.         0.83117478 1.         0.33333333]
 [0.78865053 0.97588211 1.         0.2       ]
 [0.78865053 1.         1.         0.2       ]
 [0.78865053 0.71058534 0.66666667 1.        ]
 [0.78865053 0.90352845 1.         0.33333333]
 [0.78865053 0.95176422 0.66666667 1.        ]
 [0.78865053 0.85046909 0.66666667 1.        ]
 [1.         0.80705689 1.         0.33333333]]
[[2      66.5
28     96.8
13     96.4
10     99.0
26     98.2
24    100.0
27     97.6
11     99.0
17     96.2
22    100.0
5      81.8
16     71.4
8      96.0
14     91.9
23    100.0
20    100.0
1      65.8
29     90.3
6      94.4
4      71.8
18     91.9
Name: density, dtype: float64], [2      4.000
28     0.688
13     0.474
10     0.564
26     0.688
24     0.811
27     0.688
11     0.564
17     0.082
22    25.000
5      4.000
16     0.564
8      4.000
14     0.444
23     0.877
20    51.000
1      4.000
29     0.688
6      4.000
4      4.000
18     0.074
Name: grain size, dtype: float64], [2       400000000
28    29400000000
13    31800000000
10    31800000000
26    32300000000
24    35600000000
27    31800000000
11    31800000000
17    31800000000
22    30700000000
5      6700000000
16    31800000000
8     33300000000
14    31800000000
23    34200000000
20    28500000000
1       200000000
29    22800000000
6     32000000000
4      2400000000
18    31800000000
Name: hardness, dtype: int64]]

class PrintDot(keras.callbacks.Callback):
    def on_epoch_end(self,epoch,logs):
        if epoch % 100 == 0: print('')
        print('.',end='')

EPOCH=1000

history = model.fit(normed_train_data, train_labels,
epochs=EPOCH, validation_split = 0.2, verbose=0,
callbacks=[PrintDot()])

ValueError: Error when checking model target: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 1 array(s), but instead got the following list of 3 arrays

I'm expecting to train the machine to give me those 3 outputs and plot them with the corresponding real value and get the error.

Body:
I presume you are trying to pass an array of shape [rows, columns] as input, where you have mentioned columns = 4. If that is the case the below code should work for you.

The None in the input shape corresponds to the length of the data (or rows).

model = keras.Sequential([
            layers.Dense(64, activation = tf.nn.sigmoid, input_shape = [None, 4]),
            layers.Dense(64, activation = tf.nn.relu),
            layers.Dense(64, activation = tf.nn.relu),
            layers.Dense(3)
        ])

The above model takes an input each of size 4 and passes it along 3 hidden layers of 64 neurons and outputs a vector of size 3.


问:
How to exclude library from all dependencies in Kotlin DSL build.gradle?
I started migration from build.gradle (Groovy) to build.gradle.kts (Kotlin DSL). The thing is that com.google.common.util.concurrent.ListenableFuture (from com.google.guava) exists in several dependecies. Because of that build fails with java.lang.RuntimeException: Duplicate class ... error.

Previously (when I had build.gradle in Groovy) this problem was solved with this snippet:

```<code>configurations {
    all*.exclude group: 'com.google.guava', module: 'listenablefuture'
}
</code>```

But I can't find anything similar using Kotlin DSL.
Could you please provide Kotlin alternative for the snippet above or suggest any other solution on how to deal with this?

答:
This might work (though I haven't tried it):</p>

```<code>configurations.forEach { it.exclude("com.google.guava", "listenablefuture") }
</code>```

Body:
I started migration from build.gradle (Groovy) to build.gradle.kts (Kotlin DSL). The thing is that com.google.common.util.concurrent.ListenableFuture (from com.google.guava) exists in several dependecies. Because of that build fails with java.lang.RuntimeException: Duplicate class ... error.

Previously (when I had build.gradle in Groovy) this problem was solved with this snippet:

configurations {
    all*.exclude group: 'com.google.guava', module: 'listenablefuture'
}

But I can't find anything similar using Kotlin DSL.
Could you please provide Kotlin alternative for the snippet above or suggest any other solution on how to deal with this?

Body:
This might work (though I haven't tried it):

configurations.forEach { it.exclude("com.google.guava", "listenablefuture") }


问:
Creating 2 numbers from a one #C
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

```<code>int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }
</code>```

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

答:
Another solution could be...</p>

```<code>var num1 = 94321;
var oddFinal = 0;
var evenFinal = 0;

var odd = new List<int>();
var even = new List<int>();

while( num1>0 )
{
    if( num1 % 2 == 0 )
        odd.Add( num1 % 10 );
    else
        even.Add( num1 % 10 );

    num1 = num1 / 10;
}

for (int i = 0; i < odd.Count; i++)
{
    oddFinal += odd[i] * (int) Math.Pow(10,i);
}

for (int i = 0; i < even.Count; i++)
{
    evenFinal += even[i] * (int) Math.Pow(10,i);
}
</code>```

Title: Creating 2 numbers from a one #C

Body:
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

Body:
Another solution could be...

var num1 = 94321;
var oddFinal = 0;
var evenFinal = 0;

var odd = new List<int>();
var even = new List<int>();

while( num1>0 )
{
    if( num1 % 2 == 0 )
        odd.Add( num1 % 10 );
    else
        even.Add( num1 % 10 );

    num1 = num1 / 10;
}

for (int i = 0; i < odd.Count; i++)
{
    oddFinal += odd[i] * (int) Math.Pow(10,i);
}

for (int i = 0; i < even.Count; i++)
{
    evenFinal += even[i] * (int) Math.Pow(10,i);
}


问:
Truncate inline HTML for Read More/Less Button
I am trying to truncate the text which is inside inline html by the length of the text (excluding html) / 2 and add read more button and reverse - add read less button and hide the half of the text. It works if the text is only raw paragraph. But when the text is inline html like below - with ol,ul,headings, it doesn't work. Can someone give a hand on this? Thank you! </p>

```<code><div class="truncate">
 <div class="toggledText" id="toggledText">
 <h1>Lorem Ipsum is simply </h1>
  <h2>Lorem Ipsum is simply </h2>
  <p><strong>Thank you for scanning. </strong></p>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text
    ever since the 1500s, when an unknown printer took a galley of type
    and scrambled it to make a type specimen book. It has survived not
    only five
   <ol>
    <li>Lorem Ipsum is simply </li>
    <li>Lorem Ipsum is simply. </li>
   </ol>
   <ul>
    <li>Lorem Ipsum is simply </li>
    </ul>

   var numberOfToggled = document.getElementsByClassName('toggledText');

   for(i=0; i<numberOfToggled.length; i++){

    var el = numberOfToggled[i];

  var elText = el.innerHTML.trim();
  var charLimit = elText.length / 2;

        if(elText.length > charLimit){
            var showStr = elText.slice(0,charLimit);
            var hideStr = elText.slice(charLimit);
            el.innerHTML = showStr + '<span class="morePoints">...</span> <span class="trimmed">' + hideStr + '</span>';
            el.parentElement.innerHTML = el.parentElement.innerHTML + "<div class='read-more'><a href='#' class='more'></a>";
        }

    }

    window.onclick = function(event) {
        if (event.target.className == 'more') {
    event.preventDefault();
            event.target.parentElement.parentElement.classList.toggle('showAll');
        }
    }
</code>```

答:
You could also consider the height aspect.

document.querySelector('#readmore').addEventListener("click", function(e) {
  e.preventDefault();
  document.querySelector('#toggledText').classList.toggle('toggle');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.toggledText {
  height: 200px;
  overflow: hidden;
}

.toggledText.toggle {
 height: auto;
}

.readless-txt,
.toggledText.toggle~#readmore span.readmore-txt {
  display: none;
 }

.toggledText.toggle~#readmore span.readless-txt {
   display: block;
}</code>```

Lorem Ipsum is simply

Lorem Ipsum is simply

Thank you for scanning.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five

Lorem Ipsum is simply

Lorem Ipsum is simply.

Lorem Ipsum is simply

  Read moreRead Less

```

Body:
I am trying to truncate the text which is inside inline html by the length of the text (excluding html) / 2 and add read more button and reverse - add read less button and hide the half of the text. It works if the text is only raw paragraph. But when the text is inline html like below - with ol,ul,headings, it doesn't work. Can someone give a hand on this? Thank you!

Lorem Ipsum is simply

Lorem Ipsum is simply

Thank you for scanning.

Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text
    ever since the 1500s, when an unknown printer took a galley of type
    and scrambled it to make a type specimen book. It has survived not
    only five

Lorem Ipsum is simply

Lorem Ipsum is simply.

Lorem Ipsum is simply

   var numberOfToggled = document.getElementsByClassName('toggledText');

   for(i=0; i<numberOfToggled.length; i++){

    var el = numberOfToggled[i];

  var elText = el.innerHTML.trim();
  var charLimit = elText.length / 2;

        if(elText.length > charLimit){
            var showStr = elText.slice(0,charLimit);
            var hideStr = elText.slice(charLimit);
            el.innerHTML = showStr + '... ' + hideStr + '';
            el.parentElement.innerHTML = el.parentElement.innerHTML + "
";
        }

    }

    window.onclick = function(event) {
        if (event.target.className == 'more') {
    event.preventDefault();
            event.target.parentElement.parentElement.classList.toggle('showAll');
        }
    }

Body:
You could also consider the height aspect.

document.querySelector('#readmore').addEventListener("click", function(e) {
  e.preventDefault();
  document.querySelector('#toggledText').classList.toggle('toggle');
});

.toggledText {
  height: 200px;
  overflow: hidden;
}

.toggledText.toggle {
 height: auto;
}

.readless-txt,
.toggledText.toggle~#readmore span.readmore-txt {
  display: none;
 }

.toggledText.toggle~#readmore span.readless-txt {
   display: block;
}

<div class="truncate">
  <div class="toggledText" id="toggledText">
    <h1>Lorem Ipsum is simply </h1>
    <h2>Lorem Ipsum is simply </h2>
    <p><strong>Thank you for scanning. </strong></p>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five
      <ol>
        <li>Lorem Ipsum is simply </li>
        <li>Lorem Ipsum is simply. </li>
      </ol>
      <ul>
        <li>Lorem Ipsum is simply </li>
      </ul>
  </div>
  <a href="#" id="readmore"><span class="readmore-txt">Read more</span><span class="readless-txt">Read Less</span></a>
</div>


问:
Real time notifications for chatting applications
I am creating chatting web app. I implemented realtime functionality and typing indicator using pusher, but m unable to apply real time notification functionality.
please tell me how I can do that.
and is there any way to  use bootstrap tickers for notifications ?</p>

答:
If you creating just simple web app, I advise to you to read about SignalR in ASP.NET. It is easy to use, and simple to control.

Also you can check out this url:The Simplest Thing Possible: Creating Push Notifications with SignalR

By the way, here the best example to create chat application using Pusher: Web PUSH Notifications быстро и просто ...but in Russian language))