问:
Migration from WebSphere to WebLogic
I have an webapplication running on WebSphere using JDK 1.6, Spring 2.5.6 and iceFaces 1.8.2. I need to migrate that webapp to WebLogic. So I updated JDK to 1.8 and Spring to 4.2. The iceFaces framework I dont change because of the number of change on my source code.
When I deploy the application I got the following:

```<code>com.sun.faces.config.ConfigurationException: Factory 'javax.faces.lifecycle.ClientWindowFactory' was not configured properly.
        at com.sun.faces.config.processor.FactoryConfigProcessor.verifyFactoriesExist(FactoryConfigProcessor.java:330)
        at com.sun.faces.config.processor.FactoryConfigProcessor.process(FactoryConfigProcessor.java:236)
        at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:439)
        at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:227)
        at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:705)
        Truncated. see log file for complete stacktrace
Caused By: javax.faces.FacesException: com.sun.faces.lifecycle.ClientWindowFactoryImpl
        at javax.faces.FactoryFinderInstance.getImplGivenPreviousImpl(FactoryFinderInstance.java:409)
        at javax.faces.FactoryFinderInstance.getImplementationInstance(FactoryFinderInstance.java:253)
        at javax.faces.FactoryFinderInstance.getFactory(FactoryFinderInstance.java:549)
        at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:283)
        at com.sun.faces.config.processor.FactoryConfigProcessor.verifyFactoriesExist(FactoryConfigProcessor.java:328)
        Truncated. see log file for complete stacktrace
Caused By: java.lang.UnsupportedOperationException
        at javax.faces.application.Application.subscribeToEvent(Application.java:1797)
        at com.sun.faces.lifecycle.ClientWindowFactoryImpl.<init>(ClientWindowFactoryImpl.java:62)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        Truncated. see log file for complete stacktrace
</code>```

Are there some way to resolve that or I need to change my iceFaces version?

答:
I think i resolved that including jsf 1.2 libs on my war file.

Still getting another errors, soon I update the answer if it worked or not.

UPDATE:

Yes, this solved my problem... Now webapplication is deployed sucessful. (Still getting httpError 500 when open my login page...)

Title: Migration from WebSphere to WebLogic

Body:
I have an webapplication running on WebSphere using JDK 1.6, Spring 2.5.6 and iceFaces 1.8.2. I need to migrate that webapp to WebLogic. So I updated JDK to 1.8 and Spring to 4.2. The iceFaces framework I dont change because of the number of change on my source code.
When I deploy the application I got the following:

com.sun.faces.config.ConfigurationException: Factory 'javax.faces.lifecycle.ClientWindowFactory' was not configured properly.
        at com.sun.faces.config.processor.FactoryConfigProcessor.verifyFactoriesExist(FactoryConfigProcessor.java:330)
        at com.sun.faces.config.processor.FactoryConfigProcessor.process(FactoryConfigProcessor.java:236)
        at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:439)
        at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:227)
        at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:705)
        Truncated. see log file for complete stacktrace
Caused By: javax.faces.FacesException: com.sun.faces.lifecycle.ClientWindowFactoryImpl
        at javax.faces.FactoryFinderInstance.getImplGivenPreviousImpl(FactoryFinderInstance.java:409)
        at javax.faces.FactoryFinderInstance.getImplementationInstance(FactoryFinderInstance.java:253)
        at javax.faces.FactoryFinderInstance.getFactory(FactoryFinderInstance.java:549)
        at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:283)
        at com.sun.faces.config.processor.FactoryConfigProcessor.verifyFactoriesExist(FactoryConfigProcessor.java:328)
        Truncated. see log file for complete stacktrace
Caused By: java.lang.UnsupportedOperationException
        at javax.faces.application.Application.subscribeToEvent(Application.java:1797)
        at com.sun.faces.lifecycle.ClientWindowFactoryImpl.<init>(ClientWindowFactoryImpl.java:62)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        Truncated. see log file for complete stacktrace

Are there some way to resolve that or I need to change my iceFaces version?


来源: stackexchange

问:
How can I save the FREQUENCIES of one variable as a new variable in SPSS?
I've got a DataSet with repeated measures. Now I want to know how many measures I've got for each participant. I kind of get the information by using the FREQUENCIES command on the Participant_ID variable. But I actually want to know the frequencies of the frequencies of Participant_ID so that I can make statements like "5 Participants replied 38 times, 60 participants replied 39 times...."

So is there a way to save the frequencies as a new variable (so that I can use the FREQUENCIES command on it)?
Or is there another way to get what I want?

答:
You can get that information as a new variable in the main dataset or as a separate dataset by using AGGREGATE (Data > Aggregate) and choosing Number of Cases as the statistic with Participant_ID as the break variable.

In general, although Aggregate is simpler here, you can use OMS (the Output Management System) to save any table as a dataset.  See Utilities > OMS Control Panel for more information.

ContentLicense: CC BY-SA 3.0


问:
C# Replace all characters in string with value of character key in dictionary
hi i have this dictionary

```<code>Dictionary<char, string> keys = new Dictionary<char, string>();
keys.Add("a", "23");
keys.Add("A", "95");
keys.Add("d", "12");
keys.Add("D", "69");
</code>```

and for example this string

```<code>string text = "Dad";
</code>```

i want to encrypt the string with dictionary keys and values!

the final encrypted string will be:

692312

anyone can  help?!

答:
I suggest using Linq and string.Concat:

```<code>// Dictionary<string, string> - actual keys are strings
Dictionary<string, string> keys = new Dictionary<string, string>();

keys.Add("a", "23");
keys.Add("A", "95");
keys.Add("d", "12");
keys.Add("D", "69");

string result = string.Concat(text.Select(c => keys[c.ToString()]));
</code>```

a better design is to declare keys as Dictionary<char, string>:

```<code>Dictionary<char, string> keys = new Dictionary<char, string>() {
  {'a', "23"},
  {'A', "95"},
  {'d', "12"},
  {'D', "69"},
};

...

string result = string.Concat(text.Select(c => keys[c]));
</code>```

Edit: proving that each character is encoded as a fixed length string (2 in the example) it's easy to decode:

```<code>Dictionary<string, char> decode = keys
  .ToDictionary(pair => pair.Value, pair => pair.Key);

int fixedSize = decode.First().Key.Length;

string decoded = string.Concat(Enumerable
  .Range(0, result.Length / fixedSize)
  .Select(i => decode[result.Substring(i * fixedSize, fixedSize)]));
</code>```

Body:
hi i have this dictionary

Dictionary<char, string> keys = new Dictionary<char, string>();
keys.Add("a", "23");
keys.Add("A", "95");
keys.Add("d", "12");
keys.Add("D", "69");

and for example this string

string text = "Dad";

i want to encrypt the string with dictionary keys and values!

the final encrypted string will be:

692312

anyone can  help?!

Body:
I suggest using Linq and string.Concat:

// Dictionary<string, string> - actual keys are strings
Dictionary<string, string> keys = new Dictionary<string, string>();

keys.Add("a", "23");
keys.Add("A", "95");
keys.Add("d", "12");
keys.Add("D", "69");

string result = string.Concat(text.Select(c => keys[c.ToString()]));

a better design is to declare keys as Dictionary<char, string>:

Dictionary<char, string> keys = new Dictionary<char, string>() {
  {'a', "23"},
  {'A', "95"},
  {'d', "12"},
  {'D', "69"},
};

...

string result = string.Concat(text.Select(c => keys[c]));

Edit: proving that each character is encoded as a fixed length string (2 in the example) it's easy to decode:

Dictionary<string, char> decode = keys
  .ToDictionary(pair => pair.Value, pair => pair.Key);

int fixedSize = decode.First().Key.Length;

string decoded = string.Concat(Enumerable
  .Range(0, result.Length / fixedSize)
  .Select(i => decode[result.Substring(i * fixedSize, fixedSize)]));


问:
Only one toggle open at a time?
I am new to JS, so please bear with me.

I am trying to create a basic content toggle, however I am struggling to get my code to only show one toggle at a time.

The code I am using is:

```<code><div>
    <h3 class = "trigger"><a href="#box1"> Heading 1</a></h3>
    <h3 class = "trigger"><a href="#box2"> Heading 2</a></h3>

</div>
<div class ="toggle" id="box1">
        box one content
</div>

<div class ="toggle" id="box2">
    box two content
</div>

$("a").click(function(){
   var myelement = $(this).attr("href")
   $(myelement).slideToggle("slow");
   $(".toggle:visible").not(myelement).hide();
});
</code>```

答:
It's only showing one item at a time. Click on them and you'll see:

