问:
Is there a difference between concurrency and parallelism in java?
I have been doing some research in Google and cant quite get my head around the differences (if any) between concurrent and parallel programs in java. Some of the information I have looked at suggests no differences between both. Is this the case?? </p>

答:
From oracle documentation page:

In a multithreaded process on a single processor, the processor can switch execution resources between threads, resulting in concurrent execution.

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run on a separate processor at the same time, resulting in parallel execution.

When the process has fewer or as many threads as there are processors, the threads support system in conjunction with the operating environment ensure that each thread runs on a different processor.

Java SE 7 further enhanced parallel processing by adding ForkJoinPool API.

Refer to below posts for more details:

Parallel programming with threads in Java  ( Java specific )

Concurrency vs Parallelism - What is the difference? ( Language agnostic)


来源: stackexchange

问:
SelectListItem properties in view model are not passed back from view to controller
I have this View Model:

```<code>public class UserViewModel
{
    public string ID { get; set; }

    [Required]
    [Display(Name = "Nombre")]
    public string Nombre { get; set; }

    [Required]
    [Display(Name = "Login")]
    public string Login { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Contraseña")]
    public string Password { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "E-mail")]
    public string Email { get; set; }

    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Teléfono")]
    public string PhoneNumber { get; set; }

    [Display(Name = "Ciudad")]
    public System.Web.Mvc.SelectListItem City { get; set; }

    [Display(Name = "Empresas")]
    public IEnumerable<System.Web.Mvc.SelectListItem> Empresas { get; set; }

    [Required]
    [Display(Name = "Perfil")]
    public string Role { get; set; }

    [Display(Name = "Está Vigente")]
    public bool Vigente { get; set; }
}
</code>```

the problem I am having is that when I select something in City and Empresas in the form (they are both SELECT fields), they are not passed to controller in UserViewModel parameter:

```<code>    public JsonResult EditUser(UserViewModel model)
    {
          .....
    }
</code>```

Only other properties are passed.

What is the right way to manage this?

EDIT:

this is part of the view:

```<code>            @using (Html.BeginForm("EditUser", "Account", new { area = "Security" }, FormMethod.Post, new { @class = "form-horizontal form-label-left", role = "form", novalidate = "novalidate", id = "frmUsuario" }))
            {
                var id = Model == null ? String.Empty : Model.ID;
                <div class="errores col-md-12 col-sm-12 col-xs-12" style="display: none">
                    <div class='validation-summary-errors alert alert-danger alert-white rounded' data-valmsg-summary="true">
                        <div class="icon">
                            <i class="fa fa-times-circle"></i>
                        </div>
                        <p>Debe completar los campos marcados en forma correcta.</p>
                    </div>
                </div>
                @Html.AntiForgeryToken();
                <input type="hidden" value="@id" id="id" name="id" />
                <div class="item col-md-12 col-sm-12 col-xs-12 form-group has-feedback">
                    @Html.TextBoxFor(m => m.Nombre, new { @class = "form-control has-feedback-left", placeholder = "Nombre", required = "required" })
                    <span class="fa fa-user form-control-feedback left" aria-hidden="true"></span>
                </div>
                <div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                    @Html.TextBoxFor(m => m.Login, new { @class = "form-control has-feedback-left", placeholder = "Login", required = "required" })
                    <span class="fa fa-sign-in form-control-feedback left" aria-hidden="true"></span>
                </div>

                <div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                    @{
                        //var requerido = String.IsNullOrEmpty(userId) ? "required" : String.Empty;
                        var requerido = Model == null || String.IsNullOrEmpty(Model.ID);
                        object htmlAttributes = null;
                        if (requerido)
                        {
                            htmlAttributes = new { @class = "form-control has-feedback-left", placeholder = "Contraseña", required = "required" };
                        }
                        else
                        {
                            htmlAttributes = new { @class = "form-control has-feedback-left", placeholder = "Contraseña" };
                        }
                    }
                    <!-- Para evitar que los password managers llenen los campos -->
                    <input type="text" id="hidUser" style="display: none" />
                    <!-- Para evitar que los password managers llenen los campos -->
                    <input type="password" id="hidPassword" style="display: none" />

                    @Html.PasswordFor(m => m.Password, htmlAttributes)
                    <span class="fa fa-key form-control-feedback left" aria-hidden="true"></span>
                </div>

                <div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control has-feedback-left", placeholder = "E-mail", required = "required" })
                    <span class="fa fa-envelope form-control-feedback left" aria-hidden="true"></span>
                </div>

                <div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
                    @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control has-feedback-left", placeholder = "Teléfono" })
                    <span class="fa fa-phone form-control-feedback left" aria-hidden="true"></span>
                </div>

                <div class="item col-md-12 col-sm-12 col-xs-12 form-group">
                    @Html.DropDownListFor(m => m.City, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })
                </div>

                <div class="item col-md-12 col-sm-12 col-xs-12 form-group">
                    @Html.DropDownListFor(m => m.Role, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })
                </div>

                <div class="item col-md-12 col-sm-12 col-xs-12 form-group">
                    @Html.DropDownListFor(m => m.Empresas, new SelectList(new List<SelectListItem>()), new { style = "width: 100%", multiple = "multiple" })
                </div>

                <div class="item col-md-12 col-sm-12 col-xs-12 form-group">
                    Está Vigente
                    @Html.CheckBoxFor(m => m.Vigente, new { @class = "flat" })
                </div>
            }
</code>```

答:
I wonder there's show nothing in your dropdown.
In your view model, it should contain at least two properties, such as AvailableCities and City.

```<code>public List<SelectListItem> AvailableCities { get;set; }
public string City { get;set; }
</code>```

AvailableCities contains all cities which should show in dropdow. And the City is using for getting the value user selected.

In your view,

```<code> @Html.DropDownListFor(m => m.City, Model.AvailableCities, new { @class = "form-control" })
</code>```

For now, you should see the dropdown shawn and which could get the selected value in your action.

ContentLicense: CC BY-SA 3.0

Body:
I have this View Model:

public class UserViewModel
{
    public string ID { get; set; }

    [Required]
    [Display(Name = "Nombre")]
    public string Nombre { get; set; }

    [Required]
    [Display(Name = "Login")]
    public string Login { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Contraseña")]
    public string Password { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "E-mail")]
    public string Email { get; set; }

    [DataType(DataType.PhoneNumber)]
    [Display(Name = "Teléfono")]
    public string PhoneNumber { get; set; }

    [Display(Name = "Ciudad")]
    public System.Web.Mvc.SelectListItem City { get; set; }

    [Display(Name = "Empresas")]
    public IEnumerable<System.Web.Mvc.SelectListItem> Empresas { get; set; }

    [Required]
    [Display(Name = "Perfil")]
    public string Role { get; set; }

    [Display(Name = "Está Vigente")]
    public bool Vigente { get; set; }
}

the problem I am having is that when I select something in City and Empresas in the form (they are both SELECT fields), they are not passed to controller in UserViewModel parameter:

    public JsonResult EditUser(UserViewModel model)
    {
          .....
    }

Only other properties are passed.

What is the right way to manage this?

EDIT:

this is part of the view:

            @using (Html.BeginForm("EditUser", "Account", new { area = "Security" }, FormMethod.Post, new { @class = "form-horizontal form-label-left", role = "form", novalidate = "novalidate", id = "frmUsuario" }))
            {
                var id = Model == null ? String.Empty : Model.ID;

Debe completar los campos marcados en forma correcta.

                @Html.AntiForgeryToken();
                <input type="hidden" value="@id" id="id" name="id" />

                    @Html.TextBoxFor(m => m.Nombre, new { @class = "form-control has-feedback-left", placeholder = "Nombre", required = "required" })

                    @Html.TextBoxFor(m => m.Login, new { @class = "form-control has-feedback-left", placeholder = "Login", required = "required" })

                    @{
                        //var requerido = String.IsNullOrEmpty(userId) ? "required" : String.Empty;
                        var requerido = Model == null || String.IsNullOrEmpty(Model.ID);
                        object htmlAttributes = null;
                        if (requerido)
                        {
                            htmlAttributes = new { @class = "form-control has-feedback-left", placeholder = "Contraseña", required = "required" };
                        }
                        else
                        {
                            htmlAttributes = new { @class = "form-control has-feedback-left", placeholder = "Contraseña" };
                        }
                    }

                    <input type="text" id="hidUser" style="display: none" />

                    <input type="password" id="hidPassword" style="display: none" />

                    @Html.PasswordFor(m => m.Password, htmlAttributes)

                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control has-feedback-left", placeholder = "E-mail", required = "required" })

                    @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control has-feedback-left", placeholder = "Teléfono" })

                    @Html.DropDownListFor(m => m.City, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })

                    @Html.DropDownListFor(m => m.Role, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })

                    @Html.DropDownListFor(m => m.Empresas, new SelectList(new List<SelectListItem>()), new { style = "width: 100%", multiple = "multiple" })

                    Está Vigente
                    @Html.CheckBoxFor(m => m.Vigente, new { @class = "flat" })

            }

Body:
I wonder there's show nothing in your dropdown.
In your view model, it should contain at least two properties, such as AvailableCities and City.

public List<SelectListItem> AvailableCities { get;set; }
public string City { get;set; }

AvailableCities contains all cities which should show in dropdow. And the City is using for getting the value user selected.

In your view,

 @Html.DropDownListFor(m => m.City, Model.AvailableCities, new { @class = "form-control" })

For now, you should see the dropdown shawn and which could get the selected value in your action.


问:
Basics of Routing in Angular 2.0
It is a very basic scenario but, being a beginner in Angular 2.0, I am having a hard time to figure out how to achieve the same.

Prior to Routing Implementation I would have a line like this in
app.component.html

```<code><app-home [selectedNinja] = "ninja" (onYell) = "yell($event)">Hello There</app-home>
</code>```

And in app.component.ts I have like

```<code>export class AppComponent {

  ninja = {
    name : 'Yoshi',
    belt: 'Black'
  }
  ......
  ......
</code>```

So it's an @Input parameter that would be accepted in our home.component.ts file.

Now after Routing implementation I can only have :

```<code>  <!--<app-home [selectedNinja] = "ninja" (onYell) = "yell($event)">Hello There</app-home>-->
  <nav>
    <a routerLink="/" routerLinkActive="active">Home</a>
    <a routerLink="/directory" routerLinkActive="active">Directory</a>
  </nav>
  <router-outlet></router-outlet>
</code>```

So I want to load home component when default route is asked for.

But I don't know now how to pass the input data and the event like before ?

We do not have the <app-home> like declaration right ?

Or am I missing very basic something ?

答:
Your home component is not really a home component. It's a ninja component: it takes a ninja as input and emits events when this ninja yells. Such a component is not a good candidate for a routing component.

So, if you want your home page to display a hard-coded ninja, create a routing component that defines this ninja, and passes it as input to your ninja component. Just like your app component does currently.

