问:
Generic Method That takes unique parameter and returns unique parameters Java
I have a requirement where in the function takes different parameters and returns unique objects. All these functions perform the same operation.

ie.

```<code>public returnObject1 myfunction( paramObject1 a, int a) {
returnObject1 = new returnObject1();
returnObject1.a = paramObject1.a;
return returnObject1;
}

public returnOject2 myfunction( paramObject2 a, int a){
 returnObject2 = new returnObject2();
 returnObject2.a = paramObject2.a;
 return returnObject2;
}
</code>```

As you can see above, both the function do the same task but they take different parameters as input and return different objects.

I would like to minimize writing different functions that does the same task.

Is it possible to write a generic method for this that can substitute the parameters based on the call to the function?

paramObject and returnObject are basically two classes that have different variables. They are not related to each other.

My objective is that I do not want to do function overloading since the functions do almost the same work. I would like to have a single function that can handle different input and different return output.

my aim is to do something like this (if possible):

```<code>public static < E > myfunction( T a, int a ) {
  // do work
}
</code>```

The return type E and the input T can keep varying.

答:
you can using the 3rd apply method to remove the code duplications, you separate creation & initialization from the apply method in this approach. and don't care about which type of T is used. for example:

```<code>returnObject1 myfunction(paramObject1 a, int b) {
    return apply(returnObject1::new, b, value -> {
        //uses paramObject1
        //populates returnObject1
        //for example:
        value.foo = a.bar;
    });
}

returnOject2 myfunction(paramObject2 a, int b) {
    return apply(returnOject2::new, b, value -> {
        //uses paramObject2
        //populates returnObject2
        //for example:
        value.key = a.value;
    });
}

<T> T apply(Supplier<T> factory, int b, Consumer<T> initializer) {
    T value = factory.get();
    initializer.accept(value);
    //does work ...
    return value;
}
</code>```

Note the 2 myfunction is optional, you can remove them from you source code, and call the apply method directly, for example:

```<code>paramObject2 a = ...;

returnObject2  result = apply(returnOject2::new, 2, value -> {
    //for example:
    value.key = a.value;
});
</code>```

Body:
I have a requirement where in the function takes different parameters and returns unique objects. All these functions perform the same operation.

ie.

public returnObject1 myfunction( paramObject1 a, int a) {
returnObject1 = new returnObject1();
returnObject1.a = paramObject1.a;
return returnObject1;
}

public returnOject2 myfunction( paramObject2 a, int a){
 returnObject2 = new returnObject2();
 returnObject2.a = paramObject2.a;
 return returnObject2;
}

As you can see above, both the function do the same task but they take different parameters as input and return different objects.

I would like to minimize writing different functions that does the same task.

Is it possible to write a generic method for this that can substitute the parameters based on the call to the function?

paramObject and returnObject are basically two classes that have different variables. They are not related to each other.

My objective is that I do not want to do function overloading since the functions do almost the same work. I would like to have a single function that can handle different input and different return output.

my aim is to do something like this (if possible):

public static < E > myfunction( T a, int a ) {
  // do work
}

The return type E and the input T can keep varying.

Body:
you can using the 3rd apply method to remove the code duplications, you separate creation & initialization from the apply method in this approach. and don't care about which type of T is used. for example:

returnObject1 myfunction(paramObject1 a, int b) {
    return apply(returnObject1::new, b, value -> {
        //uses paramObject1
        //populates returnObject1
        //for example:
        value.foo = a.bar;
    });
}

returnOject2 myfunction(paramObject2 a, int b) {
    return apply(returnOject2::new, b, value -> {
        //uses paramObject2
        //populates returnObject2
        //for example:
        value.key = a.value;
    });
}

<T> T apply(Supplier<T> factory, int b, Consumer<T> initializer) {
    T value = factory.get();
    initializer.accept(value);
    //does work ...
    return value;
}

Note the 2 myfunction is optional, you can remove them from you source code, and call the apply method directly, for example:

paramObject2 a = ...;

returnObject2  result = apply(returnOject2::new, 2, value -> {
    //for example:
    value.key = a.value;
});


来源: stackexchange

问:
Matrix multiplication very slow in Eigen
I have implemented a Gauss-Newton optimization process which involves calculating the increment by solving a linearized system Hx = b. The H matrx is calculated by H = J.transpose() * W * J and b is calculated from b = J.transpose() * (W * e) where e is the error vector. Jacobian here is a n-by-6 matrix where n is in thousands and stays unchanged across iterations and W is a n-by-n diagonal weight matrix which will change across iterations (some diagonal elements will be set to zero). However I encountered a speed issue.

When I do not add the weight matrix W, namely H = J.transpose()*J and b = J.transpose()*e, my Gauss-Newton process can run very fast in 0.02 sec for 30 iterations. However when I add the W matrix which is defined outside the iteration loop, it becomes so slow (0.3~0.7 sec for 30 iterations) and I don't understand if it is my coding problem or it normally takes this long.

Everything here are Eigen matrices and vectors.

I defined my W matrix using .asDiagonal() function in Eigen library from a vector of inverse variances. then just used it in the calculation for H ad b. Then it gets very slow. I wish to get some hints about the potential reasons for this huge slowdown.

EDIT:

There are only two matrices. Jacobian is definitely dense. Weight matrix is generated from a vector by the function vec.asDiagonal() which comes from the dense library so I assume it is also dense.

The code is really simple and the only difference that's causing the time change is the addition of the weight matrix. Here is a code snippet:

```<code>for (int iter=0; iter<max_iter; ++iter) {
    // obtain error vector
    error = ...
    // calculate H and b - the fast one
    Eigen::MatrixXf H = J.transpose() * J;
    Eigen::VectorXf b = J.transpose() * error;
    // calculate H and b - the slow one
    Eigen::MatrixXf H = J.transpose() * weight_ * J;
    Eigen::VectorXf b = J.transpose() * (weight_ * error);
    // obtain delta and update state
    del = H.ldlt().solve(b);
    T <- T(del)   // this is pseudo code, meaning update T with del
}
</code>```

It is in a function in a class, and weight matrix now for debug purposes is defined as a class variable that can be accessed by the function and is defined before the function is called.

答:
Because the matrix multiplication is just the diagonal, you can change it to use coefficient wise multiplication like so:

```<code>MatrixXd m;
VectorXd w;
w.setLinSpaced(5, 2, 6);

m.setOnes(5,5);

std::cout << (m.array().rowwise() * w.array().transpose()).matrix() << "\n";
</code>```

Likewise, the matrix vector product can be written as:

```<code>(w.array() * error.array()).matrix()
</code>```

This avoids the zero elements in the matrix. Without an MCVE for me to base this on, YMMV...

ContentLicense: CC BY-SA 3.0

Body:
I have implemented a Gauss-Newton optimization process which involves calculating the increment by solving a linearized system Hx = b. The H matrx is calculated by H = J.transpose() * W * J and b is calculated from b = J.transpose() * (W * e) where e is the error vector. Jacobian here is a n-by-6 matrix where n is in thousands and stays unchanged across iterations and W is a n-by-n diagonal weight matrix which will change across iterations (some diagonal elements will be set to zero). However I encountered a speed issue.

When I do not add the weight matrix W, namely H = J.transpose()*J and b = J.transpose()*e, my Gauss-Newton process can run very fast in 0.02 sec for 30 iterations. However when I add the W matrix which is defined outside the iteration loop, it becomes so slow (0.3~0.7 sec for 30 iterations) and I don't understand if it is my coding problem or it normally takes this long.

Everything here are Eigen matrices and vectors.

I defined my W matrix using .asDiagonal() function in Eigen library from a vector of inverse variances. then just used it in the calculation for H ad b. Then it gets very slow. I wish to get some hints about the potential reasons for this huge slowdown.

EDIT:

There are only two matrices. Jacobian is definitely dense. Weight matrix is generated from a vector by the function vec.asDiagonal() which comes from the dense library so I assume it is also dense.

The code is really simple and the only difference that's causing the time change is the addition of the weight matrix. Here is a code snippet:

for (int iter=0; iter<max_iter; ++iter) {
    // obtain error vector
    error = ...
    // calculate H and b - the fast one
    Eigen::MatrixXf H = J.transpose() * J;
    Eigen::VectorXf b = J.transpose() * error;
    // calculate H and b - the slow one
    Eigen::MatrixXf H = J.transpose() * weight_ * J;
    Eigen::VectorXf b = J.transpose() * (weight_ * error);
    // obtain delta and update state
    del = H.ldlt().solve(b);
    T <- T(del)   // this is pseudo code, meaning update T with del
}

It is in a function in a class, and weight matrix now for debug purposes is defined as a class variable that can be accessed by the function and is defined before the function is called.