$("a").click(function(){
   var myelement = $(this).attr("href")
   $(myelement).slideToggle("slow");
   $(".toggle:visible").not(myelement).hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<h3 class = "trigger"> Heading 1</h3>
<h3 class = "trigger"> Heading 2</h3>

</div>
<div class ="toggle" id="box1">
    box one content
</div>

<div class ="toggle" id="box2">
box two content
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script></code>```

JSFiddle: https://jsfiddle.net/xd146x1s/2/

If you want to hide the elements at the start just use $(".toggle").hide(); Like this:

$(".toggle").hide();

$("a").click(function(){
   var myelement = $(this).attr("href")
   $(myelement).slideToggle("slow");
   $(".toggle:visible").not(myelement).hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<h3 class = "trigger"> Heading 1</h3>
<h3 class = "trigger"> Heading 2</h3>

</div>
<div class ="toggle" id="box1">
    box one content
</div>

<div class ="toggle" id="box2">
box two content
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script></code>```

JSFiddle: https://jsfiddle.net/xd146x1s/3/

Title: Only one toggle open at a time?

Body:
I am new to JS, so please bear with me.

I am trying to create a basic content toggle, however I am struggling to get my code to only show one toggle at a time.

The code I am using is:

 Heading 1

 Heading 2

        box one content

    box two content

$("a").click(function(){
   var myelement = $(this).attr("href")
   $(myelement).slideToggle("slow");
   $(".toggle:visible").not(myelement).hide();
});

Body:
It's only showing one item at a time. Click on them and you'll see:

$("a").click(function(){
   var myelement = $(this).attr("href")
   $(myelement).slideToggle("slow");
   $(".toggle:visible").not(myelement).hide();
});

<div>
<h3 class = "trigger"><a href="#box1"> Heading 1</a></h3>
<h3 class = "trigger"><a href="#box2"> Heading 2</a></h3>

</div>
<div class ="toggle" id="box1">
    box one content
</div>

<div class ="toggle" id="box2">
box two content
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>

JSFiddle: https://jsfiddle.net/xd146x1s/2/

If you want to hide the elements at the start just use $(".toggle").hide(); Like this:

$(".toggle").hide();

$("a").click(function(){
   var myelement = $(this).attr("href")
   $(myelement).slideToggle("slow");
   $(".toggle:visible").not(myelement).hide();
});

<div>
<h3 class = "trigger"><a href="#box1"> Heading 1</a></h3>
<h3 class = "trigger"><a href="#box2"> Heading 2</a></h3>

</div>
<div class ="toggle" id="box1">
    box one content
</div>

<div class ="toggle" id="box2">
box two content
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>

JSFiddle: https://jsfiddle.net/xd146x1s/3/


问:
How to test with Mocha a Javascript Singleton
I'm new in Javascript, and I want to create units tests to test a Singleton.

So I have the following Singleton in a authentication.js file :

```<code>var AuthenticationService = (function () {

  /**
   * Instance du singleton
   */
  var instance;

  /**
   * Private property du service d'authentification de firebase.
   * @type {firebase.auth.Auth}
   */
  var privateFirebaseAuthService = null;

  function init(firebaseAuthService) {

    privateFirebaseAuthService = firebaseAuthService;

    /**
     * Crée un nouvel utilisateur de l'application
     * @param  {String} email    l'email de l'utilisateur
     * @param  {String} password le password de l'utilisateur
     * @return {Promise<firebase.User>}          Renvoie l'utilisateur créé en cas de succès.
     */
    function privateCreateUserAsync(email, password) {
      return new Promise(function(resolve, reject){
        if(privateFirebaseAuthService === null){
          console.log("Le service d'authentification firebase n'est pas initialisé.");
          reject(Error(Enum.Authentication.CreateUserErrorCode.AuthenticationServiceNotInitialized));
        }

        privateFirebaseAuthService.createUserWithEmailAndPassword(email, password)
          .then(function(firebaseUser) {
            console.log("createUserAsync ok " + email);
            // TODO : renvoyer un application user plutôt qu'un user firebase.
            resolve(firebaseUser);

          })
          .catch(function(error) {
            var errorCode = error.code;
            console.log("createUserAsync KO " + errorCode);

            if (errorCode == 'auth/email-already-in-use') {
              reject(Error(Enum.Authentication.CreateUserErrorCode.EmailAlreadyUsed));
            }
            else if(errorCode == 'auth/invalid-email'){
              reject(Error(Enum.Authentication.CreateUserErrorCode.InvalidEmail));
            }
            else if(errorCode == 'auth/operation-not-allowed'){
              reject(Error(Enum.Authentication.CreateUserErrorCode.OperationNotAllowed));
            }
            else if(errorCode == 'auth/weak-password'){
              reject(Error(Enum.Authentication.CreateUserErrorCode.WeakPassword));
            }
            else{
              reject(Error(Enum.Authentication.CreateUserErrorCode.Unknown));
            }
        });

      });
    }

    return {

      // Public methods and variables
      createUserAsync: function(email, password){
          return privateCreateUserAsync(email, password);
        }

    };
  };

  return {

    // Get the Singleton instance if one exists
    // or create one if it doesn't
    getInstance: function(firebaseAuthService) {

      if ( !instance ) {
        instance = init(firebaseAuthService);
      }

      return instance;
    }
  };
})();
</code>```

So I create a authenticationTest.js :

```<code>var chai = require('chai');
var expect = chai.expect;
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var firebase = require('firebase');

var authenticationLib = require('../app/public/scripts/authentication');

describe("Authentication", function(){

  before(function(){

    // dev firebase 3
    var config = {
        apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxx",
        databaseURL: "xxxxxxxxxxxxxxxxxxxxxx",
        storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxx",
    };

    firebase.initializeApp(config);
    var firebaseAuthService = firebase.auth();
    console.log(authenticationLib);
    authenticationLib.getInstance(firebaseAuthService);
  });

  describe("Create User", function(){
    it("should be return a rejected promise with EmailAlreadyUsed error", function(){

      authenticationLib.getInstance().createUserAsync('hfdzjfezzpf@fezkfjezofez.fr', 'dhkofefzefs456fefz45').should.be.fulfilled;

    });
  });
});
</code>```

But when I launch 'npm test', I have the following :

```<code>1) Authentication "before all" hook:
 TypeError: authenticationLib.getInstance is not a function
  at Context.<anonymous> (test\authenticationTest.js:24:23)
</code>```

Can anyone explain me what i'm done wrong?

Thanks a lot.

Mike.

答:
since you did not post the whole js file i can only give you these hints.

check if ../app/public/scripts/authentication is the correct path

make sure you exported the authentication module, this in particular is not visible in your code and must be done because you're explicitely requiring it inside your test

edit: seems that you're missing the export

in place of returning the object, you should export it.

```<code>module.export = {

    // Get the Singleton instance if one exists
    // or create one if it doesn't
    getInstance: function(firebaseAuthService) {

      if ( !instance ) {
        instance = init(firebaseAuthService);
      }

      return instance;
    }
 }
</code>```

Body:
I'm new in Javascript, and I want to create units tests to test a Singleton.

So I have the following Singleton in a authentication.js file :

var AuthenticationService = (function () {

  /**
   * Instance du singleton
   */
  var instance;

  /**
   * Private property du service d'authentification de firebase.
   * @type {firebase.auth.Auth}
   */
  var privateFirebaseAuthService = null;

  function init(firebaseAuthService) {

    privateFirebaseAuthService = firebaseAuthService;

    /**
     * Crée un nouvel utilisateur de l'application
     * @param  {String} email    l'email de l'utilisateur
     * @param  {String} password le password de l'utilisateur
     * @return {Promise<firebase.User>}          Renvoie l'utilisateur créé en cas de succès.
     */
    function privateCreateUserAsync(email, password) {
      return new Promise(function(resolve, reject){
        if(privateFirebaseAuthService === null){
          console.log("Le service d'authentification firebase n'est pas initialisé.");
          reject(Error(Enum.Authentication.CreateUserErrorCode.AuthenticationServiceNotInitialized));
        }

        privateFirebaseAuthService.createUserWithEmailAndPassword(email, password)
          .then(function(firebaseUser) {
            console.log("createUserAsync ok " + email);
            // TODO : renvoyer un application user plutôt qu'un user firebase.
            resolve(firebaseUser);

          })
          .catch(function(error) {
            var errorCode = error.code;
            console.log("createUserAsync KO " + errorCode);

            if (errorCode == 'auth/email-already-in-use') {
              reject(Error(Enum.Authentication.CreateUserErrorCode.EmailAlreadyUsed));
            }
            else if(errorCode == 'auth/invalid-email'){
              reject(Error(Enum.Authentication.CreateUserErrorCode.InvalidEmail));
            }
            else if(errorCode == 'auth/operation-not-allowed'){
              reject(Error(Enum.Authentication.CreateUserErrorCode.OperationNotAllowed));
            }
            else if(errorCode == 'auth/weak-password'){
              reject(Error(Enum.Authentication.CreateUserErrorCode.WeakPassword));
            }
            else{
              reject(Error(Enum.Authentication.CreateUserErrorCode.Unknown));
            }
        });

      });
    }

    return {

      // Public methods and variables
      createUserAsync: function(email, password){
          return privateCreateUserAsync(email, password);
        }

    };
  };

  return {

    // Get the Singleton instance if one exists
    // or create one if it doesn't
    getInstance: function(firebaseAuthService) {

      if ( !instance ) {
        instance = init(firebaseAuthService);
      }

      return instance;
    }
  };
})();

So I create a authenticationTest.js :

var chai = require('chai');
var expect = chai.expect;
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var firebase = require('firebase');

var authenticationLib = require('../app/public/scripts/authentication');

describe("Authentication", function(){

  before(function(){

    // dev firebase 3
    var config = {
        apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxx",
        databaseURL: "xxxxxxxxxxxxxxxxxxxxxx",
        storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxx",
    };

    firebase.initializeApp(config);
    var firebaseAuthService = firebase.auth();
    console.log(authenticationLib);
    authenticationLib.getInstance(firebaseAuthService);
  });

  describe("Create User", function(){
    it("should be return a rejected promise with EmailAlreadyUsed error", function(){

      authenticationLib.getInstance().createUserAsync('hfdzjfezzpf@fezkfjezofez.fr', 'dhkofefzefs456fefz45').should.be.fulfilled;

    });
  });
});

But when I launch 'npm test', I have the following :

1) Authentication "before all" hook:
 TypeError: authenticationLib.getInstance is not a function
  at Context.<anonymous> (test\authenticationTest.js:24:23)

Can anyone explain me what i'm done wrong?

Thanks a lot.

Mike.

Body:
since you did not post the whole js file i can only give you these hints.

check if ../app/public/scripts/authentication is the correct path

make sure you exported the authentication module, this in particular is not visible in your code and must be done because you're explicitely requiring it inside your test

edit: seems that you're missing the export

in place of returning the object, you should export it.

module.export = {

    // Get the Singleton instance if one exists
    // or create one if it doesn't
    getInstance: function(firebaseAuthService) {

      if ( !instance ) {
        instance = init(firebaseAuthService);
      }

      return instance;
    }
 }


问:
Unable to deploy WAR in an EAR on WebLogic
I have a web application running on JSF 2.2 on WebLogic Application server 12.2.1.1.

I have a simple java class and trying to initialize it as an ApplicationScoped object using CDI. This gets deployed perfectly fine as a WAR.

```<code>import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

@Named
@ApplicationScoped
public class AppContext {
    public AppContext() {
    }
}
</code>```

However, when I add this WAR to an EAR it fails to deploy. I am trying all possible solutions and nothing seems to work at this point. The exception log is as below:

```<code>weblogic.management.DeploymentException: CDI deployment failure:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]:org.jboss.weld.exceptions.DeploymentException:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]
    at org.jboss.weld.bootstrap.Validator.validateBeanNames(Validator.java:641)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:487)
    at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:446)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
    at com.oracle.injection.provider.weld.WeldInjectionContainer.start(WeldInjectionContainer.java:150)
    Truncated. see log file for complete stacktrace
</code>```

Also WEB-INF\beans.xml is as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
</code>```

Application Running On:

```<code>NetBeans IDE 8.2;
JDK 1.8 b121;
Mojarra JSF 2.2;
WebLogic 12.2.1.1;
</code>```

Any hint on fixing this issue is highly appreciated.

答:
Remove the WAR from EAR and deploy it separately. For some reason, packaging the WAR in the EAR and deploying fails. Not sure if this is an issue with WebLogic or EAR configuration.

Taken from identical question with accepted answer - Initializing CDI Bean Name Ambiguous

Body:
I have a web application running on JSF 2.2 on WebLogic Application server 12.2.1.1.

I have a simple java class and trying to initialize it as an ApplicationScoped object using CDI. This gets deployed perfectly fine as a WAR.

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

@Named
@ApplicationScoped
public class AppContext {
    public AppContext() {
    }
}

However, when I add this WAR to an EAR it fails to deploy. I am trying all possible solutions and nothing seems to work at this point. The exception log is as below:

weblogic.management.DeploymentException: CDI deployment failure:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]:org.jboss.weld.exceptions.DeploymentException:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]
    at org.jboss.weld.bootstrap.Validator.validateBeanNames(Validator.java:641)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:487)
    at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:446)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
    at com.oracle.injection.provider.weld.WeldInjectionContainer.start(WeldInjectionContainer.java:150)
    Truncated. see log file for complete stacktrace

Also WEB-INF\beans.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

Application Running On:

NetBeans IDE 8.2;
JDK 1.8 b121;
Mojarra JSF 2.2;
WebLogic 12.2.1.1;

Any hint on fixing this issue is highly appreciated.


问:
CSS margin prevents area from beeing clickable
I am enclosing the main content of my page into a div which has a top margin of 80px like in the screenshot:

This works, the problem is that there is a leaderboard banner just above it and the div prevents the banner to be clickable just for the area illustrated in green.

The code is nothing special:

```<code>#content {
  position: relative;
  padding: 80px 10px 15px;
  min-height: 400px;
}
</code>```

The problem also occurs if I use margin instead of padding.

How could I maintain the margin/padding and in the same time keep the leaderboard clickable?

答:
try adding this to your css :

```<code>#content{
    z-index: 1;
}

