问:
Why are these FactoryGirl factory instances not being created to pass this index test?
I am trying to test presence of all model objects in an index view, index renders just fine with manual in browser use, so the problem must be with with my FactoryGirl factory and or the way I'm passing arguments into the FactoryGirl.create method, though research fails to reveal to me what exactly I'm doing wrong, any ideas? Thanks

quotes.rb

```<code>FactoryGirl.define do
  factory :quote do
    prev_cover true
    sequence(:co_name) { |n| "Acme Co #{n}" }
    co_number 9999
    postcode "al1 1aa"
    industry :financial_services
    lives_overseas true
    scheme_start_date "2018-01-01"
    payment_frequency :monthly
    commission_level 12
    gla 1

    factory :quote2 do
    end

    factory :quote3 do
    end
  end
end
</code>```

quotes_page_spec.rb

```<code>    require 'rails_helper'

feature 'index page' do
    let(:user) { FactoryGirl.create(:user) }
    let(:quote) { FactoryGirl.create(:quote, user: user, co_name: "Co1") }
    let(:quote2) { FactoryGirl.create(:quote, user: user, co_name: "Co2") }
    let(:quote3) { FactoryGirl.create(:quote, user: user, co_name: "Co3") }

    before do
        login_as(user, :scope => :user)
    end

    scenario 'when user view all their quotes' do
        visit("/quotes")
        expect(page).to have_content("Co1")
        expect(page).to have_content("Co2")
        expect(page).to have_content("Co3")
    end
</code>```

This is the failure message i get;

```<code> 1) index page when user view all their quotes
 Failure/Error: expect(page).to have_content("Co1")
   expected to find text "Co1" in "Toggle navigation QuoteEngine My Quotes My Account Sign out"
 # ./spec/features/quotes_page_spec.rb:15:in `block (2 levels) in <top (required)>'
</code>```

答:
Error was that I was not actually creating the multiple quotes by declaring them as lets. Moved the quotes that I want to be created into a before block and all is well, as below:

```<code>let(:user) { FactoryGirl.create(:user) }

before do
    login_as(user, :scope => :user)
    FactoryGirl.create(:quote, user: user, co_name: "Co1")
    FactoryGirl.create(:quote, user: user, co_name: "Co2")
    FactoryGirl.create(:quote, user: user, co_name: "Co3")
end
</code>```

Body:
I am trying to test presence of all model objects in an index view, index renders just fine with manual in browser use, so the problem must be with with my FactoryGirl factory and or the way I'm passing arguments into the FactoryGirl.create method, though research fails to reveal to me what exactly I'm doing wrong, any ideas? Thanks

quotes.rb

FactoryGirl.define do
  factory :quote do
    prev_cover true
    sequence(:co_name) { |n| "Acme Co #{n}" }
    co_number 9999
    postcode "al1 1aa"
    industry :financial_services
    lives_overseas true
    scheme_start_date "2018-01-01"
    payment_frequency :monthly
    commission_level 12
    gla 1

    factory :quote2 do
    end

    factory :quote3 do
    end
  end
end

quotes_page_spec.rb

    require 'rails_helper'

feature 'index page' do
    let(:user) { FactoryGirl.create(:user) }
    let(:quote) { FactoryGirl.create(:quote, user: user, co_name: "Co1") }
    let(:quote2) { FactoryGirl.create(:quote, user: user, co_name: "Co2") }
    let(:quote3) { FactoryGirl.create(:quote, user: user, co_name: "Co3") }

    before do
        login_as(user, :scope => :user)
    end

    scenario 'when user view all their quotes' do
        visit("/quotes")
        expect(page).to have_content("Co1")
        expect(page).to have_content("Co2")
        expect(page).to have_content("Co3")
    end

This is the failure message i get;

 1) index page when user view all their quotes
 Failure/Error: expect(page).to have_content("Co1")
   expected to find text "Co1" in "Toggle navigation QuoteEngine My Quotes My Account Sign out"
 # ./spec/features/quotes_page_spec.rb:15:in `block (2 levels) in <top (required)>'

Body:
Error was that I was not actually creating the multiple quotes by declaring them as lets. Moved the quotes that I want to be created into a before block and all is well, as below:

let(:user) { FactoryGirl.create(:user) }

before do
    login_as(user, :scope => :user)
    FactoryGirl.create(:quote, user: user, co_name: "Co1")
    FactoryGirl.create(:quote, user: user, co_name: "Co2")
    FactoryGirl.create(:quote, user: user, co_name: "Co3")
end


来源: stackexchange

问:
who do you prefer ObjectSet or CreateQuery in EF 4?
i have been coding below. But i find another method secand part . which one is more preferable than other. what is the differece? whic one has more performance than other?

```<code>public T Single(Func<T, bool> predicate)
{
    return _context.CreateQuery<T>("[" + typeof(T).Name + "]").Where(predicate).Single();
}
</code>```

ANOTHER USAGE

```<code>public T Single(Func<T, bool> predicate)
{
    return _objectSet.Single<T>(predicate);
}
</code>```

which one is more prefer than other?

答: I would prefer using IObjectSet since you can create a fake that implements IObjectSet<TEntity> for unit testing.  For a discussion of this, see this thread and this post.

ContentLicense: CC BY-SA 2.5

Body:
i have been coding below. But i find another method secand part . which one is more preferable than other. what is the differece? whic one has more performance than other?

public T Single(Func<T, bool> predicate)
{
    return _context.CreateQuery<T>("[" + typeof(T).Name + "]").Where(predicate).Single();
}

ANOTHER USAGE

public T Single(Func<T, bool> predicate)
{
    return _objectSet.Single<T>(predicate);
}

which one is more prefer than other?


问:
React Native initial database
I want to develop a React Native app, and I want to have locally stored some data of the format:

```<code>[
  {
    "id": 1,
    "text": "Lorem ipsum",
    "viewed": false
  },
  {
    "id": 2,
    "text": "Second lorem",
    "viewed": false
  },
  {
    "id": 3,
    "text": "Last lorem",
    "viewed": false
  }
]
</code>```

I want this data to be available when the user first downloads the app. Then based on the user's navigation, the corresponding data in the db will change the viewed flag to true. This has to be persistent when the app will be updated by the user on the next version.

Any tips/ideas on how to achieve this?

Currently I'm looking into Realm.io but I'm not sure if this is the right tool for me.

答:
You can use AsyncStorage for that like so:

```<code>const data = [
  {
    "id": 1,
    "text": "Lorem ipsum",
    "viewed": false
  },
  {
    "id": 2,
    "text": "Second lorem",
    "viewed": false
  },
  {
    "id": 3,
    "text": "Last lorem",
    "viewed": false
  }
]

try {
  await AsyncStorage.setItem(
    'SOME_KEY', JSON.stringify(data)
  );
} catch (error) {
  // Handle error
}
</code>```

Later on if you want to fetch/change you can do:

```<code>AsyncStorage.getItem('SOME_KEY', (err, result) => {
  console.log(JOSN.parse(result));
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: React Native initial database

Body:
I want to develop a React Native app, and I want to have locally stored some data of the format:

[
  {
    "id": 1,
    "text": "Lorem ipsum",
    "viewed": false
  },
  {
    "id": 2,
    "text": "Second lorem",
    "viewed": false
  },
  {
    "id": 3,
    "text": "Last lorem",
    "viewed": false
  }
]

I want this data to be available when the user first downloads the app. Then based on the user's navigation, the corresponding data in the db will change the viewed flag to true. This has to be persistent when the app will be updated by the user on the next version.

Any tips/ideas on how to achieve this?

Currently I'm looking into Realm.io but I'm not sure if this is the right tool for me.

Body:
You can use AsyncStorage for that like so:

const data = [
  {
    "id": 1,
    "text": "Lorem ipsum",
    "viewed": false
  },
  {
    "id": 2,
    "text": "Second lorem",
    "viewed": false
  },
  {
    "id": 3,
    "text": "Last lorem",
    "viewed": false
  }
]

try {
  await AsyncStorage.setItem(
    'SOME_KEY', JSON.stringify(data)
  );
} catch (error) {
  // Handle error
}

Later on if you want to fetch/change you can do:

AsyncStorage.getItem('SOME_KEY', (err, result) => {
  console.log(JOSN.parse(result));
});


问:
Why does BindingResult have to follow @Valid?
I was struggling to get my Spring MVC validation to return to the page submitted page when I had errors. I finally solved the problem by noticing that BindingResult needs to be next to form parameter I'm validating.

For example if I amend the checkPersonInfo method in the spring.io tutorial(http://spring.io/guides/gs/validating-form-input/) to -

```<code>@RequestMapping(value="/", method=RequestMethod.POST)
public String checkPersonInfo(@Valid Person person, BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors()) {
        return "form";
    }
    return "redirect:/results";
}
</code>```

Then it will work and redirect to the form page, but if I change it to -

```<code>@RequestMapping(value="/", method=RequestMethod.POST)
public String checkPersonInfo(@Valid Person person, Model model, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "form";
    }
    return "redirect:/results";
}
</code>```

Then it redirects to /errors

What is the cause of this?

答:
Yeah, Today I took a long time to check why cannot back to the submitted page but goes to a default whitelable error page.

After debugging got the source code

```<code>// org.springframework.web.method.annotation.ModelAttributeMethodProcessor#resolveArgument
if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
    throw new BindException(binder.getBindingResult());
}
</code>```

if BindingResult does not follow @Valid , causes isBindExceptionRequired(binder, parameter) return true and then directly throw exception so cannot execute code in controller method.

```<code>// org.springframework.web.method.annotation.ModelAttributeMethodProcessor#isBindExceptionRequired
protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter methodParam) {
    int i = methodParam.getParameterIndex();
    Class<?>[] paramTypes = methodParam.getMethod().getParameterTypes();
    boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1]));
    return !hasBindingResult;
}
</code>```

Body:
I was struggling to get my Spring MVC validation to return to the page submitted page when I had errors. I finally solved the problem by noticing that BindingResult needs to be next to form parameter I'm validating.

For example if I amend the checkPersonInfo method in the spring.io tutorial(http://spring.io/guides/gs/validating-form-input/) to -

@RequestMapping(value="/", method=RequestMethod.POST)
public String checkPersonInfo(@Valid Person person, BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors()) {
        return "form";
    }
    return "redirect:/results";
}

Then it will work and redirect to the form page, but if I change it to -

@RequestMapping(value="/", method=RequestMethod.POST)
public String checkPersonInfo(@Valid Person person, Model model, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "form";
    }
    return "redirect:/results";
}

Then it redirects to /errors

What is the cause of this?

Body:
Yeah, Today I took a long time to check why cannot back to the submitted page but goes to a default whitelable error page.

After debugging got the source code

// org.springframework.web.method.annotation.ModelAttributeMethodProcessor#resolveArgument
if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
    throw new BindException(binder.getBindingResult());
}

if BindingResult does not follow @Valid , causes isBindExceptionRequired(binder, parameter) return true and then directly throw exception so cannot execute code in controller method.

// org.springframework.web.method.annotation.ModelAttributeMethodProcessor#isBindExceptionRequired
protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter methodParam) {
    int i = methodParam.getParameterIndex();
    Class<?>[] paramTypes = methodParam.getMethod().getParameterTypes();
    boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1]));
    return !hasBindingResult;
}


问:
FTPClient with append functionality
i want to upload files to FTP server from Android application . i am using ftp4j.jar for this as it has the append function to append to file which is already on server . It was working fine before but now it has stopped working appending file .Rest is working . I don't know what is the issue . I did't find any other substitute for ftp4j .</p>

答:
You can try Apache Commons Net FTPClient appendFile() methods as scai mentioned in the comments. I'm not sure how it works in Android.

https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#appendFile(java.lang.String,%20java.io.InputStream)

Title: FTPClient with append functionality


问:
Is it possible to get current travel time in traffic for a precise route with Google Maps API?
I've had success getting current travel time from location A to location B with API calls -- for example doing something like this:

https://maps.googleapis.com/maps/api/distancematrix/xml?units=imperial&traffic_model=best_guess&departure_time=now&origins=San+Bernardino,CA&destinations=Irvine,CA&key=xx

But what I'm wondering is if it's possible to make the same call pegged to a specific route. i.e. When Google gives you three options from A to B in the web interface, and you pick one, i.e. like this:

https://www.google.com/maps/dir/new+york+ny/brooklyn+ny/@40.6954797,-73.9936332,14z/data=!4m15!4m14!1m5!1m1!1s0x89c24fa5d33f083b:0xc80b8f06e177fe62!2m2!1d-74.0059413!2d40.7127837!1m5!1m1!1s0x89c24416947c2109:0x82765c7404007886!2m2!1d-73.9441579!2d40.6781784!3e0!5i1

It gives it a unique data tag (the string beginning with "!4m"). I'm wondering if it's possible to specify that data tag in an API call.

Any thoughts? Much appreciated.

答: The Google Maps Directions API allows you to set waypoints for your route and it also gives you the duration in traffic. If you set enough waypoints, you'll probably get the same route in the response of the API.</p>


问:
Why does calling GetDlgItem cause an access violation?
I am trying to access one of my MFC view's dialog elements. To do this, I run the following line of code:

```<code>    ((CButton*)GetDlgItem( IDC_RADIO_VIEW2 ))->SetCheck( 0 );
</code>```

This causes the following exception:

Exception thrown at 0x53072844 (mfc140ud.dll) in NameOfMyApplication.exe: 0xC0000005: Access violation reading location 0x00000020.

What's strange about this is that the line above it does not cause an access violation, despite being basically the same thing. The line above it is:

```<code>    ((CButton*)GetDlgItem( IDC_RADIO_VIEW1 ))->SetCheck( 1 );
</code>```

Does anyone know why this is happening?

答:
There is no control with ID IDC_RADIO_VIEW2 as an immediate child of the dialog where you are calling the code.

The line of code that doesn't fail references a control with ID IDC_RADIO_VIEW1. It stands to reason, that the dialog has an immediate child window with ID IDC_RADIO_VIEW1.

I'm sure, that calling ((CButton*)GetDlgItem( IDC_RADIO_VIEW999 ))->SetCheck( 1 ); will exhibit a totally different error, although being "basically the same thing". You really need to learn, how computers work. Code doesn't work because it is similar to other working code (for some definition of "similar").

Body:
I am trying to access one of my MFC view's dialog elements. To do this, I run the following line of code:

    ((CButton*)GetDlgItem( IDC_RADIO_VIEW2 ))->SetCheck( 0 );

This causes the following exception:

Exception thrown at 0x53072844 (mfc140ud.dll) in NameOfMyApplication.exe: 0xC0000005: Access violation reading location 0x00000020.

What's strange about this is that the line above it does not cause an access violation, despite being basically the same thing. The line above it is:

    ((CButton*)GetDlgItem( IDC_RADIO_VIEW1 ))->SetCheck( 1 );

Does anyone know why this is happening?


问:
Conditional Compilation and Objective-C/Xcode
So I am working on a learning project and I am trying to create a header file that contains a store of URL's so that you can just change a single flag to change from Debug to Production.  This is what I am trying to do with the compiler and it is clearly wrong.  I can't find any information on how to do this in Objective-C, so that's why I came here.

```<code>#define DEBUG 1
#if DEBUG
  NSString *URL = @"dev.myserver.com";
#else
  NSString *URL = @"myserver.com";
#endif

@interface GlobalURLRefrences : NSObject {
  //NSString *URL; removed this
}

//@property (nonatomic, retain) NSString *URL; removed this

@end
</code>```

Now I am not sure if I need to declare that as a property or not.  Also, once this is compiled properly, how to I access it from an outside class (of course after you #import the globalURL's class)  Any sort of guidance on the proper method of doing this would be greatly appreciated.

答:
Geoff: I have a need for this kind of conditional in my Mac App Store app for validating receipts, and I do it with a separate build configuration and a -D flag. In Debug configuration, add a compiler flag something like -DDEBUG_BUILD (Note the double D at the beginning and no space.) and then use

```<code>#ifdef DEBUG_BUILD
    #define SERVER_URL_STRING @"http://dev.myserver.com"
#else
    #define SERVER_URL_STRING @"http://myserver.com"
#endif
</code>```

This way, you don't have to remember to swap that #define each time you build for production. (You'll forget eventually. Everyone has.) -If you do it this way, then you don't need the @property or the ivar declaration either.- Just saw you took these out already.

Body:
So I am working on a learning project and I am trying to create a header file that contains a store of URL's so that you can just change a single flag to change from Debug to Production.  This is what I am trying to do with the compiler and it is clearly wrong.  I can't find any information on how to do this in Objective-C, so that's why I came here.

#define DEBUG 1
#if DEBUG
  NSString *URL = @"dev.myserver.com";
#else
  NSString *URL = @"myserver.com";
#endif

@interface GlobalURLRefrences : NSObject {
  //NSString *URL; removed this
}

//@property (nonatomic, retain) NSString *URL; removed this

@end

Now I am not sure if I need to declare that as a property or not.  Also, once this is compiled properly, how to I access it from an outside class (of course after you #import the globalURL's class)  Any sort of guidance on the proper method of doing this would be greatly appreciated.

Body:
Geoff: I have a need for this kind of conditional in my Mac App Store app for validating receipts, and I do it with a separate build configuration and a -D flag. In Debug configuration, add a compiler flag something like -DDEBUG_BUILD (Note the double D at the beginning and no space.) and then use

#ifdef DEBUG_BUILD
    #define SERVER_URL_STRING @"http://dev.myserver.com"
#else
    #define SERVER_URL_STRING @"http://myserver.com"
#endif

This way, you don't have to remember to swap that #define each time you build for production. (You'll forget eventually. Everyone has.) -If you do it this way, then you don't need the @property or the ivar declaration either.- Just saw you took these out already.


问:
Running docker container in Jenkins container, How can I set the volume from host?
I'm running a container with jenkins using "docker outside of docker". My docker compose is:

```<code>---
version: '2'
services:
  jenkins-master:
    build:
      context: .
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /dev/urandom:/dev/random
      - /home/jj/jenkins/jenkins_home/:/var/jenkins_home
    ports:
      - "8080:8080"
</code>```

So all containers launched from "jenkins container" are running in host machine.

But when I try to run docker-compose in "jenkins container" in a job thats needs a volume, it takes the path from host instead of jenkins. I mean, when I run docker-compose with

```<code>volumes:
  - .:/app