Body:
Because the matrix multiplication is just the diagonal, you can change it to use coefficient wise multiplication like so:

MatrixXd m;
VectorXd w;
w.setLinSpaced(5, 2, 6);

m.setOnes(5,5);

std::cout << (m.array().rowwise() * w.array().transpose()).matrix() << "\n";

Likewise, the matrix vector product can be written as:

(w.array() * error.array()).matrix()

This avoids the zero elements in the matrix. Without an MCVE for me to base this on, YMMV...


问:
How do I pluralize or singularize multiple nouns?
I'm using the excellent nlp-compromise module for NLP.

I'm stuck at what should be a rather straightforward process: pluralizing or singularizing all nouns.

So far, I've got this:

```<code>let a = nlp("apples, oranges, pears")
a.nouns().toSingular()
a.out("text")
</code>```

However, this returns

apple, oranges, pears

Whilst what I really want is

apple, orange, pear

Runkit here

答:
this was a bug that just got fixed in v10.6.0.

https://runkit.com/spencermountain/595e48ab230e340012e1d314

(especially) with the commas, they are indeed three nouns, which all now inflect individually.

thanks for your help.

Body:
I'm using the excellent nlp-compromise module for NLP.

I'm stuck at what should be a rather straightforward process: pluralizing or singularizing all nouns.

So far, I've got this:

let a = nlp("apples, oranges, pears")
a.nouns().toSingular()
a.out("text")

However, this returns

apple, oranges, pears

Whilst what I really want is

apple, orange, pear

Runkit here


问:
Get Text String from Doc Body and preserve line breaks
I have a Google Doc which has the following in the document:

```<code>Hello
Replace me
Line 2
</code>```

I am trying to replace "Replace me" including the line break, with "I am replaced\nwith 2 lines" to make the final Doc contents equal:

```<code>Hello
I am replaced
with 2 linesLine 2
</code>```

My code is simply:

```<code>function myFunction() {
  var searchString = 'Replace me\n';
  var newString = 'I am replaced\nwith 2 lines';
  var stringData = DocumentApp.getActiveDocument().getBody();
  stringData.replaceText(searchString, newString);
}
</code>```

I have tried changing searchString to use \\n, \v,
,
, and maybe a few other items.

What do I need the searchString to contain to also include the line break?

Here is the sample file with script

答:
```<code>function myFunction() {
  var searchStringNoLineBreak = 'Replace me';
  var searchStringRegex = "Replace me\\v";
  var substring = "I am replaced\nwith 2 lines";

  var body = DocumentApp.getActiveDocument().getBody();

  // get all paragraphs
  var paragraphs = body.getParagraphs();

  // loop paragraphs
  for (var i = 0; i < paragraphs.length; i++)
  {
    // current paragraph
    var p = paragraphs[i];

    // if found text with soft return, replace it
    if (p.findText(searchStringRegex))
    {
      p.replaceText(searchStringRegex, substring);
    }

    var isAtTheEnd = p.findText(searchStringNoLineBreak);

    // if text without newline was found but at the end of paragraph, we need to replace it too
    if (isAtTheEnd)
    {
      // replace text without new line character
      p.replaceText(searchStringNoLineBreak, substring);

      // then merge next paragraph with current to remove that new line between them
      if (i+1 < paragraphs.length)
      {
        var nextP = paragraphs[i+1];
        nextP.merge();
      }
    }
  }
}
</code>```

Input:

Result:

Body:
I have a Google Doc which has the following in the document:

Hello
Replace me
Line 2

I am trying to replace "Replace me" including the line break, with "I am replaced\nwith 2 lines" to make the final Doc contents equal:

Hello
I am replaced
with 2 linesLine 2

My code is simply:

function myFunction() {
  var searchString = 'Replace me\n';
  var newString = 'I am replaced\nwith 2 lines';
  var stringData = DocumentApp.getActiveDocument().getBody();
  stringData.replaceText(searchString, newString);
}

I have tried changing searchString to use \\n, \v,
,
, and maybe a few other items.

What do I need the searchString to contain to also include the line break?

Here is the sample file with script

Body:
function myFunction() {
  var searchStringNoLineBreak = 'Replace me';
  var searchStringRegex = "Replace me\\v";
  var substring = "I am replaced\nwith 2 lines";

  var body = DocumentApp.getActiveDocument().getBody();

  // get all paragraphs
  var paragraphs = body.getParagraphs();

  // loop paragraphs
  for (var i = 0; i < paragraphs.length; i++)
  {
    // current paragraph
    var p = paragraphs[i];

    // if found text with soft return, replace it
    if (p.findText(searchStringRegex))
    {
      p.replaceText(searchStringRegex, substring);
    }

    var isAtTheEnd = p.findText(searchStringNoLineBreak);

    // if text without newline was found but at the end of paragraph, we need to replace it too
    if (isAtTheEnd)
    {
      // replace text without new line character
      p.replaceText(searchStringNoLineBreak, substring);

      // then merge next paragraph with current to remove that new line between them
      if (i+1 < paragraphs.length)
      {
        var nextP = paragraphs[i+1];
        nextP.merge();
      }
    }
  }
}

Input:

Result:


问:
Best way"less time" to bulk insert using entity framework excluding duplicated records for two related tables?
I am trying to bulk insert to tables "TU" and "TUV" (one to many relationship) with no duplicated records of "TU" table column "HashText" so I did this:

```<code>    /// <summary>
    /// Check if the selected TranslationUnit is exsists at db.
    /// </summary>
    /// <param name="translationUnit"></param>
    /// <returns></returns>
    public bool CheckDuplicate(TranslationUnit translationUnit)
    {

        int FoundedTusCount = db.TUs.Where(tu => tu.HashText == translationUnit.Hash && TmIDList.Any(tm => tm == tu.TMID)).Count();
        if(FoundedTusCount > 0)
        {
            return true;
        }
        return false;
    }
</code>```

this is a lot of connection to DB and a lot of time.

Then insert the remains items to the database using addRange() every 10000 (saving connection time)record like this:

```<code>            foreach (TranslationUnit item in Options.TMXFile.Data.Body.TranslationUnits.ToList())
            {
                TU tu = FillTU(TMID, item);
                ReadyTUs.Add(tu);
                tu.TUVs = new List<TUV>();
                foreach (TranslationUnitVariant item1 in item.TranslationUnitVariants)
                {
                    tu.TUVs.Add( FillTUV(item1));
                }
                if (ReadyTUs.Count >= 10000)
                {
                    Save();
                }
            }
            Save();
</code>```

this is the save function:

```<code>    private void Save()
    {
        db.TUs.AddRange(ReadyTUs);
        db.SaveChanges();
        ReadyTUs.Clear();
        db.Dispose();
        db = new GTMEntities();
    }
</code>```

My main problem now is time and many connections to DB So, if there is some way to bulk insert TU and TUV table with no duplicated TUs -that contains millions of records- it will be much better.

答:
One option would be to use SqlBulkCopy.

Basically you bulk insert all data into a staging table.

Then join the main and the staging tables and DELETE all records in the staging table that match.

Then INSERT into the real table with the results of a SELECT DISTINCT from the staging table.

Body:
I am trying to bulk insert to tables "TU" and "TUV" (one to many relationship) with no duplicated records of "TU" table column "HashText" so I did this:

    ///
    /// Check if the selected TranslationUnit is exsists at db.
    ///
    /// <param name="translationUnit"></param>
    /// <returns></returns>
    public bool CheckDuplicate(TranslationUnit translationUnit)
    {

        int FoundedTusCount = db.TUs.Where(tu => tu.HashText == translationUnit.Hash && TmIDList.Any(tm => tm == tu.TMID)).Count();
        if(FoundedTusCount > 0)
        {
            return true;
        }
        return false;
    }

this is a lot of connection to DB and a lot of time.

Then insert the remains items to the database using addRange() every 10000 (saving connection time)record like this:

            foreach (TranslationUnit item in Options.TMXFile.Data.Body.TranslationUnits.ToList())
            {
                TU tu = FillTU(TMID, item);
                ReadyTUs.Add(tu);
                tu.TUVs = new List<TUV>();
                foreach (TranslationUnitVariant item1 in item.TranslationUnitVariants)
                {
                    tu.TUVs.Add( FillTUV(item1));
                }
                if (ReadyTUs.Count >= 10000)
                {
                    Save();
                }
            }
            Save();

this is the save function:

    private void Save()
    {
        db.TUs.AddRange(ReadyTUs);
        db.SaveChanges();
        ReadyTUs.Clear();
        db.Dispose();
        db = new GTMEntities();
    }

My main problem now is time and many connections to DB So, if there is some way to bulk insert TU and TUV table with no duplicated TUs -that contains millions of records- it will be much better.