#yourBanner{
    position: relative;
    z-index: 2;
}
</code>```

Body:
I am enclosing the main content of my page into a div which has a top margin of 80px like in the screenshot:

This works, the problem is that there is a leaderboard banner just above it and the div prevents the banner to be clickable just for the area illustrated in green.

The code is nothing special:

#content {
  position: relative;
  padding: 80px 10px 15px;
  min-height: 400px;
}

The problem also occurs if I use margin instead of padding.

How could I maintain the margin/padding and in the same time keep the leaderboard clickable?

Body:
try adding this to your css :

#content{
    z-index: 1;
}

#yourBanner{
    position: relative;
    z-index: 2;
}


问:
transparent png not showing video in background
I made a transparent png with a theatre setup thing and i'm putting a 1 second video to play like a gif in the background but instead of seeing the video i see a body background color background, also letting z index be smaller than the other one, but deleting it on inspect element will show the video.

This is not the original one just that to show the problem

 <video style='width:100%;height:100%;' alt='[]' autoplay loop>
  <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4" />
  Unfortunately, this site cannot run on your computer. Please upgrade your browser/buy a new computer.
</video>

```

答:
You need of css declaration background-color: transparent to see the video above a transparent color. Moreover, you need of css declaration position: absolute to position both image and video on the top. So, the css rule could be the following: img {position: absolute; background-color: transparent;}
Note that the rules assigned to #bg may be useless.

I hope I was of any help.

