问:
How to create a 2D array using single array angular js
How can we create 2D array from single array

```<code>angular.forEach(angular.fromJson(value.resource_type_efforts), function (value1, key1) {
          $scope.data.resource_type.push(key1);
});
</code>```

when I do console.log($scope.data.resource_type) output is :-

```<code>0 :  "Senior Software Engineer"
1 :  "Software Engineer"
2 :  "QA Engineer"
3 :  "UI Developer"
4 :  "UI Designer"
5 :  "UI Developer"
6 :  "QA Engineer"
7 :  "Software Engineer"
</code>```

Now i need to split this array in 2-d array after every 4 values.

```<code>0:
  0 :  "Senior Software Engineer"
  1 :  "Software Engineer"
  2 :  "QA Engineer"
  3 :  "UI Developer"
1:
  0 :  "UI Designer"
  1 :  "UI Developer"
  2 :  "QA Engineer"
  3 :  "Software Engineer"
</code>```

Please suggest some answers

答:
You can achieve this with a little helper function using Array.slice like in this little demo fiddle. You could parse a number as splitCount. This number could be changed by yourself for your needs. It also collects the rest of your array e.g. you have 9 items in your initial array.

> fiddle demo

```<code>var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.myArray = [
      "Senior Software Engineer",
      "Software Engineer",
      "QA Engineer",
      "UI Developer",
      "UI Designer",
      "UI Developer",
      "QA Engineer",
      "Software Engineer",
      "Software Engineer",
    ];

    $scope.normalizedArray = normalize($scope.myArray, 4);

    function normalize (myArray, splitCount) {
      var result = [];
      for (var i = 0; i < (myArray.length / splitCount); i++) {
        result[i] = myArray.slice(i*splitCount, (i*splitCount) + splitCount);
      }
      return result;
    }
});
</code>```

In that way this should do it for you:

```<code>$scope.myData = normalize(angular.fromJson(value.resource_type_efforts), 4);
</code>```

Body:
How can we create 2D array from single array

angular.forEach(angular.fromJson(value.resource_type_efforts), function (value1, key1) {
          $scope.data.resource_type.push(key1);
});

when I do console.log($scope.data.resource_type) output is :-

0 :  "Senior Software Engineer"
1 :  "Software Engineer"
2 :  "QA Engineer"
3 :  "UI Developer"
4 :  "UI Designer"
5 :  "UI Developer"
6 :  "QA Engineer"
7 :  "Software Engineer"

Now i need to split this array in 2-d array after every 4 values.

0:
  0 :  "Senior Software Engineer"
  1 :  "Software Engineer"
  2 :  "QA Engineer"
  3 :  "UI Developer"
1:
  0 :  "UI Designer"
  1 :  "UI Developer"
  2 :  "QA Engineer"
  3 :  "Software Engineer"

Please suggest some answers

Body:
You can achieve this with a little helper function using Array.slice like in this little demo fiddle. You could parse a number as splitCount. This number could be changed by yourself for your needs. It also collects the rest of your array e.g. you have 9 items in your initial array.

> fiddle demo

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.myArray = [
      "Senior Software Engineer",
      "Software Engineer",
      "QA Engineer",
      "UI Developer",
      "UI Designer",
      "UI Developer",
      "QA Engineer",
      "Software Engineer",
      "Software Engineer",
    ];

    $scope.normalizedArray = normalize($scope.myArray, 4);

    function normalize (myArray, splitCount) {
      var result = [];
      for (var i = 0; i < (myArray.length / splitCount); i++) {
        result[i] = myArray.slice(i*splitCount, (i*splitCount) + splitCount);
      }
      return result;
    }
});

In that way this should do it for you:

$scope.myData = normalize(angular.fromJson(value.resource_type_efforts), 4);


来源: stackexchange

问:
Parsing a Quickbook IIF format file
I'm working with Quickbook's IIF file format and I need to write a parser to read and write IIF files and I'm running into some issues reading the files.

The files are simple, they're tab deliminated. Every line is either a table definition or a row. Definitions begin with'!' and the table name, and rows begin with just the table name. Here's the problem I'm running into: some of the fields allow line breaks.

When I first encountered this, I thought, okay just parse it tab by tab instead of line by line, but to do that I had to replace the line breaks with tabs, and wound up with more values than there were columns, but I wound up with the values with line breaks spread out across too many columns.

How would you parse such a file?

Edit: An example

```<code>!CUST   NAME    REFNUM  TIMESTAMP   BADDR1  BADDR2  BADDR3  BADDR4  BADDR5  SADDR1  SADDR2  SADDR3  SADDR4  SADDR5  PHONE1  PHONE2  FAXNUM  CONT1   CONT2   CTYPE   TERMS   TAXABLE LIMIT   RESALENUM   REP TAXITEM NOTEPAD SALUTATION  COMPANYNAME FIRSTNAME   MIDINIT LASTNAME    CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    CUSTFLD6    CUSTFLD7    CUSTFLD8    CUSTFLD9    CUSTFLD10   CUSTFLD11   CUSTFLD12   CUSTFLD13   CUSTFLD14   CUSTFLD15   JOBDESC JOBTYPE JOBSTATUS   JOBSTART    JOBPROJEND  JOBEND  HIDDEN  DELCOUNT
CUST    St. Mark    359 1176670332  Saint Mark Catholic Church  609 W Main St   City, State Zip
!CLASS  NAME    REFNUM  TIMESTAMP   HIDDEN  DELCOUNT
!INVITEM    NAME    REFNUM  TIMESTAMP   INVITEMTYPE DESC    PURCHASEDESC    ACCNT   ASSETACCNT  COGSACCNT   QNTY    QNTY    PRICE   COST    TAXABLE PAYMETH TAXVEND TAXDIST PREFVEND    REORDERPOINT    EXTRA   CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    DEP_TYPE    ISPASSEDTHRU    HIDDEN  DELCOUNT    USEID
INVITEM Labor   1   1119915308  SERV    Labor                                                                                0
!TIMEACT    DATE    JOB EMP ITEM    PITEM   DURATION    PROJ    NOTE    XFERTOPAYROLL   BILLINGSTATUS
TIMEACT 3/8/08  876 Development Jane Doe {Consultant}   Labor       00:15       Renewing all domain name for 876 Development.
REIMBURSEMENT: 44.72 for one year renewal on all domain names.  N   1
TIMEACT 3/17/08 Greg:Bridge Jane Doe {Consultant}   Labor       01:00       Preparing Studio    N   1
TIMEACT 3/17/08 John Doe and Associates Jane Doe {Consultant}   Labor       00:06       REIMBURSEMENT: Toner cartridge on ebay & Fuser from FastPrinters- ask wendell before invoicing to see if this fixed the problem
49.99 (include tax) toner
$175.18 (include tax) fuser
    N   1
TIMEACT 3/17/08 John Doe II Jane Doe {Consultant}   Labor       01:00       Fixing Kandis's computer - replaced entire computer with similar system N   1
</code>```

答:
It has been a while since I have done IIF but unless they have fixed it QuickBooks will barf on those line breaks anyway. It seems these folks have the same issue and they handled it with spaces. </p>

<p>Personally I would lean toward pipes or something that will clearly delineate the line break when it comes into QuickBooks. If you absolutely positively must have the line breaks, join the Intuit Developer Network and use the SDK to send these values to QB once your program imports them. </p>

OwnerDisplayName: Malfist

ContentLicense: CC BY-SA 3.0

Title: Parsing a Quickbook IIF format file

Body:
I'm working with Quickbook's IIF file format and I need to write a parser to read and write IIF files and I'm running into some issues reading the files.

The files are simple, they're tab deliminated. Every line is either a table definition or a row. Definitions begin with'!' and the table name, and rows begin with just the table name. Here's the problem I'm running into: some of the fields allow line breaks.

When I first encountered this, I thought, okay just parse it tab by tab instead of line by line, but to do that I had to replace the line breaks with tabs, and wound up with more values than there were columns, but I wound up with the values with line breaks spread out across too many columns.

How would you parse such a file?

Edit: An example

!CUST   NAME    REFNUM  TIMESTAMP   BADDR1  BADDR2  BADDR3  BADDR4  BADDR5  SADDR1  SADDR2  SADDR3  SADDR4  SADDR5  PHONE1  PHONE2  FAXNUM  CONT1   CONT2   CTYPE   TERMS   TAXABLE LIMIT   RESALENUM   REP TAXITEM NOTEPAD SALUTATION  COMPANYNAME FIRSTNAME   MIDINIT LASTNAME    CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    CUSTFLD6    CUSTFLD7    CUSTFLD8    CUSTFLD9    CUSTFLD10   CUSTFLD11   CUSTFLD12   CUSTFLD13   CUSTFLD14   CUSTFLD15   JOBDESC JOBTYPE JOBSTATUS   JOBSTART    JOBPROJEND  JOBEND  HIDDEN  DELCOUNT
CUST    St. Mark    359 1176670332  Saint Mark Catholic Church  609 W Main St   City, State Zip
!CLASS  NAME    REFNUM  TIMESTAMP   HIDDEN  DELCOUNT
!INVITEM    NAME    REFNUM  TIMESTAMP   INVITEMTYPE DESC    PURCHASEDESC    ACCNT   ASSETACCNT  COGSACCNT   QNTY    QNTY    PRICE   COST    TAXABLE PAYMETH TAXVEND TAXDIST PREFVEND    REORDERPOINT    EXTRA   CUSTFLD1    CUSTFLD2    CUSTFLD3    CUSTFLD4    CUSTFLD5    DEP_TYPE    ISPASSEDTHRU    HIDDEN  DELCOUNT    USEID
INVITEM Labor   1   1119915308  SERV    Labor                                                                                0
!TIMEACT    DATE    JOB EMP ITEM    PITEM   DURATION    PROJ    NOTE    XFERTOPAYROLL   BILLINGSTATUS
TIMEACT 3/8/08  876 Development Jane Doe {Consultant}   Labor       00:15       Renewing all domain name for 876 Development.
REIMBURSEMENT: 44.72 for one year renewal on all domain names.  N   1
TIMEACT 3/17/08 Greg:Bridge Jane Doe {Consultant}   Labor       01:00       Preparing Studio    N   1
TIMEACT 3/17/08 John Doe and Associates Jane Doe {Consultant}   Labor       00:06       REIMBURSEMENT: Toner cartridge on ebay & Fuser from FastPrinters- ask wendell before invoicing to see if this fixed the problem
49.99 (include tax) toner
$175.18 (include tax) fuser
    N   1