</code>```

It is mounted in /var/jenkins_home/workspace/JOB_NAME in the host but I want that it is mounted in /home/jj/jenkins/jenkins_home/workspace/JOB_NAME

Any idea for doing this with a "clean" mode?

P.D.: I did a workaround using environments variables.

答:
Docker on the host will map the path as is from the request, and docker-compose will make the request with the path it sees inside the container. This leaves you with a few options:

Don't use host volumes in your builds. If you need volumes, you can use named volumes and use docker io to read in and out of those volumes. That would look like:
tar -cC data . | docker run -i --rm -v app-data:/target busybox /bin/sh -c "tar -xC /target". You'd reverse the docker/tar commands to pull data back out.

Make the path on the host match that of the container. On your host, if you have access to make a symlink in var, you can ln -s /home/jj/jenkins/jenkins_home /var/jenkins_home and then update your compose file to have the same path (you may need to specify /var/jenkins_home/. to follow the symlink).

Make the path of the container match that of the host. This may be the easiest option, but I'm not positive it would work (depends on where compose thinks it's running). Your Dockerfile for the jenkins master can include the following:

RUN mkdir -p /home/jj/jenkins \
 && ln -s /var/jenkins_home /home/jj/jenkins/jenkins_home
ENV JENKINS_HOME /home/jj/jenkins/jenkins_home

If the easy option doesn't work, you can rebuild the image from jenkins and change the JENKINS_HOME variable to match your environment.

Make your compose paths absolute. You can add some code to set a variable:
export CUR_DIR=$(pwd | sed 's#/var/jenkins_home#/home/jj/jenkins/jenkins_home#'). Then you can set your volume with that variable:

volumes:
  - ${CUR_DIR:-.}:/app

Body:
I'm running a container with jenkins using "docker outside of docker". My docker compose is:

---
version: '2'
services:
  jenkins-master:
    build:
      context: .
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /dev/urandom:/dev/random
      - /home/jj/jenkins/jenkins_home/:/var/jenkins_home
    ports:
      - "8080:8080"

So all containers launched from "jenkins container" are running in host machine.

But when I try to run docker-compose in "jenkins container" in a job thats needs a volume, it takes the path from host instead of jenkins. I mean, when I run docker-compose with

volumes:
  - .:/app

It is mounted in /var/jenkins_home/workspace/JOB_NAME in the host but I want that it is mounted in /home/jj/jenkins/jenkins_home/workspace/JOB_NAME

Any idea for doing this with a "clean" mode?

P.D.: I did a workaround using environments variables.


问:
Modifying to.period to include "semi-annual"
I would like to calculate semi-annual aggregations of an xts object. I thought I could use to.period, but the output is still an xts with 4 data points per year whereas I would like only two.

```<code>data(edhec, package="PerformanceAnalytics")
xts::to.period(edhec[,1],period="quarters",k=2,OHLC=FALSE)
</code>```

I would like to modify this to.period function to include a semi-annual output. Any suggestions? The code is a little too complex for me. I think it must have something to do with endpoints which is a second function in the xts package.

```<code>function (x, period = "months", k = 1, indexAt = NULL, name = NULL,
OHLC = TRUE, ...)
{
    if (missing(name))
        name <- deparse(substitute(x))
    xo <- x
    x <- try.xts(x)
    if (NROW(x) == 0 || NCOL(x) == 0)
        stop(sQuote("x"), " contains no data")
    if (any(is.na(x))) {
        x <- na.omit(x)
        warning("missing values removed from data")
    }
    if (!OHLC) {
        xx <- x[endpoints(x, period, k), ]
    }
    else {
        if (!is.null(indexAt)) {
            index_at <- switch(indexAt, startof = TRUE, endof = FALSE,
                FALSE)
        }
        else index_at <- FALSE
        cnames <- c("Open", "High", "Low", "Close")
        if (has.Vo(x))
            cnames <- c(cnames, "Volume")
        if (has.Ad(x) && is.OHLC(x))
            cnames <- c(cnames, "Adjusted")
        cnames <- paste(name, cnames, sep = ".")
        if (is.null(name))
            cnames <- NULL
        xx <- .Call("toPeriod", x, endpoints(x, period, k), has.Vo(x),
            has.Vo(x, which = TRUE), has.Ad(x) && is.OHLC(x),
            index_at, cnames, PACKAGE = "xts")
    }
    if (!is.null(indexAt)) {
        if (indexAt == "yearmon" || indexAt == "yearqtr")
            indexClass(xx) <- indexAt
        if (indexAt == "firstof") {
            ix <- as.POSIXlt(c(.index(xx)), tz = indexTZ(xx))
            if (period %in% c("years", "months", "quarters",
                "days"))
                index(xx) <- firstof(ix$year + 1900, ix$mon +
                  1)
            else index(xx) <- firstof(ix$year + 1900, ix$mon +
                1, ix$mday, ix$hour, ix$min, ix$sec)
        }
        if (indexAt == "lastof") {
        ix <- as.POSIXlt(c(.index(xx)), tz = indexTZ(xx))
            if (period %in% c("years", "months", "quarters",
                "days"))
                index(xx) <- as.Date(lastof(ix$year + 1900, ix$mon +
                  1))
            else index(xx) <- lastof(ix$year + 1900, ix$mon +
                1, ix$mday, ix$hour, ix$min, ix$sec)
        }
    }
    reclass(xx, xo)
}
</code>```

答:
This looks like a bug in xts::endpoints(). In the case of period = "months" and k > 1, endpoints() makes this adjustment:

```<code>if (k > 1) ep[seq(1, length(ep), k)] else ep
</code>```

And to.period() with OHLC = FALSE just subsets the input object by the output of endpoints().  So it is equivalent to:

```<code>data(edhec, package="PerformanceAnalytics")
ep <- endpoints(edhec[,1], "quarters", 2)
edhec[ep, 2]
</code>```

See if the fix for this bug is as simple as adding the same adjustment as when period = "months":

```<code>data(edhec, package="PerformanceAnalytics")
ep <- endpoints(edhec[,1], "quarters", 1)
ep <- ep[seq(1, length(ep), 2)]
edhec[ep, 2]
</code>```

Body:
I would like to calculate semi-annual aggregations of an xts object. I thought I could use to.period, but the output is still an xts with 4 data points per year whereas I would like only two.

data(edhec, package="PerformanceAnalytics")
xts::to.period(edhec[,1],period="quarters",k=2,OHLC=FALSE)

I would like to modify this to.period function to include a semi-annual output. Any suggestions? The code is a little too complex for me. I think it must have something to do with endpoints which is a second function in the xts package.

function (x, period = "months", k = 1, indexAt = NULL, name = NULL,
OHLC = TRUE, ...)
{
    if (missing(name))
        name <- deparse(substitute(x))
    xo <- x
    x <- try.xts(x)
    if (NROW(x) == 0 || NCOL(x) == 0)
        stop(sQuote("x"), " contains no data")
    if (any(is.na(x))) {
        x <- na.omit(x)
        warning("missing values removed from data")
    }
    if (!OHLC) {
        xx <- x[endpoints(x, period, k), ]
    }
    else {
        if (!is.null(indexAt)) {
            index_at <- switch(indexAt, startof = TRUE, endof = FALSE,
                FALSE)
        }
        else index_at <- FALSE
        cnames <- c("Open", "High", "Low", "Close")
        if (has.Vo(x))
            cnames <- c(cnames, "Volume")
        if (has.Ad(x) && is.OHLC(x))
            cnames <- c(cnames, "Adjusted")
        cnames <- paste(name, cnames, sep = ".")
        if (is.null(name))
            cnames <- NULL
        xx <- .Call("toPeriod", x, endpoints(x, period, k), has.Vo(x),
            has.Vo(x, which = TRUE), has.Ad(x) && is.OHLC(x),
            index_at, cnames, PACKAGE = "xts")
    }
    if (!is.null(indexAt)) {
        if (indexAt == "yearmon" || indexAt == "yearqtr")
            indexClass(xx) <- indexAt
        if (indexAt == "firstof") {
            ix <- as.POSIXlt(c(.index(xx)), tz = indexTZ(xx))
            if (period %in% c("years", "months", "quarters",
                "days"))
                index(xx) <- firstof(ix$year + 1900, ix$mon +
                  1)
            else index(xx) <- firstof(ix$year + 1900, ix$mon +
                1, ix$mday, ix$hour, ix$min, ix$sec)
        }
        if (indexAt == "lastof") {
        ix <- as.POSIXlt(c(.index(xx)), tz = indexTZ(xx))
            if (period %in% c("years", "months", "quarters",
                "days"))
                index(xx) <- as.Date(lastof(ix$year + 1900, ix$mon +
                  1))
            else index(xx) <- lastof(ix$year + 1900, ix$mon +
                1, ix$mday, ix$hour, ix$min, ix$sec)
        }
    }
    reclass(xx, xo)
}

Body:
This looks like a bug in xts::endpoints(). In the case of period = "months" and k > 1, endpoints() makes this adjustment:

if (k > 1) ep[seq(1, length(ep), k)] else ep

And to.period() with OHLC = FALSE just subsets the input object by the output of endpoints().  So it is equivalent to:

data(edhec, package="PerformanceAnalytics")
ep <- endpoints(edhec[,1], "quarters", 2)
edhec[ep, 2]

See if the fix for this bug is as simple as adding the same adjustment as when period = "months":

data(edhec, package="PerformanceAnalytics")
ep <- endpoints(edhec[,1], "quarters", 1)
ep <- ep[seq(1, length(ep), 2)]
edhec[ep, 2]


问:
Find string in list within list of objects
I have a list of objects with lists:

```<code>ls = [
    {'id': 1, 'content': ['lorem', 'ipsum']},
    {'id': 1, 'content': ['dolor', 'sit', 'amet']},
]
</code>```

i want to get the index of the object with e.g. 'lorem'

So far i tried:

```<code>'lorem' in [x['content'] for x in ls]
</code>```

This does not return true nor does it return an index.

答:
I would do:

```<code> >>> tgt='ipsum'
 >>> [(x, di['content'].index(tgt)) for x, di in enumerate(ls) if tgt in di['content']]
 [(0, 1)]
 >>> tgt='amet'
 >>> [(x, di['content'].index(tgt)) for x, di in enumerate(ls) if tgt in di['content']]
 [(1, 2)]
</code>```

This assumes that a dict with ['content'] is inside the list of dicts.

Body:
I have a list of objects with lists:

ls = [
    {'id': 1, 'content': ['lorem', 'ipsum']},
    {'id': 1, 'content': ['dolor', 'sit', 'amet']},
]

i want to get the index of the object with e.g. 'lorem'

So far i tried:

'lorem' in [x['content'] for x in ls]

This does not return true nor does it return an index.

Body:
I would do:

 >>> tgt='ipsum'
 >>> [(x, di['content'].index(tgt)) for x, di in enumerate(ls) if tgt in di['content']]
 [(0, 1)]
 >>> tgt='amet'
 >>> [(x, di['content'].index(tgt)) for x, di in enumerate(ls) if tgt in di['content']]
 [(1, 2)]

This assumes that a dict with ['content'] is inside the list of dicts.


问:
NodeJS Mocha Chai - Unit Test Socket Emit After Chai Request To Node Event
I have an application which dynamically updates the client side data whenever there comes data update on the server side. I am using AngularJS as front end and NodJS as the relay server. So when there is data update happens another application of someone else would post the data to my NodeJS server, which will be handled by a NodeJS route API (eg: route.post(/send)). For the testing purpose, I am using REST CLIENT for sending data to this API, and these all are working fine too.

When I do unit testing this route(/send) I should confirm whether there happens an event emit to the front end or not when I post a valid data to the node route right?. I am using mocha chai for unit test purpose. I could send the post request to the above-mentioned API using chai.request() method.But how can I verify whether API emitted the data to the client or not?.Below is my sample code and I think it is self-explanatory.

Issue facing is: This piece of code is working, and which is the proof of the success of the event being called.

```<code> `server.on('gotData',function(){
     console.log('event emitted');
     assert(true);
     done();
   });`
</code>```

Node Code:

```<code>router.post('/send', jsonParser, function (req, res) {
      //some logic here
      io.to(socketId).emit('gotData', data);
});
</code>```

Client side

```<code>var socket = io.connect(serverUrl);
socket.on('gotData', function(data){
      console.log('Data got in client side');
});
</code>```

Test Suite:

```<code>it('should be sent event to client-side when valid object has provided', function (done) {
   chai.request(server)
                .post('/send')
                .set({'Content-Type':'application/json'})
                .send(data);

   var socket;
   socket = io.connect(server);
   socket.on('gotData',function(){
     console.log('event emitted'); // not get firing after chai request
     assert(true);
     done();
   });
});
</code>```

答:
I'm not really sure what you are asking, but your tests can become more focused if they ignore the event plumbing and router plumbing and focus on the logic of your test.  If you audit your router, and io framework and both have tests to reasonably verify that event emissions work then you could isolate your specific logic and only exercise it:

```<code>router.post('/send', jsonParser, function (req, res) {
      //some logic here
      io.to(socketId).emit('gotData', data);
});
</code>```

could become:

```<code>function yourSendHandler(req, res, ioModule) {
   // allow for user passed in ioModule, if not present use global
   var io = ioModule || io;
   //some logic here
   io.to(socketId).emit('gotData', data);
}
router.post('/send', jsonParser, yourSendHandler);
</code>```

Now, if you export your handler, your test can import and exercise yourSendHandler directly, without having to worry about events, you could provide a mock io in your unit test and assert on its calls.

Having your function defined anonymously in the router couples it tightly to the router and doesn't allow for easy isolation or testing.

Body:
I have an application which dynamically updates the client side data whenever there comes data update on the server side. I am using AngularJS as front end and NodJS as the relay server. So when there is data update happens another application of someone else would post the data to my NodeJS server, which will be handled by a NodeJS route API (eg: route.post(/send)). For the testing purpose, I am using REST CLIENT for sending data to this API, and these all are working fine too.

When I do unit testing this route(/send) I should confirm whether there happens an event emit to the front end or not when I post a valid data to the node route right?. I am using mocha chai for unit test purpose. I could send the post request to the above-mentioned API using chai.request() method.But how can I verify whether API emitted the data to the client or not?.Below is my sample code and I think it is self-explanatory.

Issue facing is: This piece of code is working, and which is the proof of the success of the event being called.

 `server.on('gotData',function(){
     console.log('event emitted');
     assert(true);
     done();
   });`

Node Code:

router.post('/send', jsonParser, function (req, res) {
      //some logic here
      io.to(socketId).emit('gotData', data);
});

Client side

var socket = io.connect(serverUrl);
socket.on('gotData', function(data){
      console.log('Data got in client side');
});

Test Suite:

it('should be sent event to client-side when valid object has provided', function (done) {
   chai.request(server)
                .post('/send')
                .set({'Content-Type':'application/json'})
                .send(data);

   var socket;
   socket = io.connect(server);
   socket.on('gotData',function(){
     console.log('event emitted'); // not get firing after chai request
     assert(true);
     done();
   });
});

Body:
I'm not really sure what you are asking, but your tests can become more focused if they ignore the event plumbing and router plumbing and focus on the logic of your test.  If you audit your router, and io framework and both have tests to reasonably verify that event emissions work then you could isolate your specific logic and only exercise it:

router.post('/send', jsonParser, function (req, res) {
      //some logic here
      io.to(socketId).emit('gotData', data);
});

could become:

function yourSendHandler(req, res, ioModule) {
   // allow for user passed in ioModule, if not present use global
   var io = ioModule || io;
   //some logic here
   io.to(socketId).emit('gotData', data);
}
router.post('/send', jsonParser, yourSendHandler);

Now, if you export your handler, your test can import and exercise yourSendHandler directly, without having to worry about events, you could provide a mock io in your unit test and assert on its calls.

Having your function defined anonymously in the router couples it tightly to the router and doesn't allow for easy isolation or testing.


问:
How to get the key in Collectors.toMap merge function?
When a duplicate key entry is found during Collectors.toMap(), the merge function (o1, o2) is called.

Question: how can I get the key that caused the duplication?

```<code>String keyvalp = "test=one\ntest2=two\ntest2=three";