img {
  position: absolute;
  background-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bg" style='position:absolute;z-index:0;left:0;top:0;width:100%;height:100%'>
 <img style='width:100%;height:100%;' alt='[]' src="http://www.moviebowlgrille.com/img/nav/rental.png">
 <video style='width:100%;height:100%;' alt='[]' autoplay loop>
  <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4" />
  Unfortunately, this site cannot run on your computer. Please upgrade your browser/buy a new computer.
</video>
</div></code>```

Body:
You need of css declaration background-color: transparent to see the video above a transparent color. Moreover, you need of css declaration position: absolute to position both image and video on the top. So, the css rule could be the following: img {position: absolute; background-color: transparent;}
Note that the rules assigned to #bg may be useless.

I hope I was of any help.

img {
  position: absolute;
  background-color: transparent;
}

<div id="bg" style='position:absolute;z-index:0;left:0;top:0;width:100%;height:100%'>
 <img style='width:100%;height:100%;' alt='[]' src="http://www.moviebowlgrille.com/img/nav/rental.png">
 <video style='width:100%;height:100%;' alt='[]' autoplay loop>
  <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4" />
  Unfortunately, this site cannot run on your computer. Please upgrade your browser/buy a new computer.
</video>
</div>


问:
django, accessing meta properties outside of the page that generates them
So basically, I'm using the PersistentRemoteUser middelware in django to handle authentication requests through a login page that is monitored by apache using pubcookie

I can do the basic user.is_authenticated bit's fine, but my problem comes from the fact that I have 2 types of users that require two different kinds of authentication. I have my admin users that require authenticating with 2 factor authentication, and standard users that use only user/password,

The authentication type can easily be viewed on the login page itself by accessing: self.request.META['AUTH_TYPE'] which will read as either "SecureID" or "NetID" depending on theauthtype`.

But I need to be able to perform a check on different pages to see if the user authenticated with secureid or netid to determine what parts of a page are viewable, or if they are allowed to see the page at all. But the meta data does not exist outside of the initial login page, only the request.user data, which does not, unless i'm missing something, contain any type of auth_type.

is it possible to either access the metadata from another page, or save the users authtype to some kind of post or session variable that gets carried around for the session?

Sorry if this question is a bit...dumb, I'm still fairly new to django and still trying to wrap my head around certain aspects of it.

答:
You've answered your question.

Use a session that will persist the value (as long as the session is active).

```<code>request.session['auth_type'] = 'SecureID'
</code>```

Then you can always make a decision based on the session value you stored earlier.

```<code>if request.session['auth_type'] == 'SecureID':
    # do two factor auth stuff
    pass
else:
    # do normal stuff
    pass
</code>```

Body:
You've answered your question.

Use a session that will persist the value (as long as the session is active).

request.session['auth_type'] = 'SecureID'

Then you can always make a decision based on the session value you stored earlier.

if request.session['auth_type'] == 'SecureID':
    # do two factor auth stuff
    pass
else:
    # do normal stuff
    pass


问:
How to synchronise Angular2 http get?
I understand using observable I can execute a method when the request is completed, but how can i wait till a http get is completed and return the response using in ng2 http?

```<code>getAllUser(): Array<UserDTO> {
    this.value = new Array<UserDTO>();
    this.http.get("MY_URL")
                    .map(res => res.json())
                    .subscribe(
                        data => this.value = data,
                        err => console.log(err),
                        () => console.log("Completed")
    );

    return this.value;
}
</code>```

the "value" will is null when its returned because get is async..

答: By looking at the angular source (https://github.com/angular/angular/blob/master/packages/http/src/backends/xhr_backend.ts#L46), it is apparent that the async attribute of the XMLHttpRequest is not getting used. The third parameter of XMLHttpRequest needs to be set to "false" for synchronous requests.

ContentLicense: CC BY-SA 4.0

Title: How to synchronise Angular2 http get?

Body:
I understand using observable I can execute a method when the request is completed, but how can i wait till a http get is completed and return the response using in ng2 http?

getAllUser(): Array<UserDTO> {
    this.value = new Array<UserDTO>();
    this.http.get("MY_URL")
                    .map(res => res.json())
                    .subscribe(
                        data => this.value = data,
                        err => console.log(err),
                        () => console.log("Completed")
    );

    return this.value;
}

the "value" will is null when its returned because get is async..


问:
How to get BlogEngine.NET to run outside of a local environment?
I am trying to run BlogEngine.NET. It works fine locally in Visual Studio but whenever I publish it outside of my local computer none of the posts are showing up.

I think this is because none of the scripts or CSS are being loaded (the posts are done via AngularJS). I've made sure that the read and write permissions are allowed in IIS so I know that isn't the problem.

I believe that AngularJS isn't loading properly, as when I go to the admin panel the url returned with the 404 error is this:

```<code>8926/admin/%7B%7BSiteVars.RelativeWebRoot%7D%7Dadmin/#/dashboard
</code>```

instead of:

```<code>8926/admin/#/dashboard
</code>```

Even If I manually take out all of the %7B%7BSiteVars.RelativeWebRoot%7D%7Dadmin text, the posts still don't show up as they do locally which leads me to believe the posts are also tied to AngularJS as well.

Does anyone know how to fix this? This may not be a BlogEngine.NET problem as much as it is just a loading of Javascript and CSS problem inside of IIS

The documentation for my project is here.

答:
BlogEngine.Net had moved to GitHub that is where the latest updates are at.

Best to go here:

https://github.com/rxtur/BlogEngine.NET

and try again with a fresh install.

I have a fresh install working with no issues here:

http://blogengine07.azurewebsites.net

Took a total of around 30 mins to it it 100% up and running, creating new web app service,database, change web.config, publish to Azure, and making some changes in settings.

What web host are you using to host your website?

You can also try Azure Web App Service for free here:

https://azure.microsoft.com/en-us/try/app-service/web/?language=cs

If you can get it to work there but not at your current web host then that points to a web server issue, since you are able to run it locally and on Azure.

Hope this helps.

Have a great Day!

Brian Keith Davis

Body:
I am trying to run BlogEngine.NET. It works fine locally in Visual Studio but whenever I publish it outside of my local computer none of the posts are showing up.

I think this is because none of the scripts or CSS are being loaded (the posts are done via AngularJS). I've made sure that the read and write permissions are allowed in IIS so I know that isn't the problem.

I believe that AngularJS isn't loading properly, as when I go to the admin panel the url returned with the 404 error is this:

8926/admin/%7B%7BSiteVars.RelativeWebRoot%7D%7Dadmin/#/dashboard

instead of:

8926/admin/#/dashboard

Even If I manually take out all of the %7B%7BSiteVars.RelativeWebRoot%7D%7Dadmin text, the posts still don't show up as they do locally which leads me to believe the posts are also tied to AngularJS as well.

Does anyone know how to fix this? This may not be a BlogEngine.NET problem as much as it is just a loading of Javascript and CSS problem inside of IIS

The documentation for my project is here.


问:
Clarify the use of bind in this context?
Can someone help explain what is the use of bind in this context is?

```<code><button onClick={this.add.bind(null, 'Bacon tuna')} className="button-info-create">Add New</button>
</code>```

https://youtu.be/OKRu7i49X54?list=PL6gx4Cwl9DGBuKtLgPR_zWYnrwv-JllpA&t=3m3s

From what I understand, when null passed to bind, this refers to the global scope. Yet somehow it is seems to be referring to the Board instance.

答:
bind allows you to seed arguments into the resulting function.

fun.bind(thisArg[, arg1[, arg2[, ...]]])

so that is calling this.add, passing in null for the context (which is ignored when the constructor is called with new), and seeding "bacon tuna" for the first argument.

you can read more about function.prototype.bind here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Body:
Can someone help explain what is the use of bind in this context is?

<button onClick={this.add.bind(null, 'Bacon tuna')} className="button-info-create">Add New</button>

https://youtu.be/OKRu7i49X54?list=PL6gx4Cwl9DGBuKtLgPR_zWYnrwv-JllpA&t=3m3s

From what I understand, when null passed to bind, this refers to the global scope. Yet somehow it is seems to be referring to the Board instance.


问:
GNU split (UNIX command) creating files not matching pattern after reaching "z"
So  I was spliting some large files, everything worked properly until a file of 81GB came to scene. The split command seems that made its job, but the last files has a non correlated name. Look at the right bottom of picture.

And I'm using the command like this:

```<code>split -b 125M ./2014.txt 2014/2014_
</code>```

Anyone knows why instead of create the file 2014_za created the 2014_zaaa?

答:
You can only have 676 files named [a-z][a-z], while your command required more.

Here are some options for what split could do:

Crash.

This is the behavior mandated by POSIX, and followed by macOS.

Start writing larger suffixes.

This is a bad choice because after _zz comes _aaa, but now the files will show up in the wrong order in ls and cat * will no longer join them in correct order.

Save the last range, _z, for longer suffixes.

This is a good choice because after _yz comes _zaaa, which has room to grow while still remaining in alphabetical order. This is what GNU does, and the behavior you're seeing.

If you want all the names to be uniform without triggering any of these behaviors, just use a larger suffix length with -a 6 to ensure you have enough room.

Body:
So  I was spliting some large files, everything worked properly until a file of 81GB came to scene. The split command seems that made its job, but the last files has a non correlated name. Look at the right bottom of picture.

And I'm using the command like this:

split -b 125M ./2014.txt 2014/2014_

Anyone knows why instead of create the file 2014_za created the 2014_zaaa?


问:
Ruby Time object for midnight UTC
I need to be able to create UTC Time objects in Rails, but no matter what I try it ends up being a local Time object converted to UTC.

application.rb

```<code>config.time_zone = "UTC"
</code>```

Examples

I try to create a Time object for midnight on New Years 2017:

```<code>Time.new(year, month, 1, 0, 0, 0)
</code>```

=> 2017-03-01 00:00:00 -0500

```<code>Time.new(year, month, 1, 0, 0, 0).in_time_zone
</code>```

=> Wed, 01 Mar 2017 05:00:00 UTC +00:00

```<code>Time.new(year, month, 1, 0, 0, 0).in_time_zone('UTC')
</code>```

=> Wed, 01 Mar 2017 05:00:00 UTC +00:00

答:
You should be able to use:

```<code>Time.utc(year, month, 1, 0, 0, 0)
</code>```

or just

```<code>Time.utc(year, month, 1)
</code>```

Title: Ruby Time object for midnight UTC

Body:
I need to be able to create UTC Time objects in Rails, but no matter what I try it ends up being a local Time object converted to UTC.

application.rb

config.time_zone = "UTC"

Examples

I try to create a Time object for midnight on New Years 2017:

Time.new(year, month, 1, 0, 0, 0)

=> 2017-03-01 00:00:00 -0500

Time.new(year, month, 1, 0, 0, 0).in_time_zone

=> Wed, 01 Mar 2017 05:00:00 UTC +00:00

Time.new(year, month, 1, 0, 0, 0).in_time_zone('UTC')

=> Wed, 01 Mar 2017 05:00:00 UTC +00:00

Body:
You should be able to use:

Time.utc(year, month, 1, 0, 0, 0)

or just

Time.utc(year, month, 1)


答:
You can use the json module to convert your string into a dictionary. Then use the csv module to save them into a file.

```<code>import json, csv
json_string = '[{"Lat": "-122.37391463199998", "Long": "47.630880207000075"}, {"Lat": "-122.38447021399998", "Long": "47.70118823100006"}, {"Lat": "-122.34729431799997", "Long": "47.64717111900006"} ]'
data = json.loads(json_string)

with open('foo.csv', 'wb') as csvfile:
    csv_writer = csv.DictWriter(csvfile, delimiter=',', fieldnames=['Lat', 'Long'])
    csv_writer.writeheader()
    csv_writer.writerows(data)
</code>```

Title: Multi column csv from json in python

Body:
how to convert json to csv in python. want it open in excel with the lat and long columns.

[
  {
    "Lat": "-122.37391463199998",
    "Long": "47.630880207000075"
  },
  {
    "Lat": "-122.38447021399998",
    "Long": "47.70118823100006"
  },
  {
    "Lat": "-122.34729431799997",
    "Long": "47.64717111900006"
  }
]

Body:
You can use the json module to convert your string into a dictionary. Then use the csv module to save them into a file.

import json, csv
json_string = '[{"Lat": "-122.37391463199998", "Long": "47.630880207000075"}, {"Lat": "-122.38447021399998", "Long": "47.70118823100006"}, {"Lat": "-122.34729431799997", "Long": "47.64717111900006"} ]'
data = json.loads(json_string)

with open('foo.csv', 'wb') as csvfile:
    csv_writer = csv.DictWriter(csvfile, delimiter=',', fieldnames=['Lat', 'Long'])
    csv_writer.writeheader()
    csv_writer.writerows(data)


问:
How I could change line colour in livecycle?
I'm developing a form with Livecycle ES2. I need to change color of a line in a field:

I can change background colour with:

```<code>var GREY = "225, 225, 225";

this.ui.oneOfChild.border.fill.color.value = GREY;
</code>```

But, i don't know how to change color of line using "Adobe Javascript"

答:
If you only want to change the top border, then you need to do a couple of things:
1) Go into the Border tab of the field and set the Edges to be "Edit Individually"
2) Change one border to be different from the others (doesn't matter which one, but probably the top one).

This will force Designer to generate separate <edge> tags within the <border> tag.  You can verify this by going into the XML Source tab and viewing the field.  Before you make that change there will be one <edge> tag under <border> and afterwards, there will be 4 separate tags (one for each edges of the field's border - top, right, bottom, and left).

Once that's done, then the following line should work:

```<code>this.resolveNode("border.edge[0].color").value = "0,0,255"; // Set line to blue
</code>```

What this is doing, is setting the first border.edge element's color child to have a value of 0,0,255.  You need to do the resolveNode() call because JavaScript interprets the square brackets as an array reference.  The resolveNode, passes the square brackets to the SOM expression engine which correctly interprets it as meaning the index number of a multiply occurring element.

You can replace edge[0] with edge[1], edge[2] or edge[3] for the other borders.

Body:
I'm developing a form with Livecycle ES2. I need to change color of a line in a field:

I can change background colour with:

var GREY = "225, 225, 225";

this.ui.oneOfChild.border.fill.color.value = GREY;

But, i don't know how to change color of line using "Adobe Javascript"

Body:
If you only want to change the top border, then you need to do a couple of things:
1) Go into the Border tab of the field and set the Edges to be "Edit Individually"
2) Change one border to be different from the others (doesn't matter which one, but probably the top one).

This will force Designer to generate separate <edge> tags within the <border> tag.  You can verify this by going into the XML Source tab and viewing the field.  Before you make that change there will be one <edge> tag under <border> and afterwards, there will be 4 separate tags (one for each edges of the field's border - top, right, bottom, and left).

Once that's done, then the following line should work:

this.resolveNode("border.edge[0].color").value = "0,0,255"; // Set line to blue

What this is doing, is setting the first border.edge element's color child to have a value of 0,0,255.  You need to do the resolveNode() call because JavaScript interprets the square brackets as an array reference.  The resolveNode, passes the square brackets to the SOM expression engine which correctly interprets it as meaning the index number of a multiply occurring element.

You can replace edge[0] with edge[1], edge[2] or edge[3] for the other borders.


问:
How to transform an array into an object in javascript
I have an array like this:

```<code>[
{ id: “Идент”, name: “Назв”, price: “Сто”, quantity: “Коло” },
[ 1, “продукт 1”, “400”, 5 ],
[ 2, “продукт 2”, “300”, 7 ],
[ 2, “продукт 2”, “300”, 7 ]]
</code>```

How can I transform it into something like this:

```<code>{
    items: [
        { name: "Хлеб", id: 1, price: 15.9, quantity: 3 },
        { name: "Масло", id: 2, price: 60, quantity: 1 },
        { name: "Картофель", id: 3, price: 22.6, quantity: 6 },
        { name: "Сыр", id: 4, price:310, quantity: 9 }
    ]
};
</code>```

答:
To convert an array with data to an array with objects, you could use another array with keys and iterate it for the assignment of the properties for the new objects.

var data = [{ id: 'id', name: 'name', price: 'price', quantity: 'quantity' }, [0, 'foo', 1.99, 201], [1, 'abc', 2.5, 42], [2, 'baz', 10, 99], [6, 'bar', 21.99, 1]],
    keys = Object.keys(data[0]),
    result = {
        items: data.slice(1).map(function (a) {
            var temp = {};
            keys.forEach(function (k, i) {
                temp[k] = a[i];
            });
            return temp;
        })
    };

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array like this:

[
{ id: “Идент”, name: “Назв”, price: “Сто”, quantity: “Коло” },
[ 1, “продукт 1”, “400”, 5 ],
[ 2, “продукт 2”, “300”, 7 ],
[ 2, “продукт 2”, “300”, 7 ]]

How can I transform it into something like this:

{
    items: [
        { name: "Хлеб", id: 1, price: 15.9, quantity: 3 },
        { name: "Масло", id: 2, price: 60, quantity: 1 },
        { name: "Картофель", id: 3, price: 22.6, quantity: 6 },
        { name: "Сыр", id: 4, price:310, quantity: 9 }
    ]
};

Body:
To convert an array with data to an array with objects, you could use another array with keys and iterate it for the assignment of the properties for the new objects.

var data = [{ id: 'id', name: 'name', price: 'price', quantity: 'quantity' }, [0, 'foo', 1.99, 201], [1, 'abc', 2.5, 42], [2, 'baz', 10, 99], [6, 'bar', 21.99, 1]],
    keys = Object.keys(data[0]),
    result = {
        items: data.slice(1).map(function (a) {
            var temp = {};
            keys.forEach(function (k, i) {
                temp[k] = a[i];
            });
            return temp;
        })
    };

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Can we fetch the call details of an iPhone?
Can we fetch the call details like dialed numbers, missed calls of an iPhone?

UPDATE

Can we do it in jail broken phones for CYDIA store?

答:
No, no information about phone calls is available, nor SMS messages.

iOS apps are sandboxed to prevent developers from doing nasty things like sending that data back to their servers. It limits some potentially cool apps, but it also protects privacy.

ContentLicense: CC BY-SA 2.5


问:
pipe child process stdout & stdin to browser in node.js & browserify
I am attempting to pipe the stdout & stdin of a child_process to a browser & display it in an html page. I am using browserify to get node.js to run on the browser. My code for spawning the child_process is like this.

```<code>var child = require('child_process');

var myREPL = child.spawn('myshell.exe', ['args']);

 // myREPL.stdout.pipe(process.stdout, { end: false });

 process.stdin.resume();

 process.stdin.pipe(myREPL.stdin, { end: false });

 myREPL.stdin.on('end', function() {
   process.stdout.write('REPL stream ended.');
 });

 myREPL.on('exit', function (code) {
   process.exit(code);
 });

 myREPL.stdout.on('data', function(data) {
    console.log('\n\nSTDOUT: \n');
    console.log('**************************');
    console.log('' + data);
    console.log('==========================');
 });
</code>```

I created a bundle.js using browserify and my html looks like this.

```<code><!doctype html>
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <title></title>
            <!--[if IE]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
            <![endif]-->
            <script src="bundle.js"></script>
            <script src="main.js"></script>
        </head>
        <body>

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

I am trying to avoid running an http server and piping the results to it in the browser. Is there any other way where I can do it ?
Thanks

答:
I think the frontail NPM module can also do what you want to do -

https://github.com/mthenw/frontail

I have used it and it works

Body:
I am attempting to pipe the stdout & stdin of a child_process to a browser & display it in an html page. I am using browserify to get node.js to run on the browser. My code for spawning the child_process is like this.

var child = require('child_process');

var myREPL = child.spawn('myshell.exe', ['args']);

 // myREPL.stdout.pipe(process.stdout, { end: false });

 process.stdin.resume();

 process.stdin.pipe(myREPL.stdin, { end: false });

 myREPL.stdin.on('end', function() {
   process.stdout.write('REPL stream ended.');
 });

 myREPL.on('exit', function (code) {
   process.exit(code);
 });

 myREPL.stdout.on('data', function(data) {
    console.log('\n\nSTDOUT: \n');
    console.log('**************************');
    console.log('' + data);
    console.log('==========================');
 });

I created a bundle.js using browserify and my html looks like this.

<!doctype html>

            <meta charset="utf-8" />
            <title></title>

I am trying to avoid running an http server and piping the results to it in the browser. Is there any other way where I can do it ?
Thanks


问:
403 Forbidden - Deploying Spring Boot application in Weblogic
I have an application that I'm currently trying to convert to Spring Boot but I'm having issues getting Weblogic configured to run the application. I get 403 Forbidden response on HTTP request.

Any help would be greatly appreciated!

This is my @SpringBootApplication class.

```<code>@SpringBootApplication
public class AgisSpringApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

    public static void main(String[] args) {
        SpringApplication.run(AgisSpringApplication.class, args);
    }

    @Override
    public void onStartup(ServletContext context) throws ServletException {

    }
}
</code>```

This is my weblogic.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
    <wls:weblogic-web-app
        xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd
        http://xmlns.oracle.com/weblogic/weblogic-web-app
        http://xmlns.oracle.com/weblogic/weblogic-web-app/1.7/weblogic-web-app.xsd">
    <wls:weblogic-version>12.1.3</wls:weblogic-version>
    <wls:context-root>agis-spring</wls:context-root>
    <wls:container-descriptor>
        <wls:prefer-application-packages>
            <wls:package-name>org.slf4j.*</wls:package-name>
        </wls:prefer-application-packages>
    </wls:container-descriptor>
</wls:weblogic-web-app>
</code>```

And this is my only controller at the moment

```<code>@RestController
public class MapController {

    private TemplateService templateService;

    public MapController(TemplateService templateService) {
        this.templateService = templateService;
    }

    @GetMapping("/")
    public String getName() throws Exception {
        return templateService.getTemplate("map.vm");
    }
}
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.group</groupId>
    <artifactId>agis-spring</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>agis-spring</name>
    <description></description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-velocity</artifactId>
            <version>1.4.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

答:
1) your Application.java doesn't look correct.
Try this one:

```<code>@SpringBootApplication
public class Application
        extends SpringBootServletInitializer
        implements WebApplicationInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

2) Make sure your weblogic.xml is placed under src/main/webapp/WEB-INF/.