问:
Numpy stack with unequal shapes
I've noticed that the solution to combining 2D arrays to 3D arrays through np.stack, np.dstack, or simply passing a list of arrays only works when the arrays have same .shape[0].

For instance, say I have:

```<code>print(arr)
[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]
</code>```

it easy easy to get to:

```<code>print(np.array([arr[2:4], arr[3:5]])) # same shape
[[[4 5]
  [6 7]]

 [[6 7]
  [8 9]]]
</code>```

However, if I pass a list of arrays of unequal length, I get:

```<code>print(np.array([arr[:2], arr[:3]]))
[array([[0, 1],
       [2, 3]])
 array([[0, 1],
       [2, 3],
       [4, 5]])]
</code>```

How can I get to simply:

```<code>[[[0, 1]
  [2, 3]]
 [[0, 1]
  [2, 3]
  [4, 5]]]
</code>```

What I've tried: a number of other Array manipulation routines.

Note: ultimately want to do this for more than 2 arrays, so np.append is probably not ideal.

答:
Numpy arrays have to be rectangular, so what you are trying to get is not possible with a numpy array.

You need a different data structure. Which one is suitable depends on what you want to do with that data.

Title: Numpy stack with unequal shapes

Body:
I've noticed that the solution to combining 2D arrays to 3D arrays through np.stack, np.dstack, or simply passing a list of arrays only works when the arrays have same .shape[0].

For instance, say I have:

print(arr)
[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]

it easy easy to get to:

print(np.array([arr[2:4], arr[3:5]])) # same shape
[[[4 5]
  [6 7]]

 [[6 7]
  [8 9]]]

However, if I pass a list of arrays of unequal length, I get:

print(np.array([arr[:2], arr[:3]]))
[array([[0, 1],
       [2, 3]])
 array([[0, 1],
       [2, 3],
       [4, 5]])]

How can I get to simply:

[[[0, 1]
  [2, 3]]
 [[0, 1]
  [2, 3]
  [4, 5]]]

What I've tried: a number of other Array manipulation routines.

Note: ultimately want to do this for more than 2 arrays, so np.append is probably not ideal.


问:
Appcelerator Titanium Animation
I am working with titanium expand and collapse for Android.I have created a tablerow with a Label and image.When i click on the image then make bottom view visibility true and set height for tablerow.Then applied animation for the expand view

```<code>    for (var i = 0; i < sectionItems.length; i++) {

              tblCell[i] = Ti.UI.createTableViewRow({
                  height: 50,
                  backgroundColor: 'white',
                  id: i,

                  layout:"horizontal",
                  rowId:i
              });
            topView[i]=Ti.UI.createView({

                  height: 50,
                  backgroundColor: 'white',
                  id: i,
                 rowId:i,
                  layout:"horizontal",
                  width:"100%",

              });

              lbltitle[i] = Ti.UI.createLabel({
                  text: sectionItems[i],
                  id:i,
                  color:'#000',
                  font: {
                      fontSize: '16dp',
                      fontFamily: 'Myriad Pro',
                      fontWeight: 'bold'
                  },
                 left: "1%",
                 width:'80%',
                 rowId:i,
                  //right: '10',
                  textAlign: Titanium.UI.TEXT_ALIGNMENT_LEFT,

              });
                lblDescription[i] = Ti.UI.createLabel({
                 // text: sectionItems[i].description,
                  id: i,
                  text:"Test Answer",
                  color:'#000',
                  font: {
                      fontSize: '14dp',
                      fontFamily: 'Myriad Pro',
                  },
                  backgroundColor:'green',
                  rowId:i,
                  left: "10%",
                  right:"10%",
                  top:"10dp",
                  width:'80%',
                  height:"25%",
                 textAlign: Titanium.UI.TEXT_ALIGNMENT_LEFT,

              });
              addPic[i] = Ti.UI.createImageView({
                image:"/images/carat_down.png",

               rowId:i,
                id: i,

                right:"1%",

                height:'9dp',
                width:"16dp"

              });
                expandView[i]=Ti.UI.createView({
                width:"100%",
                left:'0dp',
                height:"0dp",
                backgroundColor:'red',
                 id: i,
                rowId:i,
                visible:false,
                 layout:"vertical"

              });

              topView[i].add(lbltitle[i]);
              topView[i].add(addPic[i]);
              expandView[i].add(lblDescription[i]);
              tblCell[i].add(expandView[i]);

               tblCell[i].add(topView[i]);
                addPic[i].addEventListener('singletap', function(e) {

                toggleExpand(e);
             });

function toggleExpand(e){

             if(expandView[e.source.rowId].visible==true){

             expandView[e.source.rowId].visible=false;

                tblCell[e.source.rowId].height=tblCell[e.source.rowId].height-(topView[e.source.rowId].height*3);
             expandView[e.source.rowId].animate({
                height:"0dp",duration:250});

           }else{
            for (var i = 0; i < tblsectionItems.length; i++) {
                if(expandView[i].visible==true){
                    expandView[i].visible=false;
                    tblCell[i].height=tblCell[i].height-(topView[i].height*3);
                    expandView[i].animate({
                    height:"0dp",duration:250});
                }}

              expandView[e.source.rowId].visible=true;

              expandView[e.source.rowId].animate({
                height:"auto",duration:250});//"auto"
              tblCell[e.source.rowId].height=tblCell[e.source.rowId].height+(topView[e.source.rowId].height*3);

           }
}
</code>```

But when the row expand then i can't see my previous elements of tblcell.I can't find the reason.Please help me

答:
I think you need to change the logic you are using to add elements in the row.
First do not use separate arrays to add each elements instead use row variable to attach elements like below..

```<code>var row = Ti.UI.createTableViewRow({});
row.topView = Ti.UI.createView({});
row.expandView = Ti.UI.createView({}); like that..
</code>```

then use only 2 objects for expanView or whatever view you want to show/hide in toggleExpand function.. like

```<code>if(previousView.visible == true)
{
...
}
else{
...
}
previousView = e.row.expandView;
</code>```

Title: Appcelerator Titanium Animation

Body:
I am working with titanium expand and collapse for Android.I have created a tablerow with a Label and image.When i click on the image then make bottom view visibility true and set height for tablerow.Then applied animation for the expand view

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

              tblCell[i] = Ti.UI.createTableViewRow({
                  height: 50,
                  backgroundColor: 'white',
                  id: i,

                  layout:"horizontal",
                  rowId:i
              });
            topView[i]=Ti.UI.createView({

                  height: 50,
                  backgroundColor: 'white',
                  id: i,
                 rowId:i,
                  layout:"horizontal",
                  width:"100%",

              });

              lbltitle[i] = Ti.UI.createLabel({
                  text: sectionItems[i],
                  id:i,
                  color:'#000',
                  font: {
                      fontSize: '16dp',
                      fontFamily: 'Myriad Pro',
                      fontWeight: 'bold'
                  },
                 left: "1%",
                 width:'80%',
                 rowId:i,
                  //right: '10',
                  textAlign: Titanium.UI.TEXT_ALIGNMENT_LEFT,

              });
                lblDescription[i] = Ti.UI.createLabel({
                 // text: sectionItems[i].description,
                  id: i,
                  text:"Test Answer",
                  color:'#000',
                  font: {
                      fontSize: '14dp',
                      fontFamily: 'Myriad Pro',
                  },
                  backgroundColor:'green',
                  rowId:i,
                  left: "10%",
                  right:"10%",
                  top:"10dp",
                  width:'80%',
                  height:"25%",
                 textAlign: Titanium.UI.TEXT_ALIGNMENT_LEFT,

              });
              addPic[i] = Ti.UI.createImageView({
                image:"/images/carat_down.png",

               rowId:i,
                id: i,

                right:"1%",

                height:'9dp',
                width:"16dp"

              });
                expandView[i]=Ti.UI.createView({
                width:"100%",
                left:'0dp',
                height:"0dp",
                backgroundColor:'red',
                 id: i,
                rowId:i,
                visible:false,
                 layout:"vertical"

              });

              topView[i].add(lbltitle[i]);
              topView[i].add(addPic[i]);
              expandView[i].add(lblDescription[i]);
              tblCell[i].add(expandView[i]);

               tblCell[i].add(topView[i]);
                addPic[i].addEventListener('singletap', function(e) {

                toggleExpand(e);
             });