Pattern.compile("\n")
    .splitAsStream(keyval)
    .map(entry -> entry.split("="))
    .collect(Collectors.toMap(
        split -> split[0],
        split -> split[1],
        (o1, o2) -> {
            //TODO how to access the key that caused the duplicate? o1 and o2 are the values only
            //split[0]; //which is the key, cannot be accessed here
        },
    HashMap::new));
</code>```

Inside the merge function I want to decide based on the key which if I cancel the mapping, or continue and take on of those values.

答:
The merge function has no chance to get the key, which is the same issue, the builtin function has, when you omit the merge function.

The solution is to use a different toMap implementation, which does not rely on Map.merge:

```<code>public static <T, K, V> Collector<T, ?, Map<K,V>>
    toMap(Function<? super T, ? extends K> keyMapper,
          Function<? super T, ? extends V> valueMapper) {
    return Collector.of(HashMap::new,
        (m, t) -> {
            K k = keyMapper.apply(t);
            V v = Objects.requireNonNull(valueMapper.apply(t));
            if(m.putIfAbsent(k, v) != null) throw duplicateKey(k, m.get(k), v);
        },
        (m1, m2) -> {
            m2.forEach((k,v) -> {
                if(m1.putIfAbsent(k, v)!=null) throw duplicateKey(k, m1.get(k), v);
            });
            return m1;
        });
}
private static IllegalStateException duplicateKey(Object k, Object v1, Object v2) {
    return new IllegalStateException("Duplicate key "+k+" (values "+v1+" and "+v2+')');
}
</code>```

(This is basically what Java 9’s implementation of toMap without a merge function will do)

So all you need to do in your code, is to redirect the toMap call and omit the merge function:

```<code>String keyvalp = "test=one\ntest2=two\ntest2=three";

Map<String, String> map = Pattern.compile("\n")
        .splitAsStream(keyvalp)
        .map(entry -> entry.split("="))
        .collect(toMap(split -> split[0], split -> split[1]));
</code>```

(or ContainingClass.toMap if its neither in the same class nor static imports)<\sup>

The collector supports parallel processing like the original toMap collector, though it’s not very likely to get a benefit from parallel processing here, even with more elements to process.

If, if I get you correctly, you only want to pick either, the older or newer value, in the merge function based on the actual key, you could do it with a key Predicate like this

```<code>public static <T, K, V> Collector<T, ?, Map<K,V>>
    toMap(Function<? super T, ? extends K> keyMapper,
          Function<? super T, ? extends V> valueMapper,
          Predicate<? super K> useOlder) {
    return Collector.of(HashMap::new,
        (m, t) -> {
            K k = keyMapper.apply(t);
            m.merge(k, valueMapper.apply(t), (a,b) -> useOlder.test(k)? a: b);
        },
        (m1, m2) -> {
            m2.forEach((k,v) -> m1.merge(k, v, (a,b) -> useOlder.test(k)? a: b));
            return m1;
        });
}
</code>```

```<code>Map<String, String> map = Pattern.compile("\n")
        .splitAsStream(keyvalp)
        .map(entry -> entry.split("="))
        .collect(toMap(split -> split[0], split -> split[1], key -> condition));
</code>```

There are several ways to customize this collector…

Body:
When a duplicate key entry is found during Collectors.toMap(), the merge function (o1, o2) is called.

Question: how can I get the key that caused the duplication?

String keyvalp = "test=one\ntest2=two\ntest2=three";

Pattern.compile("\n")
    .splitAsStream(keyval)
    .map(entry -> entry.split("="))
    .collect(Collectors.toMap(
        split -> split[0],
        split -> split[1],
        (o1, o2) -> {
            //TODO how to access the key that caused the duplicate? o1 and o2 are the values only
            //split[0]; //which is the key, cannot be accessed here
        },
    HashMap::new));

Inside the merge function I want to decide based on the key which if I cancel the mapping, or continue and take on of those values.

Body:
The merge function has no chance to get the key, which is the same issue, the builtin function has, when you omit the merge function.

The solution is to use a different toMap implementation, which does not rely on Map.merge:

public static <T, K, V> Collector<T, ?, Map<K,V>>
    toMap(Function<? super T, ? extends K> keyMapper,
          Function<? super T, ? extends V> valueMapper) {
    return Collector.of(HashMap::new,
        (m, t) -> {
            K k = keyMapper.apply(t);
            V v = Objects.requireNonNull(valueMapper.apply(t));
            if(m.putIfAbsent(k, v) != null) throw duplicateKey(k, m.get(k), v);
        },
        (m1, m2) -> {
            m2.forEach((k,v) -> {
                if(m1.putIfAbsent(k, v)!=null) throw duplicateKey(k, m1.get(k), v);
            });
            return m1;
        });
}
private static IllegalStateException duplicateKey(Object k, Object v1, Object v2) {
    return new IllegalStateException("Duplicate key "+k+" (values "+v1+" and "+v2+')');
}

(This is basically what Java 9’s implementation of toMap without a merge function will do)

So all you need to do in your code, is to redirect the toMap call and omit the merge function:

String keyvalp = "test=one\ntest2=two\ntest2=three";

Map<String, String> map = Pattern.compile("\n")
        .splitAsStream(keyvalp)
        .map(entry -> entry.split("="))
        .collect(toMap(split -> split[0], split -> split[1]));

(or ContainingClass.toMap if its neither in the same class nor static imports)<\sup>

The collector supports parallel processing like the original toMap collector, though it’s not very likely to get a benefit from parallel processing here, even with more elements to process.

If, if I get you correctly, you only want to pick either, the older or newer value, in the merge function based on the actual key, you could do it with a key Predicate like this

public static <T, K, V> Collector<T, ?, Map<K,V>>
    toMap(Function<? super T, ? extends K> keyMapper,
          Function<? super T, ? extends V> valueMapper,
          Predicate<? super K> useOlder) {
    return Collector.of(HashMap::new,
        (m, t) -> {
            K k = keyMapper.apply(t);
            m.merge(k, valueMapper.apply(t), (a,b) -> useOlder.test(k)? a: b);
        },
        (m1, m2) -> {
            m2.forEach((k,v) -> m1.merge(k, v, (a,b) -> useOlder.test(k)? a: b));
            return m1;
        });
}

Map<String, String> map = Pattern.compile("\n")
        .splitAsStream(keyvalp)
        .map(entry -> entry.split("="))
        .collect(toMap(split -> split[0], split -> split[1], key -> condition));

There are several ways to customize this collector…


问:
How to change the inputs' onchange event by name or id?
I have a snippet of HTML which is the simple version of my site. The inputs name is related to the row index. So, I am wondering how to change the inputs' onchange event using the jQuery?

For each row, it has its own function related to the row index. For example, for tr index = 0, it has the function Test1(), for tr index = 1, it has the function Test2()...

Cannot simply using the input selector, because there are some other inputs in the page. Only the id and name for the input are unique.

```<code><tr stampId = '1001' index = '0'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@0@1" id="QuickOrderQty@6@0@1" ct="Field" onchange=" SaveControlState(event,'Text');">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '1'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@1@1" id="QuickOrderQty@6@1@1" ct="Field" onchange=" SaveControlState(event,'Text');">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '2'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@2@1" id="QuickOrderQty@6@2@1" ct="Field" onchange=" SaveControlState(event,'Text');">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '3'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@3@1" id="QuickOrderQty@6@3@1" ct="Field" onchange=" SaveControlState(event,'Text');">
        </span>
    </td>
</tr>
</code>```

Well, maybe I should put my desired result here.

```<code><script>Do something here, then change the onchange events to below.</script>
<tr stampId = '1001' index = '0'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@0@1" id="QuickOrderQty@6@0@1" ct="Field" onchange="Test1();">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '1'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@1@1" id="QuickOrderQty@6@1@1" ct="Field" onchange="Test2();">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '2'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@2@1" id="QuickOrderQty@6@2@1" ct="Field" onchange="Test3();">
        </span>
    </td>
</tr>
<tr stampId = '1001' index = '3'>
    <td>
        <span>
        <input type="text" name="QuickOrderQty@6@3@1" id="QuickOrderQty@6@3@1" ct="Field" onchange="Test4();">
        </span>
    </td>