3) Make sure you package the app into war.

```<code><packaging>war</packaging>
</code>```

4) Make sure embedded tomcat is disabled.

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
</code>```

5) I'm not sure if wls:package-name can be specified as wildcart. According to spring-boot documentation it should be like this:

```<code><wls:package-name>org.slf4j</wls:package-name>
</code>```

6) Build the war artifact by performing mvn clean package.

The .war artifact will be placed to your-app/build/lib. Use this file for deploying into the server.

Hope that some of this hints will solve the problem.

Body:
I have an application that I'm currently trying to convert to Spring Boot but I'm having issues getting Weblogic configured to run the application. I get 403 Forbidden response on HTTP request.

Any help would be greatly appreciated!

This is my @SpringBootApplication class.

@SpringBootApplication
public class AgisSpringApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

    public static void main(String[] args) {
        SpringApplication.run(AgisSpringApplication.class, args);
    }

    @Override
    public void onStartup(ServletContext context) throws ServletException {

    }
}

This is my weblogic.xml

<?xml version="1.0" encoding="UTF-8"?>
    <wls:weblogic-web-app
        xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd
        http://xmlns.oracle.com/weblogic/weblogic-web-app
        http://xmlns.oracle.com/weblogic/weblogic-web-app/1.7/weblogic-web-app.xsd">
    <wls:weblogic-version>12.1.3</wls:weblogic-version>
    <wls:context-root>agis-spring</wls:context-root>
    <wls:container-descriptor>
        <wls:prefer-application-packages>
            <wls:package-name>org.slf4j.*</wls:package-name>
        </wls:prefer-application-packages>
    </wls:container-descriptor>
</wls:weblogic-web-app>

And this is my only controller at the moment

@RestController
public class MapController {

    private TemplateService templateService;

    public MapController(TemplateService templateService) {
        this.templateService = templateService;
    }

    @GetMapping("/")
    public String getName() throws Exception {
        return templateService.getTemplate("map.vm");
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.group</groupId>
    <artifactId>agis-spring</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>agis-spring</name>
    <description></description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-velocity</artifactId>
            <version>1.4.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Body:
1) your Application.java doesn't look correct.
Try this one:

@SpringBootApplication
public class Application
        extends SpringBootServletInitializer
        implements WebApplicationInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

2) Make sure your weblogic.xml is placed under src/main/webapp/WEB-INF/.

3) Make sure you package the app into war.

<packaging>war</packaging>

4) Make sure embedded tomcat is disabled.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

5) I'm not sure if wls:package-name can be specified as wildcart. According to spring-boot documentation it should be like this:

<wls:package-name>org.slf4j</wls:package-name>

6) Build the war artifact by performing mvn clean package.

The .war artifact will be placed to your-app/build/lib. Use this file for deploying into the server.

Hope that some of this hints will solve the problem.


问:
Scrapy - Duplicates first 2 pages and finishes
I will preface this by saying I have very little experience with coding in general. I'm currently using Scrapy with Python 3.5 to pull SKU# and Pricing values for Home Depot's website. Using the scrappy tutorial documentation I managed to put together something that will pull the correct data and move on to the next page.

The problem is that after Scrapy yields the second page of items it goes back to the first again and then repeats before closing. Essentially it's just going Url 1-> Url 2 -> Url 1 -> Url -> 2 and then finishing without error. The code I'm using is below:

```<code># -*- coding: utf-8 -*-
import scrapy