TIMEACT 3/17/08 John Doe II Jane Doe {Consultant}   Labor       01:00       Fixing Kandis's computer - replaced entire computer with similar system N   1

LastEditorDisplayName: Malfist

Body:
It has been a while since I have done IIF but unless they have fixed it QuickBooks will barf on those line breaks anyway. It seems these folks have the same issue and they handled it with spaces.

Personally I would lean toward pipes or something that will clearly delineate the line break when it comes into QuickBooks. If you absolutely positively must have the line breaks, join the Intuit Developer Network and use the SDK to send these values to QB once your program imports them.

OwnerDisplayName: nshaw

ContentLicense: CC BY-SA 2.5


问:
ASP.NET: List of Page_Events via Intellisense? How do i know the signature?
is there a way to find and insert a page event via intellisense so i can get a list of what is available and the signature is automatically created?

Currently I create a page_init but with no parameters ... unsure if this is correct or no?

With controls you can take a look at Properties and then Events and you get a list of all events..

Any help really appreciated

thanks

答:
I usually override the methods in the base Page class which end up triggering the events, rather than subscribing to the events themselves. Intellisense helps there because as soon as you type override for a new method, VS presents a list of the methods which can be overridden.

The methods in question will be named On[Event], for example; OnLoad() OnInit() OnPreInit(). Just be sure if you use this method that you always maintain the call to the base method as well, which VS will automatically insert for you if you let Intellisense build the method for you.


问:
ASP.net core web API CORS issue with Angular2
I am trying a simple HTTP GET from my angular2 frontend as following:

```<code>  getGoals(): Observable<CoreGoalModel[]> {

    let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers });

    return this.http.get(this.base_url + 'coregoal', options)
    .map(this.extractData)
    .catch(this.handleError);
  }
</code>```

I have set up CORS in my ASP.Net core backend. I have "Microsoft.AspNetCore.Cors": "1.1.1" in projects.json.

My startup.cs:

```<code>public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddScoped<ICoreGoalRepository, CoreGoalRepository>();

    // Enable Cors
    services.AddCors();

    services.AddMvc();

    services.AddSwaggerGen();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, WebAPIDataContext context)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseMvc();

    app.UseCors(builder =>
        builder.AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod());

    app.UseSwagger();
    app.UseSwaggerUi();
}
</code>```

However I still get Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. error.

What am I missing? For now I want to allow all origins, all methods, no restrictions.

答: The sequence of addCors() and addMVC() was incorrect. addCors() has to come before addMVC()</p>

Body:
I am trying a simple HTTP GET from my angular2 frontend as following:

  getGoals(): Observable<CoreGoalModel[]> {

    let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers });

    return this.http.get(this.base_url + 'coregoal', options)
    .map(this.extractData)
    .catch(this.handleError);
  }

I have set up CORS in my ASP.Net core backend. I have "Microsoft.AspNetCore.Cors": "1.1.1" in projects.json.

My startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddScoped<ICoreGoalRepository, CoreGoalRepository>();

    // Enable Cors
    services.AddCors();

    services.AddMvc();

    services.AddSwaggerGen();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, WebAPIDataContext context)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseMvc();

    app.UseCors(builder =>
        builder.AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod());

    app.UseSwagger();
    app.UseSwaggerUi();
}

However I still get Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. error.

What am I missing? For now I want to allow all origins, all methods, no restrictions.


问:
JPA with Spring MVC doesn't insert into database using persist
I am using spring 4 and hibernate 4 to create some web services and when I try to retrieve data from the database. It work fine but the problem is when I try to insert data.
When I lunch the project as a java application every thing work fine. The problem is only when I lunch it on the server and I am using tomcat.

This is my entity:

```<code>package com.pfe.ecole.entity;

import java.io.Serializable;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

import com.fasterxml.jackson.annotation.JsonIgnore;

@SuppressWarnings("serial")
@Entity
public class Specialite implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String specialite;
    @ManyToMany(mappedBy="specialites")
    @JsonIgnore
    private List<Professeur> professeurs;

    public List<Professeur> getProfesseurs() {
        return professeurs;
    }

    public void setProfesseurs(List<Professeur> professeurs) {
        this.professeurs = professeurs;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getSpecialite() {
        return specialite;
    }

    public void setSpecialite(String specialite) {
        this.specialite = specialite;
    }

    public Specialite() {
        // TODO Auto-generated constructor stub
    }

    public Specialite(int id, String specialite) {
        super();
        this.id = id;
        this.specialite = specialite;
    }

    public Specialite(String specialite) {
        super();
        this.specialite = specialite;
    }

}

package com.pfe.ecole.entity;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@SuppressWarnings("serial")
@Entity
public class Professeur implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;
    @Column(unique=true, nullable=false)
    private String cin;
    @Column(unique=true, nullable=false)
    private int tel;
    @ManyToMany(targetEntity=Specialite.class, cascade = CascadeType.PERSIST)
    private Set<Specialite> specialites;
    private String nom;
    private String prenom;
    @Column(unique=true, nullable=false)
    private String email;
    private String adresse;

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAdresse() {
        return adresse;
    }

    public void setAdresse(String adresse) {
        this.adresse = adresse;
    }

    public Set<Specialite> getSpecialites() {
        return specialites;
    }

    public void setSpecialite(Set<Specialite> specialites) {
        this.specialites = specialites;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getCin() {
        return cin;
    }

    public void setCin(String cin) {
        this.cin = cin;
    }

    public int getTel() {
        return tel;
    }

    public void setTel(int tel) {
        this.tel = tel;
    }

    public Professeur() {
        // TODO Auto-generated constructor stub
    }

    public Professeur(String cin, int tel, Set<Specialite> specialites, String nom, String prenom, String email,
            String adresse) {
        super();
        this.cin = cin;
        this.tel = tel;
        this.specialites = specialites;
        this.nom = nom;
        this.prenom = prenom;
        this.email = email;
        this.adresse = adresse;
    }

    public Professeur(long id, String cin, int tel, Set<Specialite> specialites, String nom, String prenom,
            String email, String adresse) {
        super();
        this.id = id;
        this.cin = cin;
        this.tel = tel;
        this.specialites = specialites;
        this.nom = nom;
        this.prenom = prenom;
        this.email = email;
        this.adresse = adresse;
    }

}
</code>```

and this is my services

```<code>package com.pfe.ecole.services;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pfe.ecole.entity.Agent;
import com.pfe.ecole.entity.Specialite;
@Service("specialiteImpl")
@Transactional
public class SpecialiteImpl implements ISpecialite{
    @PersistenceContext
    private EntityManager em;

    @Override
    public Specialite add(Specialite specialite) {
        em.persist(new Agent());
        return specialite;
    }

    @Override
    public Specialite update(Specialite specialite) {
        em.persist(specialite);
        return specialite;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Specialite> listAllSpecialite() {
        return em.createQuery("select s from Specialite s").getResultList();
    }

}

package com.pfe.ecole.services;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pfe.ecole.entity.Professeur;
import com.pfe.ecole.entity.Specialite;

@Service("professeurImpl")
@Transactional
public class ProfesseurImpl implements IProfesseur{
    @PersistenceContext
    private EntityManager em;

    @SuppressWarnings("unchecked")
    @Override
    public List<Professeur> listAll(int page, int items) {
        List<Professeur> profList;
        profList=em.createQuery("select p from Professeur p order by p.prenom").setFirstResult(page-1).setMaxResults(items).getResultList();

        return profList;
    }

    @Override
    public Professeur findByCin(int cin) {
        Query req=em.createQuery("select  p from Professeur p where p.cin=:cin").setParameter("cin", cin);
        try{
            return (Professeur) req.getSingleResult();
        }
        catch(NoResultException nrEx) {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Professeur> findByNom(String nom) {
        Query req = em.createQuery("select p from  Professeur p where p.nom=:nom ").setParameter("nom", nom);
        return req.getResultList();
    }

    @Override
    public List<Professeur> listProfBySpec(Specialite spec) {
        List<Professeur> profs = new ArrayList<Professeur>();
        profs.addAll(spec.getProfesseurs());

        return profs;
    }

    @Override
    public Professeur add(Professeur professeur) {
        em.persist(professeur);
        return professeur;
    }

    @Override
    public Professeur update(Professeur professeur) {
        em.persist(professeur);
        return professeur;
    }

    @Override
    public int count() {
        // TODO Auto-generated method stub
        return (int) em.createQuery("select COUNT(p) from Professeur p").getFirstResult();
    }

}
</code>```

and this is the controller