function toggleExpand(e){

             if(expandView[e.source.rowId].visible==true){

             expandView[e.source.rowId].visible=false;

                tblCell[e.source.rowId].height=tblCell[e.source.rowId].height-(topView[e.source.rowId].height*3);
             expandView[e.source.rowId].animate({
                height:"0dp",duration:250});

           }else{
            for (var i = 0; i < tblsectionItems.length; i++) {
                if(expandView[i].visible==true){
                    expandView[i].visible=false;
                    tblCell[i].height=tblCell[i].height-(topView[i].height*3);
                    expandView[i].animate({
                    height:"0dp",duration:250});
                }}

              expandView[e.source.rowId].visible=true;

              expandView[e.source.rowId].animate({
                height:"auto",duration:250});//"auto"
              tblCell[e.source.rowId].height=tblCell[e.source.rowId].height+(topView[e.source.rowId].height*3);

           }
}

But when the row expand then i can't see my previous elements of tblcell.I can't find the reason.Please help me

Body:
I think you need to change the logic you are using to add elements in the row.
First do not use separate arrays to add each elements instead use row variable to attach elements like below..

var row = Ti.UI.createTableViewRow({});
row.topView = Ti.UI.createView({});
row.expandView = Ti.UI.createView({}); like that..

then use only 2 objects for expanView or whatever view you want to show/hide in toggleExpand function.. like

if(previousView.visible == true)
{
...
}
else{
...
}
previousView = e.row.expandView;


问:
when do you use Object.defineProperty()
I'm wondering when I should use

```<code>Object.defineProperty
</code>```

to create new properties for an object. I'm aware that I'm able to set things like

```<code>enumerable: false
</code>```

but when do you need this really? If you just set a property like

```<code>myObject.myprop = 5;
</code>```

its descriptors are all set to true, right? I'm actually more curious when you guys use that rather verbose call to .defineProperty() and for what reasons.

答:
A good use is when you need to do some interception or apply a classical Observer/Observable pattern in a elegant way:

https://www.monterail.com/blog/2016/how-to-build-a-reactive-engine-in-javascript-part-1-observable-objects

Title: when do you use Object.defineProperty()

Body:
I'm wondering when I should use

Object.defineProperty

to create new properties for an object. I'm aware that I'm able to set things like

enumerable: false

but when do you need this really? If you just set a property like

myObject.myprop = 5;

its descriptors are all set to true, right? I'm actually more curious when you guys use that rather verbose call to .defineProperty() and for what reasons.


问:
Create marker on polyline from distance
I have the following code that draws a polyline between 13 GPS coordinates.The polyline is drawn correctly. I'm trying to put a marker on the distance of 5 KM from the starting point of the polyline. I'm trying to use GetPointAtDistance() from v3_epoly but when I reference it, using

```<code> flightPath.GetPointAtDistance(5000);
</code>```

just before flightPath.setMap(map); but the polyline disappears and no new marker appears. I'm ripping my hair out about why this isn't working, any help would be much appreciated

```<code><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>VM 2</title>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry"></script>
<script type="text/javascript" src="scripts/v3_epoly.js"></script>
</head>
<body style="font-family: Arial; font-size: 12px;">

<div style="width: 100%;" id="mapDiv">
    <div id="map" style="width: 70%; height: 600px; float: left;margin:0px;color:black;"></div>
    <div id="panel" style="width: 30%; float: left;margin:0px;"></div>
</div>

<script type="text/javascript">
    var locations = [
        {
            title: "Point 1",
            lat  : -0.004259,
            lng  : 36.96367099999998,
        },
        {
            title: "Point 2",
            lat  : 0.3606,
            lng  : 36.782,
        },
        {
            title: "Point 3",
            lat  : 0.3145033,
            lng  : 36.9755982,
        },
        {
            title: "Point 4",
            lat  : 0.2336305,
            lng  : 37.3166943,
        },
        {
            title: "Point 5",
            lat  : 0.2253856,
            lng  : 37.440852,
        },
        {
            title: "Point 6",
            lat  : 0.0880828,
            lng  : 38.1899782,
        },
        {
            title: "Point 7",
            lat  : -0.2356904,
            lng  : 36.8766403,
        },
        {
            title: "Point 8",
            lat  : -0.4169027,
            lng  : 36.6666989,
        },
        {
            title: "Point 9",
            lat  : -0.3666667,
            lng  : 36.0833333,
        },
        {
            title: "Point 10",
            lat  : -1.4065513,
            lng  : 34.906551,
        },
        {
            title: "Point 11",
            lat  : -1.3666667,
            lng  : 36.8333333,
        },
        {
            title: "Point 12",
            lat  : -2.55143,
            lng  : 37.79738,
        },
        {
            title: "Point 13",
            lat  : -3.3951791,
            lng  : 37.9572584,
        },
    ];

    function initialize() {

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom     : 2,
            center   : new google.maps.LatLng(10, -10),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var infowindow = new google.maps.InfoWindow();
        var marker, i;

        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
                map     : map
            });
            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infowindow.setContent(locations[i].title);
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }

        var flightPath = new google.maps.Polyline({
            path         : locations,
            geodesic     : true,
            strokeColor  : '#5589ca',
            strokeOpacity: 1.0,
            strokeWeight : 2
        });

    var latlngex = new google.maps.LatLng(-4.0434771,39.6682065);
    var titleex = "Test Marker";
    createMarker(map,latlngex,titleex);

    flightPath.setMap(map);

    }

    function createMarker(map, latlng, title){
           var marker = new google.maps.Marker({
                  position:latlng,
                  map:map,
                  title: title,
                  icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
           });
    }

    google.maps.event.addDomListener(window, "load", initialize);

</script>
</body>
</code>```

答:
I had no luck getting v3_epoly to connect to JSfiddle.

Instead, I used the method from geocodezips implementation and added the function locally:

```<code> GetPointAtDistance = function(metres) {
    // some awkward special cases
    if (metres == 0) return flightPath.getPath().getAt(0);
    if (metres < 0) return null;
    if (flightPath.getPath().getLength() < 2) return null;
    var dist = 0;
    var olddist = 0;
    for (var i = 1;
      (i < flightPath.getPath().getLength() && dist < metres); i++) {
      olddist = dist;
      dist += google.maps.geometry.spherical.computeDistanceBetween(
        flightPath.getPath().getAt(i),
        flightPath.getPath().getAt(i - 1)
      );
    }
    if (dist < metres) {
      return null;
    }
    var p1 = flightPath.getPath().getAt(i - 2);
    var p2 = flightPath.getPath().getAt(i - 1);
    var m = (metres - olddist) / (dist - olddist);
    return new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m);
  }
</code>```

and called it using the following:

```<code>createMarker(map, GetPointAtDistance(30000), titleex);
</code>```

And the green marker will appear.

I made some other slight altercation, here is JsFiddle : https://jsfiddle.net/cmjcs5eL/19/

Title: Create marker on polyline from distance

Body:
I have the following code that draws a polyline between 13 GPS coordinates.The polyline is drawn correctly. I'm trying to put a marker on the distance of 5 KM from the starting point of the polyline. I'm trying to use GetPointAtDistance() from v3_epoly but when I reference it, using

 flightPath.GetPointAtDistance(5000);

just before flightPath.setMap(map); but the polyline disappears and no new marker appears. I'm ripping my hair out about why this isn't working, any help would be much appreciated

<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>VM 2</title>

Body:
I had no luck getting v3_epoly to connect to JSfiddle.

Instead, I used the method from geocodezips implementation and added the function locally:

 GetPointAtDistance = function(metres) {
    // some awkward special cases
    if (metres == 0) return flightPath.getPath().getAt(0);
    if (metres < 0) return null;
    if (flightPath.getPath().getLength() < 2) return null;
    var dist = 0;
    var olddist = 0;
    for (var i = 1;
      (i < flightPath.getPath().getLength() && dist < metres); i++) {
      olddist = dist;
      dist += google.maps.geometry.spherical.computeDistanceBetween(
        flightPath.getPath().getAt(i),
        flightPath.getPath().getAt(i - 1)
      );
    }
    if (dist < metres) {
      return null;
    }
    var p1 = flightPath.getPath().getAt(i - 2);
    var p2 = flightPath.getPath().getAt(i - 1);
    var m = (metres - olddist) / (dist - olddist);
    return new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m);
  }

and called it using the following:

createMarker(map, GetPointAtDistance(30000), titleex);

And the green marker will appear.

I made some other slight altercation, here is JsFiddle : https://jsfiddle.net/cmjcs5eL/19/


问:
json arrays of object with quotaions mark
I am trying to send an json object to my apiController :

myJson Object that I construct dynamicaly like this :

```<code>var course= new Object();
course.info= $scope.info;
course.studentList = [];
course.studentList = $scope.results;
</code>```

$scope.results is an array that I get from my view :

```<code><select  ng-model="results[$index]" >
    <option value=""></option>
    <option ng-repeat="r in myList" value={{r}}>{{r.studlastname}}</option>
</select>
</code>```

what I expect :