class ScraperSpider(scrapy.Spider):
    name = "scraper"
    allowed_domains = ["www.homedepot.com"]
    start_urls = ["http://www.homedepot.com/s/whirlpool?NCNI-5"]

    def parse(self, response):
        for sku in response.css('div.plp-pod'):
            yield {
            'model' : sku.css('div.pod-plp__model::text').extract_first(),
            'price' : sku.css('div.price__wrapper > div:nth-child(1) > span::text').extract_first()
            }

        next = response.css('li.hd-pagination__item.hd-pagination__button > a::attr(href)').extract_first()
        print(next)
        if next is not None:
            next = response.urljoin(next)
            yield scrapy.Request(next, callback=self.parse)
</code>```

As far as I can tell by inspecting the webpages, the second URL shares the same CSS as the first and should request a subsequent link. Any help would be appreciated!

答:
The reason this is happening is because the previous button looks like this:

```<code><li class="hd-pagination__item hd-pagination__button">
    <a class="hd-pagination__link" title="Previous" href="/b/N-5yc1v/Ntk-BrandSearch/Ntt-whirlpool?NCNI-5" data-pagenumber="1">
    </a>
</li>
</code>```

So once you get to the second page you're selecting the previous button. The next button, on the other hand looks like this:

```<code><li class="hd-pagination__item hd-pagination__button">
    <a class="hd-pagination__link" title="Next" href="/b/N-5yc1v/Ntk-BrandSearch/Ntt-whirlpool?NCNI-5&Nao=48&Ns=None" data-pagenumber="3">
    </a>
</li>
</code>```

So you need to select it not only based on the class but also on the title.

Body:
I will preface this by saying I have very little experience with coding in general. I'm currently using Scrapy with Python 3.5 to pull SKU# and Pricing values for Home Depot's website. Using the scrappy tutorial documentation I managed to put together something that will pull the correct data and move on to the next page.

The problem is that after Scrapy yields the second page of items it goes back to the first again and then repeats before closing. Essentially it's just going Url 1-> Url 2 -> Url 1 -> Url -> 2 and then finishing without error. The code I'm using is below:

# -*- coding: utf-8 -*-
import scrapy

class ScraperSpider(scrapy.Spider):
    name = "scraper"
    allowed_domains = ["www.homedepot.com"]
    start_urls = ["http://www.homedepot.com/s/whirlpool?NCNI-5"]

    def parse(self, response):
        for sku in response.css('div.plp-pod'):
            yield {
            'model' : sku.css('div.pod-plp__model::text').extract_first(),
            'price' : sku.css('div.price__wrapper > div:nth-child(1) > span::text').extract_first()
            }

        next = response.css('li.hd-pagination__item.hd-pagination__button > a::attr(href)').extract_first()
        print(next)
        if next is not None:
            next = response.urljoin(next)
            yield scrapy.Request(next, callback=self.parse)

As far as I can tell by inspecting the webpages, the second URL shares the same CSS as the first and should request a subsequent link. Any help would be appreciated!

Body:
The reason this is happening is because the previous button looks like this:

<li class="hd-pagination__item hd-pagination__button">
    <a class="hd-pagination__link" title="Previous" href="/b/N-5yc1v/Ntk-BrandSearch/Ntt-whirlpool?NCNI-5" data-pagenumber="1">
    </a>
</li>

So once you get to the second page you're selecting the previous button. The next button, on the other hand looks like this:

<li class="hd-pagination__item hd-pagination__button">
    <a class="hd-pagination__link" title="Next" href="/b/N-5yc1v/Ntk-BrandSearch/Ntt-whirlpool?NCNI-5&amp;Nao=48&amp;Ns=None" data-pagenumber="3">
    </a>
</li>

So you need to select it not only based on the class but also on the title.


问:
The Decorator Design Pattern: What is meant by adding functionality?
I have just gone into studying the Decorator Design Pattern using C#.

I have made an example which kinda functions as I think it is intended except for one thing.

I kinda understood that the whole point of the pattern is to add functionality to an object dynamically.

So when I create an object like this:

```<code>Inventory a = new Ashbringer(new TravelersBagpack());
a.Execute();
</code>```

Then I kinda expected that the point was that the a object would now be able to call the Execute() method which only exists in the Ashbringer class. Thus adding functionality to the a object.

Though this I can't do without adding the Execute() method to the Inventory interface which would ultimately mean I would have to implement the Execute() method to all the classes implementing Inventory Interface or the abstract Decorator.

Perhaps there is a thing or two I don't know about interfaces or perhaps I misunderstand the point of the Decorator Design Pattern?

答:
It's not supposed to add anything new to the interface,  it's trying to decorate existing functionality.

So you'd extend what the Execute of TravelersBagpack does in someway.

Body:
I have just gone into studying the Decorator Design Pattern using C#.

I have made an example which kinda functions as I think it is intended except for one thing.

I kinda understood that the whole point of the pattern is to add functionality to an object dynamically.

So when I create an object like this:

Inventory a = new Ashbringer(new TravelersBagpack());
a.Execute();

Then I kinda expected that the point was that the a object would now be able to call the Execute() method which only exists in the Ashbringer class. Thus adding functionality to the a object.

Though this I can't do without adding the Execute() method to the Inventory interface which would ultimately mean I would have to implement the Execute() method to all the classes implementing Inventory Interface or the abstract Decorator.

Perhaps there is a thing or two I don't know about interfaces or perhaps I misunderstand the point of the Decorator Design Pattern?


问:
How to position images on the same line as an h1 element in HTML/CSS?
I am completely stuck trying to get a left chevron and a right chevron to display on either side of a date in an h1 tag. I want a user to be able to click on either chevron to move forward or backward one day. However, no matter what combination of div or img classes and position, float, display it still looks like the screenshot attached, even though I've made sure the document is updating.

How can I modify the HTML/CSS so the chevrons are placed on the same line as the date?

```<code><div class= "dater">
  <div class="chevron-left">
     <img src="glyphicons-225-chevron-left.png"/>
  </div>
  <h2><%= @todie %></h2>
  <div class="chevron-right">
     <img src="glyphicons-224-chevron-right.png"/>
  </div>
</div>
</code>```

EDIT: My solution based on Rob's answer.

```<code>.chevron-right img {
  float: right;

}

.chevron-left img {
 float: left;

}

.dater {
  margin-left: auto;
  margin-right: auto;
  width: 100%;
  margin-top: 60px;
  margin-bottom: 40px;
}