</tr>
</code>```

答:
Sorry if any mistakes occurred. This is my first time answering questions. I am not even that experienced.

if I understood you correctly, you want to know the element that caused the event to trigger. You can use the word this

```<code>$("input").change(function(event) {
    var x = $(this).val();
    // x = the value of the input element that triggered the event.
});
</code>```

I hope this helps.

Body:
I have a snippet of HTML which is the simple version of my site. The inputs name is related to the row index. So, I am wondering how to change the inputs' onchange event using the jQuery?

For each row, it has its own function related to the row index. For example, for tr index = 0, it has the function Test1(), for tr index = 1, it has the function Test2()...

Cannot simply using the input selector, because there are some other inputs in the page. Only the id and name for the input are unique.

        <input type="text" name="QuickOrderQty@6@0@1" id="QuickOrderQty@6@0@1" ct="Field" onchange=" SaveControlState(event,'Text');">

        <input type="text" name="QuickOrderQty@6@1@1" id="QuickOrderQty@6@1@1" ct="Field" onchange=" SaveControlState(event,'Text');">

        <input type="text" name="QuickOrderQty@6@2@1" id="QuickOrderQty@6@2@1" ct="Field" onchange=" SaveControlState(event,'Text');">

        <input type="text" name="QuickOrderQty@6@3@1" id="QuickOrderQty@6@3@1" ct="Field" onchange=" SaveControlState(event,'Text');">

Well, maybe I should put my desired result here.

        <input type="text" name="QuickOrderQty@6@0@1" id="QuickOrderQty@6@0@1" ct="Field" onchange="Test1();">

        <input type="text" name="QuickOrderQty@6@1@1" id="QuickOrderQty@6@1@1" ct="Field" onchange="Test2();">

        <input type="text" name="QuickOrderQty@6@2@1" id="QuickOrderQty@6@2@1" ct="Field" onchange="Test3();">

        <input type="text" name="QuickOrderQty@6@3@1" id="QuickOrderQty@6@3@1" ct="Field" onchange="Test4();">

Body:
Sorry if any mistakes occurred. This is my first time answering questions. I am not even that experienced.

if I understood you correctly, you want to know the element that caused the event to trigger. You can use the word this

$("input").change(function(event) {
    var x = $(this).val();
    // x = the value of the input element that triggered the event.
});

I hope this helps.


问:
Algorithm Analysis -- Big O Notation
What's a good strategy to determine the running time (Big O notation) of data structures and algorithms. I have the following to figure out the running times for and I'm having
trouble determining what it would be.

AINC is an array containing n integers arranged in increasing order.

AD is an array containing n integers arranged in decreasing order.

AR is an array containing n integers in random order.

Q is a queue implemented as a linked list and containing p elements.

LINK is a linked list containing n nodes.

CIRC is a circular linked list containing n elements, where C points to the last element.

T is a binary search tree containing n nodes.

a) Searching for an element in AINC using linear search.

b) Deleting the 10thnode of linked list LINK.

c) Calling a function which uses Q, and calls dequeue m times.

d) Inserting an element at the end of the list CIRC.

e) Deleting the last element of CIRC.

f) Finding the largest element of T.

g) Determining the height of T.

h) Making the call selectionsort (AINC, n).

i) Making two calls one after another. The first call is mergesort(AD,n), followed by the call insertionsort(AD,n).

j) Converting a decimal integer num into its binary equivalent.

***This is not hw. I am preparing for an exam.

答:
(Since the OP asked for it)

You pick up a piece of paper.

If your question mentions a number (e.g. repeat n times, or find the n-th last element):

You perform by hand on paper the operations needed to perform the mentioned action when that number is 1 (if applicable).

You repeat for each of the following values of that number: 2, 10, 20, 100, 1000 and 10000. Just for kicks you can also try with the actual number mentioned in the question.

You measure the time it took you for each case and then you plot on a piece of paper (oh, a spreadsheed would also do, I suppose) the function t(n), where t is the time, and n the number.

You look through your old math books to identify the curve. E.g. if it's a parabol, you most probably have an O(n^2) algorithm in your hands.

If your question does not mention a number:

Repeat the previous procedure above by using 2, 10, 20, 100, 1000 and 10000 elements in any data structure mentioned (array, list etc). If the "structure" is a number, just use that many digits.

NOTE:

If you manage to visualise the procedure above without turning half of this planet's remaining trees into paper or having your hand fall off, then you are half-way towards a semi-decent intuitive technique.

You should read up on the proper mathematical way to deal with this, though - intuition can only take you so far in this case.

Additionally, most of the examples that you mentioned are so basic that most people just memorize (and a bit later they just know) their complexities. You should really get a book or some decent notes on this. Introduction to Algorithms is a nice, big fat introductory book on this field.

EDIT:

Searching for algorithms and complexity in Google also produces a whole pile of interesting results. You should try it once in a while...

Title: Algorithm Analysis -- Big O Notation


问:
LESS: combine properties (rules) with same value
I am using LESS CSS preprocessor. For example if there are two (or more) rules with same value

```<code>.my-class {
    border-top: 2px solid @main-bg-color - #123456;
    border-bottom: 2px solid @main-bg-color - #123456;
}
</code>```

can I combine those two into one somehow like this?

```<code>.my-class {
    border-top, border-bottom: 2px solid @main-bg-color - #123456;
}
</code>```

UPDATE: You shouldn't be concentrated on the props (border) I wrote just as example. I'd like to know if there's any way to combine any multiple props with same value. If there is no way to do so, please say it explicitly.

答:
Why not just use something like:</p>

```<code>.my-class {
    border:  2px solid @main-bg-color - #123456;
    border-width: 2px 0;
}
</code>```

Body:
I am using LESS CSS preprocessor. For example if there are two (or more) rules with same value

.my-class {
    border-top: 2px solid @main-bg-color - #123456;
    border-bottom: 2px solid @main-bg-color - #123456;
}

can I combine those two into one somehow like this?

.my-class {
    border-top, border-bottom: 2px solid @main-bg-color - #123456;
}

UPDATE: You shouldn't be concentrated on the props (border) I wrote just as example. I'd like to know if there's any way to combine any multiple props with same value. If there is no way to do so, please say it explicitly.

Body:
Why not just use something like:

.my-class {
    border:  2px solid @main-bg-color - #123456;
    border-width: 2px 0;
}


问:
Error while running desktop app converter on VLC installer
I'm getting E_STARTING_ISOLATED_ENV_FAILED error while running the converter on VLC installer. I chose VLC because in one of the channel 9 videos, VLC was used as an example. I want to first try running converter on a sample exe installer before running it on an actual exe installer.

I even tried -Cleanup All and did the setup again but still the same error. Any idea how to trouble shoot and fix this issue? Below is the error message from converter :

```<code>PS C:\Program Files\WindowsApps\Microsoft.DesktopAppConverter_2.0.2.0_x64__8wekyb3d8bbwe> DesktopAppConverter.exe -Installer C:\Project\vlc\vlc-2.2.6-win32.exe -InstallerArguments  "/S /L=1033" -Destination C:\Project\MSI\Output -PackageName "VLC" -Publisher "CN=VLC" -Version 0.0.0.1 -Verbose
VERBOSE: Log file can be found in
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\logs\DesktopAppConverter.log
VERBOSE: Desktop App Converter
2.0.2.release_2017-04-20_15-32_d5d861e622cd5bd166242b726909575b22b31f27
VERBOSE: --------------------------------------------------

Checking Prerequisites

VERBOSE: Checking Windows Version to ensure it meets minimum requirements
VERBOSE: Minimum Windows Version requirement is met.
VERBOSE: Checking if Microsoft Windows 10 SDK is installed
VERBOSE: Checking Windows SDK version to ensure it meets minimum requirements.
VERBOSE: The installed Windows SDK version 10.0.15063.400 is supported
VERBOSE: Checking if MAKEAPPX.exe is available in the Microsoft Windows 10 SDK tools
VERBOSE: Checking if SIGNTOOL.exe is available in the Microsoft Windows 10 SDK tools
VERBOSE: Checking if MAKEPRI.exe is available in the Microsoft Windows 10 SDK tools
VERBOSE: Ensuring the provided Installer (C:\Project\vlc\vlc-2.2.6-win32.exe) exists
VERBOSE: Testing for required feature enabled...
VERBOSE: Target Image Version 10.0.14393.0
VERBOSE: Required feature is enabled. Checking if reboot is required
VERBOSE: Target Image Version 10.0.14393.0
VERBOSE: Required feature is enabled.
VERBOSE: Checking network config...
VERBOSE: Checking virtual network: "Windows Desktop App Converter Network"
VERBOSE: Using virtual network: "Windows Desktop App Converter Network"
VERBOSE: --------------------------------------------------

Initializing AppxManifest.xml

VERBOSE: Creating working directory structure at
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58
VERBOSE: Attempting to set appx manifest property 'Package.Identity.Name' to 'VLC'.
VERBOSE: Attempting to set appx manifest property 'Package.Identity.Publisher' to 'CN=VLC'.
VERBOSE: Attempting to set appx manifest property 'Package.Identity.Version' to '0.0.0.1'.
VERBOSE: No value provided for appx manifest property 'Package.Properties.PublisherDisplayName'.
Attempting to set it to the default value 'VLC'
VERBOSE: Attempting to set appx manifest property 'Package.Properties.PublisherDisplayName' to
'VLC'.
VERBOSE: No value provided for appx manifest property 'Package.Properties.DisplayName'. Attempting
 to set it to the default value 'VLC'
VERBOSE: Attempting to set appx manifest property 'Package.Properties.DisplayName' to 'VLC'.
VERBOSE: No value provided for appx manifest property
'Package.Applications.Application.VisualElement.Description'. Attempting to set it to the default
value 'VLC'
VERBOSE: Attempting to set appx manifest property
'Package.Applications.Application.VisualElement.Description' to 'VLC'.
VERBOSE: No value provided for appx manifest property
'Package.Applications.Application.VisualElement.DisplayName'. Attempting to set it to the default
value 'VLC'
VERBOSE: Attempting to set appx manifest property
'Package.Applications.Application.VisualElement.DisplayName' to 'VLC'.
VERBOSE: No value provided for appx manifest property 'Package.Applications.Application.Id'.
Attempting to set it to the default value 'VLC'
VERBOSE: Attempting to set appx manifest property 'Package.Applications.Application.Id' to 'VLC'.
VERBOSE: --------------------------------------------------

Validating Input

VERBOSE: Expanded base image(s) found at C:\ProgramData\Microsoft\Windows\Images. Attempting to
choose the most recent one compatible with your version of Windows.
VERBOSE: Testing if expanded base image at C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
 is compatible with your OS
VERBOSE: Your Windows version was determined to be 10.0.14393.0
VERBOSE: Attempting to determine Windows version for expanded base image at
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
VERBOSE: Attempting to determine version from version file
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json if it exists
VERBOSE: Version found in 'C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json'
is: 10.0.14393.0
VERBOSE: C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393 is of windows version
10.0.14393.0
VERBOSE: The expanded base image version was determined to be 10.0.14393.0
VERBOSE: Ignoring revision numbers
VERBOSE: Expanded base image at C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393 IS
compatible with your OS
VERBOSE: Expanded base image with compatible Windows version found:
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
VERBOSE: Using expanded base image: C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
VERBOSE: Checking that the ExpandedBaseImage
'C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393' is valid
VERBOSE: Testing if expanded base image at C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
 is compatible with your OS