```<code>{
"course": {
     "courseName":"yyy",
     "courseDesc":"xxxx",
     "prof":"prof1"
},
"studentList" :[
    {"studfirstname":"2","studlastname":"","studAge":"21"},
    {"studfirstname":"4","studlastname":"","studAge":"40"},
    {"studfirstname":"6","studlastname":"","studAge":"60"}
]
}
</code>```

what  I have :

```<code>{
"course": {
     "courseName":"yyy",
     "courseDesc":"xxxx",
     "prof":"prof1"
},
"studentList" :[
    "{"studfirstname":"2","studlastname":"","studAge":"21"}",
    "{"studfirstname":"4","studlastname":"","studAge":"40"}",
    "{"studfirstname":"6","studlastname":"","studAge":"60"}"
]
}
</code>```

notice the quotations on every studentList element, this is causing deserialization problem on server side.

please can you help me to remove the quotations ?

thank you in advance.

答:
I found an easy solution :

```<code>let objectArray = $scope.results.map((each)=>{return JSON.parse(each)});
course.studentsList = objectArray;
</code>```

this solved my problem.

Body:
I am trying to send an json object to my apiController :

myJson Object that I construct dynamicaly like this :

var course= new Object();
course.info= $scope.info;
course.studentList = [];
course.studentList = $scope.results;

$scope.results is an array that I get from my view :

<select  ng-model="results[$index]" >
    <option value=""></option>
    <option ng-repeat="r in myList" value={{r}}>{{r.studlastname}}</option>
</select>

what I expect :

{
"course": {
     "courseName":"yyy",
     "courseDesc":"xxxx",
     "prof":"prof1"
},
"studentList" :[
    {"studfirstname":"2","studlastname":"","studAge":"21"},
    {"studfirstname":"4","studlastname":"","studAge":"40"},
    {"studfirstname":"6","studlastname":"","studAge":"60"}
]
}

what  I have :

{
"course": {
     "courseName":"yyy",
     "courseDesc":"xxxx",
     "prof":"prof1"
},
"studentList" :[
    "{"studfirstname":"2","studlastname":"","studAge":"21"}",
    "{"studfirstname":"4","studlastname":"","studAge":"40"}",
    "{"studfirstname":"6","studlastname":"","studAge":"60"}"
]
}

notice the quotations on every studentList element, this is causing deserialization problem on server side.

please can you help me to remove the quotations ?

thank you in advance.

Body:
I found an easy solution :

let objectArray = $scope.results.map((each)=>{return JSON.parse(each)});
course.studentsList = objectArray;

this solved my problem.


问:
Python - 'call' a class
If I have a class, is there anyway to catch the event of calling it as if it were a function?

```<code>obj = ExampleClass()
obj() -- and error occurs because I am 'calling' a class instance
</code>```

I would like to handle this event inside the actual class definition.

答:
You can define a __call__ method on your class.

```<code>class ExampleClass(object):
    def __call__(self):
        # do whatever you want here!
</code>```

Title: Python - 'call' a class

Body:
If I have a class, is there anyway to catch the event of calling it as if it were a function?

obj = ExampleClass()
obj() -- and error occurs because I am 'calling' a class instance

I would like to handle this event inside the actual class definition.

Body:
You can define a __call__ method on your class.

class ExampleClass(object):
    def __call__(self):
        # do whatever you want here!


问:
Using node.js and wget, wait for the download to end
I am using wget to download some images, but sometimes the image does not download entirely (it starts at the top, and then stop abruptly...)
Here is my code :

```<code>try {
  var img = fs.readFileSync(pathFile);
}
catch (err) {
  // Download image
  console.log('download')
  wget({
    url: reqUrl,
    dest: pathFile,
    timeout : 100000
  }, function (error, response, body) {

    if (error) {
      console.log('--- error:');
      console.log(error);            // error encountered
    } else {
      console.log('--- headers:');
      console.log(response); // response headers
      console.log('--- body:');
      //console.log(body);             // content of package
      var img = fs.readFileSync(pathFile);
</code>```

and so on...

basically, it tries to find the file located at pathFile, and if he does not exist, I download it on my server with wget. But it seems that wget launch the callback before finishing the download...

Thank you!

答:
It seems that you are possibly responding to some requests but you're using blocking function calls (those with "Sync" in their name). I'm not sure if you realize but that is blocking your entire process for the duration of that operation and will completely ruin any chance for concurrency if you ever need it.

Today you can use async/await in Node that looks synchronous but doesn't block your code at all. For example using request-promise and mz modules you can use:

```<code>const request = require('request-promise');
const fs = require('mz/fs');
</code>```

and now you can use:

```<code>var img = await fs.readFile(pathFile);
</code>```

which is not blocking but still lets you easily wait for the file to load before the next instruction is run.

Keep in mind that you need to use it inside of a function declared with the async keyword, e.g.:

```<code>(async () => {
  // you can use await here
})();
</code>```

You can get the file with:

```<code>const contents = await request(reqUrl);
</code>```

and you can write it with:

```<code>await fs.writeFile(name, data);
</code>```

There's no need to use blocking calls for that.

You can even use try/catch with that:

```<code>let img;
try {
  img = await fs.readFile(pathFile);
} catch (e) {
  img = await request(reqUrl);
  await fs.writeFile(pathFile, img);
}
// do something with the file contents in img
</code>```

One could even argue that you could remove the last await but you can leave it to wait for potential errors to be raised as exception on the promise rejection.

Body:
I am using wget to download some images, but sometimes the image does not download entirely (it starts at the top, and then stop abruptly...)
Here is my code :