.dater h2 {
  text-align: center;
  font-weight: 400;
  float: left;
}
</code>```

答:
The reason for your problem is you have the images contained within block level elements which occupy the full width of the browser viewport. Even then it won't work exactly as you wish but there are many ways to accomplish it.

First, you can put the images inside the
 to the left and right of the text. That's the easiest way.

Second, you can use the CSS pseudo classes ::before and ::after

You can also set the width of the
 and float the everything, images included but the  must be set to inline to help this along.

There are more ways than just those.

Body:
I am completely stuck trying to get a left chevron and a right chevron to display on either side of a date in an h1 tag. I want a user to be able to click on either chevron to move forward or backward one day. However, no matter what combination of div or img classes and position, float, display it still looks like the screenshot attached, even though I've made sure the document is updating.

How can I modify the HTML/CSS so the chevrons are placed on the same line as the date?

<%= @todie %>

EDIT: My solution based on Rob's answer.

.chevron-right img {
  float: right;

}

.chevron-left img {
 float: left;

}

.dater {
  margin-left: auto;
  margin-right: auto;
  width: 100%;
  margin-top: 60px;
  margin-bottom: 40px;
}

.dater h2 {
  text-align: center;
  font-weight: 400;
  float: left;
}

Body:
The reason for your problem is you have the images contained within block level elements which occupy the full width of the browser viewport. Even then it won't work exactly as you wish but there are many ways to accomplish it.

First, you can put the images inside the <h2> to the left and right of the text. That's the easiest way.

Second, you can use the CSS pseudo classes ::before and ::after

You can also set the width of the <h2> and float the everything, images included but the  must be set to inline to help this along.

There are more ways than just those.


问:
Python pandas series: convert float to string, preserving nulls
How can I preserve nulls after converting to string? I'm working with social security numbers, where it's necessary to go back and forth between float and string.

```<code>import pandas as pd
import numpy as np
x = pd.Series([np.nan, 123., np.nan, 456.], dtype = float)
x.isnull()
</code>```

...Has nulls

```<code>y = x.astype(str)
y.isnull()
</code>```

...No nulls

So ideally x.isnull() and y.isnull() would be the same.

I think it's dangerous to use a Series of mixed dtypes, but thinking this is the best solution for the time being:

```<code>z = y.copy()
z[z == 'nan'] = np.nan
z.isnull() # works as desired
type(z[0]) # but has floats for nulls
type(z[1]) # and strings for values
</code>```

答:
You can cast to to string, conditional on not being null.</p>

```<code>x[x.notnull()] = x.astype(str)

x
Out[32]
0      NaN
1    123.0
2      NaN
3    456.0
dtype: object

x.values
Out[33]: array([nan, '123.0', nan, '456.0'], dtype=object)

x.isnull()
Out[34]
0     True
1    False
2     True
3    False
dtype: bool
</code>```

Body:
How can I preserve nulls after converting to string? I'm working with social security numbers, where it's necessary to go back and forth between float and string.

import pandas as pd
import numpy as np
x = pd.Series([np.nan, 123., np.nan, 456.], dtype = float)
x.isnull()

...Has nulls

y = x.astype(str)
y.isnull()

...No nulls

So ideally x.isnull() and y.isnull() would be the same.

I think it's dangerous to use a Series of mixed dtypes, but thinking this is the best solution for the time being:

z = y.copy()
z[z == 'nan'] = np.nan
z.isnull() # works as desired
type(z[0]) # but has floats for nulls
type(z[1]) # and strings for values

Body:
You can cast to to string, conditional on not being null.

x[x.notnull()] = x.astype(str)

x
Out[32]
0      NaN
1    123.0
2      NaN
3    456.0
dtype: object

x.values
Out[33]: array([nan, '123.0', nan, '456.0'], dtype=object)

x.isnull()
Out[34]
0     True
1    False
2     True
3    False
dtype: bool


问:
php searching empty fields in the db
I'm constructing a good code to check the database and some more things, but i stopped in the line... it says:

```<code>notice: Undefined variable: getUserNew in D:\xampp\htdocs\SilverCommunity(1.6.2)\asp\class\giveaway\winner.php on line 134
</code>```

My Started code:

```<code>         if(isset($_POST['giftID'])) {

            //select user from db.
            $getUserNew = getUser_ID_($db, $id_us);

            if(!empty($getUserNew)) {

                //if empty, add new ticket.
                newGiveaway($db, $id_us);
                $hide = rand_line("../../codes.txt");
                echo $hide;

            }
            else
            {
                    //check dates and return
                    echo "Next step";
            }
 }
</code>```

Function Code to search the user.

```<code>            function getUser_ID_($db, $id_us)
        {
            $id_us = $_SESSION['steamid'];
            global $host; $username; $password; $dbname;

            $sqlu = "SELECT id_steam FROM public_giveaway WHERE id='$id_us'";
            $query = mysqli_query($db, $sqlu);

            while($Qrow = mysqli_fetch_array($query))
            {

                $getUserNew = $Qrow['id_steam'];

            }

            return $getUserNew;

        }
</code>```

maybe i'm blind... but i can't find the error.. maybe is an "', or ;"... Really... i don't know...

答:
I think your problems comes form getUser_ID_, your mysql_fetch_array return 0 result then you don't go into your while then your $getUserNew is not initialized.

To avoid this problem you need to initialize your variable $getUserNew before the while statement.

like this:

```<code>function getUser_ID_($db, $id_us)
    {
        $id_us = $_SESSION['steamid'];
        global $host; $username; $password; $dbname;

        $sqlu = "SELECT id_steam FROM public_giveaway WHERE id='$id_us'";
        $query = mysqli_query($db, $sqlu);

        $getUserNew = false;
        while($Qrow = mysqli_fetch_array($query))
        {

            $getUserNew = $Qrow['id_steam'];

        }

        return $getUserNew;

    }
</code>```

Title: php searching empty fields in the db

Body:
I'm constructing a good code to check the database and some more things, but i stopped in the line... it says:

notice: Undefined variable: getUserNew in D:\xampp\htdocs\SilverCommunity(1.6.2)\asp\class\giveaway\winner.php on line 134

My Started code:

         if(isset($_POST['giftID'])) {

            //select user from db.
            $getUserNew = getUser_ID_($db, $id_us);

            if(!empty($getUserNew)) {

                //if empty, add new ticket.
                newGiveaway($db, $id_us);
                $hide = rand_line("../../codes.txt");
                echo $hide;

            }
            else
            {
                    //check dates and return
                    echo "Next step";
            }
 }

Function Code to search the user.

            function getUser_ID_($db, $id_us)
        {
            $id_us = $_SESSION['steamid'];
            global $host; $username; $password; $dbname;

            $sqlu = "SELECT id_steam FROM public_giveaway WHERE id='$id_us'";
            $query = mysqli_query($db, $sqlu);

            while($Qrow = mysqli_fetch_array($query))
            {

                $getUserNew = $Qrow['id_steam'];

            }

            return $getUserNew;

        }

maybe i'm blind... but i can't find the error.. maybe is an "', or ;"... Really... i don't know...

Body:
I think your problems comes form getUser_ID_, your mysql_fetch_array return 0 result then you don't go into your while then your $getUserNew is not initialized.

To avoid this problem you need to initialize your variable $getUserNew before the while statement.

like this:

function getUser_ID_($db, $id_us)
    {
        $id_us = $_SESSION['steamid'];
        global $host; $username; $password; $dbname;

        $sqlu = "SELECT id_steam FROM public_giveaway WHERE id='$id_us'";
        $query = mysqli_query($db, $sqlu);

        $getUserNew = false;
        while($Qrow = mysqli_fetch_array($query))
        {

            $getUserNew = $Qrow['id_steam'];

        }

        return $getUserNew;

    }


问:
Question on creating a Gallery view containing buttons?
I created a Gallery that contains buttons.

Example code is below:

```<code>public class Adapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return 10;
    }

    public Object getItem(int position) {
        return position;
    }

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

    public View getView(int position, View convertView, ViewGroup parent) {
        Button but = new Button(mContext);
        return but;
    }
}
</code>```

The gallery view is displayed well. The problem is that this gallery is not scrollable any more. If I replace Button with ImageView in the getView method, the gallery view scroll well. Then, how can I make the gallery containing buttons to scroll?

Thanks.

答: Gallery eats touch events. You cannot put any interactive controls within it</p>

Body:
I created a Gallery that contains buttons.

Example code is below:

public class Adapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return 10;
    }

    public Object getItem(int position) {
        return position;
    }

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

    public View getView(int position, View convertView, ViewGroup parent) {
        Button but = new Button(mContext);
        return but;
    }
}

The gallery view is displayed well. The problem is that this gallery is not scrollable any more. If I replace Button with ImageView in the getView method, the gallery view scroll well. Then, how can I make the gallery containing buttons to scroll?

Thanks.


答:
The csv module has a handy writerows() method on the DictWriter class:

```<code>import csv
import json

data = json.loads(""" My Json """)

with open('lat_long.csv', 'w') as csvfile:
    fieldnames = ['Lat', 'Long']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(data)
</code>```

Title: Multi column csv from json in python

Body:
how to convert json to csv in python. want it open in excel with the lat and long columns.

[
  {
    "Lat": "-122.37391463199998",
    "Long": "47.630880207000075"
  },
  {
    "Lat": "-122.38447021399998",
    "Long": "47.70118823100006"
  },
  {
    "Lat": "-122.34729431799997",
    "Long": "47.64717111900006"
  }
]

Body:
The csv module has a handy writerows() method on the DictWriter class:

import csv
import json

data = json.loads(""" My Json """)

with open('lat_long.csv', 'w') as csvfile:
    fieldnames = ['Lat', 'Long']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(data)


问:
My video doesn't show up with youtubebackground api
I have a issue, a issue that still remains after 1 week, couldn't discover why my video doesn't show up using the youtubebackground api,
Basicly i am using bootstrap and i defined a container for my video
like this:

```<code><section class="content_section">
    <div class="embed-responsive embed-responsive-16by9" id="video">

    </div>