```<code>package com.pfe.ecole.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.pfe.ecole.entity.Specialite;
import com.pfe.ecole.services.ISpecialite;

@Controller
@RestController
@EnableWebMvc
@CrossOrigin
public class SpecialiteCtrl {
    @Autowired
    ISpecialite metier;

    @RequestMapping(value="/specialites",method=RequestMethod.GET)
    @ResponseBody Map<String, List<Specialite>> get(){metier.add(new Specialite("ddd"));
        Map<String, List<Specialite>> result = new HashMap<String,List<Specialite>>();
        result.put("content", metier.listAllSpecialite());
        return result;
    }

}

package com.pfe.ecole.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.pfe.ecole.entity.Professeur;
import com.pfe.ecole.services.IProfesseur;
import com.pfe.ecole.services.Page;

@Controller
@RestController
@EnableWebMvc
@CrossOrigin
public class ProfCtrl {
    @Autowired
    IProfesseur metier;

    @RequestMapping(value="/teacher",method=RequestMethod.POST)
    @ResponseBody Professeur add(@RequestBody Professeur professeur) {
        return metier.add(professeur);
    }

    @RequestMapping(value="/teachers/{page}/{items}",method=RequestMethod.GET)
    @ResponseBody Page getByParm(@PathVariable("page") int page, @PathVariable("items") int items){
        return getAll(page, items);
    }

    @RequestMapping(value="/teachers/{page}",method=RequestMethod.GET)
    @ResponseBody Page getByParm(@PathVariable("page") int page){
        return getAll(page, 10);
    }

    @RequestMapping(value="/teachers",method=RequestMethod.GET)
    @ResponseBody Page getByParm(){
        return getAll(1, 10);
    }

    private Page getAll(int page, int items){
        return new Page(page,metier.count(),metier.listAll(page, items));
    }
}
</code>```

this is the test that works as java application

```<code>public static void main(String[] args) {
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("root-context.xml");
        ISpecialite m = (ISpecialite) context.getBean("specialiteImpl");
        Specialite s= new Specialite("Web Dev");
        m.add(s);
    }
</code>```

This is the error I am getting

```<code>javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
</code>```

答: adding this annotation to service solved the problem @EnableTransactionManagement

Body:
I am using spring 4 and hibernate 4 to create some web services and when I try to retrieve data from the database. It work fine but the problem is when I try to insert data.
When I lunch the project as a java application every thing work fine. The problem is only when I lunch it on the server and I am using tomcat.

This is my entity:

package com.pfe.ecole.entity;

import java.io.Serializable;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

import com.fasterxml.jackson.annotation.JsonIgnore;

@SuppressWarnings("serial")
@Entity
public class Specialite implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String specialite;
    @ManyToMany(mappedBy="specialites")
    @JsonIgnore
    private List<Professeur> professeurs;

    public List<Professeur> getProfesseurs() {
        return professeurs;
    }

    public void setProfesseurs(List<Professeur> professeurs) {
        this.professeurs = professeurs;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getSpecialite() {
        return specialite;
    }

    public void setSpecialite(String specialite) {
        this.specialite = specialite;
    }

    public Specialite() {
        // TODO Auto-generated constructor stub
    }

    public Specialite(int id, String specialite) {
        super();
        this.id = id;
        this.specialite = specialite;
    }

    public Specialite(String specialite) {
        super();
        this.specialite = specialite;
    }

}

package com.pfe.ecole.entity;

import java.io.Serializable;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@SuppressWarnings("serial")
@Entity
public class Professeur implements Serializable {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;
    @Column(unique=true, nullable=false)
    private String cin;
    @Column(unique=true, nullable=false)
    private int tel;
    @ManyToMany(targetEntity=Specialite.class, cascade = CascadeType.PERSIST)
    private Set<Specialite> specialites;
    private String nom;
    private String prenom;
    @Column(unique=true, nullable=false)
    private String email;
    private String adresse;

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAdresse() {
        return adresse;
    }

    public void setAdresse(String adresse) {
        this.adresse = adresse;
    }

    public Set<Specialite> getSpecialites() {
        return specialites;
    }

    public void setSpecialite(Set<Specialite> specialites) {
        this.specialites = specialites;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getCin() {
        return cin;
    }

    public void setCin(String cin) {
        this.cin = cin;
    }

    public int getTel() {
        return tel;
    }

    public void setTel(int tel) {
        this.tel = tel;
    }

    public Professeur() {
        // TODO Auto-generated constructor stub
    }

    public Professeur(String cin, int tel, Set<Specialite> specialites, String nom, String prenom, String email,
            String adresse) {
        super();
        this.cin = cin;
        this.tel = tel;
        this.specialites = specialites;
        this.nom = nom;
        this.prenom = prenom;
        this.email = email;
        this.adresse = adresse;
    }

    public Professeur(long id, String cin, int tel, Set<Specialite> specialites, String nom, String prenom,
            String email, String adresse) {
        super();
        this.id = id;
        this.cin = cin;
        this.tel = tel;
        this.specialites = specialites;
        this.nom = nom;
        this.prenom = prenom;
        this.email = email;
        this.adresse = adresse;
    }

}

and this is my services

package com.pfe.ecole.services;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pfe.ecole.entity.Agent;
import com.pfe.ecole.entity.Specialite;
@Service("specialiteImpl")
@Transactional
public class SpecialiteImpl implements ISpecialite{
    @PersistenceContext
    private EntityManager em;

    @Override
    public Specialite add(Specialite specialite) {
        em.persist(new Agent());
        return specialite;
    }

    @Override
    public Specialite update(Specialite specialite) {
        em.persist(specialite);
        return specialite;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Specialite> listAllSpecialite() {
        return em.createQuery("select s from Specialite s").getResultList();
    }

}

package com.pfe.ecole.services;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pfe.ecole.entity.Professeur;
import com.pfe.ecole.entity.Specialite;

@Service("professeurImpl")
@Transactional
public class ProfesseurImpl implements IProfesseur{
    @PersistenceContext
    private EntityManager em;

    @SuppressWarnings("unchecked")
    @Override
    public List<Professeur> listAll(int page, int items) {
        List<Professeur> profList;
        profList=em.createQuery("select p from Professeur p order by p.prenom").setFirstResult(page-1).setMaxResults(items).getResultList();

        return profList;
    }