try {
  var img = fs.readFileSync(pathFile);
}
catch (err) {
  // Download image
  console.log('download')
  wget({
    url: reqUrl,
    dest: pathFile,
    timeout : 100000
  }, function (error, response, body) {

    if (error) {
      console.log('--- error:');
      console.log(error);            // error encountered
    } else {
      console.log('--- headers:');
      console.log(response); // response headers
      console.log('--- body:');
      //console.log(body);             // content of package
      var img = fs.readFileSync(pathFile);

and so on...

basically, it tries to find the file located at pathFile, and if he does not exist, I download it on my server with wget. But it seems that wget launch the callback before finishing the download...

Thank you!

Body:
It seems that you are possibly responding to some requests but you're using blocking function calls (those with "Sync" in their name). I'm not sure if you realize but that is blocking your entire process for the duration of that operation and will completely ruin any chance for concurrency if you ever need it.

Today you can use async/await in Node that looks synchronous but doesn't block your code at all. For example using request-promise and mz modules you can use:

const request = require('request-promise');
const fs = require('mz/fs');

and now you can use:

var img = await fs.readFile(pathFile);

which is not blocking but still lets you easily wait for the file to load before the next instruction is run.

Keep in mind that you need to use it inside of a function declared with the async keyword, e.g.:

(async () => {
  // you can use await here
})();

You can get the file with:

const contents = await request(reqUrl);

and you can write it with:

await fs.writeFile(name, data);

There's no need to use blocking calls for that.

You can even use try/catch with that:

let img;
try {
  img = await fs.readFile(pathFile);
} catch (e) {
  img = await request(reqUrl);
  await fs.writeFile(pathFile, img);
}
// do something with the file contents in img

One could even argue that you could remove the last await but you can leave it to wait for potential errors to be raised as exception on the promise rejection.


问:
How to manage hardcoded (VBA) EU date formats in Access when system locality is US
This is probably a shot in the dark and a little odd but here it goes.. We use an Access 2003 application built by a 3rd party.  It's REALLY horribly written but it calculates behavior measures with tons of scientific research and validation behind it.  This means that we CANNOT modify the application whatsoever.  To be clear we have requested even SMALL changes to be made or to allow us to make and we were denied (changing s to z in wording to be more US format)... based on the grounds that the application is validated and that any change in the application would make the outcome data void per that validation.

The above is important because we CANNOT make any direct changes to any asset inside the MDB file.  Any solutions MUST be a change in the behavior of Access and not a system wide change like changing locality.  Maybe a command line switch or something.

The problem exists that this application was written in a EU country and therefore conforms to EU locality standards hard coded into the VBA.  If there were a command line switch to force EU locality on Access during a single session this would be a great solution... I cannot find one however.

This issue only exposes itself with DATES in this application.

There is an access form that is used whenever date entry is required.  It pops up and requests month by NAME, day and year each it it's own field.  For example a birth date.  Since these fields are filled in separately the VBA code then concatenates them into a date... using EU format only..  Publisher did not take locality into consideration at all. So it places DAY FIRST instead of Month as the US format does.

This is a problem because the date conversions that Microsoft uses apparently doesn't consider EU formatted dates as invalid US dates and will happily convert them..  WRONG 30% of the time.

So what occurs is that a date of May 10, 2000 becomes October 10, 2000 because the date is converted to "DD/MM/YYYY' or 5/10/2000 becomes 10/5/2000.  10/5/2000 is a valid US formatted date but it's not the date entered by the user.  MS considers this a proper date for US, since technically it is,  but does not consider this an error in our date when a number above 12 is placed into the MONTH position.  13/5/2000 is not invalid when MS coverts it.. since there are only 12 months the MS algorithm apparently simply just identifies the date as EU format and converts it to US format... So, 13/5/2000 becomes May 13, 2000 even tho 13 is in a position that should be invalid for US locality but it is turned into the day of month and the 5 is turned into the Month number.  These types of dates come out correct because of this.. 5/13/2000 becomes 13/5/2000 but MS converts it back to 5/13/2000 however 5/10/2000 becomes 10/5/2000 and MS does NOT convert it back to 5/10/2000.

Hope you've followed that so far.

So, as I said, I need a solution that does not involve changing the application (forms, queries, vba or anything else because legally and scientifically we cannot) and does not involve changing system settings like locality.  Any solution needs to affect access only and also only affect it during the use of this single database ... ie: command line switch.

答:
Date values carries no format - but:

It pops up and requests month by NAME, day and year each it it's own
  field.

and - assuming month is a combobox returning the month number - these are used to build the date like:

```<code>EnteredDate = DateSerial(Me!Year.Value, Me!Month.Value, Me!Day.Value)
</code>```

the date will be correct.

So the application probably uses some phony string to date handling; if this is the case, and you cannot alter the form and the method, there is nothing to do.

This is trivial stuff, so you should address the issue to the developer.

Body:
Date values carries no format - but:

It pops up and requests month by NAME, day and year each it it's own
  field.

and - assuming month is a combobox returning the month number - these are used to build the date like:

EnteredDate = DateSerial(Me!Year.Value, Me!Month.Value, Me!Day.Value)

the date will be correct.

So the application probably uses some phony string to date handling; if this is the case, and you cannot alter the form and the method, there is nothing to do.

This is trivial stuff, so you should address the issue to the developer.


问:
Django: get_absolute_url not working
In Django, I want to display a detailed view of model objects by using the get_absolute_url method as described here.

The URL structure for each detail is something like this...

```<code>url.com/company/(?P< company_id >[0-9]+)/people/(?P< slug >[0-9]+)/$
</code>```

where .../people/ is the list view and the .../people/slug/ is the detail for each object

Which returns the NoReverseMatch error like so

NoReverseMatch at /company/google/people/

as I put the href='{{ people.get_absolute_url }}' in my template.

Does anybody know if using the 'company_id' kwarg in the URL is causing problems rendering the page with the get_absolute_url href for the 'slug' kwarg?

I've done this many times before with a hardcoded URL before the kwarg variable which worked; such as 'company/people/(?P< slug >[0-9]+)/$' - note there's only one keyword

Full Error:

Reverse for 'people-detail' with arguments '()' and keyword arguments
  '{u'slug': u'798224891221678'}' not found. 1 pattern(s) tried:
  ['company/(?P< company_id >[0-9]+)/people/(?P< slug >[0-9]+)/$']

get_absolute_url method:

```<code>def get_absolute_url(self):
        return reverse('people-detail', kwargs={'slug': self.slug})
</code>```

答:
If your url pattern people-detail contains a named group company_id, then you must include that when you try to reverse it. For example, if your model has a foreign key to the Company model, then you might be able to do:

```<code>def get_absolute_url(self):
    return reverse('people-detail', kwargs={'slug': self.slug, 'company_id': self.company_id})
</code>```

Title: Django: get_absolute_url not working

Body:
In Django, I want to display a detailed view of model objects by using the get_absolute_url method as described here.

The URL structure for each detail is something like this...

url.com/company/(?P< company_id >[0-9]+)/people/(?P< slug >[0-9]+)/$

where .../people/ is the list view and the .../people/slug/ is the detail for each object

Which returns the NoReverseMatch error like so

NoReverseMatch at /company/google/people/

as I put the href='{{ people.get_absolute_url }}' in my template.

Does anybody know if using the 'company_id' kwarg in the URL is causing problems rendering the page with the get_absolute_url href for the 'slug' kwarg?

I've done this many times before with a hardcoded URL before the kwarg variable which worked; such as 'company/people/(?P< slug >[0-9]+)/$' - note there's only one keyword

Full Error:

Reverse for 'people-detail' with arguments '()' and keyword arguments
  '{u'slug': u'798224891221678'}' not found. 1 pattern(s) tried:
  ['company/(?P< company_id >[0-9]+)/people/(?P< slug >[0-9]+)/$']

get_absolute_url method:

def get_absolute_url(self):
        return reverse('people-detail', kwargs={'slug': self.slug})

Body:
If your url pattern people-detail contains a named group company_id, then you must include that when you try to reverse it. For example, if your model has a foreign key to the Company model, then you might be able to do:

def get_absolute_url(self):
    return reverse('people-detail', kwargs={'slug': self.slug, 'company_id': self.company_id})


问:
OSGI bundle (or service)- how to register for a given time period?
Search did not give me a hint, how can i behave with the following situation:

I'd love to have 2 OSGI implementations of the same interface: one is regular, the other should work (be active/present/whatever) on the given time period (f.e for Christmas weeks :))

The main goal is to call the same interface without specifying any flags/properties/without manual switching of ranking. Application should somehow switch implementation for this special period, doing another/regular job before and after :)

I'm a newbie, maybe i do not completely understand OSGI concept somewhere, sorry for that of give me a hint or link, sorry for my English.

Using Felix/Equinox with Apache Aries.

答:
I don't believe there is any framework support for what you are asking for.

If you are intent on avoiding service filters, you might try this.

Implement a PolicyService.  This service is in charge of deciding which instance of your service should be registered at a given point in time.  When its time for the policy service to switch implementations, it just uses the register/unregister apis as usual.  You policy service implementation can read in a config file that specifies the date range to service implementation mapping.  This will allow you to add new behavior by modifying your config file and installing a new bundle with the new service.

ContentLicense: CC BY-SA 2.5


问:
How do i make and attache action to button
Hello I have created a button on my Odoo 10 form "SET geprint" now i want to attach an action to the button. If i press the button the value of the boolean geprint must change to 1. How can I make this possible?

If possible i would also like to create that button in the list view to update multiple records.
Thx for your help

I tried your code but i am getting the following error now
(name field to update is x_geprint)
button code :

答:
Make a server action (settings - > technical - > Server actions)

After that search for the action number in your link please see image (my number is 638)

Then go to the form where you want to add the button. In my example its stock.move

Go into edit formview and add the following code

```<code><button name="638" string=" Set geprint" type="action" />
</code>```

Body:
Make a server action (settings - > technical - > Server actions)

After that search for the action number in your link please see image (my number is 638)

Then go to the form where you want to add the button. In my example its stock.move

Go into edit formview and add the following code

<button name="638" string=" Set geprint" type="action" />


问:
Making the side nav push content to the right when open (JQuery)
I've been trying to make my page contents be pushed to the right by 300px (the width of the side nav) when it is opened, as in this github repo here.

I have contained all the content to be pushed in a div #content.

However for some reason this is not impacting here:

```<code>function openNav() {
  document.getElementById("Therightnav").style.width = "300px";
  document.getElementById("content").style.marginRight = "300px";
}

function closeNav() {
  document.getElementById("Therightnav").style.width = "0";
  document.getElementById("content").style.marginRight = "50px";
}
</code>```

Any help would be appreciated.

答:
Try This Code,</p>

```<code>function openNav() {
  document.getElementById("Therightnav").style.width = "300px";
  document.getElementById("footer_container").style.marginRight = "300px";
  var x = document.getElementsByClassName("slideshow-container");
  x[0].style.marginRight = "300px";
}

function closeNav() {
  document.getElementById("Therightnav").style.width = "0";
  document.getElementById("footer_container").style.marginRight = "50px";
var x =   document.getElementsByClassName("slideshow-container");
  x[0].style.marginRight = "50px";
}
</code>```

Body:
I've been trying to make my page contents be pushed to the right by 300px (the width of the side nav) when it is opened, as in this github repo here.

I have contained all the content to be pushed in a div #content.

However for some reason this is not impacting here:

function openNav() {
  document.getElementById("Therightnav").style.width = "300px";
  document.getElementById("content").style.marginRight = "300px";
}

function closeNav() {
  document.getElementById("Therightnav").style.width = "0";
  document.getElementById("content").style.marginRight = "50px";
}

Any help would be appreciated.

Body:
Try This Code,

function openNav() {
  document.getElementById("Therightnav").style.width = "300px";
  document.getElementById("footer_container").style.marginRight = "300px";
  var x = document.getElementsByClassName("slideshow-container");
  x[0].style.marginRight = "300px";
}

function closeNav() {
  document.getElementById("Therightnav").style.width = "0";
  document.getElementById("footer_container").style.marginRight = "50px";
var x =   document.getElementsByClassName("slideshow-container");
  x[0].style.marginRight = "50px";
}


问:
What are the units of wavelet?
I'm using the continuous wavelet transform on EEG data (originally in micoVolt) as follows:

```<code>coef, freqs = pywt.cwt(EEG_data, np.arange(0.5, 50, 0.5),'morl',
sampling_period=sampling_period)
</code>```

I know that the freqs's unit is Hz. What about coef?

答:
your coef are the transform has said here. There is no unity it's a ratio of frequencies.

But I think what you need is to understand what a wavelet transform do :

In some way it's a generalization of the Fourier transform which will transform the Time-Amplitude space in a Time-Frequency space.

A wavelet transform will represent your signal as a pondered sum of your original wave translated and/or dilated

you can read about here or here

Title: What are the units of wavelet?

Body:
I'm using the continuous wavelet transform on EEG data (originally in micoVolt) as follows:

coef, freqs = pywt.cwt(EEG_data, np.arange(0.5, 50, 0.5),'morl',
sampling_period=sampling_period)

I know that the freqs's unit is Hz. What about coef?


问:
getline error, reading every line
```<code>#include <iostream>
#include <cstdlib>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;

int main() {
  char input;

  while (true) {
    input = _getch();
    cout << "The input is: " << input << "\n";
  }
  ifstream level1;

  level1.open("level1.txt");

  string str[255];
  while (true) {
    getline(level1 , str );
    cout << str;
  }

   system("PAUSE");
}
</code>```

error im getting:

no no instance of overloaded function "getline" matches the argument list

what im trying to do is real every line inside the text file

答:
The error you are getting says no instance of overloaded function "getline" matches the argument list.

If you look at getline prototype you'll see istream& getline (istream& is, string& str); that getline expects a string&, not a string[255]& which is what you are sending it.

Either change your call to getline(level1 , str[0] ); or change the declaration of string to string str;

Title: getline error, reading every line

Body:
#include <iostream>
#include <cstdlib>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;

int main() {
  char input;

  while (true) {
    input = _getch();
    cout << "The input is: " << input << "\n";
  }
  ifstream level1;

  level1.open("level1.txt");

  string str[255];
  while (true) {
    getline(level1 , str );
    cout << str;
  }

   system("PAUSE");
}

error im getting:

no no instance of overloaded function "getline" matches the argument list

what im trying to do is real every line inside the text file


问:
Qml QtQuickControls2, change style properties at runtime
I should set property of Material style at runtime, for example to change theme value (light/dark) when the user click on a defined button.
I have configured Material style with qtquickcontrols2.conf and its properties (theme, accent and primary). I can't import QtQuick.Controls.Materials 2.0 because I don't know, but I'm working on Ubuntu with QtCreator 4.0.2 and the QtQuick.Controls.Materials and QtQuick.Controls.Universal imports are not detected.
My goal is simply change theme of material style from light to dark and viceversa on runtime. How can I integrate this feature? Thanks in advice.

Best Regards
Daniele

答:
I can't import QtQuick.Controls.Materials 2.0 because I don't know, but I'm working on Ubuntu with QtCreator 4.0.2 and the QtQuick.Controls.Materials and QtQuick.Controls.Universal imports are not detected.

You need at least Qt 5.7.0 in order to have the Qt Quick Controls 2.0 import available.

My goal is simply change theme of material style from light to dark and viceversa on runtime.

You switch the theme at runtime like this:

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Controls.Material 2.0

ApplicationWindow {
    id: window
    width: 200
    height: 200
    visible: true

    Material.theme: themeSwitch.checked ? Material.Dark : Material.Light

    Switch {
        id: themeSwitch
        text: "Dark"
        anchors.centerIn: parent
    }
}
</code>```

Body:
I can't import QtQuick.Controls.Materials 2.0 because I don't know, but I'm working on Ubuntu with QtCreator 4.0.2 and the QtQuick.Controls.Materials and QtQuick.Controls.Universal imports are not detected.

You need at least Qt 5.7.0 in order to have the Qt Quick Controls 2.0 import available.

My goal is simply change theme of material style from light to dark and viceversa on runtime.

You switch the theme at runtime like this:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Controls.Material 2.0

ApplicationWindow {
    id: window
    width: 200
    height: 200
    visible: true

    Material.theme: themeSwitch.checked ? Material.Dark : Material.Light

    Switch {
        id: themeSwitch
        text: "Dark"
        anchors.centerIn: parent
    }
}


问:
Idea PyCharm database tool returns same result for MySql
Using PyCharm database tool for a mysql database over SSH tunnel.

I simply select * from table_x however database tool returns the same result (even after insertions/updates to the table). I double checked all the cache options, all off.

I tried different queries such as select ... from table_x where id > ... on the same table but result doesn't change.

I also tried select SQL_NO_CACHE * from table_x but no luck.

Other tools work ok that's why rather it looks like a bug or what is it at all?

答:
If the Data Source works not in Auto-commit mode (for the Data Source it is controlled by Auto-commit check box in General connection settings) the transaction must be manually committed for the changes to be visible in other transactions.

Since 2017.2.X version new way of controlling transactions was added to make such things more obvious.


问:
Remove/change Matching Brackets Highlight in VSCode
The default matching brackets/parentheses highlight is too intrusive/bold for my liking and compare to Atom.
I can't find a way to disable it or change.
Is there CSS somewhere or an extension?
PS: This is for VSCode not Visual Studio.</p>

答:
preferences -> settings and add this line in settings.json file

editor.matchBrackets": false


问:
AccessibilityNodeInfo Incompatible Types
I have this code here below and I keep getting incompatible types, could someone explain to me how to fix this? Required is AccessibilityNodeInfo, but it finds charSequence.</p>

```<code> public static String getAppType(AccessibilityNodeInfo source)
{
    if (source == null) {
        return "";
    }

    source = source.getPackageName();  <<~~~~ This line is the problem

    if (source == null) {
        return "";
    }
    return source.toString();
}
</code>```

答:
source is already defined as the type AccessibilityNodeInfo, it cannot be reassigned as a String. You need to create a new local variable,

```<code>public static String getAppType(AccessibilityNodeInfo source)
{
    if (source == null) {
        return "";
    }

    String pkg = source.getPackageName().toString();

    if (pkg == null) {
        return "";
    }
    return pkg;
}
</code>```

Body:
I have this code here below and I keep getting incompatible types, could someone explain to me how to fix this? Required is AccessibilityNodeInfo, but it finds charSequence.

 public static String getAppType(AccessibilityNodeInfo source)
{
    if (source == null) {
        return "";
    }

    source = source.getPackageName();  <<~~~~ This line is the problem

    if (source == null) {
        return "";
    }
    return source.toString();
}

Body:
source is already defined as the type AccessibilityNodeInfo, it cannot be reassigned as a String. You need to create a new local variable,

public static String getAppType(AccessibilityNodeInfo source)
{
    if (source == null) {
        return "";
    }

    String pkg = source.getPackageName().toString();

    if (pkg == null) {
        return "";
    }
    return pkg;
}


问:
Cosmos DB Not Respecting Json.Net CamelCaseNamingStrategy in Query
I am creating a repository for Cosmos DB in .Net, and to be DRY and avoid decorating each class property with [JsonProperty(PropertyName = "thePropertyName")], I have decorated my classes with     [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))].

CreateDocumentAsync (for example) correctly serializes my Cosmos DB documents in JSON, using camel case names of the properties. So far so good.

My issue, however, is that when I query Cosmos DB via LINQ the SQL it generates to query COSMOS DB does not respect the [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] attribute decorating the class, and therefore no documents are returned. This is because Cosmos DB queries are case sensitive with respect to field/property names. For example, the following yield different results (note the case difference on Name):

```<code>SELECT * FROM c WHERE c.name = "Health"
</code>```

vs.

```<code>SELECT * FROM c WHERE c.Name = "Health"
</code>```

I have confirmed this by checking the query SQL generated by CreateDocumentQuery, and have looked for options that may allow me to indicate casing of property names in SqlQuerySpec with no success.

So, my question is: Does anyone know how to have a LINQ query in Cosmos Db use the class defined camel casing strategy and not have to set each and every property manually via [JsonProperty(PropertyName = "thePropertyName")].

Thank you all in advance for any assistance.

答:
Currently not possible. See https://stackoverflow.com/a/37490316/37421

I find setting it via property quite risky, and a bugfest.

Body:
I am creating a repository for Cosmos DB in .Net, and to be DRY and avoid decorating each class property with [JsonProperty(PropertyName = "thePropertyName")], I have decorated my classes with     [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))].

CreateDocumentAsync (for example) correctly serializes my Cosmos DB documents in JSON, using camel case names of the properties. So far so good.

My issue, however, is that when I query Cosmos DB via LINQ the SQL it generates to query COSMOS DB does not respect the [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] attribute decorating the class, and therefore no documents are returned. This is because Cosmos DB queries are case sensitive with respect to field/property names. For example, the following yield different results (note the case difference on Name):

SELECT * FROM c WHERE c.name = "Health"

vs.

SELECT * FROM c WHERE c.Name = "Health"

I have confirmed this by checking the query SQL generated by CreateDocumentQuery, and have looked for options that may allow me to indicate casing of property names in SqlQuerySpec with no success.

So, my question is: Does anyone know how to have a LINQ query in Cosmos Db use the class defined camel casing strategy and not have to set each and every property manually via [JsonProperty(PropertyName = "thePropertyName")].

Thank you all in advance for any assistance.


问:
SerializationPolicy error when performing RPC from within GWT application
I'm getting the following exception:

com.google.gwt.user.client.rpc.SerializationException: Type 'java.lang.Long' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized

using GWT 2.1 and the built in Jetty server. According to the docs, this type is definitely serializable... How can I include it in the SerializationPolicy?

答:
Make sure that the class is in shared folder.
This is what I was Missing.</p>


问:
Remove prompt when leaving site (Wordpress)
Hey so I've been asked to fix an issue on this wordpress site (www.thetailife.com).

Whenever the user is trying to leave the page a prompt pops up asking them if they're sure they want to leave. I need to get rid of it so I've browsed this site and came across the code

```<code>window.onbeforeunload = null;
</code>```

but that doesn't help at all. Any suggestions? Thanks!

Update: It's been fixed!

答:
try putting this at the very very end of your theme (footer)
so that this is the last js code... right before the end of  tag.

```<code><script>
    window.onbeforeunload = null;
</script>
</body>
</html>
</code>```

a better solution is scan through your theme code / plugin and remove the actual code that was used to generate this prompt in the first place.

Body:
Hey so I've been asked to fix an issue on this wordpress site (www.thetailife.com).

Whenever the user is trying to leave the page a prompt pops up asking them if they're sure they want to leave. I need to get rid of it so I've browsed this site and came across the code

window.onbeforeunload = null;

but that doesn't help at all. Any suggestions? Thanks!

Update: It's been fixed!

Body:
try putting this at the very very end of your theme (footer)
so that this is the last js code... right before the end of  tag.

<script>
    window.onbeforeunload = null;
</script>
</body>
</html>

a better solution is scan through your theme code / plugin and remove the actual code that was used to generate this prompt in the first place.


问:
Automating vmrun with PowerShell
I have a PowerShell 2.0 script that I use to clone a target vmware workstation guest using vmrun in a windows host environment.
The code to clone a virtual machine executes correctly.

I am now trying to expand on this script to automate more of the process, for example, to check to see if a virtual machine is running, vmrun list, and to stop the virtual machine, vmrun stop [pathToVMXfile] if running.

With a windows command prompt, when I run vmrun list, it returns the following:

Total running VMs: 2

  D:\[path]\[name].vmx

  E:\[path]\[name].vmx

When I attempt the following in PowerShell, nothing returns. Here is what I have attempted so far. I am expecting an array to return with the values I see when I run from a command prompt.

```<code>$vmwareRun = "C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe"

#Original test, also tried with single quotes and no quotes,
#also tried quoting the -filePath
Start-Process $vmwareRun -ArgumentList "list"

#This gives a handle to the process but no return value
$myProcess = Start-Process $vmwareRun -ArgumentList "list" -PassThru

#$t is empty
Start-Process $vmwareRun -ArgumentList "list" -OutVariable $t

#$t is empty, clone command requires the -T ws parameters
Start-Process $vmwareRun -ArgumentList "-T ws list" -OutVariable $t

#RedirectStandardOutput creates a file with the expected output, $t is empty
Start-Process -FilePath "$vmwareRun" -ArgumentList $argList -OutVariable $t -RedirectStandardError "C:\testError.log" -RedirectStandardOutput C:\testOut.log"
</code>```

No matter what I attempt, I do not get any output. What am I missing?
Note: Vmrun command line documentation is found here: "https://www.vmware.com/support/developer/vix-api/vix112_vmrun_command.pdf"

Thanks.

答:
I found a similar post here: Capturing standard out and error with Start-Process

For whatever reason the powershell solution doesn't send results of the process to the -OutVariable as I expected.

So instead I followed the steps on the page indicated to create a new $pinfo = New-Object System.Diagnostics.ProcessStartInfo.
I set the corresponding properties and then started the process using System.Diagnostics.Process and it allows me to output the results to a string variable.

Title: Automating vmrun with PowerShell

Body:
I have a PowerShell 2.0 script that I use to clone a target vmware workstation guest using vmrun in a windows host environment.
The code to clone a virtual machine executes correctly.

I am now trying to expand on this script to automate more of the process, for example, to check to see if a virtual machine is running, vmrun list, and to stop the virtual machine, vmrun stop [pathToVMXfile] if running.

With a windows command prompt, when I run vmrun list, it returns the following:

Total running VMs: 2

  D:\[path]\[name].vmx

  E:\[path]\[name].vmx

When I attempt the following in PowerShell, nothing returns. Here is what I have attempted so far. I am expecting an array to return with the values I see when I run from a command prompt.

$vmwareRun = "C:\Program Files (x86)\VMware\VMware Workstation\vmrun.exe"

#Original test, also tried with single quotes and no quotes,
#also tried quoting the -filePath
Start-Process $vmwareRun -ArgumentList "list"

#This gives a handle to the process but no return value
$myProcess = Start-Process $vmwareRun -ArgumentList "list" -PassThru

#$t is empty
Start-Process $vmwareRun -ArgumentList "list" -OutVariable $t

#$t is empty, clone command requires the -T ws parameters
Start-Process $vmwareRun -ArgumentList "-T ws list" -OutVariable $t

#RedirectStandardOutput creates a file with the expected output, $t is empty
Start-Process -FilePath "$vmwareRun" -ArgumentList $argList -OutVariable $t -RedirectStandardError "C:\testError.log" -RedirectStandardOutput C:\testOut.log"

No matter what I attempt, I do not get any output. What am I missing?
Note: Vmrun command line documentation is found here: "https://www.vmware.com/support/developer/vix-api/vix112_vmrun_command.pdf"

Thanks.


问:
Linq extract a count() value from a data object
I have divAssignments that has potential multiple rows by rNI, an official id, according to a compound key of Indictment and booking numbers.

```<code>rNI    Booking  Indictment
12345  954445   10 12345
12345  954445   10 12346
12345  954445   10 12347
</code>```

So ID has a count of 3 for a single booking number for this rni.

I get lost attempting to generate a count and a group by booking Number:

```<code>var moreThen = from dA in divAssignments
    select new { dA.rNI, IndictmentCount = dA.indictmentNumber.Count() };
</code>```

Most of the examples are dealing with static int[] and don't seem to work in my case.

How do I get a group and then a count?  If I could put in a having that would be fantastic.

from a t-sql POV I'd use this:

```<code>Select rni, bookingNumber, count(*) IndictmentCount
from divAssignments
group by rni, bookingNumber
having count(*) > 0
</code>```

TIA

答:
Using Method syntax (much easier to read in my opinion):

First group the records, then select a new result for each group that contains the count.

```<code>var groups = divAssignments.GroupBy(d => new { d.rNI, d.Booking });
groups.Select(g=> new { g.Key.rNI, g.Key.Booking, IndictmentCount = g.Count() });
</code>```

Body:
I have divAssignments that has potential multiple rows by rNI, an official id, according to a compound key of Indictment and booking numbers.

rNI    Booking  Indictment
12345  954445   10 12345
12345  954445   10 12346
12345  954445   10 12347

So ID has a count of 3 for a single booking number for this rni.

I get lost attempting to generate a count and a group by booking Number:

var moreThen = from dA in divAssignments
    select new { dA.rNI, IndictmentCount = dA.indictmentNumber.Count() };

Most of the examples are dealing with static int[] and don't seem to work in my case.

How do I get a group and then a count?  If I could put in a having that would be fantastic.

from a t-sql POV I'd use this:

Select rni, bookingNumber, count(*) IndictmentCount
from divAssignments
group by rni, bookingNumber
having count(*) > 0

TIA

Body:
Using Method syntax (much easier to read in my opinion):

First group the records, then select a new result for each group that contains the count.

var groups = divAssignments.GroupBy(d => new { d.rNI, d.Booking });
groups.Select(g=> new { g.Key.rNI, g.Key.Booking, IndictmentCount = g.Count() });