First step: rename your home component to ninja.

Second step: define a real home component:

```<code>@Component({
  template: '<app-ninja [selectedNinja] = "ninja" (onYell) = "yell($event)">Hello There</app-ninja>'
})
export class HomeComponent {

  ninja = {
    name : 'Yoshi',
    belt: 'Black'
  }

  yell(event) {
    // ...
  }
}
</code>```

Title: Basics of Routing in Angular 2.0

Body:
It is a very basic scenario but, being a beginner in Angular 2.0, I am having a hard time to figure out how to achieve the same.

Prior to Routing Implementation I would have a line like this in
app.component.html

<app-home [selectedNinja] = "ninja" (onYell) = "yell($event)">Hello There</app-home>

And in app.component.ts I have like

export class AppComponent {

  ninja = {
    name : 'Yoshi',
    belt: 'Black'
  }
  ......
  ......

So it's an @Input parameter that would be accepted in our home.component.ts file.

Now after Routing implementation I can only have :

    Home
    Directory

  <router-outlet></router-outlet>

So I want to load home component when default route is asked for.

But I don't know now how to pass the input data and the event like before ?

We do not have the <app-home> like declaration right ?

Or am I missing very basic something ?

Body:
Your home component is not really a home component. It's a ninja component: it takes a ninja as input and emits events when this ninja yells. Such a component is not a good candidate for a routing component.

So, if you want your home page to display a hard-coded ninja, create a routing component that defines this ninja, and passes it as input to your ninja component. Just like your app component does currently.

First step: rename your home component to ninja.

Second step: define a real home component:

@Component({
  template: '<app-ninja [selectedNinja] = "ninja" (onYell) = "yell($event)">Hello There</app-ninja>'
})
export class HomeComponent {

  ninja = {
    name : 'Yoshi',
    belt: 'Black'
  }

  yell(event) {
    // ...
  }
}


问:
Cloneable and WebDriver ( Selenium )
I am beginning with selenium WebDriver, I want to make an independente copy of my WebDriver,  I try to use the interface Cloneable but I could not because the class WebDriver doesn't implements the interface Cloneable.

I also try to create a class containing an attribute WebDriver like that

```<code>public class A implemnts Cloneable{
       private WebDriver driver;

       public A(WebDriver driver){
              this.driver = driver;
       }

       public WebDriver clone throws CloneNotSupportedException {
              A mClass = (A) super.clone();
              return mClass.driver;
       }
}
</code>```

```<code>WebDriver driver = new A().clone();
</code>```

but it does not work well ...
Does anyone know how I can do this ???

答:
You can find how to copy object here.

But I'm suggesting to use the same webdriver in another thread.

Title: Cloneable and WebDriver ( Selenium )

Body:
I am beginning with selenium WebDriver, I want to make an independente copy of my WebDriver,  I try to use the interface Cloneable but I could not because the class WebDriver doesn't implements the interface Cloneable.

I also try to create a class containing an attribute WebDriver like that

public class A implemnts Cloneable{
       private WebDriver driver;

       public A(WebDriver driver){
              this.driver = driver;
       }

       public WebDriver clone throws CloneNotSupportedException {
              A mClass = (A) super.clone();
              return mClass.driver;
       }
}

WebDriver driver = new A().clone();

but it does not work well ...
Does anyone know how I can do this ???


问:
Create subclass of NodeJS Buffer
I'm trying to create a subclass of NodeJS's buffer. I tried the following:

```<code>const SubClass = Object.create(Buffer)
SubClass.prototype.isZero = function () {
    for(const value of this.buffer) { // Fails on this line
        ...
    }
}
</code>```

Then I do the following

```<code>SubClass.from([0, 0]).isZero()
</code>```

It throws

```<code>TypeError: undefined is not a function
</code>```

But this.buffer is defined. So whats the problem (maybe an iterator problem?)? Am I doing something wrong with extending the buffer?

答:
The Buffer isn't a class to extend as you're expecting - it's worthwhile to read the modules function which you are having problems with:

https://github.com/nodejs/node/blob/master/lib/buffer.js#L172

Extending the Buffer class will duplicate all the methods which initialise new instances of Buffer instead of your new SubClass. So you won't be able to extend the buffer class for your defined behaviour. Alternatively, you can wrap it with a class to create a similar interface.

```<code>class MyBuffer {
  constructor(arg) {
    this.buffer = Buffer.from(arg)
  }

  static from(arg) {
    return new MyBuffer(arg);
  }

  isZero() {
    for(const value of this.buffer) {
      // Fails on this line
      console.log(value)
    }
  }
}
</code>```

Then using your preferred syntax:

```<code>MyBuffer.from([0, 0]).isZero()
</code>```

Title: Create subclass of NodeJS Buffer

Body:
I'm trying to create a subclass of NodeJS's buffer. I tried the following:

const SubClass = Object.create(Buffer)
SubClass.prototype.isZero = function () {
    for(const value of this.buffer) { // Fails on this line
        ...
    }
}

Then I do the following

SubClass.from([0, 0]).isZero()

It throws

TypeError: undefined is not a function

But this.buffer is defined. So whats the problem (maybe an iterator problem?)? Am I doing something wrong with extending the buffer?

Body:
The Buffer isn't a class to extend as you're expecting - it's worthwhile to read the modules function which you are having problems with:

https://github.com/nodejs/node/blob/master/lib/buffer.js#L172

Extending the Buffer class will duplicate all the methods which initialise new instances of Buffer instead of your new SubClass. So you won't be able to extend the buffer class for your defined behaviour. Alternatively, you can wrap it with a class to create a similar interface.

class MyBuffer {
  constructor(arg) {
    this.buffer = Buffer.from(arg)
  }

  static from(arg) {
    return new MyBuffer(arg);
  }

  isZero() {
    for(const value of this.buffer) {
      // Fails on this line
      console.log(value)
    }
  }
}

Then using your preferred syntax:

MyBuffer.from([0, 0]).isZero()


问:
Filter elements of fetched collection. EclipseLInk. Criteria API
I have an object:

```<code>@Entity
@Table(name = "users", catalog = "adm", uniqueConstraints = @UniqueConstraint(columnNames = "loginUser"))
public class User implements GenericEntityPK<Integer> {

    private Set<Permission> permissions = new HashSet<Permission>(0);
@ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "user_l_permission", catalog = "adm", joinColumns = {
            @JoinColumn(name = "idUser", nullable = false, updatable = false) }, inverseJoinColumns = {
                    @JoinColumn(name = "idPermission", nullable = false, updatable = false) })
    public Set<Permission> getPermissions() {
        return this.permissions;
    }
}
</code>```

I want to select user entity and fetch collection of permissions, with where clause. In other words permissions collection must contain only elements that satisfy where conditions.
I've tried to do it with SetJoin but with no success..

Is there a way to do it?

答:
I would recommend you instead query for the permissions that match the user and filter you want when needed.  You can even cache this collection in your entity with a transient collection to pass it around in the object.  Using filters on relationships ends up causing problems and corrupts the cache as what is in the object is no longer a true representation of what is in the database.

That said, there is no JPA way to do it, but Eclipselink supports additional criteria

Body:
I have an object:

@Entity
@Table(name = "users", catalog = "adm", uniqueConstraints = @UniqueConstraint(columnNames = "loginUser"))
public class User implements GenericEntityPK<Integer> {

    private Set<Permission> permissions = new HashSet<Permission>(0);
@ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "user_l_permission", catalog = "adm", joinColumns = {
            @JoinColumn(name = "idUser", nullable = false, updatable = false) }, inverseJoinColumns = {
                    @JoinColumn(name = "idPermission", nullable = false, updatable = false) })
    public Set<Permission> getPermissions() {
        return this.permissions;
    }
}

I want to select user entity and fetch collection of permissions, with where clause. In other words permissions collection must contain only elements that satisfy where conditions.
I've tried to do it with SetJoin but with no success..

Is there a way to do it?


问:
Google search with Python
How do you perform a search query on Google using Python? How do you store the search results in a Microsoft Word document?</p>

答:
http://code.google.com/apis/customsearch/v1/getting_started.html

http://code.google.com/apis/customsearch/v1/using_rest.html

Google's custom search API looks to be what you're looking for. You'll need to get a API key first; then it seems they let you do up to 100 searches a day.

Use urllib2 to fetch the URL, and simplejson to decode it. (Google around for these packages if you don't already have them.) You can use json.load() to turn the response into a python dictionary that you can easily read from. Happy hacking!

Edit: As for creating the word document, you have a variety of options, detailed here: How can I create a Word document using Python?

ContentLicense: CC BY-SA 2.5

Title: Google search with Python


问:
How can I migrate from CFURLCreateStringByAddingPercentEscapes to stringByAddingPercentEncodingWIthAllowedCharacters?
In my code, the method CFURLCreateStringByAddingPercentEscapes is marked as deprecated as of iOS 9. My code is as follows:

```<code>static NSString *encodeByAddingPercentEscapes(NSString *input) {
    NSString *encodedValue = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)input, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
    return encodedValue;
}
</code>```

The warning suggests that I use [NSString stringByAddingPercentEncodingWithAllowedCharacters:]

How can I accomplish the same result using the newer method?

答:
you can use [@"" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]].
And there are many set to use:URLPathAllowedCharacterSet、URLQueryAllowedCharacterSet.etc</p>

Body:
In my code, the method CFURLCreateStringByAddingPercentEscapes is marked as deprecated as of iOS 9. My code is as follows:

static NSString *encodeByAddingPercentEscapes(NSString *input) {
    NSString *encodedValue = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)input, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
    return encodedValue;
}

The warning suggests that I use [NSString stringByAddingPercentEncodingWithAllowedCharacters:]

How can I accomplish the same result using the newer method?


问:
Google Apps script Sort
Using App Scripts I've pulled all the headers in an array, strip out the text part and built an array of the below format:

[1,10,23,45,7,12,76,88,9]

Sample code:

```<code>var shHeader = sh.getRange(1, 3, 1, 20);
var shH1 = shHeader.getValues();
shH1 = shH1[0].sort();
</code>```

When I do the normal sort() on the array, the order I'm getting is like:

[1,10,12,23,45,7,76,88,9]

I want sort to give me an output:

[1,7,9,10,12,23,45,76,88]

Can anyone help with any function or some easy hack to get my desired results?

答:
You can pass a function into the sort method that takes two parameters.

```<code>shH1 = shH1[0].sort(function(a, b) {return a - b;});
</code>```

Here is documentation to help you:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Title: Google Apps script Sort

Body:
Using App Scripts I've pulled all the headers in an array, strip out the text part and built an array of the below format:

[1,10,23,45,7,12,76,88,9]

Sample code:

var shHeader = sh.getRange(1, 3, 1, 20);
var shH1 = shHeader.getValues();
shH1 = shH1[0].sort();