VERBOSE: Your Windows version was determined to be 10.0.14393.0
VERBOSE: Attempting to determine Windows version for expanded base image at
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
VERBOSE: Attempting to determine version from version file
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json if it exists
VERBOSE: Version found in 'C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json'
is: 10.0.14393.0
VERBOSE: C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393 is of windows version
10.0.14393.0
VERBOSE: The expanded base image version was determined to be 10.0.14393.0
VERBOSE: Ignoring revision numbers
VERBOSE: Expanded base image at C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393 IS
compatible with your OS
VERBOSE: Attempting to determine Windows version for expanded base image at
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
VERBOSE: Attempting to determine version from version file
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json if it exists
VERBOSE: Version found in 'C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json'
is: 10.0.14393.0
VERBOSE: C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393 is of windows version
10.0.14393.0
VERBOSE: Ensuring the provided Installer (C:\Project\vlc\vlc-2.2.6-win32.exe) exists
VERBOSE: Ensuring the provided Installer (C:\Project\vlc\vlc-2.2.6-win32.exe) exists
VERBOSE: Checking if Destination (C:\Project\MSI\Output\VLC) exists
VERBOSE: C:\Project\MSI\Output\VLC exists
VERBOSE: C:\Project\MSI\Output\VLC exists but is not empty
VERBOSE: Moving files currently at 'C:\Project\MSI\Output\VLC' to 'C:\Project\MSI\Output\VLC.old3'
VERBOSE: Ensuring that this script has write permissions to C:\Project\MSI\Output\VLC...
VERBOSE: Checking that installer is not sibling to working directory
VERBOSE: --------------------------------------------------

Setting up Conversion Environment

VERBOSE: Copying contents of C:\Project\vlc to
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\shared\installer to be shared with
isolated environment
VERBOSE: Copying KnownFolderDump.exe and its dependencies to
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\shared\dac\bin
VERBOSE: --------------------------------------------------

Running Installer in Isolated Environment

VERBOSE: No installer valid exit codes specified. Using defaults: 0
VERBOSE: Replace any occurence of <log_folder> in -InstallerArguments with C:\shared\logs
VERBOSE: Creating Isolated Environment
VERBOSE: Starting the Isolated Environment
VERBOSE: An error occurred running your installer in isolation
VERBOSE: Disposing of the Isolated Environment
VERBOSE: Moving any logs in
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\shared\logs to
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\logs
VERBOSE: Moving any dac output in
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\shared\dac\out to
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\output\dac
VERBOSE: Cleaning up by removing isolated environment shared folder
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\shared
VERBOSE: An error occurred converting your application. Here is the full error record:
VERBOSE:

PowerShell Error Record:
DesktopAppConverter : error 'E_STARTING_ISOLATED_ENV_FAILED': Failed to start the isolated
environment. See inner exception for more details.
PowerShell Stack Trace:
at RaiseUserException, C:\Program
Files\WindowsApps\Microsoft.DesktopAppConverter_2.0.2.0_x64__8wekyb3d8bbwe\converter_util\DACLogge
r.ps1: line 154
at Invoke-IsolatedInstall, C:\Program
Files\WindowsApps\Microsoft.DesktopAppConverter_2.0.2.0_x64__8wekyb3d8bbwe\converter_util\Isolated
EnvironmentOps.ps1: line 162
at <ScriptBlock><Process>, C:\Program
Files\WindowsApps\Microsoft.DesktopAppConverter_2.0.2.0_x64__8wekyb3d8bbwe\DesktopAppConverter.ps1
: line 684
at <ScriptBlock>, <No file>: line 1

Inner Exception[0]:
System.Management.Automation.RuntimeException: DesktopAppConverter : error
'E_STARTING_ISOLATED_ENV_FAILED': Failed to start the isolated environment. See inner exception
for more details. ---> System.Management.Automation.MethodInvocationException: Exception calling
"Start" with "0" argument(s): "One or more errors occurred." ---> System.AggregateException: One
or more errors occurred. ---> Microsoft.Windows.ComputeVirtualization.HcsException: HCS function
call returned error. ---> System.Runtime.InteropServices.COMException: This operation returned
because the timeout period expired. (Exception from HRESULT: 0x800705B4)
   --- End of inner exception stack trace ---
   at Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.ProcessHcsCall(Int32 resultCode,
String result)
   at
Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.Microsoft.Windows.ComputeVirtualization.IHc
s.StartComputeSystem(IntPtr computeSystem, String options)
   at Microsoft.Windows.ComputeVirtualization.Container.<StartAsync>d__8.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken
cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at Microsoft.Windows.ComputeVirtualization.Container.Start()
   at CallSite.Target(Closure , CallSite , Object )
   --- End of inner exception stack trace ---
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext
funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame
frame)
   at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
   at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
   --- End of inner exception stack trace ---
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext
funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame
frame)
   at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
   at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
Inner Exception Stack Trace[0]
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext
funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame
frame)
   at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
   at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)

Inner Exception[1]:
System.Management.Automation.MethodInvocationException: Exception calling "Start" with "0"
argument(s): "One or more errors occurred." ---> System.AggregateException: One or more errors
occurred. ---> Microsoft.Windows.ComputeVirtualization.HcsException: HCS function call returned
error. ---> System.Runtime.InteropServices.COMException: This operation returned because the
timeout period expired. (Exception from HRESULT: 0x800705B4)
   --- End of inner exception stack trace ---
   at Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.ProcessHcsCall(Int32 resultCode,
String result)
   at
Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.Microsoft.Windows.ComputeVirtualization.IHc
s.StartComputeSystem(IntPtr computeSystem, String options)
   at Microsoft.Windows.ComputeVirtualization.Container.<StartAsync>d__8.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken
cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at Microsoft.Windows.ComputeVirtualization.Container.Start()
   at CallSite.Target(Closure , CallSite , Object )
   --- End of inner exception stack trace ---
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext
funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame
frame)
   at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
   at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
Inner Exception Stack Trace[1]
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext
funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame
frame)
   at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
   at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)

Inner Exception[2]:
System.AggregateException: One or more errors occurred. --->
Microsoft.Windows.ComputeVirtualization.HcsException: HCS function call returned error. --->
System.Runtime.InteropServices.COMException: This operation returned because the timeout period
expired. (Exception from HRESULT: 0x800705B4)
   --- End of inner exception stack trace ---
   at Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.ProcessHcsCall(Int32 resultCode,
String result)
   at
Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.Microsoft.Windows.ComputeVirtualization.IHc
s.StartComputeSystem(IntPtr computeSystem, String options)
   at Microsoft.Windows.ComputeVirtualization.Container.<StartAsync>d__8.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken
cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at Microsoft.Windows.ComputeVirtualization.Container.Start()
   at CallSite.Target(Closure , CallSite , Object )