</section>
</code>```

then i used the youtubeBackgroundapi here is the order of the scripts:

```<code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/jquery.youtubebackground.js"></script>
<script src="js/plugins.js"></script>
<script src="js/jquery.themepunch.tools.min.js" type="text/javascript"></script>
<script src="js/jquery.themepunch.revolution.min.js" type="text/javascript"></script>
<script src="js/isotope.pkgd.min.js"></script>
<!-- this is where we put our custom functions -->
<script type="text/javascript" src="js/functions.js"></script>
<script src="js/app.js"></script>
</code>```

my app.js is where i put the javascript code related to the behaviour of the video

like this:

```<code>$(document).ready(function() {
  $('#video').YTPlayer({
    fitToBackground: true,
    videoId: 'mcFYvy0L2vI',
    playerVars: {
      modestbranding: 0,
      autoplay: 1,
      controls: 1,
      showinfo: 0,
      branding: 0,
      rel: 0,
      autohide: 0,
      start: 10
    }
  });
})
</code>```

and finnally i changed my css like the docs said to do:

```<code>#video {
  position: relative;
  background: transparent;
}

.ytplayer-container {
  position: absolute;
  top: 0;
  z-index: -1;
}
</code>```

i have no idea why it doesn't show up, i just can see the white content of the div, nothing in there, do i need to run my app in a server to put that on work?

答:
Are you including the right libraries and in the right order? Note that you should include jquery before including the jquery youtube background script (see my HTML).  I was able to get it working in JSfiddle and in a Stack Overflow code snippet (see below)

EDIT Another discrepancy is that you are including Jquery 1.11.3 where the Jquery Youtube Background docs include 1.10.2. Perhaps this is making the difference?

$(document).ready(function() {
  $('#video').YTPlayer({
    fitToBackground: true,
    videoId: 'mcFYvy0L2vI',
    playerVars: {
      modestbranding: 0,
      autoplay: 1,
      controls: 1,
      showinfo: 0,
      branding: 0,
      rel: 0,
      autohide: 0,
      start: 10
    }
  });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#video {
  position: relative;
  background: transparent;
}

.ytplayer-container {
  position: absolute;
  top: 0;
  z-index: -1;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>

```

Body:
I have a issue, a issue that still remains after 1 week, couldn't discover why my video doesn't show up using the youtubebackground api,
Basicly i am using bootstrap and i defined a container for my video
like this:

then i used the youtubeBackgroundapi here is the order of the scripts:

my app.js is where i put the javascript code related to the behaviour of the video

like this:

$(document).ready(function() {
  $('#video').YTPlayer({
    fitToBackground: true,
    videoId: 'mcFYvy0L2vI',
    playerVars: {
      modestbranding: 0,
      autoplay: 1,
      controls: 1,
      showinfo: 0,
      branding: 0,
      rel: 0,
      autohide: 0,
      start: 10
    }
  });
})

and finnally i changed my css like the docs said to do:

#video {
  position: relative;
  background: transparent;
}

.ytplayer-container {
  position: absolute;
  top: 0;
  z-index: -1;
}

i have no idea why it doesn't show up, i just can see the white content of the div, nothing in there, do i need to run my app in a server to put that on work?

Body:
Are you including the right libraries and in the right order? Note that you should include jquery before including the jquery youtube background script (see my HTML).  I was able to get it working in JSfiddle and in a Stack Overflow code snippet (see below)

EDIT Another discrepancy is that you are including Jquery 1.11.3 where the Jquery Youtube Background docs include 1.10.2. Perhaps this is making the difference?

$(document).ready(function() {
  $('#video').YTPlayer({
    fitToBackground: true,
    videoId: 'mcFYvy0L2vI',
    playerVars: {
      modestbranding: 0,
      autoplay: 1,
      controls: 1,
      showinfo: 0,
      branding: 0,
      rel: 0,
      autohide: 0,
      start: 10
    }
  });
})

#video {
  position: relative;
  background: transparent;
}

.ytplayer-container {
  position: absolute;
  top: 0;
  z-index: -1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/rochestb/jQuery.YoutubeBackground/dbdfa723/src/jquery.youtubebackground.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<section class="content_section">
    <div class="embed-responsive embed-responsive-16by9" id="video">

    </div>
</section>


问:
Set margins between items on BrowseFragment
Developing an application for Android TV, I faced a problem for the usage of BrowseFragment provided by Leanback support library.
Can we change the margin between items of RowsFragment?</p>

答:
Ideally override the style details as @Billy answered. It can unfortunately take a while to figure out whats what. If what you are looking for is not styleable you can apparently override the built-in leanback resources (not sure if reliable/safe though). eg:</p>

```<code><dimen name="lb_browse_rows_margin_top">167dp</dimen>
<dimen name="lb_browse_item_vertical_spacing">8dp</dimen>
<dimen name="lb_browse_expanded_row_no_hovercard_bottom_padding">28dp</dimen>
</code>```

Body:
Ideally override the style details as @Billy answered. It can unfortunately take a while to figure out whats what. If what you are looking for is not styleable you can apparently override the built-in leanback resources (not sure if reliable/safe though). eg:

<dimen name="lb_browse_rows_margin_top">167dp</dimen>
<dimen name="lb_browse_item_vertical_spacing">8dp</dimen>
<dimen name="lb_browse_expanded_row_no_hovercard_bottom_padding">28dp</dimen>


问:
Autofac DI error in WebApi2 with OWIN
I have problem with DI in WebApi. I have add autofac accordingly with the instruction. But something is wrong with resolving controller.

I get an error:

```<code>{
"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'ValuesController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Type 'WebApiOwinAutoFac.Controllers.ValuesController' does not have a default constructor",
"ExceptionType": "System.ArgumentException",
"StackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
   }
}
</code>```

Startup.cs

```<code>public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        // STANDARD WEB API SETUP:

        // Get your HttpConfiguration. In OWIN, you'll create one
        // rather than using GlobalConfiguration.
        var config = new HttpConfiguration();

        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();
        builder.RegisterType<TestRepository>().As<ITestRepository>();

        // Run other optional steps, like registering filters,
        // per-controller-type services, etc., then set the dependency resolver
        // to be Autofac.
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        // OWIN WEB API SETUP:

        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        ConfigureAuth(app);
    }
}
</code>```

ValuesController.cs

```<code>[RoutePrefix("api/Values")]
public class ValuesController : ApiController
{
    private ITestRepository _context { get; set; }

    public ValuesController(ITestRepository context)
    {
        _context = context;
    }

    // GET api/values/5
    [HttpGet]
    public string GetTest()
    {
        var testList = _context.GetAll();
        return String.Join(",", testList.Select(s => s.Name));
    }
}
</code>```

ITestRepository.cs

```<code>public interface ITestRepository
{
    IEnumerable<TestModel> GetAll();
}
</code>```

TestRepository.cs

```<code>public class TestRepository : ITestRepository
{
    private ApplicationDbContext _context = new ApplicationDbContext();

    public IEnumerable<TestModel> GetAll()
    {
        return _context.Tests;
    }
}
</code>```

My sample project where I try to make it works, is available on GitHub:
Thank you for any help.

答:
The problem is that your sample project isn't using OWIN. It's still using classic non-OWIN ASP.NET Web API. If you look at your Global.asax.cs you'll see that you're still using GlobalConfiguration. You can't use GlobalConfiguration when using OWIN.

You will notice in the Autofac docs on Web API and OWIN integration the following:

A common error in OWIN integration is use of the GlobalConfiguration.Configuration. In OWIN you create the configuration from scratch. You should not reference GlobalConfiguration.Configuration anywhere when using the OWIN integration.

Remove the usage of GlobalConfiguration from your Global.asax and switch entirely to OWIN. You can't mix and match or you will run into trouble like this.

Title: Autofac DI error in WebApi2 with OWIN

Body:
I have problem with DI in WebApi. I have add autofac accordingly with the instruction. But something is wrong with resolving controller.

I get an error:

{
"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'ValuesController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Type 'WebApiOwinAutoFac.Controllers.ValuesController' does not have a default constructor",
"ExceptionType": "System.ArgumentException",
"StackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
   }
}

Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        // STANDARD WEB API SETUP:

        // Get your HttpConfiguration. In OWIN, you'll create one
        // rather than using GlobalConfiguration.
        var config = new HttpConfiguration();

        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();
        builder.RegisterType<TestRepository>().As<ITestRepository>();

        // Run other optional steps, like registering filters,
        // per-controller-type services, etc., then set the dependency resolver
        // to be Autofac.
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        // OWIN WEB API SETUP:

        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        ConfigureAuth(app);
    }
}

ValuesController.cs

[RoutePrefix("api/Values")]
public class ValuesController : ApiController
{
    private ITestRepository _context { get; set; }

    public ValuesController(ITestRepository context)
    {
        _context = context;
    }

    // GET api/values/5
    [HttpGet]
    public string GetTest()
    {
        var testList = _context.GetAll();
        return String.Join(",", testList.Select(s => s.Name));
    }
}

ITestRepository.cs

public interface ITestRepository
{
    IEnumerable<TestModel> GetAll();
}

TestRepository.cs

public class TestRepository : ITestRepository
{
    private ApplicationDbContext _context = new ApplicationDbContext();

    public IEnumerable<TestModel> GetAll()
    {
        return _context.Tests;
    }
}

My sample project where I try to make it works, is available on GitHub:
Thank you for any help.


问:
Silverlight (w/ SQL database) desktop application example?
Are there any freeware/shareware examples of Silverlight desktop applications with a local SQL backend?
I am planning to write a freeware/shareware personal finance application and I'm thinking if whether to do it on Silverlight or WPF.</p>

答:
For data storage you can use SQL CE4 or even a file based db like SQLite.
As rawpower said, I would recommand WPF, too.</p>