When I do the normal sort() on the array, the order I'm getting is like:

[1,10,12,23,45,7,76,88,9]

I want sort to give me an output:

[1,7,9,10,12,23,45,76,88]

Can anyone help with any function or some easy hack to get my desired results?

Body:
You can pass a function into the sort method that takes two parameters.

shH1 = shH1[0].sort(function(a, b) {return a - b;});

Here is documentation to help you:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


问:
Hide a form based on referer_url value
I have a small form on my 404 page that I only want to be shown if the visitor comes from a website -- thus if a visitor comes from an email link or directly accesses the URL, then I don't want them to see the form at all.

The reason: this form is about a broken link they have clicked to get to this 404 web page. If they clicked on an email link, or if they just typed the URL, then there's nothing I can correct. So there's no need for a form. But if they arrived from a link (on the same site or another site), then I want the form to show.

I do understand that I may have to use the Javascript referer_url option, but is there any way to hide the form if the visitor has no referer_url value?

Thank you so much.

答:
It should be pretty straight forward, if document.referrer has a value show, otherwise hide. This one liner seems to do what you need it to:</p>

```<code>document.getElementById("theForm").style.display = document.referrer ?  "block" : "none";
</code>```

Title: Hide a form based on referer_url value

Body:
It should be pretty straight forward, if document.referrer has a value show, otherwise hide. This one liner seems to do what you need it to:

document.getElementById("theForm").style.display = document.referrer ?  "block" : "none";


问:
Using value of ng-model in ng-if
I have a text box where I enter an idNumber. I want to check if that id number appears in my table. If it does, I want to add a glyphicon to that row.

Now, my problem is that I don't know how to access ng-model="idNumber" from ng-if.

I try using ng-if="data.id== {{idNumber}}" but that does not work.

```<code>        <div class="container" id="inputDiv">
            <div>
                <input type="text" class="form-control" ng-model="idNumber">
            </div>
        </div>

        <div class="container col-md-12">
            <table class="table table-hover">
                <thead>
                <tr>
                    <th>Id number</th>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Status</th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="data in idData">
                    <td>{{data.id}}</td>
                    <td>{{data.name}}</td>
                    <td>{{data.dokumenttype}}</td>
                    <td>
                      <span ng-if="data.id== {{idNumber}}">
                        <span class="glyphicon glyphicon-asterisk"></span>
                      </span>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
</code>```

答:
You do not need to put an expression here, just replace it as,

```<code><span ng-if="data.id===idNumber">
    <span class="glyphicon glyphicon-asterisk"></span>
</span>
</code>```

DEMO

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