---> (Inner Exception #0) Microsoft.Windows.ComputeVirtualization.HcsException: HCS function call
returned error. ---> System.Runtime.InteropServices.COMException: This operation returned because
the timeout period expired. (Exception from HRESULT: 0x800705B4)
   --- End of inner exception stack trace ---
   at Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.ProcessHcsCall(Int32 resultCode,
String result)
   at
Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.Microsoft.Windows.ComputeVirtualization.IHc
s.StartComputeSystem(IntPtr computeSystem, String options)
   at Microsoft.Windows.ComputeVirtualization.Container.<StartAsync>d__8.MoveNext()<---

Inner Exception Stack Trace[2]
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken
cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at Microsoft.Windows.ComputeVirtualization.Container.Start()
   at CallSite.Target(Closure , CallSite , Object )

Inner Exception[3]:
Microsoft.Windows.ComputeVirtualization.HcsException: HCS function call returned error. --->
System.Runtime.InteropServices.COMException: This operation returned because the timeout period
expired. (Exception from HRESULT: 0x800705B4)
   --- End of inner exception stack trace ---
   at Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.ProcessHcsCall(Int32 resultCode,
String result)
   at
Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.Microsoft.Windows.ComputeVirtualization.IHc
s.StartComputeSystem(IntPtr computeSystem, String options)
   at Microsoft.Windows.ComputeVirtualization.Container.<StartAsync>d__8.MoveNext()
Inner Exception Stack Trace[3]
   at Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.ProcessHcsCall(Int32 resultCode,
String result)
   at
Microsoft.Windows.ComputeVirtualization.HcsFactory.Hcs.Microsoft.Windows.ComputeVirtualization.IHc
s.StartComputeSystem(IntPtr computeSystem, String options)
   at Microsoft.Windows.ComputeVirtualization.Container.<StartAsync>d__8.MoveNext()

Inner Exception[4]:
System.Runtime.InteropServices.COMException (0x800705B4): This operation returned because the
timeout period expired. (Exception from HRESULT: 0x800705B4)
VERBOSE: The full error record is saved in the logs at
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\logs
C:\Program Files\WindowsApps\Microsoft.DesktopAppConverter_2.0.2.0_x64__8wekyb3d8bbwe\DesktopAppCo
nverter.ps1 : DesktopAppConverter : error 'E_STARTING_ISOLATED_ENV_FAILED': Failed to start the
isolated environment. See inner exception for more details.
At line:1 char:1
+ &'C:\Program Files\WindowsApps\Microsoft.DesktopAppConverter_2.0.2.0_ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,DesktopAppConvert
   er.ps1

Output Paths:

Name                           Value
----                           -----
CertPath
PackageFilesPath
PackagePath
LogFilesPath                   C:\Project\MSI\Output\VLC\logs

PS C:\Program Files\WindowsApps\Microsoft.DesktopAppConverter_2.0.2.0_x64__8wekyb3d8bbwe>
</code>```

答:
You can also try this free alternative solution built by our company, that can help you convert the application much easier.

It is much easier to use, it has a GUI (no command line), built-in support for digital signing and allows you to customize the list of files that get inside your AppX.

Also, you can generate AppX packages for applications which do not (cannot) install silently.

It runs on Windows 7 too, not just Windows 10 (recommended).

Body:
I'm getting E_STARTING_ISOLATED_ENV_FAILED error while running the converter on VLC installer. I chose VLC because in one of the channel 9 videos, VLC was used as an example. I want to first try running converter on a sample exe installer before running it on an actual exe installer.

I even tried -Cleanup All and did the setup again but still the same error. Any idea how to trouble shoot and fix this issue? Below is the error message from converter :

PS C:\Program Files\WindowsApps\Microsoft.DesktopAppConverter_2.0.2.0_x64__8wekyb3d8bbwe> DesktopAppConverter.exe -Installer C:\Project\vlc\vlc-2.2.6-win32.exe -InstallerArguments  "/S /L=1033" -Destination C:\Project\MSI\Output -PackageName "VLC" -Publisher "CN=VLC" -Version 0.0.0.1 -Verbose
VERBOSE: Log file can be found in
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\logs\DesktopAppConverter.log
VERBOSE: Desktop App Converter
2.0.2.release_2017-04-20_15-32_d5d861e622cd5bd166242b726909575b22b31f27
VERBOSE: --------------------------------------------------

Checking Prerequisites

VERBOSE: Checking Windows Version to ensure it meets minimum requirements
VERBOSE: Minimum Windows Version requirement is met.
VERBOSE: Checking if Microsoft Windows 10 SDK is installed
VERBOSE: Checking Windows SDK version to ensure it meets minimum requirements.
VERBOSE: The installed Windows SDK version 10.0.15063.400 is supported
VERBOSE: Checking if MAKEAPPX.exe is available in the Microsoft Windows 10 SDK tools
VERBOSE: Checking if SIGNTOOL.exe is available in the Microsoft Windows 10 SDK tools
VERBOSE: Checking if MAKEPRI.exe is available in the Microsoft Windows 10 SDK tools
VERBOSE: Ensuring the provided Installer (C:\Project\vlc\vlc-2.2.6-win32.exe) exists
VERBOSE: Testing for required feature enabled...
VERBOSE: Target Image Version 10.0.14393.0
VERBOSE: Required feature is enabled. Checking if reboot is required
VERBOSE: Target Image Version 10.0.14393.0
VERBOSE: Required feature is enabled.
VERBOSE: Checking network config...
VERBOSE: Checking virtual network: "Windows Desktop App Converter Network"
VERBOSE: Using virtual network: "Windows Desktop App Converter Network"
VERBOSE: --------------------------------------------------

Initializing AppxManifest.xml

VERBOSE: Creating working directory structure at
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58
VERBOSE: Attempting to set appx manifest property 'Package.Identity.Name' to 'VLC'.
VERBOSE: Attempting to set appx manifest property 'Package.Identity.Publisher' to 'CN=VLC'.
VERBOSE: Attempting to set appx manifest property 'Package.Identity.Version' to '0.0.0.1'.
VERBOSE: No value provided for appx manifest property 'Package.Properties.PublisherDisplayName'.
Attempting to set it to the default value 'VLC'
VERBOSE: Attempting to set appx manifest property 'Package.Properties.PublisherDisplayName' to
'VLC'.
VERBOSE: No value provided for appx manifest property 'Package.Properties.DisplayName'. Attempting
 to set it to the default value 'VLC'
VERBOSE: Attempting to set appx manifest property 'Package.Properties.DisplayName' to 'VLC'.
VERBOSE: No value provided for appx manifest property
'Package.Applications.Application.VisualElement.Description'. Attempting to set it to the default
value 'VLC'
VERBOSE: Attempting to set appx manifest property
'Package.Applications.Application.VisualElement.Description' to 'VLC'.
VERBOSE: No value provided for appx manifest property
'Package.Applications.Application.VisualElement.DisplayName'. Attempting to set it to the default
value 'VLC'
VERBOSE: Attempting to set appx manifest property
'Package.Applications.Application.VisualElement.DisplayName' to 'VLC'.
VERBOSE: No value provided for appx manifest property 'Package.Applications.Application.Id'.
Attempting to set it to the default value 'VLC'
VERBOSE: Attempting to set appx manifest property 'Package.Applications.Application.Id' to 'VLC'.
VERBOSE: --------------------------------------------------

Validating Input

VERBOSE: Expanded base image(s) found at C:\ProgramData\Microsoft\Windows\Images. Attempting to
choose the most recent one compatible with your version of Windows.
VERBOSE: Testing if expanded base image at C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
 is compatible with your OS
VERBOSE: Your Windows version was determined to be 10.0.14393.0
VERBOSE: Attempting to determine Windows version for expanded base image at
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
VERBOSE: Attempting to determine version from version file
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json if it exists
VERBOSE: Version found in 'C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json'
is: 10.0.14393.0
VERBOSE: C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393 is of windows version
10.0.14393.0
VERBOSE: The expanded base image version was determined to be 10.0.14393.0
VERBOSE: Ignoring revision numbers
VERBOSE: Expanded base image at C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393 IS
compatible with your OS
VERBOSE: Expanded base image with compatible Windows version found:
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
VERBOSE: Using expanded base image: C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
VERBOSE: Checking that the ExpandedBaseImage
'C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393' is valid
VERBOSE: Testing if expanded base image at C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
 is compatible with your OS
VERBOSE: Your Windows version was determined to be 10.0.14393.0
VERBOSE: Attempting to determine Windows version for expanded base image at
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
VERBOSE: Attempting to determine version from version file
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json if it exists
VERBOSE: Version found in 'C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json'
is: 10.0.14393.0
VERBOSE: C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393 is of windows version
10.0.14393.0
VERBOSE: The expanded base image version was determined to be 10.0.14393.0
VERBOSE: Ignoring revision numbers
VERBOSE: Expanded base image at C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393 IS
compatible with your OS
VERBOSE: Attempting to determine Windows version for expanded base image at
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393
VERBOSE: Attempting to determine version from version file
C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json if it exists
VERBOSE: Version found in 'C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393\version.json'
is: 10.0.14393.0
VERBOSE: C:\ProgramData\Microsoft\Windows\Images\BaseImage-14393 is of windows version
10.0.14393.0
VERBOSE: Ensuring the provided Installer (C:\Project\vlc\vlc-2.2.6-win32.exe) exists
VERBOSE: Ensuring the provided Installer (C:\Project\vlc\vlc-2.2.6-win32.exe) exists
VERBOSE: Checking if Destination (C:\Project\MSI\Output\VLC) exists
VERBOSE: C:\Project\MSI\Output\VLC exists
VERBOSE: C:\Project\MSI\Output\VLC exists but is not empty
VERBOSE: Moving files currently at 'C:\Project\MSI\Output\VLC' to 'C:\Project\MSI\Output\VLC.old3'
VERBOSE: Ensuring that this script has write permissions to C:\Project\MSI\Output\VLC...
VERBOSE: Checking that installer is not sibling to working directory
VERBOSE: --------------------------------------------------

Setting up Conversion Environment

VERBOSE: Copying contents of C:\Project\vlc to
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\shared\installer to be shared with
isolated environment
VERBOSE: Copying KnownFolderDump.exe and its dependencies to
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\shared\dac\bin
VERBOSE: --------------------------------------------------

Running Installer in Isolated Environment

VERBOSE: No installer valid exit codes specified. Using defaults: 0
VERBOSE: Replace any occurence of <log_folder> in -InstallerArguments with C:\shared\logs
VERBOSE: Creating Isolated Environment
VERBOSE: Starting the Isolated Environment
VERBOSE: An error occurred running your installer in isolation
VERBOSE: Disposing of the Isolated Environment
VERBOSE: Moving any logs in
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\shared\logs to
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\logs
VERBOSE: Moving any dac output in
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\shared\dac\out to
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\output\dac
VERBOSE: Cleaning up by removing isolated environment shared folder
C:\DesktopAppConverter\9848b14c-013f-48d3-bc43-3b10b5987c58\shared
VERBOSE: An error occurred converting your application. Here is the full error record:
VERBOSE:

PowerShell Error Record:
DesktopAppConverter : error 'E_STARTING_ISOLATED_ENV_FAILED': Failed to start the isolated
environment. See inner exception for more details.
PowerShell Stack Trace:
at RaiseUserException, C:\Program
Files\WindowsApps\Microsoft.DesktopAppConverter_2.0.2.0_x64__8wekyb3d8bbwe\converter_util\DACLogge
r.ps1: line 154
at Invoke-IsolatedInstall, C:\Program
Files\WindowsApps\Microsoft.DesktopAppConverter_2.0.2.0_x64__8wekyb3d8bbwe\converter_util\Isolated
EnvironmentOps.ps1: line 162
at


问:
How to get replies count of individual comment in wordpress
I use traded comments so each comments receive multiple replies in it. I need to get replies count of each individual comment. I don't need the total replies count of all the comments.

I tried to use this code:

```<code>$comment_id = get_comment_ID();

$childrenCount = get_comment_meta( $comment_id, "childrenCount" );

$childrenCountNumber = count($childrenCount);

echo $childrenCountNumber
</code>```

The other way round that shows total replies which not what I'm looking for.. This code shows all the replies of all the comments.`

Code in functions.php

```<code>function replies_counter($id){
global $wpdb;
$query = "SELECT COUNT(comment_post_id) AS count FROM $wpdb->comments
WHERE `comment_approved` = 1 AND `comment_post_ID` = $id AND
`comment_parent` = 0";
$parents = $wpdb->get_row($query);
return $parents->count;
}
</code>```

Then echo out in the template page:

```<code>$parents_count = replies_counter($post->ID);
$children_count = $post->comment_count - $parents_count;

echo $children_count;
</code>```

This one is all about getting total replies count of all the comments. But I need replies count of each comment individually.

It will be nice if someone help me.

答:
why don't you write such a custom function to get subcomments for each individual comment by ID like this?</p>

```<code>function subreplies_counter($id){
  global $wpdb;
  $query = "SELECT COUNT(comment_ID) AS count FROM $wpdb->comments
  WHERE `comment_approved` = 1 AND `comment_parent` = $id";
  $data = $wpdb->get_row($query);
  return $data->count;
}
</code>```

Body:
I use traded comments so each comments receive multiple replies in it. I need to get replies count of each individual comment. I don't need the total replies count of all the comments.

I tried to use this code:

$comment_id = get_comment_ID();

$childrenCount = get_comment_meta( $comment_id, "childrenCount" );

$childrenCountNumber = count($childrenCount);

echo $childrenCountNumber

The other way round that shows total replies which not what I'm looking for.. This code shows all the replies of all the comments.`

Code in functions.php

function replies_counter($id){
global $wpdb;
$query = "SELECT COUNT(comment_post_id) AS count FROM $wpdb->comments
WHERE `comment_approved` = 1 AND `comment_post_ID` = $id AND
`comment_parent` = 0";
$parents = $wpdb->get_row($query);
return $parents->count;
}

Then echo out in the template page:

$parents_count = replies_counter($post->ID);
$children_count = $post->comment_count - $parents_count;

echo $children_count;

This one is all about getting total replies count of all the comments. But I need replies count of each comment individually.

It will be nice if someone help me.

Body:
why don't you write such a custom function to get subcomments for each individual comment by ID like this?

function subreplies_counter($id){
  global $wpdb;
  $query = "SELECT COUNT(comment_ID) AS count FROM $wpdb->comments
  WHERE `comment_approved` = 1 AND `comment_parent` = $id";
  $data = $wpdb->get_row($query);
  return $data->count;
}


问:
Need to delete all data after third colon of a string
i have a file say test.txt with the following contents

```<code>apple:orange:mango:123:1234:12345
</code>```

i want all data after third colon to be removed

Expected output

```<code>apple:orange:mango:
</code>```

Kinldy help

答:
```<code>echo apple:orange:mango:123:1234:12345| awk '{gsub(/[0-9]:*/,"")}1'
apple:orange:mango:
</code>```

Body:
i have a file say test.txt with the following contents

apple:orange:mango:123:1234:12345

i want all data after third colon to be removed

Expected output

apple:orange:mango:

Kinldy help


问:
Regex Crossword missing 4th capture group
On BrainF*ing regex crossword I'm looking at the fourth row ((([<+>])\3\3)|(<-])(?=>))+. I already worked on the fifth column \++\-+\.+\-+\++ and I believe - ends up on the fourth row.

What I have so far: <<< ->>  +++ (spaces here are unknown). It seems to me that the - is out of place/can't belong (unless the first and last space is [<\-\]]). Looking at it with regex101 I plugged in <<<-->>>]+++ (just for testing and it doesn't see -- or ], also on the right side the fourth capture group isn't listed. Is there a reason regex101 doesn't see the fourth capture group: (<-])? Am I right in that - is a valid possibility?