    @Override
    public Professeur findByCin(int cin) {
        Query req=em.createQuery("select  p from Professeur p where p.cin=:cin").setParameter("cin", cin);
        try{
            return (Professeur) req.getSingleResult();
        }
        catch(NoResultException nrEx) {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Professeur> findByNom(String nom) {
        Query req = em.createQuery("select p from  Professeur p where p.nom=:nom ").setParameter("nom", nom);
        return req.getResultList();
    }

    @Override
    public List<Professeur> listProfBySpec(Specialite spec) {
        List<Professeur> profs = new ArrayList<Professeur>();
        profs.addAll(spec.getProfesseurs());

        return profs;
    }

    @Override
    public Professeur add(Professeur professeur) {
        em.persist(professeur);
        return professeur;
    }

    @Override
    public Professeur update(Professeur professeur) {
        em.persist(professeur);
        return professeur;
    }

    @Override
    public int count() {
        // TODO Auto-generated method stub
        return (int) em.createQuery("select COUNT(p) from Professeur p").getFirstResult();
    }

}

and this is the controller

package com.pfe.ecole.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.pfe.ecole.entity.Specialite;
import com.pfe.ecole.services.ISpecialite;

@Controller
@RestController
@EnableWebMvc
@CrossOrigin
public class SpecialiteCtrl {
    @Autowired
    ISpecialite metier;

    @RequestMapping(value="/specialites",method=RequestMethod.GET)
    @ResponseBody Map<String, List<Specialite>> get(){metier.add(new Specialite("ddd"));
        Map<String, List<Specialite>> result = new HashMap<String,List<Specialite>>();
        result.put("content", metier.listAllSpecialite());
        return result;
    }

}

package com.pfe.ecole.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.pfe.ecole.entity.Professeur;
import com.pfe.ecole.services.IProfesseur;
import com.pfe.ecole.services.Page;

@Controller
@RestController
@EnableWebMvc
@CrossOrigin
public class ProfCtrl {
    @Autowired
    IProfesseur metier;

    @RequestMapping(value="/teacher",method=RequestMethod.POST)
    @ResponseBody Professeur add(@RequestBody Professeur professeur) {
        return metier.add(professeur);
    }

    @RequestMapping(value="/teachers/{page}/{items}",method=RequestMethod.GET)
    @ResponseBody Page getByParm(@PathVariable("page") int page, @PathVariable("items") int items){
        return getAll(page, items);
    }

    @RequestMapping(value="/teachers/{page}",method=RequestMethod.GET)
    @ResponseBody Page getByParm(@PathVariable("page") int page){
        return getAll(page, 10);
    }

    @RequestMapping(value="/teachers",method=RequestMethod.GET)
    @ResponseBody Page getByParm(){
        return getAll(1, 10);
    }

    private Page getAll(int page, int items){
        return new Page(page,metier.count(),metier.listAll(page, items));
    }
}

this is the test that works as java application

public static void main(String[] args) {
        ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("root-context.xml");
        ISpecialite m = (ISpecialite) context.getBean("specialiteImpl");
        Specialite s= new Specialite("Web Dev");
        m.add(s);
    }

This is the error I am getting

javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call


问:
5 boxes not centering correctly in the center of the page
I am totally new into programming. I've aligned 5 boxed horizontally , but what I want is to center the boxes. The boxes should also be responsive what they are right now. I am searching and searching for how to center a div, but as result I get
 margin: 0 auto; width: 800px;. When I adjust my browser to 100%, the 5th box get under the other boxes.

.square {
 float:left;
 width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="outside">
  <div class="square">
   <span>2.1</span>
  </div>
  <div class="square">
   <span>2.3</span>
  </div>
  <div class="square">
   <span>2.5</span>
  </div>
  <div class="square">
   <span>2.6</span>
  </div>
  <div class="square">
   <span>2.7</span>
  </div>
 </div></code>```

答:
Add a max-width or width to the parent container. Then center it with margin: 0 auto. Of course set the width of the parent element to you needs. I just set it to 520px as an example.

W3Schools says this:

Center Align Elements To horizontally center a block element (like ), use margin: auto;

Setting the width of the element will prevent it from stretching out
  to the edges of its container.

The element will then take up the specified width, and the remaining
  space will be split equally between the two margins:

See example below.

.outside {
  max-width: 520px;
  margin: 0 auto;
}

.square {
 float:left;
 width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outside">
  <div class="square">
   <span>2.1</span>
  </div>
  <div class="square">
   <span>2.3</span>
  </div>
  <div class="square">
   <span>2.5</span>
  </div>
  <div class="square">
   <span>2.6</span>
  </div>
  <div class="square">
   <span>2.7</span>
  </div>
 </div></code>```

Body:
I am totally new into programming. I've aligned 5 boxed horizontally , but what I want is to center the boxes. The boxes should also be responsive what they are right now. I am searching and searching for how to center a div, but as result I get
 margin: 0 auto; width: 800px;. When I adjust my browser to 100%, the 5th box get under the other boxes.

.square {
 float:left;
 width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}

   2.1

   2.3

   2.5

   2.6

   2.7

Body:
Add a max-width or width to the parent container. Then center it with margin: 0 auto. Of course set the width of the parent element to you needs. I just set it to 520px as an example.

W3Schools says this:

Center Align Elements To horizontally center a block element (like ), use margin: auto;

Setting the width of the element will prevent it from stretching out
  to the edges of its container.

The element will then take up the specified width, and the remaining
  space will be split equally between the two margins:

See example below.

.outside {
  max-width: 520px;
  margin: 0 auto;
}

.square {
 float:left;
 width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}

<div class="outside">
  <div class="square">
   <span>2.1</span>
  </div>
  <div class="square">
   <span>2.3</span>
  </div>
  <div class="square">
   <span>2.5</span>
  </div>
  <div class="square">
   <span>2.6</span>
  </div>
  <div class="square">
   <span>2.7</span>
  </div>
 </div>


问:
amcharts: legend's parts overlap
I have stock chart and first legend's item is OHLC which is displayed like this:

```<code>o:60.11, h:70.11, l:40.11, c:50.11
</code>```

other legend's items are short like this

```<code>55.11
</code>```

If I want to legend items not overlap, I need to set legend.valueWidth or legend.spacing as long as is needed for to the first item not overlap the second. Than other items has the same space which is not needed and sometime legend is on two rows.

What I want to achieve is that every legend item will have only space it needs or to set extraspace for first item.

答:
Use this property :
markerLabelGap
markerLabelGap  : Number Space between legend marker and legend text, in pixels.

Sample amchart:

 var chart = AmCharts.makeChart("chartdiv", {

            "type": "serial", "theme": "light",
            "legend": {
                "equalWidths": false,/*نمایش آیتم ها در یک سطر  */
                "pulled":true,
                "align": "left",

                "position": "bottom",

                "markerType": "circle",

                "labelText": "[[title]]",
                "rollOverGraphAlpha":80,
                "markerLabelGap": 80,//تعیین فاصله بین مارکر و لیبل ها در لجند

                "textClickEnabled": true
            },
             ...```

See More Properties: https://docs.amcharts.com/javascriptstockchart/LegendSettings

Title: amcharts: legend's parts overlap

Body:
I have stock chart and first legend's item is OHLC which is displayed like this:

o:60.11, h:70.11, l:40.11, c:50.11

other legend's items are short like this

55.11

If I want to legend items not overlap, I need to set legend.valueWidth or legend.spacing as long as is needed for to the first item not overlap the second. Than other items has the same space which is not needed and sometime legend is on two rows.

What I want to achieve is that every legend item will have only space it needs or to set extraspace for first item.

Body:
Use this property :
markerLabelGap
markerLabelGap  : Number Space between legend marker and legend text, in pixels.

Sample amchart:

 var chart = AmCharts.makeChart("chartdiv", {

            "type": "serial", "theme": "light",
            "legend": {
                "equalWidths": false,/*نمایش آیتم ها در یک سطر  */
                "pulled":true,
                "align": "left",

                "position": "bottom",

                "markerType": "circle",

                "labelText": "[[title]]",
                "rollOverGraphAlpha":80,
                "markerLabelGap": 80,//تعیین فاصله بین مارکر و لیبل ها در لجند

                "textClickEnabled": true
            },
             ...

See More Properties: https://docs.amcharts.com/javascriptstockchart/LegendSettings


问:
angular $watch is not work with d3.js
look, click the button, $scope.optionis change, but $watch is not work, can`t console.log the option value , why?

I am sorry , it is my mistake , but it still is a problem in I use width d3.js

I use d3.js append a rect into page, and I want to when I click the rect can chagne the option value, but $watch is not work, why?

```<code>angular.module('myapp',[]).controller('myCtrl', function($scope){
$scope.option = '123';
$scope.d3TreeDraw = {
    source : {
        name: 'myTree'
    },
    updata: function(){
        var _self = this;

        var tree = d3.layout.tree().nodeSize([90, 60]);

        var nodes = tree.nodes(_self.source).reverse();
        nodes.forEach(function(d) { d.y = d.depth * 90; });

        var svg = d3.select("body").append("svg")
        .attr("width", 200)
        .attr("height", 200)

        var node = svg.selectAll("g.node")
        .data(nodes)

        var nodeEnter = node.enter().append("g")
        .attr("class", "node")
        .style('cursor','pointer')
        .on('click', function(d){
            console.log('click'); // can console.log
            $scope.option = '456';
            console.log($scope.option) //is change
              })

        nodeEnter.append("rect")
        .attr('width',150)
        .attr('height', 30)
        .style('fill', '#000')
    }
}
$scope.d3TreeDraw.updata();

$scope.$watch('option', function(){
    console.log('change:' + $scope.option); // when option is change,can not console.log
})
})
</code>```

答:
1) First You have taken myTree.onClick() and your function has onclick

So, the onClick() spelling mismatched.

Change button to <button ng-click="myTree.onclick()">456</button>

<!DOCTYPE html>

<button ng-click="myTree.onclick()">{{data}}</button>

```
</div>
</div>
</p>

<p>Here is a working <strong>DEMO</strong>.</p>

<p><strong>EDIT:</strong></p>

<p><strong>By checking your edit, I saw that your <code>scope</code> assignment is outside of <code>angular</code>.</strong></p>

<p>So, you need to <code>$apply()</code> the <code>$scope</code></p>

<p>Change,</p>

<p><strong><code>$scope.option = '456';</code></strong></p>

<p>to,</p>

```$scope.$apply(function() {
    $scope.option = '456'
 });
```

The above method, runs the digest cycle manually, and apply the changes for the scope.

Performance:

If you write $scope.$apply() it will run complete digest cycle, which will affect the performance, so we sent a function into the $apply method and only ran the digest cycle of specific `scope.

Hence, you can $watch the scope whenever you want.

Title: angular $watch is not work with d3.js

Body:
look, click the button, $scope.optionis change, but $watch is not work, can`t console.log the option value , why?

I am sorry , it is my mistake , but it still is a problem in I use width d3.js

I use d3.js append a rect into page, and I want to when I click the rect can chagne the option value, but $watch is not work, why?

angular.module('myapp',[]).controller('myCtrl', function($scope){
$scope.option = '123';
$scope.d3TreeDraw = {
    source : {
        name: 'myTree'
    },
    updata: function(){
        var _self = this;

        var tree = d3.layout.tree().nodeSize([90, 60]);

        var nodes = tree.nodes(_self.source).reverse();
        nodes.forEach(function(d) { d.y = d.depth * 90; });

        var svg = d3.select("body").append("svg")
        .attr("width", 200)
        .attr("height", 200)

        var node = svg.selectAll("g.node")
        .data(nodes)

        var nodeEnter = node.enter().append("g")
        .attr("class", "node")
        .style('cursor','pointer')
        .on('click', function(d){
            console.log('click'); // can console.log
            $scope.option = '456';
            console.log($scope.option) //is change
              })

        nodeEnter.append("rect")
        .attr('width',150)
        .attr('height', 30)
        .style('fill', '#000')
    }
}
$scope.d3TreeDraw.updata();

$scope.$watch('option', function(){
    console.log('change:' + $scope.option); // when option is change,can not console.log
})
})

Body:
1) First You have taken myTree.onClick() and your function has onclick

So, the onClick() spelling mismatched.

Change button to <button ng-click="myTree.onclick()">456</button>

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="myTree.onclick()">{{data}}</button>
<br>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    $scope.data = '100';
 $scope.myTree = {
        onclick: function() {
            $scope.data = '456';
        }
    }
    $scope.$watch('data', function(){
        console.log($scope.data);
        alert($scope.data);
    })

});
</script>

</body>
</html>

Here is a working DEMO.

EDIT:

By checking your edit, I saw that your scope assignment is outside of angular.

So, you need to $apply() the $scope

Change,

$scope.option = '456';

to,

$scope.$apply(function() {
    $scope.option = '456'
 });

The above method, runs the digest cycle manually, and apply the changes for the scope.

Performance:

If you write $scope.$apply() it will run complete digest cycle, which will affect the performance, so we sent a function into the $apply method and only ran the digest cycle of specific `scope.

Hence, you can $watch the scope whenever you want.


问:
Amazon EC2 and jbossws
I've deployed a webservice to a Jboss instance running on Amazon EC2. The webservice works fine locally, but when I deploy on EC2, and go to the /jbossws/services page the Endpoint Address for the webservice is the private DNS of the ec2 instance (domU-X-X-X-X etc...), not the public dns (which I would like it to be).

I've tried loading the wsdl by changing the private hostname to the public IP; that works, but when I try to call any of the operations I get a HostNotFoundException, I'm guessing due to the fact that the generated wsdl has the stanza:

<service name='XXXService'>
     <port binding='tns:XXXBinding' name='XXXPort'>
        <soap:address location='http://domU-XX-XX-XX-XX-XX-XX.compute-1.internal:8080/xx/xx/xx'/>
     </port>
 </service>

where http://domU-XX-XX-XX-XX-XX-XX.compute-1.internal is the internal dns of the ec2 instance.

The wsdl is auto generated - Is there a JAXB annotation I can use so that I can force the generated wsdl to use the public dns of the EC2 instance?

Many thanks -

答:
In JBoss 5.1.0 GA look at
jbossws.deployer/META-INF/jboss-beans.xml
and comment the following line
${jboss.bind.address}

it is 100% worked

or see the following
http://community.jboss.org/wiki/JBossWS-UserGuide

Title: Amazon EC2 and jbossws


问:
Gremlinepipeline Edges between two Vertex
To check the edge between the vertex using Gremline pipeline in java code?
I am able to create the edges but if we give the same vertex again the new edge will be created. I want to create a unique edge between the 2 vertex.
Any help?
I am using orientDB</p>

答:
You can create a unique index on the Edge class that will give you that constraint</p>

```<code>create class Foo extends V
create class FooEdge extends E
create property FooEdge.in LINK
create property FooEdge.out LINK

create index FooEdge_in_out on FooEdge (out,in) unique
insert into Foo set name = 'Foo1'
insert into Foo set name = 'Foo2'
create edge FooEdge from (select from Foo where name = 'Foo1') to (select from Foo where name = 'Foo2')
/* fail */
create edge FooEdge from (select from Foo where name = 'Foo1') to (select from Foo where name = 'Foo2')
</code>```

Body:
You can create a unique index on the Edge class that will give you that constraint

create class Foo extends V
create class FooEdge extends E
create property FooEdge.in LINK
create property FooEdge.out LINK

create index FooEdge_in_out on FooEdge (out,in) unique
insert into Foo set name = 'Foo1'
insert into Foo set name = 'Foo2'
create edge FooEdge from (select from Foo where name = 'Foo1') to (select from Foo where name = 'Foo2')
/* fail */
create edge FooEdge from (select from Foo where name = 'Foo1') to (select from Foo where name = 'Foo2')


问:
Start Failed: Internal Error when starting Android Studio on ubuntu
I am starting Android Studio for the first time after unzipping the file that I downloaded from the Android website by calling  ./studio.sh in the android-studio/bin directory. I'm getting the following error:

```<code>    Start Failed: Internal Error. Please report to https://code.google.com/p/android/issues

java.lang.ClassNotFoundException: com.intellij.ide.plugins.PluginManager
    at com.intellij.util.lang.UrlClassLoader.findClass(UrlClassLoader.java:218)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.intellij.ide.Bootstrap.main(Bootstrap.java:36)
    at com.intellij.idea.Main.main(Main.java:119)
</code>```

I'm running java version 1.8.0_121

答:
The errors were caused by antivirus software (in this case Avast). After uninstalling it I was able to normally install and start Android Studio. this solved the problem.

the answer is took from here..

Android Studio Start Failed - ClassNotFoundException: com.intellij.ide.plugins.PluginManager

Body:
I am starting Android Studio for the first time after unzipping the file that I downloaded from the Android website by calling  ./studio.sh in the android-studio/bin directory. I'm getting the following error:

    Start Failed: Internal Error. Please report to https://code.google.com/p/android/issues

java.lang.ClassNotFoundException: com.intellij.ide.plugins.PluginManager
    at com.intellij.util.lang.UrlClassLoader.findClass(UrlClassLoader.java:218)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.intellij.ide.Bootstrap.main(Bootstrap.java:36)
    at com.intellij.idea.Main.main(Main.java:119)

I'm running java version 1.8.0_121


问:
How to change value in Request.Url in c#?
I am working in asp.net.i want to assign a value in Request.Url ,i know that is readonly but is there another way to change the url.(i don't want to redirect.)

Actually i have passed query string parameter from one page and redirected to second page. now inside second page (Page_Load) i have received that parameter value and i want my url don't show that parameter inside query string.

```<code>txtcontactsearch.Text = Request.QueryString["email"];
string myNewUrl = Request.Url.AbsolutePath;
</code>```

I want my browser shows myNewUrl  url.

答:
A proper way to do that is to use the HTTP post method ,
but if you only want to hide the query string value in url, you can use java script to change the url without reloading the page. As example below.

```<code>`
<script>
   $(document).ready(function() {
   window.history.replaceState("", "", "New URl");
   }
</script>
</code>```

`

you may send your new url from your controller action by using Viewbag.

Body:
I am working in asp.net.i want to assign a value in Request.Url ,i know that is readonly but is there another way to change the url.(i don't want to redirect.)

Actually i have passed query string parameter from one page and redirected to second page. now inside second page (Page_Load) i have received that parameter value and i want my url don't show that parameter inside query string.

txtcontactsearch.Text = Request.QueryString["email"];
string myNewUrl = Request.Url.AbsolutePath;

I want my browser shows myNewUrl  url.

Body:
A proper way to do that is to use the HTTP post method ,
but if you only want to hide the query string value in url, you can use java script to change the url without reloading the page. As example below.

`
<script>
   $(document).ready(function() {
   window.history.replaceState("", "", "New URl");
   }
</script>

`

you may send your new url from your controller action by using Viewbag.


问:
Kafka unable to receive binary data
I'm trying to send an audio clip in binary format to a Kafka topic.

But the message is not being received at Kafka.

Following is my producer:

```<code>import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.log4j.BasicConfigurator;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class AudioProducer {

public static void main(String[] args) {
    BasicConfigurator.configure();
    System.out.println("program started");
    Properties properties = new Properties();
    properties.put("bootstrap.servers", "broker-host:9092");
    properties.put("acks", "all");
    properties.put("retries", 0);
    properties.put("batch.size", 26214400);
    properties.put("linger.ms", 1);
    properties.put("buffer.memory", 2*26214400);
    properties.put("max.request.size", 26214400);
    properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    properties.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
    KafkaProducer<String,byte[]> producer = new KafkaProducer<String, byte[]>(properties);
    try {
        byte[] temp =Files.readAllBytes(Paths.get(args[0]));
        System.out.println("input path:"+args[0]);
        producer.send(new ProducerRecord<String,byte[]>("audio-queue", "test-key",temp ));
    } catch (IOException e) {
        e.printStackTrace();
    }
    producer.close();
    System.out.println("program completed");
}

}
</code>```

Following is the output with Kafka debug mode:

```<code>program started
0 [main] INFO org.apache.kafka.clients.producer.ProducerConfig  - ProducerConfig values:
    compression.type = none
    metric.reporters = []
    metadata.max.age.ms = 300000
    metadata.fetch.timeout.ms = 60000
    acks = all
    batch.size = 26214400
    reconnect.backoff.ms = 10
    bootstrap.servers = [broker-host:9092]
    receive.buffer.bytes = 32768
    retry.backoff.ms = 100
    buffer.memory = 52428800
    timeout.ms = 30000
    key.serializer = class org.apache.kafka.common.serialization.StringSerializer
    retries = 0
    max.request.size = 26214400
    block.on.buffer.full = true
    value.serializer = class org.apache.kafka.common.serialization.ByteArraySerializer
    metrics.sample.window.ms = 30000
    send.buffer.bytes = 131072
    max.in.flight.requests.per.connection = 5
    metrics.num.samples = 2
    linger.ms = 1
    client.id =

86 [main] DEBUG org.apache.kafka.clients.producer.internals.Metadata  - Updated cluster metadata version 1 to Cluster(nodes = [Node(broker-host, 9092)], partitions = [])
105 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.producer.internals.Sender  - Starting Kafka producer I/O thread.
106 [main] DEBUG org.apache.kafka.clients.producer.KafkaProducer  - Kafka producer started
input path:AUD_0030.wav
190 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Trying to send metadata request to node -1
190 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Init connection to node -1 for sending metadata request in the next iteration
190 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Initiating connection to node -1 at broker-host:9092.
251 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Trying to send metadata request to node -1
261 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Completed connection to node -1
351 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Trying to send metadata request to node -1
361 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Sending metadata request ClientRequest(expectResponse=true, payload=null, request=RequestSend(header={api_key=3,api_version=0,correlation_id=0,client_id=producer-1}, body={topics=[audio-queue]})) to node -1
977 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.producer.internals.Metadata  - Updated cluster metadata version 2 to Cluster(nodes = [Node(1, broker-host, 9092)], partitions = [Partition(topic = audio-queue, partition = 0, leader = 1, replicas = [1,], isr = [1,]])
1021 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.producer.internals.Sender  - Beginning shutdown of Kafka producer I/O thread, sending remaining records.
1021 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Initiating connection to node 1 at 01hw508208.india.tcs.com:9092.
1037 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Completed connection to node 1
11511 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.producer.internals.Sender  - Shutdown of Kafka producer I/O thread has completed.
11512 [main] DEBUG org.apache.kafka.clients.producer.KafkaProducer  - The Kafka producer has closed.
program completed
</code>```

But the same topic and the same program works fine with string message.

Also I checked the Kafka logs at broker node. I could find only string messages but not the binary message.

答:
As it solved the problem, I'll phrase my comment as an answer.

Kafka is not a file server and will perform best with message in the kilobyte range. Per default, the maximum message size is 1 MB which can be overwritten by setting the brokers max.message.bytes property to a higher value .

Doing that also has the consequence that the maximum fetch amount for consumers (in the new consumer API) should be increased via fetch.max.bytes

Big messages have performance drawbacks. When sending bigger files, it should be considered to store files on a storage system (e.g. S3) and only pass URIs to those files around in Kafka.

Title: Kafka unable to receive binary data

Body:
I'm trying to send an audio clip in binary format to a Kafka topic.

But the message is not being received at Kafka.

Following is my producer:

import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.log4j.BasicConfigurator;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class AudioProducer {

public static void main(String[] args) {
    BasicConfigurator.configure();
    System.out.println("program started");
    Properties properties = new Properties();
    properties.put("bootstrap.servers", "broker-host:9092");
    properties.put("acks", "all");
    properties.put("retries", 0);
    properties.put("batch.size", 26214400);
    properties.put("linger.ms", 1);
    properties.put("buffer.memory", 2*26214400);
    properties.put("max.request.size", 26214400);
    properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
    properties.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
    KafkaProducer<String,byte[]> producer = new KafkaProducer<String, byte[]>(properties);
    try {
        byte[] temp =Files.readAllBytes(Paths.get(args[0]));
        System.out.println("input path:"+args[0]);
        producer.send(new ProducerRecord<String,byte[]>("audio-queue", "test-key",temp ));
    } catch (IOException e) {
        e.printStackTrace();
    }
    producer.close();
    System.out.println("program completed");
}

}

Following is the output with Kafka debug mode:

program started
0 [main] INFO org.apache.kafka.clients.producer.ProducerConfig  - ProducerConfig values:
    compression.type = none
    metric.reporters = []
    metadata.max.age.ms = 300000
    metadata.fetch.timeout.ms = 60000
    acks = all
    batch.size = 26214400
    reconnect.backoff.ms = 10
    bootstrap.servers = [broker-host:9092]
    receive.buffer.bytes = 32768
    retry.backoff.ms = 100
    buffer.memory = 52428800
    timeout.ms = 30000
    key.serializer = class org.apache.kafka.common.serialization.StringSerializer
    retries = 0
    max.request.size = 26214400
    block.on.buffer.full = true
    value.serializer = class org.apache.kafka.common.serialization.ByteArraySerializer
    metrics.sample.window.ms = 30000
    send.buffer.bytes = 131072
    max.in.flight.requests.per.connection = 5
    metrics.num.samples = 2
    linger.ms = 1
    client.id =

86 [main] DEBUG org.apache.kafka.clients.producer.internals.Metadata  - Updated cluster metadata version 1 to Cluster(nodes = [Node(broker-host, 9092)], partitions = [])
105 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.producer.internals.Sender  - Starting Kafka producer I/O thread.
106 [main] DEBUG org.apache.kafka.clients.producer.KafkaProducer  - Kafka producer started
input path:AUD_0030.wav
190 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Trying to send metadata request to node -1
190 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Init connection to node -1 for sending metadata request in the next iteration
190 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Initiating connection to node -1 at broker-host:9092.
251 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Trying to send metadata request to node -1
261 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Completed connection to node -1
351 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Trying to send metadata request to node -1
361 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Sending metadata request ClientRequest(expectResponse=true, payload=null, request=RequestSend(header={api_key=3,api_version=0,correlation_id=0,client_id=producer-1}, body={topics=[audio-queue]})) to node -1
977 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.producer.internals.Metadata  - Updated cluster metadata version 2 to Cluster(nodes = [Node(1, broker-host, 9092)], partitions = [Partition(topic = audio-queue, partition = 0, leader = 1, replicas = [1,], isr = [1,]])
1021 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.producer.internals.Sender  - Beginning shutdown of Kafka producer I/O thread, sending remaining records.
1021 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Initiating connection to node 1 at 01hw508208.india.tcs.com:9092.
1037 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.NetworkClient  - Completed connection to node 1
11511 [kafka-producer-network-thread | producer-1] DEBUG org.apache.kafka.clients.producer.internals.Sender  - Shutdown of Kafka producer I/O thread has completed.
11512 [main] DEBUG org.apache.kafka.clients.producer.KafkaProducer  - The Kafka producer has closed.
program completed

But the same topic and the same program works fine with string message.

Also I checked the Kafka logs at broker node. I could find only string messages but not the binary message.


问:
AVD emulator error in android studio
I'm a newbie, my problem is when I try to make a new AVD I get this message :

"an error occurred while creating the avd. see idea.log for details"

I just downloaded android studio , dunno what to do

this is from the log file : unable to find a 'userdata.img' file for ABI x86 to copy into the avd folder

答:
If you are in linux, try this:

```<code>sudo apt-get install lib32stdc++6
</code>```

It worked for me!

Title: AVD emulator error in android studio

Body:
If you are in linux, try this:

sudo apt-get install lib32stdc++6

It worked for me!


问:
Tkinter/ttk frame size
I'm trying to set the frame size via theme_settings and it just doesn't work.

```<code>from Tkinter import *
from ttk import *

root = Tk()

style = Style()
style.theme_settings('default',{'TFrame':{'configure':{'width':100, 'height':100}}})

frame = Frame(root)
frame.pack()

root.mainloop()
</code>```

But if I set it explicitly, then it works:

```<code>frame.configure(width=100, height=100)
</code>```

Why?

ttk.version = "0.3.1"

Tkinter.version = "$Revision: 81008 $"

P.S. I need to set this size via .theme_settings() method, the question exactly about it.

UPD: I've checked the same behavior with Button element and it works. Something is wrong with frames...

```<code>style = Style()
style.theme_settings('default',{'TButton':{'configure':{'width':100}}})

button = Button(root)
button.pack()
</code>```

UPD2: The same story with 'padding'. It works with buttons, but not with frames. While frames 'background' for example can be set via theme_settings

答:
Use the Place management as following codes:

root = tk.Tk()
root.geometry("500x300+250+100")    # width x height + x_offset + y_offset

Title: Tkinter/ttk frame size

Body:
I'm trying to set the frame size via theme_settings and it just doesn't work.

from Tkinter import *
from ttk import *

root = Tk()

style = Style()
style.theme_settings('default',{'TFrame':{'configure':{'width':100, 'height':100}}})

frame = Frame(root)
frame.pack()

root.mainloop()

But if I set it explicitly, then it works:

frame.configure(width=100, height=100)

Why?

ttk.version = "0.3.1"

Tkinter.version = "$Revision: 81008 $"

P.S. I need to set this size via .theme_settings() method, the question exactly about it.

UPD: I've checked the same behavior with Button element and it works. Something is wrong with frames...

style = Style()
style.theme_settings('default',{'TButton':{'configure':{'width':100}}})

button = Button(root)
button.pack()

UPD2: The same story with 'padding'. It works with buttons, but not with frames. While frames 'background' for example can be set via theme_settings


问:
Run function only if event default is/isn't prevented
Is there a way to run a function only if event.preventDefault() is called on an event (by another unknown function). This is for a jQuery plugin, so I don't have any knowledge of what other parts of the page might be doing. I've tried this:

```<code>Event.test = Event.preventDefault;
Event.preventDefault = function () {
    alert('Success');
    this.test();
}
</code>```

but it doesn't work... just behaves as normal, with no errors.

Conversely, I want the opposite too... to call a function only if event.preventDefault() isn't called. In effect, to add a function to the default action for an event. Any ideas? Is all this at all possible?

Edit: Based on the comment, I've got a solution to the first problem: http://jsfiddle.net/nathan/VAePB/9/. It works in Chrome (alerts function preventDefault() { [native code] }, but IE alerts undefined. So IE won't let me define Event.prototype.test, but it will let me redefine Event.prototype.preventDefault. Weird. I'm sure I can come up with a solution to the the second problem based on this one if I can just get it to work in IE.

答: I'm not sure I've understand. Can't you just use event.isDefaultPrevented() like this

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to run a function only if event.preventDefault() is called on an event (by another unknown function). This is for a jQuery plugin, so I don't have any knowledge of what other parts of the page might be doing. I've tried this:

Event.test = Event.preventDefault;
Event.preventDefault = function () {
    alert('Success');
    this.test();
}

but it doesn't work... just behaves as normal, with no errors.

Conversely, I want the opposite too... to call a function only if event.preventDefault() isn't called. In effect, to add a function to the default action for an event. Any ideas? Is all this at all possible?

Edit: Based on the comment, I've got a solution to the first problem: http://jsfiddle.net/nathan/VAePB/9/. It works in Chrome (alerts function preventDefault() { [native code] }, but IE alerts undefined. So IE won't let me define Event.prototype.test, but it will let me redefine Event.prototype.preventDefault. Weird. I'm sure I can come up with a solution to the the second problem based on this one if I can just get it to work in IE.


问:
Reading from A json file, FileNotFoundException
I'm working on a simple app and im trying to understand how to read from a json file using a json parser. I wrote a simple json file and put it in one of my directories. Then I used right clock to get the path, and wrote the following code:

```<code>public void myParser() {
    JSONParser parser = new JSONParser();

    String path = "C:\\Users\\My Name\\IntelliJIDEAProjects\\Intereview\\app\\src\\main\\res\\Data\\dataStructures.json";

    try{
        JSONArray topics = (JSONArray)parser.parse(new FileReader(path));
        for(int i=0;i<topics.length();i++) {
            JSONObject object = topics.getJSONObject(i);
            String title = object.optString("title").toString();
            Log.i(TAG,title);
        }

    }

    catch(JSONException e) {
        Log.e("Internal Problem", e.getMessage());
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
</code>```

from some reason, i get this error when running the app:

```<code>java.io.FileNotFoundException: C:\Users\My Name\IntelliJIDEAProjects\Intereview\app\src\main\res\Data\dataStructures.json: open failed: ENOENT (No such file or directory)
</code>```

what could be the reason behind that? i've been working on this for the past few hours and I just can't figure it out..
Thanks

答:
you need to put json inside the assets folder.

In the perspective window open the Project Perspective.

Create the directory inside your android_test/test folder with name                      assets depending upon where you need the JSON response

Now simple put your JSON file inside the assets folder

And call your JSON by simply calling their single name like xyz.json

Body:
I'm working on a simple app and im trying to understand how to read from a json file using a json parser. I wrote a simple json file and put it in one of my directories. Then I used right clock to get the path, and wrote the following code:

public void myParser() {
    JSONParser parser = new JSONParser();

    String path = "C:\\Users\\My Name\\IntelliJIDEAProjects\\Intereview\\app\\src\\main\\res\\Data\\dataStructures.json";

    try{
        JSONArray topics = (JSONArray)parser.parse(new FileReader(path));
        for(int i=0;i<topics.length();i++) {
            JSONObject object = topics.getJSONObject(i);
            String title = object.optString("title").toString();
            Log.i(TAG,title);
        }

    }

    catch(JSONException e) {
        Log.e("Internal Problem", e.getMessage());
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

from some reason, i get this error when running the app:

java.io.FileNotFoundException: C:\Users\My Name\IntelliJIDEAProjects\Intereview\app\src\main\res\Data\dataStructures.json: open failed: ENOENT (No such file or directory)

what could be the reason behind that? i've been working on this for the past few hours and I just can't figure it out..
Thanks


问:
Create a config file to hold values like username password url in python behave
I'm trying to create a config that holds information such as username password etc.

I have created an ini file holding this:

```<code>[DEFAULT]
username: user
password: pass
</code>```

I then have a config map class like:

import configparser

```<code>class ConfigSectionMap:
    def __init__(self):
        my_config_parser = configparser.ConfigParser()
        my_config_parser.read('inilocation')
        print(my_config_parser.default_section)

    def config_map(self, section):
        dict1 = {}
        options = self.my_config_parser.options(section)
        for option in options:
            try:
                dict1[option] = self.my_config_parser.get(section, option)
                if dict1[option] == -1:
                    print("skip: %s" % option)
            except:
                print("exception on %s!" % option)
                dict1[option] = None
        return dict1
</code>```

In my main class where I want to use this I do:

```<code>from config_section_map import ConfigSectionMap

print(ConfigSectionMap.config_map(("DEFAULT")['password']))
</code>```

when running this I receive an error:

TypeError: string indices must be integers

I've been following the docs but it's not working: https://wiki.python.org/moin/ConfigParserExamples

Or if there is an easier way please show me

edit:

changing to this

```<code>print(ConfigSectionMap.config_map("DEFAULT")['password'])
</code>```

shows

```<code>TypeError: config_map() missing 1 required positional argument: 'section'
</code>```

答:
To give another answer the last part of your question
Or if there is an easier way please show me

```<code>OPTION1 = 'test'
</code>```

save it in config.py

in code

```<code>import config
getattr(config, 'OPTION1', 'default value if not found')
</code>```

Body:
I'm trying to create a config that holds information such as username password etc.

I have created an ini file holding this:

[DEFAULT]
username: user
password: pass

I then have a config map class like:

import configparser

class ConfigSectionMap:
    def __init__(self):
        my_config_parser = configparser.ConfigParser()
        my_config_parser.read('inilocation')
        print(my_config_parser.default_section)

    def config_map(self, section):
        dict1 = {}
        options = self.my_config_parser.options(section)
        for option in options:
            try:
                dict1[option] = self.my_config_parser.get(section, option)
                if dict1[option] == -1:
                    print("skip: %s" % option)
            except:
                print("exception on %s!" % option)
                dict1[option] = None
        return dict1

In my main class where I want to use this I do:

from config_section_map import ConfigSectionMap

print(ConfigSectionMap.config_map(("DEFAULT")['password']))

when running this I receive an error:

TypeError: string indices must be integers

I've been following the docs but it's not working: https://wiki.python.org/moin/ConfigParserExamples

Or if there is an easier way please show me

edit:

changing to this

print(ConfigSectionMap.config_map("DEFAULT")['password'])

shows

TypeError: config_map() missing 1 required positional argument: 'section'

Body:
To give another answer the last part of your question
Or if there is an easier way please show me

OPTION1 = 'test'

save it in config.py

in code

import config
getattr(config, 'OPTION1', 'default value if not found')


问:
Android RatingBar shows extra remainder
I'm using the standard Android RatingBar. It seems to behave quite weird. For some reason I can't select only full stars. It always shows a little bit more or less. Also the .setNumStars property doesn't seem to work. I'm using the following code:

```<code>RatingBar ratingbar = new RatingBar(this);
ratingbar.setLayoutParams(lp);
ratingbar.setVisibility(View.VISIBLE);
ratingbar.setNumStars(5);
ratingbar.setStepSize(1);
ratingbar.setRating(1);
linearLayoutReviews.addView(ratingbar);
</code>```

When I select 1 star it selects one star:

When I select 2 stars:

When I select 3 stars:

When I select 4 stars:

And when I select 5 stars:

So for some reason it shows more than 5 stars, and there will always be a remainder of the next star selected

EDIT

When I set .setNumStars to 6 I can select them one by one, but than ofcourse, I have six

EDIT

This is the xml of the LinearLayout

```<code><LinearLayout
                android:id="@+id/linearLayoutReviews"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginStart="10dp"
                android:orientation="vertical"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView5"></LinearLayout>
</code>```

答: I have fixed it by making a new linearlayout and placing it below the old linearlayout. I added the ratingbar to the new linearlayout</p>

Title: Android RatingBar shows extra remainder

Body:
I'm using the standard Android RatingBar. It seems to behave quite weird. For some reason I can't select only full stars. It always shows a little bit more or less. Also the .setNumStars property doesn't seem to work. I'm using the following code:

RatingBar ratingbar = new RatingBar(this);
ratingbar.setLayoutParams(lp);
ratingbar.setVisibility(View.VISIBLE);
ratingbar.setNumStars(5);
ratingbar.setStepSize(1);
ratingbar.setRating(1);
linearLayoutReviews.addView(ratingbar);

When I select 1 star it selects one star:

When I select 2 stars:

When I select 3 stars:

When I select 4 stars:

And when I select 5 stars:

So for some reason it shows more than 5 stars, and there will always be a remainder of the next star selected

EDIT

When I set .setNumStars to 6 I can select them one by one, but than ofcourse, I have six

EDIT

This is the xml of the LinearLayout

<LinearLayout
                android:id="@+id/linearLayoutReviews"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginStart="10dp"
                android:orientation="vertical"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView5"></LinearLayout>


问:
How to delete programatically KML nodes from Google Earth?
I build a winforms app in C# which embeds Google Earth as a viewer. Like this.
My app receives data regularly, transforms that to KML, and displays the result in Google Earth. Whenever I receive the new update, I want to delete the old KML, but I could not find how in GE API. All I found is making the old stuff invisible:

```<code>        this.ge = new ApplicationGEClass();
        // ....
        string newKml = this.ConvertNewInputToKML();
        this.ge.LoadKmlData(ref newKml);
        FeatureGE oldFeature = this.ge.GetFeatureByName("myOldKmlFeature");
        oldFeature.Visibility = 0;
</code>```

I wonder if this will cause memory/performance issue on the long run. Or is there a way to delete from Google Earth KML nodes?

答: You should be able to use ge.getFeatures().removeChild(kmlObject); if you still have a handle on the old object.</p>

Body:
I build a winforms app in C# which embeds Google Earth as a viewer. Like this.
My app receives data regularly, transforms that to KML, and displays the result in Google Earth. Whenever I receive the new update, I want to delete the old KML, but I could not find how in GE API. All I found is making the old stuff invisible:

        this.ge = new ApplicationGEClass();
        // ....
        string newKml = this.ConvertNewInputToKML();
        this.ge.LoadKmlData(ref newKml);
        FeatureGE oldFeature = this.ge.GetFeatureByName("myOldKmlFeature");
        oldFeature.Visibility = 0;

I wonder if this will cause memory/performance issue on the long run. Or is there a way to delete from Google Earth KML nodes?


问:
How to install smlnj in arch linux?
Earlier I was in Ubuntu & it was easy to install smlnj using
apt-get install smlnj
but now I shifted to Arch & I'm finding it difficult to install smlnj.

I tried to find smlnj package through yaourt but I didn't found any.
Then I tried to install it by steps given in official site by downloading tar file. I followed given steps and extracted tar file in /usr/local/sml & then compiled by running command
config/install.sh.

After doing all this I tried to run sml but was not successful. I tried setting environment variable but again was not successful.

Please tell me whether I'm missing any steps or doing it wrong way. What is correct way to install smlnj in Arch Linux?

答:
Update: As Alexander (xyproto) points out, pacman -S smlnj should work again now that SML/NJ is in the [multilib] repository. The solution below would still work, but credit for making installation more convenient should go to him. :-)

Before: It seems that the package became unavailable for x86_64 in Feb 2017, but it doesn't look like it should have happened. I've asked Alexander who maintains the package in [community].

The AUR doesn't contain an smlnj package because it's against AUR policy to overlap with official packages, unless the AUR package is compiled with some tweak that is clearly visible in the package name.

You can still build an Arch package and install that by finding the PKGBUILD and accompanying files at: https://git.archlinux.org/svntogit/community.git/tree/trunk?h=packages/smlnj (or by cloning the git repo below with those four files in it):

```<code>~ $ git clone https://github.com/sshine/smlnj-arch.git
~ $ cd smlnj-arch
~/smlnj-arch $ makepkg
~/smlnj-arch $ sudo pacman -U smlnj-110.80-3-x86_64.pkg.tar.xz
</code>```

Title: How to install smlnj in arch linux?

Body:
Update: As Alexander (xyproto) points out, pacman -S smlnj should work again now that SML/NJ is in the [multilib] repository. The solution below would still work, but credit for making installation more convenient should go to him. :-)

Before: It seems that the package became unavailable for x86_64 in Feb 2017, but it doesn't look like it should have happened. I've asked Alexander who maintains the package in [community].

The AUR doesn't contain an smlnj package because it's against AUR policy to overlap with official packages, unless the AUR package is compiled with some tweak that is clearly visible in the package name.

You can still build an Arch package and install that by finding the PKGBUILD and accompanying files at: https://git.archlinux.org/svntogit/community.git/tree/trunk?h=packages/smlnj (or by cloning the git repo below with those four files in it):

~ $ git clone https://github.com/sshine/smlnj-arch.git
~ $ cd smlnj-arch
~/smlnj-arch $ makepkg
~/smlnj-arch $ sudo pacman -U smlnj-110.80-3-x86_64.pkg.tar.xz


问:
How to find the earlier date between two events?
I have the following table:

For each member from this table, I would like to get the event date. The event date should be pulled by comparing the event dates for "run" and 'jog" events and which ever date is smaller/earlier, that date is what i need.

So my output table will look like:

答:
Assuming event_date is of date type or at least a string in YYYY-MM-DD format (and it was changed in the Excel)</p>

```<code>select      member
           ,min(event_date)
from        mytable
where       event in ('run','jog')
group by    member
</code>```

Body:
Assuming event_date is of date type or at least a string in YYYY-MM-DD format (and it was changed in the Excel)

select      member
           ,min(event_date)
from        mytable
where       event in ('run','jog')
group by    member


问:
SQL OpenQuery variable tablename
I need to transfer data from a linked server to our main SQL server. The issue is, that the table name changes everyday.
I have looked around this site to find out if it is even possible to have a variable database name, which it is, but also to see if it is possible to have variables in a OPENQUERY, which it also is.

But i am struggling to combine those needs, so i have a variable table name in a OPENQUERY.

I need something like this:

```<code>Declare @LinkedServer as varchar(max) = 'LinkedServer'
Declare @TName as varchar(max) = 'TName'+substring(cast(cast(getdate() as date) as
varchar(50)),1,4)+substring(cast(cast(getdate() as date) as
varchar(50)),6,2)+substring(cast(cast(getdate() as date) as
varchar(50)),9,2)

SELECT * FROM OPENQUERY(@LinkedServer, 'SELECT * FROM dbo.@TName')
</code>```

Is there any way i can make a variable table name in a OPENQUERY ?

Thank you for your help.

/Mikkel

答:
I'd write a synonym which gets updated every day before you kick off your data extraction job. Then you don't need to be updating (potentially a tonne of) references.</p>

```<code>CREATE SYNONYM LinkedTableA
FOR
ServerName.DBName.dbo.TName20170331

SELECT * FROM LinkedTableA
</code>```

Title: SQL OpenQuery variable tablename

Body:
I need to transfer data from a linked server to our main SQL server. The issue is, that the table name changes everyday.
I have looked around this site to find out if it is even possible to have a variable database name, which it is, but also to see if it is possible to have variables in a OPENQUERY, which it also is.

But i am struggling to combine those needs, so i have a variable table name in a OPENQUERY.

I need something like this:

Declare @LinkedServer as varchar(max) = 'LinkedServer'
Declare @TName as varchar(max) = 'TName'+substring(cast(cast(getdate() as date) as
varchar(50)),1,4)+substring(cast(cast(getdate() as date) as
varchar(50)),6,2)+substring(cast(cast(getdate() as date) as
varchar(50)),9,2)

SELECT * FROM OPENQUERY(@LinkedServer, 'SELECT * FROM dbo.@TName')

Is there any way i can make a variable table name in a OPENQUERY ?

Thank you for your help.

/Mikkel

Body:
I'd write a synonym which gets updated every day before you kick off your data extraction job. Then you don't need to be updating (potentially a tonne of) references.

CREATE SYNONYM LinkedTableA
FOR
ServerName.DBName.dbo.TName20170331

SELECT * FROM LinkedTableA


问:
Custom Smarty functions
In Smarty i want to be able to write {widget 15} or {widget id=15} , so the output will be the return value of PHP function

```<code>function widget($id){
    echo 'hi '.$id;
}
</code>```

is it possible ?

答: Smarty allows you to create such custom functions easily: see the official reference.</p>

Title: Custom Smarty functions

Body:
In Smarty i want to be able to write {widget 15} or {widget id=15} , so the output will be the return value of PHP function

function widget($id){
    echo 'hi '.$id;
}

is it possible ?


问:
Android app with fragments and listviews
I am developing an android app and I have multiple fragments with a listview  in each fragment.

I fill my listviews with data from an api.

I am wondering how can I cache my data so when a user changes the fragment(slide left - right) the data will not be loaded again.

答: I think you can just do that by adding: android:launchMode="singleTop" in your androidmanifest file for every activity tag.


问:
Linux - "-y" parameter option in Kickstart file
Currently I am setting up a Kickstart file which will install the snort software and required dependencies on a Ubuntu server (16.04.2 LTS) using the "%package" section of Kickstart.

The question, can I use the -y" parameter within the "%package" section or something equivalent to say yes to everything as I need to skip the dialogs what pop up during the installation of snort as my job is to setup a automated Linux installation using Kickstart and pressed configuration file.

Note - I know you can use post scripts in Kickstart but my supervisor requires me to use %package section of Kickstart.

答:
Please use this parameter with your package name "--resolvedeps".

Ex:-
Package_name --resolvedeps

It'll resolved all the dependencies.


问:
Retrofit2 java.lang.NoClassDefFoundError: okhttp3/Call$Factory in JAVA

I am not developing a Android Application ,

  I'm just writing some JAVA codes to support Imgur API services.

```<code>public interface ImgurAPI {
    String server = "https://api.imgur.com";
    String BASE64 = "base64";

    @POST("/3/upload")
    void postImage(
            @Header("Authorization") String auth,
            @Query("title") String title,
            @Query("description") String description,
            @Query("type") String type,
            @Body String base64Image,
            Callback<ImageResponse> cb
    );
</code>```

}

Main :

```<code>public static void main(String[] args) {

    try{
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ImgurAPI.server)
                .build();
        ImgurAPI myAPI = retrofit.create(ImgurAPI.class);
        String base64Image = new ImageReader(PATH).getBase64String();
        myAPI.postImage(AUTH, "Hi", "Test", ImgurAPI.BASE64, base64Image, new MyCallBack());

    }catch(Exception err){
        err.printStackTrace();
    }
}
</code>```

and the exception throwing :

```<code>    Exception in thread "main" java.lang.NoClassDefFoundError: okhttp3/Call$Factory
    at Main.main(Main.java:14)

Caused by: java.lang.ClassNotFoundException: okhttp3.Call$Factory
</code>```

I found out lots of solutions of Android.
So I'm wondering if Retrofit available in only JAVA.

thanks .

答:
I solved it ,
If you are writing Java (Only Java),
And you downloaded the Jar of Retrofit2,
It might not contain certain libraries which built-in in Android Studio,
So you have to download them manually.

OkHttp3 OkHttp3 3.0.0 Jar download

Okio Okio 1.6.0 Jar download

Retrofit-converter gson Retrofit converter gson-2 beta3 Jar download
(If you want to convert other types of data , just download other Jars in Retrofit )

Gson Gson 2.2.3 Jar download

Import the jar files , then It could work

Make sure you got all of its

Body:
I am not developing a Android Application ,

  I'm just writing some JAVA codes to support Imgur API services.

public interface ImgurAPI {
    String server = "https://api.imgur.com";
    String BASE64 = "base64";

    @POST("/3/upload")
    void postImage(
            @Header("Authorization") String auth,
            @Query("title") String title,
            @Query("description") String description,
            @Query("type") String type,
            @Body String base64Image,
            Callback<ImageResponse> cb
    );

}

Main :

public static void main(String[] args) {

    try{
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ImgurAPI.server)
                .build();
        ImgurAPI myAPI = retrofit.create(ImgurAPI.class);
        String base64Image = new ImageReader(PATH).getBase64String();
        myAPI.postImage(AUTH, "Hi", "Test", ImgurAPI.BASE64, base64Image, new MyCallBack());

    }catch(Exception err){
        err.printStackTrace();
    }
}

and the exception throwing :

    Exception in thread "main" java.lang.NoClassDefFoundError: okhttp3/Call$Factory
    at Main.main(Main.java:14)

Caused by: java.lang.ClassNotFoundException: okhttp3.Call$Factory

I found out lots of solutions of Android.
So I'm wondering if Retrofit available in only JAVA.

thanks .


问:
5 boxes not centering correctly in the center of the page
I am totally new into programming. I've aligned 5 boxed horizontally , but what I want is to center the boxes. The boxes should also be responsive what they are right now. I am searching and searching for how to center a div, but as result I get
 margin: 0 auto; width: 800px;. When I adjust my browser to 100%, the 5th box get under the other boxes.

.square {
 float:left;
 width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="outside">
  <div class="square">
   <span>2.1</span>
  </div>
  <div class="square">
   <span>2.3</span>
  </div>
  <div class="square">
   <span>2.5</span>
  </div>
  <div class="square">
   <span>2.6</span>
  </div>
  <div class="square">
   <span>2.7</span>
  </div>
 </div></code>```

答:
I think the easiest way would be to remove the floating from the inner divs, and display them as inline blocks instead. The outside would have the auto margins and a center text aligning, like this:

.outside {
  border: 1px solid blue;
  text-align: center;
  margin: 0 auto;
}

.square {
 display: inline-block;
 width: 12.5vw;
  height: 12.5vw;
  margin-left: 10px;
  margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outside">
  <div class="square">
    <span>2.1</span>
  </div>
  <div class="square">
    <span>2.3</span>
  </div>
  <div class="square">
    <span>2.5</span>
  </div>
  <div class="square">
    <span>2.6</span>
  </div>
  <div class="square">
    <span>2.7</span>
  </div>
</div></code>```

Body:
I am totally new into programming. I've aligned 5 boxed horizontally , but what I want is to center the boxes. The boxes should also be responsive what they are right now. I am searching and searching for how to center a div, but as result I get
 margin: 0 auto; width: 800px;. When I adjust my browser to 100%, the 5th box get under the other boxes.

.square {
 float:left;
 width: 12.5vw;
    height: 12.5vw;
    margin-left: 10px;
    margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}

   2.1

   2.3

   2.5

   2.6

   2.7

Body:
I think the easiest way would be to remove the floating from the inner divs, and display them as inline blocks instead. The outside would have the auto margins and a center text aligning, like this:

.outside {
  border: 1px solid blue;
  text-align: center;
  margin: 0 auto;
}

.square {
 display: inline-block;
 width: 12.5vw;
  height: 12.5vw;
  margin-left: 10px;
  margin-right: 10px;
 position: relative;
 border: 0.5px solid red;
 text-align: center;
}

.square span {
 font-size: 3vw;
}

<div class="outside">
  <div class="square">
    <span>2.1</span>
  </div>
  <div class="square">
    <span>2.3</span>
  </div>
  <div class="square">
    <span>2.5</span>
  </div>
  <div class="square">
    <span>2.6</span>
  </div>
  <div class="square">
    <span>2.7</span>
  </div>
</div>