myApp.controller('thecontroller',function($scope){
   $scope.idData = [{
  "id": "1",
  "name": "Kimberlyn",
  "documentType": "McGaw"
}, {
  "id": "2",
  "name": "Harmony",
  "documentType": "Sedworth"
}, {
  "id": "3",
  "name": "Adela",
  "documentType": "Blenkin"
}];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
      <title>ng-Messages Service</title>
      <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
        <script src='https://code.angularjs.org/1.5.0-rc.0/angular.min.js'></script>
    </head>
    <body ng-app="myApp">
        <div ng-controller='thecontroller'>
       <div class="container" id="inputDiv">
            <div>
                <input type="text" class="form-control" ng-model="idNumber">
            </div>
        </div>
         <div class="container col-md-12">
            <table class="table table-hover">
                <thead>
                <tr>
                    <th>Id number</th>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Status</th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="data in idData">
                    <td>{{data.id}}</td>
                    <td>{{data.name}}</td>
                    <td>{{data.dokumenttype}}</td>
                    <td>
                      <span ng-if="data.id === idNumber">
                        <span>test</span>
                      </span>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        </div>
    </body>
</html></code>```

Title: Using value of ng-model in ng-if

Body:
I have a text box where I enter an idNumber. I want to check if that id number appears in my table. If it does, I want to add a glyphicon to that row.

Now, my problem is that I don't know how to access ng-model="idNumber" from ng-if.

I try using ng-if="data.id== {{idNumber}}" but that does not work.

                <input type="text" class="form-control" ng-model="idNumber">

                    Id number
                    Name
                    Type
                    Status

                    {{data.id}}
                    {{data.name}}
                    {{data.dokumenttype}}

Body:
You do not need to put an expression here, just replace it as,

<span ng-if="data.id===idNumber">
    <span class="glyphicon glyphicon-asterisk"></span>
</span>

DEMO

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

myApp.controller('thecontroller',function($scope){
   $scope.idData = [{
  "id": "1",
  "name": "Kimberlyn",
  "documentType": "McGaw"
}, {
  "id": "2",
  "name": "Harmony",
  "documentType": "Sedworth"
}, {
  "id": "3",
  "name": "Adela",
  "documentType": "Blenkin"
}];
});

<!DOCTYPE html>
<html>
    <head>
      <title>ng-Messages Service</title>
      <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
        <script src='https://code.angularjs.org/1.5.0-rc.0/angular.min.js'></script>
    </head>
    <body ng-app="myApp">
        <div ng-controller='thecontroller'>
       <div class="container" id="inputDiv">
            <div>
                <input type="text" class="form-control" ng-model="idNumber">
            </div>
        </div>
         <div class="container col-md-12">
            <table class="table table-hover">
                <thead>
                <tr>
                    <th>Id number</th>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Status</th>
                </tr>
                </thead>
                <tbody>
                <tr ng-repeat="data in idData">
                    <td>{{data.id}}</td>
                    <td>{{data.name}}</td>
                    <td>{{data.dokumenttype}}</td>
                    <td>
                      <span ng-if="data.id === idNumber">
                        <span>test</span>
                      </span>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        </div>
    </body>
</html>


问:
for loop iterates strange
Good Morning,
I have a problem with for loop, I tried to make multiply progressbars on page and I try to triger them in one action:

```<code>function startProgressbaring(){

var progressArray = [
    progress1 = document.querySelector('.progressbar-1'),
    progress2 = document.querySelector('.progressbar-2'),
    progress3 = document.querySelector('.progressbar-3'),
    progress4 = document.querySelector('.progressbar-4'),
    progress5 = document.querySelector('.progressbar-5'),
    progress6 = document.querySelector('.progressbar-6')
];
var durationArray = [
     progress1_Duration = 90,
     progress2_Duration = 65,
     progress3_Duration = 70,
     progress4_Duration = 55,
     progress5_Duration = 95,
     progress6_Duration = 90
];

var id = setInterval(frame,30);
var width = 1;

        function frame(){
        for(var z=0; z<durationArray.length; z++){

            if(width>durationArray[z]){
                clearInterval(id);
                console.log(durationArray[z]);
            }else {
                width++;
                progressArray[z].style.width = width + '%';
            }
        }

        };
</code>```

Console Log with durationArray returns only 55, for example
six progressbars have values between 56 and 60 not the values from durationArray,
no idea whats going wrong, thanks for any advices

答:
add a single line of logging to your code and observer the output (see below).
Basicall what happens is:

your width starts with value 1, and increases with each iteration

after iterating over the 6 item array 9 times, the value of width is
54

your iteration reaches progress4_Duration with width = 58 (54 + 4)

width > durationArray[z] condition will be true, interval gets cleared, processing stops.

Assuming you only need to stop the iteration for a particular progressbar, probably you need an array of process ids and only stop the one that has sufficent width.

```<code>function startProgressbaring(){

    var progressArray = [
        progress1 = document.querySelector('.progressbar-1'),
        progress2 = document.querySelector('.progressbar-2'),
        progress3 = document.querySelector('.progressbar-3'),
        progress4 = document.querySelector('.progressbar-4'),
        progress5 = document.querySelector('.progressbar-5'),
        progress6 = document.querySelector('.progressbar-6')
    ];
    var durationArray = [
         progress1_Duration = 90,
         progress2_Duration = 65,
         progress3_Duration = 70,
         progress4_Duration = 55,
         progress5_Duration = 95,
         progress6_Duration = 90
    ];

    var intervalArray = [];
    durationArray.forEach(function(d) {
        intervalArray.push(setInterval(frame,1000))
    });

    //var id = setInterval(frame,1000);
    var width = 1;

    function frame(){
        for(var z=0; z<durationArray.length; z++){

            // debug output
            //console.log(width, durationArray[z]);

            if(width>durationArray[z]){
                //clearInterval(id);
                clearInterval(intervalArray[z]);
                console.log(durationArray[z]);
            } else {
                width++;
                progressArray[z].style.width = width + '%';
            }
        }
    }
}
</code>```

Title: for loop iterates strange

Body:
Good Morning,
I have a problem with for loop, I tried to make multiply progressbars on page and I try to triger them in one action:

function startProgressbaring(){

var progressArray = [
    progress1 = document.querySelector('.progressbar-1'),
    progress2 = document.querySelector('.progressbar-2'),
    progress3 = document.querySelector('.progressbar-3'),
    progress4 = document.querySelector('.progressbar-4'),
    progress5 = document.querySelector('.progressbar-5'),
    progress6 = document.querySelector('.progressbar-6')
];
var durationArray = [
     progress1_Duration = 90,
     progress2_Duration = 65,
     progress3_Duration = 70,
     progress4_Duration = 55,
     progress5_Duration = 95,
     progress6_Duration = 90
];

var id = setInterval(frame,30);
var width = 1;

        function frame(){
        for(var z=0; z<durationArray.length; z++){

            if(width>durationArray[z]){
                clearInterval(id);
                console.log(durationArray[z]);
            }else {
                width++;
                progressArray[z].style.width = width + '%';
            }
        }

        };

Console Log with durationArray returns only 55, for example
six progressbars have values between 56 and 60 not the values from durationArray,
no idea whats going wrong, thanks for any advices

Body:
add a single line of logging to your code and observer the output (see below).
Basicall what happens is:

your width starts with value 1, and increases with each iteration

after iterating over the 6 item array 9 times, the value of width is
54

your iteration reaches progress4_Duration with width = 58 (54 + 4)

width > durationArray[z] condition will be true, interval gets cleared, processing stops.

Assuming you only need to stop the iteration for a particular progressbar, probably you need an array of process ids and only stop the one that has sufficent width.

function startProgressbaring(){

    var progressArray = [
        progress1 = document.querySelector('.progressbar-1'),
        progress2 = document.querySelector('.progressbar-2'),
        progress3 = document.querySelector('.progressbar-3'),
        progress4 = document.querySelector('.progressbar-4'),
        progress5 = document.querySelector('.progressbar-5'),
        progress6 = document.querySelector('.progressbar-6')
    ];
    var durationArray = [
         progress1_Duration = 90,
         progress2_Duration = 65,
         progress3_Duration = 70,
         progress4_Duration = 55,
         progress5_Duration = 95,
         progress6_Duration = 90
    ];

    var intervalArray = [];
    durationArray.forEach(function(d) {
        intervalArray.push(setInterval(frame,1000))
    });

    //var id = setInterval(frame,1000);
    var width = 1;

    function frame(){
        for(var z=0; z<durationArray.length; z++){

            // debug output
            //console.log(width, durationArray[z]);

            if(width>durationArray[z]){
                //clearInterval(id);
                clearInterval(intervalArray[z]);
                console.log(durationArray[z]);
            } else {
                width++;
                progressArray[z].style.width = width + '%';
            }
        }
    }
}


问:
Filter then transfer dumped SVN repository to riouxsvn
I have a .dump file made from running svndump followed by svndumpfilter because I wish to exclude certain paths.  I am using svn version 1.8 on CentOS. I would like to import that filtered file into a newly created svn repository on riouxsvn.  I tried with this syntax (note "share-this.dump is a local file") :

```<code>svnrdump load https://svn.riouxsvn.com/(reponame)  < share-this.dump
</code>```

and received the following error message:

```<code>svnrdump: E175002: DAV request failed; it's possible that the
repository's pre-revprop-change hook either failed or is non-existent
svnrdump: E175002: Revprop change blocked by pre-revprop-change hook
(exit code 1) with output:
The subcommand "svn:rdump-lock" is prohibited by RiouxSVN.
</code>```

I have created the repo on riouxsvn without trunks/tags/branches. Nothing has been committed there yet.

I tried activating the 'hooks' on riouxsvn but I am not sure how to use this
to solve the error message above.

Does Riouxsvn support svnrdump or only svnsync ?

The only idea I have is to make a new temporary local svn repo, import my filtered content there, and then sync that across to riouxsvn.

Regarding the filtering step, the syntax I used was based on the example in the SVN Book:

```<code>svndumpfilter exclude --pattern --targets ex.txt < complete.dump > share-this.dump
</code>```

where the ex.txt file contained a list of the exclusion patterns, one per line, like this

```<code>/trunk/project/secret*
/tags/*/project/secret*
*secret_file.pas
</code>```

答:
Disclamer: im working at RiouxSVN

Hello Chloe, we investigated your request for the usage of the "svnrdump" command and we decided to allow it for all the repositories.

It was indeed blocked in the revprop commit hook until today. Now, both of these commands are allowed on RiouxSVN:

```<code>svnrdump dump < repository URL >
svnrdump load < repository URL >
</code>```

Also, make sure you have enough free space in your destination repository for your dump, or the post commit hook will deny the dump.

Thank you for bringing this matter to our attention!

Body:
I have a .dump file made from running svndump followed by svndumpfilter because I wish to exclude certain paths.  I am using svn version 1.8 on CentOS. I would like to import that filtered file into a newly created svn repository on riouxsvn.  I tried with this syntax (note "share-this.dump is a local file") :

svnrdump load https://svn.riouxsvn.com/(reponame)  < share-this.dump

and received the following error message:

svnrdump: E175002: DAV request failed; it's possible that the
repository's pre-revprop-change hook either failed or is non-existent
svnrdump: E175002: Revprop change blocked by pre-revprop-change hook
(exit code 1) with output:
The subcommand "svn:rdump-lock" is prohibited by RiouxSVN.

I have created the repo on riouxsvn without trunks/tags/branches. Nothing has been committed there yet.

I tried activating the 'hooks' on riouxsvn but I am not sure how to use this
to solve the error message above.

Does Riouxsvn support svnrdump or only svnsync ?

The only idea I have is to make a new temporary local svn repo, import my filtered content there, and then sync that across to riouxsvn.

Regarding the filtering step, the syntax I used was based on the example in the SVN Book:

svndumpfilter exclude --pattern --targets ex.txt < complete.dump > share-this.dump

where the ex.txt file contained a list of the exclusion patterns, one per line, like this

/trunk/project/secret*
/tags/*/project/secret*
*secret_file.pas

Body:
Disclamer: im working at RiouxSVN

Hello Chloe, we investigated your request for the usage of the "svnrdump" command and we decided to allow it for all the repositories.

It was indeed blocked in the revprop commit hook until today. Now, both of these commands are allowed on RiouxSVN:

svnrdump dump < repository URL >
svnrdump load < repository URL >

Also, make sure you have enough free space in your destination repository for your dump, or the post commit hook will deny the dump.

Thank you for bringing this matter to our attention!


问:
Configure NGINX to work with angular issue on reloading page
Well I have read the deployment documentation to deploy an Angular 4 proyect with an NGINX server.But when I reload with a route for the angular app shows me this error:

http://www.mydomain.com.ec/swissecomer/myRoute

code: "MethodNotAllowedError"

message: "GET is not allowed"

Here is my conf file in my nginx server:

```<code>    upstream proyectoWeb {
        ip_hash;
        server localhost:8087;

    }

    server {

        listen 8088;
        proxy_pass proyectoWeb;
        server_name 200.31.25.34 192.168.5.27  www.mydomain.com localhost;
        root /u01/servidores/;

        location swissecomer/ {
            index index.html index.htm;
            try_files $uri $uri/ /index.html;
        }

        access_log /var/log/nginx/access_log combined;

    }
</code>```

When i hit these urls, it shows the webpage just fine:

http://www.mydomain.com.ec/swissecomer/index.html

http://www.mydomain.com.ec/swissecomer/

But if i hit the next url http://www.mydomain.com.ec/swissecomer the ngix server keeps loading until it shows a timeout error in the browser.

Thanks for your responses.

答: Can you try location /swissecomer instead the forward slash needs to match also for the location block to be used.

ContentLicense: CC BY-SA 4.0

Body:
Well I have read the deployment documentation to deploy an Angular 4 proyect with an NGINX server.But when I reload with a route for the angular app shows me this error:

http://www.mydomain.com.ec/swissecomer/myRoute

code: "MethodNotAllowedError"

message: "GET is not allowed"

Here is my conf file in my nginx server:

    upstream proyectoWeb {
        ip_hash;
        server localhost:8087;

    }

    server {

        listen 8088;
        proxy_pass proyectoWeb;
        server_name 200.31.25.34 192.168.5.27  www.mydomain.com localhost;
        root /u01/servidores/;

        location swissecomer/ {
            index index.html index.htm;
            try_files $uri $uri/ /index.html;
        }

        access_log /var/log/nginx/access_log combined;

    }

When i hit these urls, it shows the webpage just fine:

http://www.mydomain.com.ec/swissecomer/index.html

http://www.mydomain.com.ec/swissecomer/

But if i hit the next url http://www.mydomain.com.ec/swissecomer the ngix server keeps loading until it shows a timeout error in the browser.

Thanks for your responses.


问:
What kind of states and transitions does Spin's "depth reached" consider?
For verifications (with ispin) that use never claims, I get outputs with depth reached larger than the number of states and the number of transitions, e.g.:

```<code>Full statespace search for:
    never claim             + (REQ5)
    assertion violations    + (if within scope of claim)
    cycle checks        - (disabled by -DSAFETY)
    invalid end states  - (disabled by never claim)

State-vector 60 byte, depth reached 87, errors: 1
       41 states, stored
       10 states, matched
       51 transitions (= stored+matched)
        9 atomic steps
hash conflicts:         0 (resolved)
</code>```

I find that a bit unintuitive. Is there a precise description of the semantics of "depth reached" somewhere (more thorough than pan's output format description)? Maybe the meaning of

longest depth-first search path contained 87 transitions

does not refer to the 51 transitions, but to the transitions of the system automata composed with the never claim?

答: Yes, you are (kind of) right when you say it refer  to the transitions of the system automaton composed with the never claim. Yet in the same time it is the length of the path in the system being verified, because one step of system composed with never claim is exactly one step of the system. Of course depending on never claim one might need to explore more or less transition than system has. Paths are not even necessary loop free (depending on the claim) and even not minimal (unless special option is set). </p>

Body:
For verifications (with ispin) that use never claims, I get outputs with depth reached larger than the number of states and the number of transitions, e.g.:

Full statespace search for:
    never claim             + (REQ5)
    assertion violations    + (if within scope of claim)
    cycle checks        - (disabled by -DSAFETY)
    invalid end states  - (disabled by never claim)

State-vector 60 byte, depth reached 87, errors: 1
       41 states, stored
       10 states, matched
       51 transitions (= stored+matched)
        9 atomic steps
hash conflicts:         0 (resolved)

I find that a bit unintuitive. Is there a precise description of the semantics of "depth reached" somewhere (more thorough than pan's output format description)? Maybe the meaning of

longest depth-first search path contained 87 transitions

does not refer to the 51 transitions, but to the transitions of the system automata composed with the never claim?


问:
How does Cakephp 2.x security.salt works?
I'm trying to move my Cakephp 2 project and I want to keep the same database. I have used a hash 'sha1' and the Cakephp security.salt to encrypt the users passwords:

```<code>public static function hash($password, $method = 'sha1', $salt = true) {
    return Security::hash($password, $method, $salt);
}
</code>```

I added (a long time ago) in myproject/app/config/core.php this (with a different password):

```<code>    Configure::write('Security.salt', 'T4R393b0qyJioxfs2guVoUubWwvniR2G0Fgartge');
</code>```

Now I don't know how to use this Security.salt code with another framework. So please:

Does anybody know if I could use this encryption in an Angular 2/4 project (e.g.)?

Any other solution?

Thank you!

答:
I found it! Thanks to everybody.

I have to concatenate the salt and the password. After that I do the hash 'sha1'.

e.g.: hash(Security.salt . $password)

Found it in myproject/cake/libs/security.php as 'ndm' said:

```<code>function hash($string, $type = null, $salt = false) {
    $_this =& Security::getInstance();

    if ($salt) {
        if (is_string($salt)) {
            $string = $salt . $string;
        } else {
            $string = Configure::read('Security.salt') . $string;
        }
    }

    ...
</code>```

Body:
I'm trying to move my Cakephp 2 project and I want to keep the same database. I have used a hash 'sha1' and the Cakephp security.salt to encrypt the users passwords:

public static function hash($password, $method = 'sha1', $salt = true) {
    return Security::hash($password, $method, $salt);
}

I added (a long time ago) in myproject/app/config/core.php this (with a different password):

    Configure::write('Security.salt', 'T4R393b0qyJioxfs2guVoUubWwvniR2G0Fgartge');

Now I don't know how to use this Security.salt code with another framework. So please:

Does anybody know if I could use this encryption in an Angular 2/4 project (e.g.)?

Any other solution?

Thank you!

Body:
I found it! Thanks to everybody.

I have to concatenate the salt and the password. After that I do the hash 'sha1'.

e.g.: hash(Security.salt . $password)

Found it in myproject/cake/libs/security.php as 'ndm' said:

function hash($string, $type = null, $salt = false) {
    $_this =& Security::getInstance();

    if ($salt) {
        if (is_string($salt)) {
            $string = $salt . $string;
        } else {
            $string = Configure::read('Security.salt') . $string;
        }
    }

    ...


问:
avoiding if else statement
I have the following ifelse statement:

```<code>Years=c(2016, 2021, 2026, 2031, 2035)
if (Year == Years[1]){OD = subset(data,data$YEAR>=Years[1] & data$YEAR <= Years[1]+2)}
if (Year == Years[2]){OD = subset(data,data$YEAR>=Years[2]-2 & data$YEAR <= Years[2]+2)}
if (Year == Years[3]){OD = subset(data,data$YEAR>=Years[3]-2 & data$YEAR <= Years[3]+2)}
if (Year == Years[4]){OD = subset(data,data$YEAR>=Years[4]-2 & data$YEAR <= Years[4]+2)}
if (Year == Years[5]){OD = subset(data,data$YEAR>=Years[5]-1 & data$YEAR <= Years[5])}
</code>```

And I would like an efficient way to write this without ifelse statement.

答:
As I understand, you're slicing your data by slices of 5 years centered on the 1st data point, and with a ceiling on the last datapoint, so I hope this does the trick:</p>

```<code>Years=c(2016, 2021, 2025) # shortenned for the demo
set.seed(1)
data = data.frame(Year = sample(2010:2030,20,replace=TRUE),anything=sample(letters,20,replace=TRUE))

# Year anything
# 1  2015        y
# 2  2017        f
# 3  2022        q
# 4  2029        d
# 5  2014        g
# 6  2028        k
# 7  2029        a
# 8  2023        j
# 9  2023        w
# 10 2011        i
# 11 2014        m
# 12 2013        p
# 13 2024        m
# 14 2018        e
# 15 2026        v
# 16 2020        r
# 17 2025        u
# 18 2030        c
# 19 2017        s
# 20 2026        k

# for all of the years of your data we assign a number, the id of the slice it'll be attributed to
group0 <- (data$Year - (min(Years)-7)) %/% 5
# it can contain negative numbers and slices after your max year though so we fix that
group0[data$Year > max(Years) | data$Year < min(Years) ] <- NA
# now we can assign a group to all your rows
data$group <- Years[group0]

#    Year anything group
# 1  2015        y  2016
# 2  2017        f  2016
# 3  2022        q  2021
# 4  2029        d    NA
# 5  2014        g  2016
# 6  2028        k    NA
# 7  2029        a    NA
# 8  2023        j  2021
# 9  2023        w  2021
# 10 2011        i    NA
# 11 2014        m  2016
# 12 2013        p    NA
# 13 2024        m  2025
# 14 2018        e  2016
# 15 2026        v    NA
# 16 2020        r  2021
# 17 2025        u  2025
# 18 2030        c    NA
# 19 2017        s  2016
# 20 2026        k    NA

# and subset it
OD_list <- lapply(Years,function(x){subset(data,group == x)})

# [[1]]
# Year anything group
# 1  2015        y  2016
# 2  2017        f  2016
# 5  2014        g  2016
# 11 2014        m  2016
# 14 2018        e  2016
# 19 2017        s  2016
#
# [[2]]
# Year anything group
# 3  2022        q  2021
# 8  2023        j  2021
# 9  2023        w  2021
# 16 2020        r  2021
#
# [[3]]
# Year anything group
# 13 2024        m  2025
# 17 2025        u  2025
</code>```

Title: avoiding if else statement

Body:
I have the following ifelse statement:

Years=c(2016, 2021, 2026, 2031, 2035)
if (Year == Years[1]){OD = subset(data,data$YEAR>=Years[1] & data$YEAR <= Years[1]+2)}
if (Year == Years[2]){OD = subset(data,data$YEAR>=Years[2]-2 & data$YEAR <= Years[2]+2)}
if (Year == Years[3]){OD = subset(data,data$YEAR>=Years[3]-2 & data$YEAR <= Years[3]+2)}
if (Year == Years[4]){OD = subset(data,data$YEAR>=Years[4]-2 & data$YEAR <= Years[4]+2)}
if (Year == Years[5]){OD = subset(data,data$YEAR>=Years[5]-1 & data$YEAR <= Years[5])}

And I would like an efficient way to write this without ifelse statement.

Body:
As I understand, you're slicing your data by slices of 5 years centered on the 1st data point, and with a ceiling on the last datapoint, so I hope this does the trick:

Years=c(2016, 2021, 2025) # shortenned for the demo
set.seed(1)
data = data.frame(Year = sample(2010:2030,20,replace=TRUE),anything=sample(letters,20,replace=TRUE))

# Year anything
# 1  2015        y
# 2  2017        f
# 3  2022        q
# 4  2029        d
# 5  2014        g
# 6  2028        k
# 7  2029        a
# 8  2023        j
# 9  2023        w
# 10 2011        i
# 11 2014        m
# 12 2013        p
# 13 2024        m
# 14 2018        e
# 15 2026        v
# 16 2020        r
# 17 2025        u
# 18 2030        c
# 19 2017        s
# 20 2026        k

# for all of the years of your data we assign a number, the id of the slice it'll be attributed to
group0 <- (data$Year - (min(Years)-7)) %/% 5
# it can contain negative numbers and slices after your max year though so we fix that
group0[data$Year > max(Years) | data$Year < min(Years) ] <- NA
# now we can assign a group to all your rows
data$group <- Years[group0]

#    Year anything group
# 1  2015        y  2016
# 2  2017        f  2016
# 3  2022        q  2021
# 4  2029        d    NA
# 5  2014        g  2016
# 6  2028        k    NA
# 7  2029        a    NA
# 8  2023        j  2021
# 9  2023        w  2021
# 10 2011        i    NA
# 11 2014        m  2016
# 12 2013        p    NA
# 13 2024        m  2025
# 14 2018        e  2016
# 15 2026        v    NA
# 16 2020        r  2021
# 17 2025        u  2025
# 18 2030        c    NA
# 19 2017        s  2016
# 20 2026        k    NA

# and subset it
OD_list <- lapply(Years,function(x){subset(data,group == x)})

# [[1]]
# Year anything group
# 1  2015        y  2016
# 2  2017        f  2016
# 5  2014        g  2016
# 11 2014        m  2016
# 14 2018        e  2016
# 19 2017        s  2016
#
# [[2]]
# Year anything group
# 3  2022        q  2021
# 8  2023        j  2021
# 9  2023        w  2021
# 16 2020        r  2021
#
# [[3]]
# Year anything group
# 13 2024        m  2025
# 17 2025        u  2025


问:
Calculate percentage in SQL
I'm trying to create table (columns) using another table(s), having trouble in the getting the desired columns. Please guide.

Table Names: Transactions, Customer, Prod_cat_info

```<code>SELECT DISTINCT T.cust_id,
                c.gender,
                C.city_code,
                Datediff(mm, c.dob, Getdate())             AS AGE_IN_MONTHS,
                (SELECT Count(transaction_id)
                 FROM   transactions
                 GROUP  BY tran_date)                      AS
                basket_count_per_day,
                (SELECT Sum(total_amt)
                 FROM   transactions)                      AS Tot_sal_amt,
                (SELECT Sum(qty)
                 FROM   transactions)                      AS tot_sal_qnty,
                (SELECT Count(DISTINCT prod_cat)
                 FROM   dbo.prod_cat_info)                 AS Unq_cat_cnt,
                (SELECT DISTINCT prod_subcat
                 FROM   dbo.prod_cat_info)                 AS Unq_Scat_cnt,
                (SELECT DISTINCT store_type
                 FROM   dbo.transactions)                  AS Unq_chnl_cnt,
                (SELECT Max(tran_date)
                 FROM   dbo.transactions)                  AS
                Last_Transaction_date,
                (SELECT Avg(qty) / Count(tran_date)
                 from transactions)                        AS
                                                           Avg_basket_qty,
                (SELECT Avg(total_amt) / Count(tran_date)
                 from transactions)
                                                         AS Avg_basket_val
INTO   customer_360
FROM   dbo.customer AS c
       INNER JOIN dbo.transactions AS t
               ON t.cust_id = c.customer_id
       INNER JOIN dbo.prod_cat_info AS pci
               ON pci.prod_cat_code = t.prod_cat_code
</code>```

Error Message:

Msg 8120, Level 16, State 1, Line 1

  Column 'dbo.Transactions.cust_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

答:
The last two columns are aggregation queries. Because you have a SELECT with no FROM it will query the tables specified in the outer query.

```<code>            (SELECT Avg(qty) / Count(tran_date))       AS Avg_basket_qty,
            (SELECT Avg(total_amt) / Count(tran_date)) AS Avg_basket_val
</code>```

In this case you're aggregating qty,tran_date and total_amount, as such every other column needs either grouping or aggregating.

Adding the following should make it a valid query, it may not do what you want though!

```<code>GROUP BY T.cust_id, c.Gender, C.city_code, DATEDIFF(mm,c.DOB,GETDATE())
</code>```

Title: Calculate percentage in SQL

Body:
I'm trying to create table (columns) using another table(s), having trouble in the getting the desired columns. Please guide.

Table Names: Transactions, Customer, Prod_cat_info

SELECT DISTINCT T.cust_id,
                c.gender,
                C.city_code,
                Datediff(mm, c.dob, Getdate())             AS AGE_IN_MONTHS,
                (SELECT Count(transaction_id)
                 FROM   transactions
                 GROUP  BY tran_date)                      AS
                basket_count_per_day,
                (SELECT Sum(total_amt)
                 FROM   transactions)                      AS Tot_sal_amt,
                (SELECT Sum(qty)
                 FROM   transactions)                      AS tot_sal_qnty,
                (SELECT Count(DISTINCT prod_cat)
                 FROM   dbo.prod_cat_info)                 AS Unq_cat_cnt,
                (SELECT DISTINCT prod_subcat
                 FROM   dbo.prod_cat_info)                 AS Unq_Scat_cnt,
                (SELECT DISTINCT store_type
                 FROM   dbo.transactions)                  AS Unq_chnl_cnt,
                (SELECT Max(tran_date)
                 FROM   dbo.transactions)                  AS
                Last_Transaction_date,
                (SELECT Avg(qty) / Count(tran_date)
                 from transactions)                        AS
                                                           Avg_basket_qty,
                (SELECT Avg(total_amt) / Count(tran_date)
                 from transactions)
                                                         AS Avg_basket_val
INTO   customer_360
FROM   dbo.customer AS c
       INNER JOIN dbo.transactions AS t
               ON t.cust_id = c.customer_id
       INNER JOIN dbo.prod_cat_info AS pci
               ON pci.prod_cat_code = t.prod_cat_code

Error Message:

Msg 8120, Level 16, State 1, Line 1

  Column 'dbo.Transactions.cust_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Body:
The last two columns are aggregation queries. Because you have a SELECT with no FROM it will query the tables specified in the outer query.

            (SELECT Avg(qty) / Count(tran_date))       AS Avg_basket_qty,
            (SELECT Avg(total_amt) / Count(tran_date)) AS Avg_basket_val

In this case you're aggregating qty,tran_date and total_amount, as such every other column needs either grouping or aggregating.

Adding the following should make it a valid query, it may not do what you want though!

GROUP BY T.cust_id, c.Gender, C.city_code, DATEDIFF(mm,c.DOB,GETDATE())


问:
What is the correct way to parse IPs and CIDRs out of text in Python
I found many threads about this topic, with distinct and complex answers.

For IPv4:

```<code>ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', file)
</code>```

That works for 8.8.8.8 but not for 8.8.8.8/32. I tried to add some (?:/(\d+) to catch the /X. Without success.

Now I also see IPv6 IPs in my file. Do you really have to regex-search for IPv6 IPs the same way? Is there some easier way to search for IPs in text with Python?

答:
You can use this pattern (for IPv4):

```<code>[0-9]+(?:\.[0-9]+){3}(?:\/[\d]+)?
</code>```

Which matches the optional subnet when present. Here's a demo.

For matching in python, you'll need to do this:

```<code>ip = re.findall(r'\b[0-9]+(?:\.[0-9]+){3}(?:\/[\d]+)?\b', file, flags=re.M)
</code>```

Assuming, file is a multiline string. If not, you'll need to do file.read().

Body:
I found many threads about this topic, with distinct and complex answers.

For IPv4:

ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', file)

That works for 8.8.8.8 but not for 8.8.8.8/32. I tried to add some (?:/(\d+) to catch the /X. Without success.

Now I also see IPv6 IPs in my file. Do you really have to regex-search for IPv6 IPs the same way? Is there some easier way to search for IPs in text with Python?

Body:
You can use this pattern (for IPv4):

[0-9]+(?:\.[0-9]+){3}(?:\/[\d]+)?

Which matches the optional subnet when present. Here's a demo.

For matching in python, you'll need to do this:

ip = re.findall(r'\b[0-9]+(?:\.[0-9]+){3}(?:\/[\d]+)?\b', file, flags=re.M)

Assuming, file is a multiline string. If not, you'll need to do file.read().


答:
Use the provided API. First register to get an API key here. Then you can use Python's urllib2 package to fetch the results, e.g.

```<code>import urllib2
import json
import pprint
data = urllib2.urlopen('https://www.googleapis.com/customsearch/v1?key=YOUR_KEY_HERE&cx=017576662512468239146:omuauf_lfve&q=lectures')
data = json.load(data)
pprint.PrettyPrinter(indent=4).pprint(data['items'][0]) # Print the raw content of the first result
</code>```

Which outputs

```<code>{   'cacheid': 'TxVqFzFZLOsJ',
    'displayLink': 'www.stanford.edu',
    'htmlSnippet': 'Apr 7, 2010 \\u003cb\\u003e...\\u003c/b\\u003e Course materials. \\u003cb\
\u003eLecture\\u003c/b\\u003e slides \xc2\xb7 \\u003cb\\u003eLecture\\u003c/b\\u003e videos (2
008) \xc2\xb7 Review sessions. \\u003cbr\\u003e  Assignments. Homework \xc2\xb7 Reading. Exams
. Final exam \\u003cb\\u003e...\\u003c/b\\u003e',
    'htmlTitle': 'EE364a: \\u003cb\\u003eLecture\\u003c/b\\u003e Videos',
    'kind': 'customsearch#result',
    'link': 'http://www.stanford.edu/class/ee364a/videos.html',
    'snippet': 'Apr 7, 2010 ... Course materials. Lecture slides \xc2\xb7 Lecture videos (2008
) \xc2\xb7 Review sessions.   Assignments. Homework \xc2\xb7 Reading. Exams. Final exam ...',
        'title': 'EE364a: Lecture Videos'}
</code>```

Please make sure to replace YOUR_KEY_HERE with your key.

To create an MS Word document from Python, read this question.

Title: Google search with Python

Body: How do you perform a search query on Google using Python? How do you store the search results in a Microsoft Word document?

Body:
Use the provided API. First register to get an API key here. Then you can use Python's urllib2 package to fetch the results, e.g.

import urllib2
import json
import pprint
data = urllib2.urlopen('https://www.googleapis.com/customsearch/v1?key=YOUR_KEY_HERE&cx=017576662512468239146:omuauf_lfve&q=lectures')
data = json.load(data)
pprint.PrettyPrinter(indent=4).pprint(data['items'][0]) # Print the raw content of the first result

Which outputs

{   'cacheid': 'TxVqFzFZLOsJ',
    'displayLink': 'www.stanford.edu',
    'htmlSnippet': 'Apr 7, 2010 \\u003cb\\u003e...\\u003c/b\\u003e Course materials. \\u003cb\
\u003eLecture\\u003c/b\\u003e slides \xc2\xb7 \\u003cb\\u003eLecture\\u003c/b\\u003e videos (2
008) \xc2\xb7 Review sessions. \\u003cbr\\u003e  Assignments. Homework \xc2\xb7 Reading. Exams
. Final exam \\u003cb\\u003e...\\u003c/b\\u003e',
    'htmlTitle': 'EE364a: \\u003cb\\u003eLecture\\u003c/b\\u003e Videos',
    'kind': 'customsearch#result',
    'link': 'http://www.stanford.edu/class/ee364a/videos.html',
    'snippet': 'Apr 7, 2010 ... Course materials. Lecture slides \xc2\xb7 Lecture videos (2008
) \xc2\xb7 Review sessions.   Assignments. Homework \xc2\xb7 Reading. Exams. Final exam ...',
        'title': 'EE364a: Lecture Videos'}

Please make sure to replace YOUR_KEY_HERE with your key.

To create an MS Word document from Python, read this question.


问:
jump to last non-empty cell in row
Saved a Macro where I would go to to the last non-empty cell in a row by using CTRL+Right Arrow.
The macro, however, was saved by logging the J23 cell.
I want it to be dynamic so that if last non-empty cell changes, for instance, it is N23, it jumps there.

I would like that my other steps would then always link to cells L30, M30, N30 and O30 but in this case they are using relative coordinates (I tried to edit the macro from J23 to N23, for instance, and the linked cells change)

What are the code lines that I can use to make it dynamic the way I need?

Thank you for your help

```<code>Sub KPILinks()
'
' KPILinks Macro
'

'
    Range("I22").Select
    Selection.End(xlToRight).Select
    Range("J23").Select
    ActiveCell.FormulaR1C1 = "=R[7]C[2]"
    Range("J24").Select
    ActiveCell.FormulaR1C1 = "=R[6]C[3]"
    Range("J25").Select
    ActiveCell.FormulaR1C1 = "=R[5]C[4]"
    Range("J26").Select
    ActiveCell.FormulaR1C1 = "=R[4]C[5]"
    Range("J27").Select

End Sub
</code>```

答:
borrowed from https://www.rondebruin.nl/win/s9/win005.htm</p>

```<code>Sub LastRowInOneColumn()
'Find the last used row in a Column: column A in this example
Dim LastRow As Long
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
MsgBox LastRow
End Sub
</code>```

Title: jump to last non-empty cell in row

Body:
Saved a Macro where I would go to to the last non-empty cell in a row by using CTRL+Right Arrow.
The macro, however, was saved by logging the J23 cell.
I want it to be dynamic so that if last non-empty cell changes, for instance, it is N23, it jumps there.

I would like that my other steps would then always link to cells L30, M30, N30 and O30 but in this case they are using relative coordinates (I tried to edit the macro from J23 to N23, for instance, and the linked cells change)

What are the code lines that I can use to make it dynamic the way I need?

Thank you for your help

Sub KPILinks()
'
' KPILinks Macro
'

'
    Range("I22").Select
    Selection.End(xlToRight).Select
    Range("J23").Select
    ActiveCell.FormulaR1C1 = "=R[7]C[2]"
    Range("J24").Select
    ActiveCell.FormulaR1C1 = "=R[6]C[3]"
    Range("J25").Select
    ActiveCell.FormulaR1C1 = "=R[5]C[4]"
    Range("J26").Select
    ActiveCell.FormulaR1C1 = "=R[4]C[5]"
    Range("J27").Select

End Sub

Body:
borrowed from https://www.rondebruin.nl/win/s9/win005.htm

Sub LastRowInOneColumn()
'Find the last used row in a Column: column A in this example
Dim LastRow As Long
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
MsgBox LastRow
End Sub


问:
ojInput date issue with storing and retrieving from oracle DB
I have used a ojInputDate field in my html form. The first time I save the form the date field value is getting stored in oracle sql Date in db. But when I reopen the form again for editing I am unable to edit it. How can I handle the OjInput date and oracle sql Date types</p>

答:
How did you implement the REST API? The API likely uses JSON and JSON doesn't support dates. Most often, dates are converted to ISO 8601 strings as they move between the client and database. It's crucial to understand what happens with time zones when these conversions happen.

Here's a link to a series where I cover this in detail. If you're using Oracle REST data services or the Node.js driver, then you should find the info you're looking for. Otherwise, please provide some more details so we can better help.


问:
SceneKit leaking when cloning a node
I have an asset loading and caching singleton defined as such:

```<code>class AssetLoader {
    fileprivate var rootNodes = Dictionary<String, SCNNode>()

    static let sharedInstance = AssetLoader()

    fileprivate init() {
    }

    func rootNode(_ named: String) -> SCNNode {
        if self.rootNodes[named] != nil {
            return self.rootNodes[named]!.clone()
        } else {
            let scene = SCNScene(named: "art.scnassets/\(named).scn")
            self.rootNodes[named] = scene!.rootNode
            return self.rootNodes[named]!.clone()
        }
    }
}
</code>```

I am using it to make my scene building faster. I'm creating assets from extensions as such:

```<code>extension CAAnimation {
    class func animationWithScene(named: String) -> CAAnimation? {
        unowned let rootNode = AssetLoader.sharedInstance.rootNode(named)
        var animation: CAAnimation?

        rootNode.enumerateChildNodes({ (child, stop) in
            if child.animationKeys.count > 0 {
                animation = child.animation(forKey: child.animationKeys.first!)
                stop.initialize(to: true)
            }
        })
        return animation
    }
}

extension SCNNode {
    class func nodeWithScene(named: String) -> SCNNode? {
        unowned let rootNode = AssetLoader.sharedInstance.rootNode(named)
        let node = SCNNode()

        for child in rootNode.childNodes {
            node.addChildNode(child)
        }

        node.eulerAngles = SCNVector3(x: Float(-M_PI_2), y: 0, z: 0)
        node.scale = SCNVector3Make(kMeshScale, kMeshScale, kMeshScale)

        return node
    }
}
</code>```

Instruments is saying I'm leaking memory like crazy on each calls to clone(). I tried using weak and unowned wherever I could without causing crashes and it doesn't change anything. Anyone has a clue? Is that a bug in SceneKit?

Thanks

答:
If I understand correctly you keep your original nodes in the rootNodes Dictionary of your AssetLoader and return a clone of those in the rootNode func.

My architecture is similar and my issue was the following : when I would remove the cloned node from the scene tree the memory wouldn't get released. Is that your problem?

I fixed the issue by adding an "unload" func in my singleton to nullify  the original nodes when removing the cloned nodes from the scene tree. That fixed my memory issues.

With your code that would look something like :

```<code>func unloadRootNode(_ named: String) {
    rootNodes.removeValue(forKey: named)
}
</code>```

Title: SceneKit leaking when cloning a node

Body:
I have an asset loading and caching singleton defined as such:

class AssetLoader {
    fileprivate var rootNodes = Dictionary<String, SCNNode>()

    static let sharedInstance = AssetLoader()

    fileprivate init() {
    }

    func rootNode(_ named: String) -> SCNNode {
        if self.rootNodes[named] != nil {
            return self.rootNodes[named]!.clone()
        } else {
            let scene = SCNScene(named: "art.scnassets/\(named).scn")
            self.rootNodes[named] = scene!.rootNode
            return self.rootNodes[named]!.clone()
        }
    }
}

I am using it to make my scene building faster. I'm creating assets from extensions as such:

extension CAAnimation {
    class func animationWithScene(named: String) -> CAAnimation? {
        unowned let rootNode = AssetLoader.sharedInstance.rootNode(named)
        var animation: CAAnimation?

        rootNode.enumerateChildNodes({ (child, stop) in
            if child.animationKeys.count > 0 {
                animation = child.animation(forKey: child.animationKeys.first!)
                stop.initialize(to: true)
            }
        })
        return animation
    }
}

extension SCNNode {
    class func nodeWithScene(named: String) -> SCNNode? {
        unowned let rootNode = AssetLoader.sharedInstance.rootNode(named)
        let node = SCNNode()

        for child in rootNode.childNodes {
            node.addChildNode(child)
        }

        node.eulerAngles = SCNVector3(x: Float(-M_PI_2), y: 0, z: 0)
        node.scale = SCNVector3Make(kMeshScale, kMeshScale, kMeshScale)

        return node
    }
}

Instruments is saying I'm leaking memory like crazy on each calls to clone(). I tried using weak and unowned wherever I could without causing crashes and it doesn't change anything. Anyone has a clue? Is that a bug in SceneKit?

Thanks

Body:
If I understand correctly you keep your original nodes in the rootNodes Dictionary of your AssetLoader and return a clone of those in the rootNode func.

My architecture is similar and my issue was the following : when I would remove the cloned node from the scene tree the memory wouldn't get released. Is that your problem?

I fixed the issue by adding an "unload" func in my singleton to nullify  the original nodes when removing the cloned nodes from the scene tree. That fixed my memory issues.

With your code that would look something like :

func unloadRootNode(_ named: String) {
    rootNodes.removeValue(forKey: named)
}


问:
Xcode type number in the power
How can I type a number in the power (exponentiation) in Xcode. I am creating a calculator in Xcode, but cannot make it out, how to type such functions into the buttons like x^2, x^3, x^y. The only way I can use to solve this problem is to copy-paste such symbols from google (x², xʸ etc.) But it does not seem right. In "emoji and symbols" cannot find them either. Maybe there is some hot key in Mac, Xcode, the analog to ctrl-shift-+ in MS Word?

答: thanks for your help! ) Indeed, by typing "superscript" in emoji and symbols' search box did help. Some symbols printed above the line really popped up, now I can easily type into my buttons something like x², x³, xʸ, sin⁻¹ etc. But after all it's a pity that there is no hot key for that in xCode, Swift like ctrl-shift-+ in MS Word.</p>

Title: Xcode type number in the power


问:
Select values out of XML column
This is the structure of my table

```<code>CREATE TABLE [dbo].[TableA]
(
    [ObjectID] [int] IDENTITY(1,1) NOT NULL,
    [CGPracticeCode] [varchar](5) NULL,
    [TotalAmt] [decimal](11, 2) NULL,
    [SplitAmt] [xml] NULL,
)
</code>```

The value in the SplitAmt Column are in the below format, no of rows may vary

```<code>'<Values>
  <Row>
    <PracticeCode>BE9</PracticeCode>
    <Value>20</Value>
  </Row>
  <Row>
    <PracticeCode>BEA</PracticeCode>
    <Value>3</Value>
  </Row>
</Values>'
</code>```

Now How do I get values like this... (No problem in repeating 1st 3 columns)

```<code>ObjectID, CGPracticeCode, TotalAmt, PracticeCode, [Value]
</code>```

答:
Have a look at this article by Alex Homer

To return the first Row elements you can use:

```<code>select a.ObjectId,
       a.CGPracticeCode,
       a.TotalAmt,
       a.SplitAmt.value('(/Values/Row/PracticeCode)[1]', 'nvarchar(50)') as PracticeCode,
       a.SplitAmt.value('(/Values/Row/Value)[1]', 'int') as [Value]
from [dbo].[TableA] a
</code>```

Title: Select values out of XML column

Body:
This is the structure of my table

CREATE TABLE [dbo].[TableA]
(
    [ObjectID] [int] IDENTITY(1,1) NOT NULL,
    [CGPracticeCode] [varchar](5) NULL,
    [TotalAmt] [decimal](11, 2) NULL,
    [SplitAmt] [xml] NULL,
)

The value in the SplitAmt Column are in the below format, no of rows may vary

'<Values>
  <Row>
    <PracticeCode>BE9</PracticeCode>
    <Value>20</Value>
  </Row>
  <Row>
    <PracticeCode>BEA</PracticeCode>
    <Value>3</Value>
  </Row>
</Values>'

Now How do I get values like this... (No problem in repeating 1st 3 columns)

ObjectID, CGPracticeCode, TotalAmt, PracticeCode, [Value]

Body:
Have a look at this article by Alex Homer

To return the first Row elements you can use:

select a.ObjectId,
       a.CGPracticeCode,
       a.TotalAmt,
       a.SplitAmt.value('(/Values/Row/PracticeCode)[1]', 'nvarchar(50)') as PracticeCode,
       a.SplitAmt.value('(/Values/Row/Value)[1]', 'int') as [Value]
from [dbo].[TableA] a


问:
Aggregate properties
I'm developing my own Fuseki endpoint from some DBpedia data.
I'm in doubt on how to aggregate properties related to a single resource.

SELECT ?name ?website ?abstract ?genre ?image
WHERE{
VALUES ?s {<http://dbpedia.org/resource/Attack_Attack!>}
  ?s  foaf:name ?name ;
      dbo:abstract ?abstract .
  OPTIONAL { ?s dbo:genre ?genre } .
  OPTIONAL { ?s dbp:website ?website } .
  OPTIONAL { ?s dbo:image ?image } .
  FILTER LANGMATCHES(LANG(?abstract ), "en")
}
```

SPARQL endpoint: http://dbpedia.org/sparql/

This query returns 2 matching results. They are different just for the dbo:genre value. There is a way I can query the knowledge base and retrieving a single result with a list of genres?

答:
@chrisis's query works well on the DBpedia SPARQL Endpoint, which is based on Virtuoso.

However, if you are using Jena Fuseki, you should use more conformant syntax:

PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://dbpedia.org/property/>

SELECT
?name
(SAMPLE(?website) AS ?sample_website)
(SAMPLE(?abstract) AS ?sample_abstract)
(SAMPLE(?image) AS ?sample_image)
(GROUP_CONCAT(?genre; separator=', ') AS ?genres)
WHERE {
  VALUES (?s) {(<http://dbpedia.org/resource/Attack_Attack!>)}
  ?s  foaf:name ?name ;
      dbo:abstract ?abstract .
  OPTIONAL { ?s dbo:genre ?genre } .
  OPTIONAL { ?s dbp:website ?website } .
  OPTIONAL { ?s dbo:image ?image} .
  FILTER LANGMATCHES(LANG(?abstract ), "en")
} GROUP BY ?name
```

The differences from the @chrisis's query are:

Since GROUP_CONCAT is an aggregation function, it might be used with GROUP BY only;

Since  GROUP BY is used, all non-grouping variables should be aggregated (e.g. via SAMPLE);

GROUP_CONCAT syntax is slightly different.

In Fuseki, these AS in the projection are in fact superfluous: see this question and comments.

Title: Aggregate properties

Body:
I'm developing my own Fuseki endpoint from some DBpedia data.
I'm in doubt on how to aggregate properties related to a single resource.

SELECT ?name ?website ?abstract ?genre ?image
WHERE{
VALUES ?s {<http://dbpedia.org/resource/Attack_Attack!>}
  ?s  foaf:name ?name ;
      dbo:abstract ?abstract .
  OPTIONAL { ?s dbo:genre ?genre } .
  OPTIONAL { ?s dbp:website ?website } .
  OPTIONAL { ?s dbo:image ?image } .
  FILTER LANGMATCHES(LANG(?abstract ), "en")
}

SPARQL endpoint: http://dbpedia.org/sparql/

This query returns 2 matching results. They are different just for the dbo:genre value. There is a way I can query the knowledge base and retrieving a single result with a list of genres?

Body:
@chrisis's query works well on the DBpedia SPARQL Endpoint, which is based on Virtuoso.

However, if you are using Jena Fuseki, you should use more conformant syntax:

PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX dbp: <http://dbpedia.org/property/>

SELECT
?name
(SAMPLE(?website) AS ?sample_website)
(SAMPLE(?abstract) AS ?sample_abstract)
(SAMPLE(?image) AS ?sample_image)
(GROUP_CONCAT(?genre; separator=', ') AS ?genres)
WHERE {
  VALUES (?s) {(<http://dbpedia.org/resource/Attack_Attack!>)}
  ?s  foaf:name ?name ;
      dbo:abstract ?abstract .
  OPTIONAL { ?s dbo:genre ?genre } .
  OPTIONAL { ?s dbp:website ?website } .
  OPTIONAL { ?s dbo:image ?image} .
  FILTER LANGMATCHES(LANG(?abstract ), "en")
} GROUP BY ?name

The differences from the @chrisis's query are:

Since GROUP_CONCAT is an aggregation function, it might be used with GROUP BY only;

Since  GROUP BY is used, all non-grouping variables should be aggregated (e.g. via SAMPLE);

GROUP_CONCAT syntax is slightly different.

In Fuseki, these AS in the projection are in fact superfluous: see this question and comments.


问:
Fixed width layout with one child spanning full screen width
Can I create a layout like on the picture below, while setting the fixed width only on the parent container?  I also cannot use position: absolute; left: 0; right: 0; on Full screen width child, as I cannot remove it from the flow, because it's size is dynamic.

I can't change the markup.

The only solution I can think of is setting the fixed width on every Fixed-width child separately, but as I have a lot of them, that's not the most comfortable solution - means adding a class for every child that I add into the parent container.

Here is an example markup you can post a solution to.

HTML

```<code><div class="fixed-width-container">
  <div class="regular-child"></div>
  <div class="full-screen-width-child"></div>
  <div class="regular-child"></div>
  <div class="regular-child"></div>
</div>
</code>```

CSS

```<code>.fixed-width-container {
  width: <some-fixed-width>;
}
</code>```

答:
This is just an attempt, and probably not a very good one. But maybe it will spawn some more sophisticated solutions by others, or even yourself.

Idea: negative margins for the full-width child.

* {
  box-sizing: border-box;
  text-align: center;
}

body {
  width: 100%;
  background: #fff;
}

div {
  border: 1px solid #333;
  margin-bottom: 10px;
}

div:last-child {
  margin-bottom: 0;
}

.fixed-width-container {
  width: 70%;
  margin: auto;
  padding: 10px;
  background: LightYellow;
}

.regular-child,
.full-screen-width-child {
  height: 45px;
  line-height: 45px;
  background: LightBlue;
}

.full-screen-width-child {
  margin-left: -24%;
  margin-right: -24%;
  background: LightGreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="fixed-width-container">
  <div class="regular-child">Fixed-width child</div>
  <div class="full-screen-width-child">Full screen width child with dynamic contents</div>
  <div class="regular-child">Fixed-width child</div>
  <div class="regular-child">Fixed-width child</div>
</div></code>```

The problematic part here is the dimension of the negative margins. If you use %, it will relate to the width of the fixed-width-container. Here, I chose width: 70% for it. Given a body width of 625px (as is the case for the Stack Snippet preview) and a margin of -24%, that would give a negative margin of 625px * 0.7 * 0.24 = 105px. I'm not sure what's the best approach of making this work for any configuration.

Body:
Can I create a layout like on the picture below, while setting the fixed width only on the parent container?  I also cannot use position: absolute; left: 0; right: 0; on Full screen width child, as I cannot remove it from the flow, because it's size is dynamic.

I can't change the markup.

The only solution I can think of is setting the fixed width on every Fixed-width child separately, but as I have a lot of them, that's not the most comfortable solution - means adding a class for every child that I add into the parent container.

Here is an example markup you can post a solution to.

HTML

CSS

.fixed-width-container {
  width: <some-fixed-width>;
}

Body:
This is just an attempt, and probably not a very good one. But maybe it will spawn some more sophisticated solutions by others, or even yourself.

Idea: negative margins for the full-width child.

* {
  box-sizing: border-box;
  text-align: center;
}

body {
  width: 100%;
  background: #fff;
}

div {
  border: 1px solid #333;
  margin-bottom: 10px;
}

div:last-child {
  margin-bottom: 0;
}

.fixed-width-container {
  width: 70%;
  margin: auto;
  padding: 10px;
  background: LightYellow;
}

.regular-child,
.full-screen-width-child {
  height: 45px;
  line-height: 45px;
  background: LightBlue;
}

.full-screen-width-child {
  margin-left: -24%;
  margin-right: -24%;
  background: LightGreen;
}

<div class="fixed-width-container">
  <div class="regular-child">Fixed-width child</div>
  <div class="full-screen-width-child">Full screen width child with dynamic contents</div>
  <div class="regular-child">Fixed-width child</div>
  <div class="regular-child">Fixed-width child</div>
</div>

The problematic part here is the dimension of the negative margins. If you use %, it will relate to the width of the fixed-width-container. Here, I chose width: 70% for it. Given a body width of 625px (as is the case for the Stack Snippet preview) and a margin of -24%, that would give a negative margin of 625px * 0.7 * 0.24 = 105px. I'm not sure what's the best approach of making this work for any configuration.


问:
A unicode error with installing win_unc library
I am trying to install a win_unc library and I get the following error:

```<code>File "unc_credentials.py", line 36 """
Syntax error: (unicode error) 'unicodescape' codec can't decode bytes in position 340-341: truncated \uXXXX escape
</code>```

and this is the code snippet from the unc_credentials.py that is causing the issue:

```<code>def __init__(self, username=None, password=None):
    """
    Returns a new `UncCredentials` object. Both `username` and `password` are optional.
    If neither are provided, the new object will mean that credentials are unnecessary.
    `username` must be a string representing a Windows username (logon). Windows usernames
               may include a domain prefix (i.e. "domain\username"). If `username` cannot be
               construed as a valid Windows username, then this will raise an
               `InvalidUsernameError`.
               Note: UNC connections that require authentication will use the username of the
                     currently logged in Windows user unless specifically provided another
                     username.
               Note: Providing `None` and `""` (the empty string) have very different meanings.
                     Usernames cannot be empty.
    `password` must be a string representing a password.
               Note: Providing `None` and `''` (the empty string) have very different meanings.
               The empty string is a meaningful, legitimate password.

    If only the first positional argument is provided and it is already an instance of the
    `UncCredentials` class (either directly or by inheritance), this constructor will clone
    it and create a new `UncCredentials` object with the same properties.
    """
</code>```

the very last line with """" is line 36.

It looks like just a comment to me, but when I get rid of it I get another error no commands supplied

And it seems like there is an issue with the triple-double quotation marks on the last line, I may be wrong though.

I have tried playing around with different quotation marks and use 'r' in front of the strings, but I either get the same error or no commands supplied.

I would really appreciate any suggestions on how I can work around or fix this issue.

答:
I no longer maintain this library. I cannot tell what's going on here but the only thing that comes to mind is the file was somehow corrupted during downloading or saving. If you open a HEX editor and inspect positions 340-341 as it suggests, you may find an odd non-ASCII character.

Please note that win_unc does not support systems using any language other than English.

Body:
I am trying to install a win_unc library and I get the following error:

File "unc_credentials.py", line 36 """
Syntax error: (unicode error) 'unicodescape' codec can't decode bytes in position 340-341: truncated \uXXXX escape

and this is the code snippet from the unc_credentials.py that is causing the issue:

def __init__(self, username=None, password=None):
    """
    Returns a new `UncCredentials` object. Both `username` and `password` are optional.
    If neither are provided, the new object will mean that credentials are unnecessary.
    `username` must be a string representing a Windows username (logon). Windows usernames
               may include a domain prefix (i.e. "domain\username"). If `username` cannot be
               construed as a valid Windows username, then this will raise an
               `InvalidUsernameError`.
               Note: UNC connections that require authentication will use the username of the
                     currently logged in Windows user unless specifically provided another
                     username.
               Note: Providing `None` and `""` (the empty string) have very different meanings.
                     Usernames cannot be empty.
    `password` must be a string representing a password.
               Note: Providing `None` and `''` (the empty string) have very different meanings.
               The empty string is a meaningful, legitimate password.

    If only the first positional argument is provided and it is already an instance of the
    `UncCredentials` class (either directly or by inheritance), this constructor will clone
    it and create a new `UncCredentials` object with the same properties.
    """

the very last line with """" is line 36.

It looks like just a comment to me, but when I get rid of it I get another error no commands supplied

And it seems like there is an issue with the triple-double quotation marks on the last line, I may be wrong though.

I have tried playing around with different quotation marks and use 'r' in front of the strings, but I either get the same error or no commands supplied.

I would really appreciate any suggestions on how I can work around or fix this issue.


问:
How to conditionally add animations in Angular 2
I have a form component that has fields, some fields I want to animate when they appear in the form, but not every field.

```<code><div *ngFor="let field of form.Fields">
    <div [ngSwitch]="field.Type" [@slideOut]>
        <!-- more field stuff -->
    </div>
</div>
</code>```

With other attributes I can do something like this [attr.required]="field.Required" But [attr.@slideOut] doesn't seem to work.

Ideally I would like to have an animation property on my field so I could pass in animations like this [@field.Animation] but I can't find any documentation on how I would do anything like this. Any ideas?

答:
I've come up against a similar problem and found that you need to take a slightly different approach.

In Angular, animations are linked to state. So instead of defining a different trigger for your animation in your HTML, you want to define multiple states that your trigger can watch for in your component class. And rather than triggering animations directly from a method, you set the state of the object an animation is linked to.

So for instance I might define the following in the component decorator after importing the necessary modules.

```<code>@Component({
  selector: 'app-some-animated',
  templateUrl: './some.component.html',
  styleUrls: ['./some-animated.component.scss'],
  animations: [
    trigger('flyInOut', [
      transition("void => fly", [
        animate(300, keyframes([
          style({transform: 'translateX(100%)', opacity: 0}),
          style({transform: 'translateX(0)', opacity: 1})
        ]))
        ]
      )
    ]),
    trigger('flyInOut', [
      transition("void => fade", [
          animate(300, keyframes([
            style({opacity: 0}),
            style({opacity: 1})
          ]))
        ]
      )
    ])
  ]
})
</code>```

In this instance I'm making the animations happen as soon as the element is instantiated. And in the ngOnInit() method I'm setting this.watchMe to "fly" or "fade".

In the html I'm attaching the flyInOut trigger like so:

```<code><div [@flyInOut]="watchMe">
  Some content...
</div>
</code>```

In your case you probably want to add the required state to your field objects or as an iterable condition from your *ngFor.

This article from coursetro has a nice explanation and a video too.

Body:
I have a form component that has fields, some fields I want to animate when they appear in the form, but not every field.

With other attributes I can do something like this [attr.required]="field.Required" But [attr.@slideOut] doesn't seem to work.

Ideally I would like to have an animation property on my field so I could pass in animations like this [@field.Animation] but I can't find any documentation on how I would do anything like this. Any ideas?

Body:
I've come up against a similar problem and found that you need to take a slightly different approach.

In Angular, animations are linked to state. So instead of defining a different trigger for your animation in your HTML, you want to define multiple states that your trigger can watch for in your component class. And rather than triggering animations directly from a method, you set the state of the object an animation is linked to.

So for instance I might define the following in the component decorator after importing the necessary modules.

@Component({
  selector: 'app-some-animated',
  templateUrl: './some.component.html',
  styleUrls: ['./some-animated.component.scss'],
  animations: [
    trigger('flyInOut', [
      transition("void => fly", [
        animate(300, keyframes([
          style({transform: 'translateX(100%)', opacity: 0}),
          style({transform: 'translateX(0)', opacity: 1})
        ]))
        ]
      )
    ]),
    trigger('flyInOut', [
      transition("void => fade", [
          animate(300, keyframes([
            style({opacity: 0}),
            style({opacity: 1})
          ]))
        ]
      )
    ])
  ]
})

In this instance I'm making the animations happen as soon as the element is instantiated. And in the ngOnInit() method I'm setting this.watchMe to "fly" or "fade".

In the html I'm attaching the flyInOut trigger like so:

<div [@flyInOut]="watchMe">
  Some content...
</div>

In your case you probably want to add the required state to your field objects or as an iterable condition from your *ngFor.

This article from coursetro has a nice explanation and a video too.