答:
The (<-]) part is a capturing group that matches a sequence of atoms, here, a  <-] 3-char substring.

To match any symbol, <, or - or ], these symbols should be put them into a character class, [<\-\]].

Note that your string contains no <-] substring, so <-] won't match. Once you added it, your regex will work.

It usually not necessary to use capturing groups inside a repeated group, as in most languages only the last value captured is kept in the match object (PyPi Python regex module and .NET regex engines keep them all).

So, you might use

```<code>(?:([<+>])\1\1|<-](?=>))+
</code>```

See the regex demo

Details:

(?:([<+>])\1\1|<-](?=>))+ - 1 or more sequences of:

([<+>])\1\1 - a <, + or > followed with exactly the same char 2 times

| - or

<-](?=>) a <-] substring that had > after it (without consuming >, it is free to be used by the next match iteration since it is inside a positive lookahead).

Body:
The (<-]) part is a capturing group that matches a sequence of atoms, here, a  <-] 3-char substring.

To match any symbol, <, or - or ], these symbols should be put them into a character class, [<\-\]].

Note that your string contains no <-] substring, so <-] won't match. Once you added it, your regex will work.

It usually not necessary to use capturing groups inside a repeated group, as in most languages only the last value captured is kept in the match object (PyPi Python regex module and .NET regex engines keep them all).

So, you might use

(?:([<+>])\1\1|<-](?=>))+

See the regex demo

Details:

(?:([<+>])\1\1|<-](?=>))+ - 1 or more sequences of:

([<+>])\1\1 - a <, + or > followed with exactly the same char 2 times

| - or

<-](?=>) a <-] substring that had > after it (without consuming >, it is free to be used by the next match iteration since it is inside a positive lookahead).


问:
How do I prevent replay attacks?
This is related to another question I asked. In summary, I have a special case of a URL where, when a form is POSTed to it, I can't rely on cookies for authentication or to maintain the user's session, but I somehow need to know who they are, and I need to know they're logged in!

I think I came up with a solution to my problem, but it needs fleshing out. Here's what I'm thinking. I create a hidden form field called "username", and place within it the user's username, encrypted. Then, when the form POSTs, even though I don't receive any cookies from the browser, I know they're logged in because I can decrypt the hidden form  field and get the username.

The major security flaw I can see is replay attacks. How do I prevent someone from getting ahold of that encrypted string, and POSTing as that user? I know I can use SSL to make it harder to steal that string, and maybe I can rotate the encryption key on a regular basis to limit the amount of time that the string is good for, but I'd really like to find a bulletproof solution. Anybody have any ideas? Does the ASP.Net ViewState prevent replay? If so, how do they do it?

Edit: I'm hoping for a solution that doesn't require anything stored in a database. Application state would be okay, except that it won't survive an IIS restart or work at all in a web farm or garden scenario. I'm accepting Chris's answer, for now, because I'm not convinced it's even possible to secure this without a database. But if someone comes up with an answer that does not involve the database, I'll accept it!

答:
Is this WebForms or MVC? If it's MVC you could utilize the AntiForgery token. This seems like it's similar to the approach you mention except it uses basically a GUID and sets a cookie with the guid value for that post. For more on that see Steve Sanderson's blog: http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/

Another thing, have you considered checking the referrer on the postback? This is not bulletproof but it may help.

OwnerDisplayName: Josh Hinman

Title: How do I prevent replay attacks?

LastEditorDisplayName: Josh Hinman


问:
How do I revert a big change in CVS?
One of my colleagues has totally messed up the contents of a directory in our main CVS repository.  I need to just revert the whole module to the state it was in at the end of last year.  What's the CVS command to do this please?

He has added and removed hundreds of files, so a simple "copy over files from old checkout and commit" isn't enough.

I have RTFM and STFW, and I tried this:

```<code>cvs co modulename  # Note no -P option
cvs up -jHEAD -jMAIN:2008-12-30 modulename
</code>```

But that doesn't work - the new files he created get removed, but the old files and directories don't get resurrected.  (I didn't commit it).

I can probably write a shell script for this, but surely this functionality must be in CVS already?

Update:  Some clarifications:

I can get a local checkout of the module at a specific date.  The question is how to get that back into CVS.

I do have backups, but the point using of a revision control system like CVS is that it's supposed to be easy to get any historical state.  Next time something like this happens I may not be lucky enough to have backups (e.g. backups are daily, so I may lose up to a day's work).

I know that CVS is old, and we should move to something newer.  But in a large team with a large number of CVS-based tools (checkout & build scripts, nightly build server, etc) the time cost of such a move is considerable.  (Evaluation, updating scripts, testing, migration, training, lost developer time, maintaining both systems in parallel as CVS would still be needed for old branches).  Hence this has to be planned & scheduled by management.

Update #2: I'm going to start a bounty on this.  To qualify for the bounty you have to explain how to revert using normal CVS commands, not with a hacky shell script.

Update #3: The server is CVS 1.12.13.  Access is via pserver.  I can use the same version of CVS on a Linux PC, or the CVSNT 2.0.51d client on Windows.

答:
I believe your second command should also be a checkout, rather than an update. I can't justify this with logic, since there is no logic in the world of CVS, but it has worked for me. Try this:

```<code>cvs co -P modulename
cvs co -P -jHEAD -jMAIN:2008-12-30 modulename
</code>```

If you're reverting a branch other than HEAD, e.g. X, pass the -rX argument in both commands:

```<code>cvs co -P -rX modulename
cvs co -P -rX -jHEAD -jMAIN:2008-12-30 modulename
</code>```

Title: How do I revert a big change in CVS?

Body:
One of my colleagues has totally messed up the contents of a directory in our main CVS repository.  I need to just revert the whole module to the state it was in at the end of last year.  What's the CVS command to do this please?

He has added and removed hundreds of files, so a simple "copy over files from old checkout and commit" isn't enough.

I have RTFM and STFW, and I tried this:

cvs co modulename  # Note no -P option
cvs up -jHEAD -jMAIN:2008-12-30 modulename

But that doesn't work - the new files he created get removed, but the old files and directories don't get resurrected.  (I didn't commit it).

I can probably write a shell script for this, but surely this functionality must be in CVS already?

Update:  Some clarifications:

I can get a local checkout of the module at a specific date.  The question is how to get that back into CVS.

I do have backups, but the point using of a revision control system like CVS is that it's supposed to be easy to get any historical state.  Next time something like this happens I may not be lucky enough to have backups (e.g. backups are daily, so I may lose up to a day's work).

I know that CVS is old, and we should move to something newer.  But in a large team with a large number of CVS-based tools (checkout & build scripts, nightly build server, etc) the time cost of such a move is considerable.  (Evaluation, updating scripts, testing, migration, training, lost developer time, maintaining both systems in parallel as CVS would still be needed for old branches).  Hence this has to be planned & scheduled by management.

Update #2: I'm going to start a bounty on this.  To qualify for the bounty you have to explain how to revert using normal CVS commands, not with a hacky shell script.

Update #3: The server is CVS 1.12.13.  Access is via pserver.  I can use the same version of CVS on a Linux PC, or the CVSNT 2.0.51d client on Windows.

Body:
I believe your second command should also be a checkout, rather than an update. I can't justify this with logic, since there is no logic in the world of CVS, but it has worked for me. Try this:

cvs co -P modulename
cvs co -P -jHEAD -jMAIN:2008-12-30 modulename

If you're reverting a branch other than HEAD, e.g. X, pass the -rX argument in both commands:

cvs co -P -rX modulename
cvs co -P -rX -jHEAD -jMAIN:2008-12-30 modulename

OwnerDisplayName: JW


答:
I see two problems with your code:

The time series intialization is off - the one below should work.

ggplot2::autoplot does not seem to be a function for plotting time series but plotting fitted models from forecast

Something like this works for me - updated after OP comment:

```<code>library(forecast)
library(ggplot2)
pond <- ts(wt$AvgWeight,start=c(2007, 25), frequency=52)
autoplot(forecast(auto.arima(pond)))
autoplot(forecast(ets(pond)))
</code>```

Title: How to convert dataframe to a time series

Body:
I have a dataframe that I would like to convert to ts and forecast the AvgWeight either starting on DOC 3 or SampleDate 2007-06-23. The AvgWeight is estimated weekly (DOC). I would like to forecast 3 weeks ahead of the last DOC (101) so I basically want predictions for DOC 108, 115, and 122. Could someone in this list help me to forecast this small dataset below?

      DOC AvgWeight PondName SampleDate
  1    3  1.000000   Pond01 2007-06-23
  2   10  1.666667   Pond01 2007-06-30
  3   17  2.066667   Pond01 2007-07-07
  4   24  2.275000   Pond01 2007-07-14
  5   31  3.833333   Pond01 2007-07-21
  6   38  6.200000   Pond01 2007-07-28
  7   45  7.400000   Pond01 2007-08-04
  8   52  8.500000   Pond01 2007-08-11
  9   59 10.250000   Pond01 2007-08-18
  10  66 11.100000   Pond01 2007-08-25
  11  73 13.625000   Pond01 2007-09-01
  12  80 15.200000   Pond01 2007-09-08
  13  87 16.375000   Pond01 2007-09-15
  14  94 17.800000   Pond01 2007-09-22
  15 101 21.500000   Pond01 2007-09-29

Here is the dput of the dataset above to be copied to R

 wt <- structure(list(DOC = c(3, 10, 17, 24, 31, 38, 45, 52, 59, 66,
 73, 80, 87, 94, 101), AvgWeight = c(1, 1.66666666666667, 2.06666666666667,
 2.275, 3.83333333333333, 6.2, 7.4, 8.5, 10.25, 11.1, 13.625,
 15.2, 16.375, 17.8, 21.5), PondName = structure(c(1L, 1L, 1L,
 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Pond01", class =

"factor"),  SampleDate = structure(c(1182585600, 1183190400,
1183795200, 1184400000, 1185004800, 1185609600, 1186214400, 1186819200,
 1187424000, 1188028800, 1188633600, 1189238400, 1189843200,
 1190448000, 1191052800), class = c("POSIXct", "POSIXt"))), .Names =
c("DOC", "AvgWeight", "PondName", "SampleDate"), row.names = c(NA, 15L
 ), class = "data.frame")

wt$SampleDate <- as.Date(wt$SampleDate)
 wt

I tried;

library(forecast)
library(ggplot2)
pond <- ts(wt$AvgWeight,start=3,frequency=52,end=101)
autoplot(pond)

But my ts call is off. I am reading about ts but can't grasp it yet. I appreciate any help.

Body:
I see two problems with your code:

The time series intialization is off - the one below should work.

ggplot2::autoplot does not seem to be a function for plotting time series but plotting fitted models from forecast

Something like this works for me - updated after OP comment:

library(forecast)
library(ggplot2)
pond <- ts(wt$AvgWeight,start=c(2007, 25), frequency=52)
autoplot(forecast(auto.arima(pond)))
autoplot(forecast(ets(pond)))