问:
Unable to get current date in Swift 3.0
I am using below code to get current date and formatting it.
But seeing error "Cannot invoke initiliazer for type "Date" with no arguments"

```<code>    let currentDateTime = Date()
    // initialize the date formatter and set the style
    let formatter = DateFormatter()
    formatter.timeStyle = .medium
    formatter.dateStyle = .long

    // get the date time String from the date object
    formatter.string(from: currentDateTime) // October 8, 2016 at 10:48:53 PM
</code>```

screenshot

答:
```<code>swift 4

==> Getting iOS device current time:-

let hh1 = Calendar.current.component(.hour, from: Date())
let mm1 = Calendar.current.component(.minute, from: Date())
let ss1 = Calendar.current.component(.second, from: Date())

print(hh1, ":", mm1, ":", ss1)

output: ---> 11 : 10: 25
</code>```

Title: Unable to get current date in Swift 3.0

Body:
I am using below code to get current date and formatting it.
But seeing error "Cannot invoke initiliazer for type "Date" with no arguments"

    let currentDateTime = Date()
    // initialize the date formatter and set the style
    let formatter = DateFormatter()
    formatter.timeStyle = .medium
    formatter.dateStyle = .long

    // get the date time String from the date object
    formatter.string(from: currentDateTime) // October 8, 2016 at 10:48:53 PM

screenshot


来源: stackexchange

问:
rails 3 : Do i need to give return true in a before_save callback for an object.save to work?
```<code>Class User
  before_save :set_searchable

  def set_searchable
    self.searchable = true if self.status == :active
  end
end

>> u = User.last
>> u.save
false
</code>```

u.save always return false. If i remove the before_save it works
also if i give a return true in before_save it works

so do i need to give return statements in before_save ?
will ActiveRecord saves an object if the before_save returns false ?

Where can i see a full documentation regarding callbacks and its workflow .

Thanks in advance

答:
From: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

If a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.

So, yes.

ContentLicense: CC BY-SA 2.5

Body:
Class User
  before_save :set_searchable

  def set_searchable
    self.searchable = true if self.status == :active
  end
end

>> u = User.last
>> u.save
false

u.save always return false. If i remove the before_save it works
also if i give a return true in before_save it works

so do i need to give return statements in before_save ?
will ActiveRecord saves an object if the before_save returns false ?

Where can i see a full documentation regarding callbacks and its workflow .

Thanks in advance


问:
Define custom error message in REST using Spring on Weblogic
I am hosting Spring Boot app on weblogic 10.3.6 for REST api
I'd like to implement these 2 features:

Whenever my custom exception occurs I would like to send a http response with message e.g. 500 - "request couldn't be parsed because of something..."

Whenever any error is thrown I would like to get the stack trace that is usually printed to console (for debugging purposes)

I tried to solve the first part the following way:

```<code>@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(MyException.class)
    public ResponseEntity handleException(MyException e) {

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }
</code>```

However as a response I only get 500 Internal Server Error with no message

As for the second part I tried simmilar approach but there was no error message either.

How can I solve this?

EDIT:
The best I could achieve was removing ExceptionHandlerAdvice and using annotation on my exception class instead like this:

```<code>@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason="This is a message I'd like to send")
</code>```

It works, but I have to add some variables from code to the message and this method does not allow it

EDIT2:
This is a bit weird, perhaps a behavior of weblogic server, but when I set the httpStatus to HttpStatus.ACCEPTED I can see the message, if it is HttpStatus.Forbidden or any other 4xx error I just get the error without message

答:
I also went through the same requirement.
Below is the code which is working for me:

```<code>String errMsg = "{\"errorMessage\":\"Parking Slot is not available\"}";
return new ResponseEntity<String>(errMsg, HttpStatus.INTERNAL_SERVER_ERROR);
</code>```

Whereas errMsg should be written in the format which you want. Like I had requirment for response in JSON.

Hope this will help some of you

ContentLicense: CC BY-SA 3.0

Body:
I am hosting Spring Boot app on weblogic 10.3.6 for REST api
I'd like to implement these 2 features:

Whenever my custom exception occurs I would like to send a http response with message e.g. 500 - "request couldn't be parsed because of something..."

Whenever any error is thrown I would like to get the stack trace that is usually printed to console (for debugging purposes)

I tried to solve the first part the following way:

@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(MyException.class)
    public ResponseEntity handleException(MyException e) {

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
    }

However as a response I only get 500 Internal Server Error with no message

As for the second part I tried simmilar approach but there was no error message either.

How can I solve this?

EDIT:
The best I could achieve was removing ExceptionHandlerAdvice and using annotation on my exception class instead like this:

@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason="This is a message I'd like to send")

It works, but I have to add some variables from code to the message and this method does not allow it

EDIT2:
This is a bit weird, perhaps a behavior of weblogic server, but when I set the httpStatus to HttpStatus.ACCEPTED I can see the message, if it is HttpStatus.Forbidden or any other 4xx error I just get the error without message

Body:
I also went through the same requirement.
Below is the code which is working for me:

String errMsg = "{\"errorMessage\":\"Parking Slot is not available\"}";
return new ResponseEntity<String>(errMsg, HttpStatus.INTERNAL_SERVER_ERROR);

Whereas errMsg should be written in the format which you want. Like I had requirment for response in JSON.

Hope this will help some of you


问:
To Compress my jQuery
How can I compress my jQuery useful? I want to add a function to show an element when I hover another one. The function below is exactly what I want, but I want it more dynamic. Maybe with an data attribute?

```<code>var item_first = $('.item_first');
var item_second = $('.item_second');
var item_third = $('.item_third');
var item_fourth = $('.item_fourth');

var image_first = $('.image_first');
var image_second = $('.image_second');
var image_third = $('.image_third');
var image_fourth = $('.image_fourth');

$(document).ready(function () {
    item_first.hover(function () {
        image_first.addClass('active');
    }, function () {
        image_first.removeClass('active');
    });

    item_second.hover(function () {
        image_second.addClass('active');
    }, function () {
        image_second.removeClass('active');
    });
    item_third.hover(function () {
        image_third.addClass('active');
    }, function () {
        image_third.removeClass('active');
    });

    item_fourth.hover(function () {
        image_fourth.addClass('active');
    }, function () {
        image_fourth.removeClass('active');
    });
});
</code>```

https://jsfiddle.net/gt5kw00q/

Sorry for my bad English. I try to write so that you understand it.

答:
Give your elements a class name and a data attribute with the target(id):

```<code><div class="myHoverElement" id="ele1" data-targetid="image_1"></div>
<div class="myHoverElement" id="ele2" data-targetid="image_2"></div>
<img id="image_1">
<img id="image_2">
</code>```

You can then bind a hover event to all those elements at once:

```<code>$('.myHoverElement').hover(
    function() { $('#' + $(this).data('targetid')).addClass('active') },
    function() { $('#' + $(this).data('targetid')).removeClass('active') }
);
</code>```

$(this) is a reference to the currently hovered element.

Title: To Compress my jQuery

Body:
How can I compress my jQuery useful? I want to add a function to show an element when I hover another one. The function below is exactly what I want, but I want it more dynamic. Maybe with an data attribute?

var item_first = $('.item_first');
var item_second = $('.item_second');
var item_third = $('.item_third');
var item_fourth = $('.item_fourth');

var image_first = $('.image_first');
var image_second = $('.image_second');
var image_third = $('.image_third');
var image_fourth = $('.image_fourth');

$(document).ready(function () {
    item_first.hover(function () {
        image_first.addClass('active');
    }, function () {
        image_first.removeClass('active');
    });

    item_second.hover(function () {
        image_second.addClass('active');
    }, function () {
        image_second.removeClass('active');
    });
    item_third.hover(function () {
        image_third.addClass('active');
    }, function () {
        image_third.removeClass('active');
    });

    item_fourth.hover(function () {
        image_fourth.addClass('active');
    }, function () {
        image_fourth.removeClass('active');
    });
});

https://jsfiddle.net/gt5kw00q/

Sorry for my bad English. I try to write so that you understand it.

Body:
Give your elements a class name and a data attribute with the target(id):

<div class="myHoverElement" id="ele1" data-targetid="image_1"></div>
<div class="myHoverElement" id="ele2" data-targetid="image_2"></div>
<img id="image_1">
<img id="image_2">

You can then bind a hover event to all those elements at once:

$('.myHoverElement').hover(
    function() { $('#' + $(this).data('targetid')).addClass('active') },
    function() { $('#' + $(this).data('targetid')).removeClass('active') }
);

$(this) is a reference to the currently hovered element.


问:
Spring @Async with CompletableFuture
I have a doubt about this code:

```<code>@Async
public CompletableFuture<String> doFoo() {
    CompletableFuture<String> fooFuture = new CompletableFuture<>();

    try {
        String fooResult = longOp();
        fooFuture.complete(fooResult);
    } catch (Exception e) {
        fooFuture.completeExceptionally(e);
    }

    return fooFuture;
}
</code>```

The question is: does doFoo return fooFuture only after longOp has finished (either correctly or exceptionally) and is therefore returning already completed futures or is Spring doing some magic and returning before executing the body? If the code is blocking on longOp(), how would you express that the computation is being fed to an executor?

Perhaps this? Any other way?

```<code>@Async
public CompletableFuture<String> doFoo() {

    CompletableFuture<String> completableFuture = new CompletableFuture<>();
    CompletableFuture.runAsync(() -> {
        try {
            String fooResult = longOp();
            completableFuture.complete(fooResult);
        } catch (Exception e) {
            completableFuture.completeExceptionally(e);
        }
    });
    return completableFuture;
}
</code>```

答:
Spring actually does all of the work behind the covers so you don't have to create the CompletableFuture yourself.
Basically, adding the @Async annotation is as if you called your original method (without the annotation) like:

```<code>CompletableFuture<User> future = CompletableFuture.runAsync(() -> doFoo());
</code>```

As for your second question, in order to feed it to an executor, you can specify the exectutor bean name in the value of the @Async annotation, like so:

```<code>    @Async("myExecutor")
    public CompletableFuture<User> findUser(String usernameString) throws InterruptedException {
        User fooResult = longOp(usernameString);
        return CompletableFuture.completedFuture(fooResult);
    }
</code>```

The above would basically be the following as if you called your original method, like:

```<code>CompletableFuture<User> future = CompletableFuture.runAsync(() -> doFoo(), myExecutor);
</code>```

And all of your exceptionally logic you would do with the returned CompletableFuture from that method.

Title: Spring @Async with CompletableFuture

Body:
I have a doubt about this code:

@Async
public CompletableFuture<String> doFoo() {
    CompletableFuture<String> fooFuture = new CompletableFuture<>();

    try {
        String fooResult = longOp();
        fooFuture.complete(fooResult);
    } catch (Exception e) {
        fooFuture.completeExceptionally(e);
    }

    return fooFuture;
}

The question is: does doFoo return fooFuture only after longOp has finished (either correctly or exceptionally) and is therefore returning already completed futures or is Spring doing some magic and returning before executing the body? If the code is blocking on longOp(), how would you express that the computation is being fed to an executor?

Perhaps this? Any other way?

@Async
public CompletableFuture<String> doFoo() {

    CompletableFuture<String> completableFuture = new CompletableFuture<>();
    CompletableFuture.runAsync(() -> {
        try {
            String fooResult = longOp();
            completableFuture.complete(fooResult);
        } catch (Exception e) {
            completableFuture.completeExceptionally(e);
        }
    });
    return completableFuture;
}

Body:
Spring actually does all of the work behind the covers so you don't have to create the CompletableFuture yourself.
Basically, adding the @Async annotation is as if you called your original method (without the annotation) like:

CompletableFuture<User> future = CompletableFuture.runAsync(() -> doFoo());

As for your second question, in order to feed it to an executor, you can specify the exectutor bean name in the value of the @Async annotation, like so:

    @Async("myExecutor")
    public CompletableFuture<User> findUser(String usernameString) throws InterruptedException {
        User fooResult = longOp(usernameString);
        return CompletableFuture.completedFuture(fooResult);
    }

The above would basically be the following as if you called your original method, like:

CompletableFuture<User> future = CompletableFuture.runAsync(() -> doFoo(), myExecutor);

And all of your exceptionally logic you would do with the returned CompletableFuture from that method.

ContentLicense: CC BY-SA 4.0


问:
Replace outer HTML in AngularJS directive
I want to write an AngularJS directive such as

```<code><my-directive>
    <inner-body>
        normal HTML and Angular constructs
    </inner-body>
</my-directive>
</code>```

And should be converted as

```<code><div class="group">
  <div> directive inserted text </div>
  <div class="groupBody">
      normal HTML and Angular constructs
  </div>
</div>
</code>```

Basically, I want to have flexibility to write HTML inside inner-body. The directive will convert it to div and apply some attributes to this div.

Is it possible?

TIA.

答:
Yes it's possible, use ngTransclude (ngTransclude)

Extract from AngularJS:

```<code><script>
  angular.module('transcludeExample', [])
   .directive('pane', function(){
      return {
        restrict: 'E',
        transclude: true,
        scope: { title:'@' },
        template: '<div style="border: 1px solid black;">' +
                    '<div style="background-color: gray">{{title}}</div>' +
                    '<ng-transclude></ng-transclude>' +
                  '</div>'
      };
  })
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.title = 'Lorem Ipsum';
    $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  }]);
</script>
<div ng-controller="ExampleController">
  <input ng-model="title" aria-label="title"> <br/>
  <textarea ng-model="text" aria-label="text"></textarea> <br/>
  <pane title="{{title}}"><span>{{text}}</span></pane>
</div>
</code>```

You can also use Multi-slot transclusion, details of which are contained in the link also here

Body:
I want to write an AngularJS directive such as

<my-directive>
    <inner-body>
        normal HTML and Angular constructs
    </inner-body>
</my-directive>

And should be converted as

 directive inserted text

      normal HTML and Angular constructs

Basically, I want to have flexibility to write HTML inside inner-body. The directive will convert it to div and apply some attributes to this div.

Is it possible?

TIA.

Body:
Yes it's possible, use ngTransclude (ngTransclude)

Extract from AngularJS:

<script>
  angular.module('transcludeExample', [])
   .directive('pane', function(){
      return {
        restrict: 'E',
        transclude: true,
        scope: { title:'@' },
        template: '<div style="border: 1px solid black;">' +
                    '<div style="background-color: gray">{{title}}</div>' +
                    '<ng-transclude></ng-transclude>' +
                  '</div>'
      };
  })
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.title = 'Lorem Ipsum';
    $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  }]);
</script>
<div ng-controller="ExampleController">
  <input ng-model="title" aria-label="title"> <br/>
  <textarea ng-model="text" aria-label="text"></textarea> <br/>
  <pane title="{{title}}"><span>{{text}}</span></pane>
</div>

You can also use Multi-slot transclusion, details of which are contained in the link also here


问:
Running C code in Termux compiled by clang
I used to compile my code with CppDroid on Android until last night.

After updating the app it began to show position independent executable error.

I reinstalled the older version but am still getting the same error.

I know it is a problem with Android 5.0 and above. But then how did CppDroid work till last night? Can anyone give me an answer or any clue?

Termux only provides Clang. Can anyone give me a way to successfully compile C code?

答:
Even though the file mode is 0777, Android does not allow files on shared storage to be executed by mounting with noexec.

If you run

```<code>/system/bin/mount | grep /storage
</code>```

You'll find something like this:

```<code>/data/media on /storage/emulated type sdcardfs (rw,nosuid,nodev,noexec,noatime,low_uid=1023,low_gid=1023,gid=9997,multi_user,mask=0007,reserved=100MB)
                                                                ^~~~~~
</code>```

The actual mount point may vary (/storage/sdcard0), but it's surely mounted with noexec.

You should move the executable to Termux's home directory (or somewhere in an ext4 mountpoint) before trying to execute it. That's what CppDroid does. It only runs executables in internal storage, though the source code may be stored anywhere.

If you want to run in Termux, follow this:

```<code>$ cp <your-program> ~/a.out
$ chmod 777 ~/a.out
$ ~/a.out
program output
$
</code>```

For the "position independent executable (PIE)" issue, I suggest you clear data for CppDroid. It uses GCC as compiler, which requires -pie option to generate PIE executable. If you know what settings are messed up you can also try fixing it by yourself.

The Clang compiler provided by Termux generates PIE executables by default.

Body:
Even though the file mode is 0777, Android does not allow files on shared storage to be executed by mounting with noexec.

If you run

/system/bin/mount | grep /storage

You'll find something like this:

/data/media on /storage/emulated type sdcardfs (rw,nosuid,nodev,noexec,noatime,low_uid=1023,low_gid=1023,gid=9997,multi_user,mask=0007,reserved=100MB)
                                                                ^~~~~~

The actual mount point may vary (/storage/sdcard0), but it's surely mounted with noexec.

You should move the executable to Termux's home directory (or somewhere in an ext4 mountpoint) before trying to execute it. That's what CppDroid does. It only runs executables in internal storage, though the source code may be stored anywhere.

If you want to run in Termux, follow this:

$ cp <your-program> ~/a.out
$ chmod 777 ~/a.out
$ ~/a.out
program output
$

For the "position independent executable (PIE)" issue, I suggest you clear data for CppDroid. It uses GCC as compiler, which requires -pie option to generate PIE executable. If you know what settings are messed up you can also try fixing it by yourself.

The Clang compiler provided by Termux generates PIE executables by default.


问:
How to Render a rotated UIlabel
I'm currently developing an app like photoshop for iPad and when i want flatten my array of layers, DrawTextInRect doesn't preserve the Transform (CAAffineTransformMakeRotation) of my UILabel. Anybody have any idea?

答:
Translate the context to the label's origin, and then apply the label's transform to the context.

The code below is in Swift.

```<code>let context = UIGraphicsGetCurrentContext()!

context.saveGState()

let t = myLabel.transform
let translationPt = CGPoint.init(x: myLabel.frame.origin.x, y: myLabel.frame.origin.y)
context.translateBy(x: translationPt.x, y: translationPt.y)

context.concatenate(t)

myLabel.layer.render(in: context)

context.restoreGState()
</code>```

Title: How to Render a rotated UIlabel

Body:
Translate the context to the label's origin, and then apply the label's transform to the context.

The code below is in Swift.

let context = UIGraphicsGetCurrentContext()!

context.saveGState()

let t = myLabel.transform
let translationPt = CGPoint.init(x: myLabel.frame.origin.x, y: myLabel.frame.origin.y)
context.translateBy(x: translationPt.x, y: translationPt.y)

context.concatenate(t)

myLabel.layer.render(in: context)

context.restoreGState()


问:
Image and div inline alignment
How to align the div inline with the image.The text is supposed to appear on the right side of the page inline with the image.

**EDIT**

<img src='/media/site.png' onclick="javascript:getfunc('/home/')"

Login

```

答:
if you want to align that right floating div with the image you should place that div BEFORE the img... i.e.</p>

```<code> <div style="padding-right:50px;padding-top:2px;float:right">
     Login
 </div>
 <div>
     <img src='/media/site.png' onclick="javascript:getfunc('/home/')" alt="this attrib should be always present" />
 </div>
</code>```

Title: Image and div inline alignment

Body:
if you want to align that right floating div with the image you should place that div BEFORE the img... i.e.

 <div style="padding-right:50px;padding-top:2px;float:right">
     Login
 </div>
 <div>
     <img src='/media/site.png' onclick="javascript:getfunc('/home/')" alt="this attrib should be always present" />
 </div>


问:
Parse string as a time.Time value
I have a string time in format 20171023T183552. I didn't find any format to parse this string value. Is there any way to convert this string value to  Go time.Time ?

Edit - This is not duplicate question. I know how to parse, but I was unaware of the fact that we can use any layout other than listed in time format package. This answer cleared my daubt.

答:
That is simply "YYYYMMDDTHHmmSS", so use the format string (layout): "20060102T150405".

Example:

```<code>s := "20171023T183552"
t, err := time.Parse("20060102T150405", s)
fmt.Println(t, err)
</code>```

Output (try it on the Go Playground):

```<code>2017-10-23 18:35:52 +0000 UTC <nil>
</code>```

Quoting from doc of time.Parse():

Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be

```<code>Mon Jan 2 15:04:05 -0700 MST 2006
</code>```

would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

So basically generate the format string by formatting the reference time using the same format your input is available in.

For the opposite direction (converting time.Time to string), see Golang: convert time.Time to string.

Title: Parse string as a time.Time value

Body:
That is simply "YYYYMMDDTHHmmSS", so use the format string (layout): "20060102T150405".

Example:

s := "20171023T183552"
t, err := time.Parse("20060102T150405", s)
fmt.Println(t, err)

Output (try it on the Go Playground):

2017-10-23 18:35:52 +0000 UTC <nil>

Quoting from doc of time.Parse():

Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be interpreted if it were the value; it serves as an example of the input format. The same interpretation will then be made to the input string.

So basically generate the format string by formatting the reference time using the same format your input is available in.

For the opposite direction (converting time.Time to string), see Golang: convert time.Time to string.


问:
How to generalize a function over two types with similar fields in different positions?
I have a function algo which works with a type S1, I also have
a type S2 which contains all of the fields of S1 plus some additional ones.

How should I modify algo to also accept S2 as input without
creating a temporary variable with type S1 and data from S2?

```<code>struct Moo1 {
    f1: String,
    f2: i32,
}

struct Moo2 {
    f1: String,
    f2: i32,
    other_fields: f32,
}

struct S1 {
    x: i32,
    v: Vec<Moo1>,
}

struct S2 {
    x: i32,
    v: Vec<Moo2>,
}

//before fn algo(s: &S1)
fn algo<???>(???) {
    //work with x and v (only with f1 and f2)
}
</code>```

Where I'm stuck

Let's assume algo has this implementation (my real application has another implementation):

```<code>fn algo(s: &S1) {
    println!("s.x: {}", s.x);
    for y in &s.v {
        println!("{} {}", y.f1, y.f2);
    }
}
</code>```

To access the field in Moo1 and Moo2 I introduce trait AsMoo, and to access x field and v I introduce trait AsS:

```<code>trait AsMoo {
    fn f1(&self) -> &str;
    fn f2(&self) -> i32;
}

trait AsS {
    fn x(&self) -> i32;
    //    fn v(&self) -> ???;
}

fn algo<S: AsS>(s: &AsS) {
    println!("s.x: {}", s.x());
}
</code>```

I'm stuck at the implementation of the AsS::v method. I do not allocate memory to use my algo, but I need a Vec<&AsMoo> in some way.

Maybe I need to return some kind of Iterator<&AsMoo>, but have no idea how to do it and that looks complex for this problem.

Maybe I should use macros instead?

答:
Any problem in computer science can be solved by adding another layer of indirection; at the exception of having too many such layers, of course.

Therefore, you are correct that you miss a S trait to generalize S1 and S2. In S, you can use a feature called associated type:

```<code>trait Moo {
    fn f1(&self) -> &str;
    fn f2(&self) -> i32;
}

trait S {
    type Mooer: Moo;
    fn x(&self) -> i32;
    fn v(&self) -> &[Self::Mooer];
}
</code>```

The bit type Mooer: Moo; says: I don't quite know what the exact type Mooer will end up being, but it'll implement the Moo trait.

This lets you write:

```<code>impl S for S1 {
    type Mooer = Moo1;
    fn x(&self) -> i32 { self.x }
    fn v(&self) -> &[Self::Mooer] { &self.v }
}

impl S for S2 {
    type Mooer = Moo2;
    fn x(&self) -> i32 { self.x }
    fn v(&self) -> &[Self::Mooer] { &self.v }
}

fn algo<T: S>(s: &T) {
    println!("s.x: {}", s.x());
    for y in s.v() {
        println!("{} {}", y.f1(), y.f2());
    }
}
</code>```

And your generic algo knows that whatever type Mooer ends up being, it conforms to the Moo trait so the interface of Moo is available.

Body:
I have a function algo which works with a type S1, I also have
a type S2 which contains all of the fields of S1 plus some additional ones.

How should I modify algo to also accept S2 as input without
creating a temporary variable with type S1 and data from S2?

struct Moo1 {
    f1: String,
    f2: i32,
}

struct Moo2 {
    f1: String,
    f2: i32,
    other_fields: f32,
}

struct S1 {
    x: i32,
    v: Vec<Moo1>,
}

struct S2 {
    x: i32,
    v: Vec<Moo2>,
}

//before fn algo(s: &S1)
fn algo<???>(???) {
    //work with x and v (only with f1 and f2)
}

Where I'm stuck

Let's assume algo has this implementation (my real application has another implementation):

fn algo(s: &S1) {
    println!("s.x: {}", s.x);
    for y in &s.v {
        println!("{} {}", y.f1, y.f2);
    }
}

To access the field in Moo1 and Moo2 I introduce trait AsMoo, and to access x field and v I introduce trait AsS:

trait AsMoo {
    fn f1(&self) -> &str;
    fn f2(&self) -> i32;
}

trait AsS {
    fn x(&self) -> i32;
    //    fn v(&self) -> ???;
}

fn algo<S: AsS>(s: &AsS) {
    println!("s.x: {}", s.x());
}

I'm stuck at the implementation of the AsS::v method. I do not allocate memory to use my algo, but I need a Vec<&AsMoo> in some way.

Maybe I need to return some kind of Iterator<&AsMoo>, but have no idea how to do it and that looks complex for this problem.

Maybe I should use macros instead?

Body:
Any problem in computer science can be solved by adding another layer of indirection; at the exception of having too many such layers, of course.

Therefore, you are correct that you miss a S trait to generalize S1 and S2. In S, you can use a feature called associated type:

trait Moo {
    fn f1(&self) -> &str;
    fn f2(&self) -> i32;
}

trait S {
    type Mooer: Moo;
    fn x(&self) -> i32;
    fn v(&self) -> &[Self::Mooer];
}

The bit type Mooer: Moo; says: I don't quite know what the exact type Mooer will end up being, but it'll implement the Moo trait.

This lets you write:

impl S for S1 {
    type Mooer = Moo1;
    fn x(&self) -> i32 { self.x }
    fn v(&self) -> &[Self::Mooer] { &self.v }
}

impl S for S2 {
    type Mooer = Moo2;
    fn x(&self) -> i32 { self.x }
    fn v(&self) -> &[Self::Mooer] { &self.v }
}

fn algo<T: S>(s: &T) {
    println!("s.x: {}", s.x());
    for y in s.v() {
        println!("{} {}", y.f1(), y.f2());
    }
}

And your generic algo knows that whatever type Mooer ends up being, it conforms to the Moo trait so the interface of Moo is available.


问:
How do I put two
s side-by-side, with the left
 taking up 100% of the space not taken up by the right
?
I've got a basic issue. Two
s side-by-side, the left
 needs to be able to have a 'flexible' width, as in when the
 on the right isn't displayed, the left
 will then stretch to 100%.

My code currently is as follows, which doesn't fulfil the above requirement.

```<code><html>
        <head>
        <style>
        #container {
                display: block;
        }

        #box-left {
                width: 100%;
                height: 100px;
                background-color: red;
                float: left;
        }

        #box-right {
                width: 15%;
                height: 100px;
                background-color: blue;
                float: right;
        }
        </style>
        </head>
        <div id="container">
                <div id="box-left"></div>
                <div id="box-right"></div>
        </div>
        <body>

        </body>
</code>```

Any pointers would be much appreciated.

答: Have you tried using max-width:100%; for 'box-left' ?

Title: How do I put two <div>s side-by-side, with the left <div> taking up 100% of the space not taken up by the right <div>?

Body:
I've got a basic issue. Two
s side-by-side, the left
 needs to be able to have a 'flexible' width, as in when the
 on the right isn't displayed, the left
 will then stretch to 100%.

My code currently is as follows, which doesn't fulfil the above requirement.

Any pointers would be much appreciated.


问:
kubectl pull image from gitlab unauthorized: HTTP Basic: Access denied
I am trying to configure gitlab ci to deploy app to google compute engine. I have succesfully pushed image to gitlab repository but after applying kubernetes deployment config i see following error in kubectl describe pods:

```<code>Failed to pull image "registry.gitlab.com/proj/subproj/api:v1": rpc error: code = 2
desc = Error response from daemon: {"message":"Get https://registry.gitlab.com/v2/proj/subproj/api/manifests/v1: unauthorized: HTTP Basic: Access denied"}
</code>```

Here is my deployment gitlab-ci job:

```<code>docker:
  stage: docker_images
  image: docker:latest
  services:
    - docker:dind
  script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
    - docker build -t registry.gitlab.com/proj/subproj/api:v1 -f Dockerfile .
    - docker push registry.gitlab.com/proj/subproj/api:v1
  only:
    - master
  dependencies:
  - build_java

k8s-deploy:
  image: google/cloud-sdk
  stage: deploy
  script:
    - echo "$GOOGLE_KEY" > key.json # Google Cloud service account key
    - gcloud auth activate-service-account --key-file key.json
    - gcloud config set compute/zone us-central1-c
    - gcloud config set project proj
    - gcloud config set container/use_client_certificate True
    - gcloud container clusters get-credentials proj-cluster
    - kubectl delete secret registry.gitlab.com  --ignore-not-found
    - kubectl create secret docker-registry registry.gitlab.com --docker-server=https://registry.gitlab.com/v1/ --docker-username="$CI_REGISTRY_USER" --docker-password="$CI_REGISTRY_PASSWORD" --docker-email=some@gmail.com
    - kubectl apply -f  cloud-kubernetes.yml
</code>```

and here is cloud-kubernetes.yml:

```<code>apiVersion: v1
kind: Service
metadata:
  annotations:
    service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
  name: proj
  labels:
    app: proj
spec:
  type: LoadBalancer
  ports:
  - port: 8082
    name: proj
    targetPort: 8082
    nodePort: 32756
  selector:
    app: proj
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: projdeployment
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: proj
    spec:
      containers:
      - name: projcontainer
        image: registry.gitlab.com/proj/subproj/api:v1
        imagePullPolicy: Always
        env:
          - name: SPRING_PROFILES_ACTIVE
            value: "cloud"
        ports:
        - containerPort: 8082
      imagePullSecrets:
        - name: registry.gitlab.com
</code>```

I have followed this article

答:
There is workaround, image could be pushed to google container registry, and then pulled from gcr without security. We can push image to gcr without gcloud cli using json token file. So .gitlab-ci.yaml could look like:

```<code>docker:
  stage: docker_images
  image: docker:latest
  services:
    - docker:dind
  script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
    - docker build -t registry.gitlab.com/proj/subproj/api:v1 -f Dockerfile .
    - docker push registry.gitlab.com/proj/subproj/api:v1
    - docker tag registry.gitlab.com/proj/subproj/api:v1 gcr.io/proj/api:v1
    - docker login -u _json_key -p "$GOOGLE_KEY" https://gcr.io
    - docker push gcr.io/proj/api:v1
  only:
    - master
  dependencies:
  - build_java

k8s-deploy:
  image: google/cloud-sdk
  stage: deploy
  script:
    - echo "$GOOGLE_KEY" > key.json # Google Cloud service account key
    - gcloud auth activate-service-account --key-file key.json
    - gcloud config set compute/zone us-central1-c
    - gcloud config set project proj
    - gcloud config set container/use_client_certificate True
    - gcloud container clusters get-credentials proj-cluster
    - kubectl apply -f cloud-kubernetes.yml
</code>```

And image in cloud-kubernetes.yaml should be:

gcr.io/proj/api:v1

Body:
I am trying to configure gitlab ci to deploy app to google compute engine. I have succesfully pushed image to gitlab repository but after applying kubernetes deployment config i see following error in kubectl describe pods:

Failed to pull image "registry.gitlab.com/proj/subproj/api:v1": rpc error: code = 2
desc = Error response from daemon: {"message":"Get https://registry.gitlab.com/v2/proj/subproj/api/manifests/v1: unauthorized: HTTP Basic: Access denied"}

Here is my deployment gitlab-ci job:

docker:
  stage: docker_images
  image: docker:latest
  services:
    - docker:dind
  script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
    - docker build -t registry.gitlab.com/proj/subproj/api:v1 -f Dockerfile .
    - docker push registry.gitlab.com/proj/subproj/api:v1
  only:
    - master
  dependencies:
  - build_java

k8s-deploy:
  image: google/cloud-sdk
  stage: deploy
  script:
    - echo "$GOOGLE_KEY" > key.json # Google Cloud service account key
    - gcloud auth activate-service-account --key-file key.json
    - gcloud config set compute/zone us-central1-c
    - gcloud config set project proj
    - gcloud config set container/use_client_certificate True
    - gcloud container clusters get-credentials proj-cluster
    - kubectl delete secret registry.gitlab.com  --ignore-not-found
    - kubectl create secret docker-registry registry.gitlab.com --docker-server=https://registry.gitlab.com/v1/ --docker-username="$CI_REGISTRY_USER" --docker-password="$CI_REGISTRY_PASSWORD" --docker-email=some@gmail.com
    - kubectl apply -f  cloud-kubernetes.yml

and here is cloud-kubernetes.yml:

apiVersion: v1
kind: Service
metadata:
  annotations:
    service.alpha.kubernetes.io/tolerate-unready-endpoints: "true"
  name: proj
  labels:
    app: proj
spec:
  type: LoadBalancer
  ports:
  - port: 8082
    name: proj
    targetPort: 8082
    nodePort: 32756
  selector:
    app: proj
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: projdeployment
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: proj
    spec:
      containers:
      - name: projcontainer
        image: registry.gitlab.com/proj/subproj/api:v1
        imagePullPolicy: Always
        env:
          - name: SPRING_PROFILES_ACTIVE
            value: "cloud"
        ports:
        - containerPort: 8082
      imagePullSecrets:
        - name: registry.gitlab.com

I have followed this article

Body:
There is workaround, image could be pushed to google container registry, and then pulled from gcr without security. We can push image to gcr without gcloud cli using json token file. So .gitlab-ci.yaml could look like:

docker:
  stage: docker_images
  image: docker:latest
  services:
    - docker:dind
  script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
    - docker build -t registry.gitlab.com/proj/subproj/api:v1 -f Dockerfile .
    - docker push registry.gitlab.com/proj/subproj/api:v1
    - docker tag registry.gitlab.com/proj/subproj/api:v1 gcr.io/proj/api:v1
    - docker login -u _json_key -p "$GOOGLE_KEY" https://gcr.io
    - docker push gcr.io/proj/api:v1
  only:
    - master
  dependencies:
  - build_java

k8s-deploy:
  image: google/cloud-sdk
  stage: deploy
  script:
    - echo "$GOOGLE_KEY" > key.json # Google Cloud service account key
    - gcloud auth activate-service-account --key-file key.json
    - gcloud config set compute/zone us-central1-c
    - gcloud config set project proj
    - gcloud config set container/use_client_certificate True
    - gcloud container clusters get-credentials proj-cluster
    - kubectl apply -f cloud-kubernetes.yml

And image in cloud-kubernetes.yaml should be:

gcr.io/proj/api:v1


问:
Changing App name from .env file
I am trying to build multiple apps from same codebase using targets. I am using Fastlane, .env files to launch different builds. Build is uploading fine with different app_identifiers but I am not able to change app name through .env files

Following is my sample .env.target1 file:

```<code>SCHEME_NAME=SampleFastlaneTesting
BUNDLE_IDENTIFIER=com.*****.SampleFastlaneTesting
APP_NAME=“SampleFastlaneTesting”
</code>```

I am storing app name of each build using "APP_NAME" key. In deliver file
I am setting as follows:

```<code>name ENV[‘APP_NAME’]
</code>```

According to this link it should work but it is not updating when I launch the build. What am I doing wrong?

答:
Try changed "APP_NAME" with "BUNDLE_DISPLAY_NAME" or "DISPLAY_NAME"

Edit:

Reading fastlane, this update_info_plist could help you.

Title: Changing App name from .env file

Body:
I am trying to build multiple apps from same codebase using targets. I am using Fastlane, .env files to launch different builds. Build is uploading fine with different app_identifiers but I am not able to change app name through .env files

Following is my sample .env.target1 file:

SCHEME_NAME=SampleFastlaneTesting
BUNDLE_IDENTIFIER=com.*****.SampleFastlaneTesting
APP_NAME=“SampleFastlaneTesting”

I am storing app name of each build using "APP_NAME" key. In deliver file
I am setting as follows:

name ENV[‘APP_NAME’]

According to this link it should work but it is not updating when I launch the build. What am I doing wrong?


问:
Unable to extract a data from Table using inner join on same table
Trying to extract the data from table called TB_Emloyee. There are 4 columns in table with C_ID, Name, Department, Count.

My table has following data

http://sqlfiddle.com/#!9/e74be

I would like to have following output.

```<code>C_ID   NAme    Department  Count
200    Max     IH          2
100    David   PR          1
101    Lex     PR          1
102    Alex    IT          2
103    Slava   IH          1
104    Tunja   PR          2
</code>```

Until now I have tried the following, but I am not able to get the whole data.

http://sqlfiddle.com/#!9/e74be/2/0

I am not an expert with inner query so help me with situation.

Thanks.

答:
Though I agree with @Kriz Poon in that you should normalize your tables. TO get the output you want there is no need to GROUP more columns. Just change the columns you actually want to select.

```<code>SELECT
    `c_ID`, `Name`, `department`, max(`Count`) AS `Count`
FROM
    Tb_Employee
GROUP BY
    C_ID
;
</code>```

Body:
Trying to extract the data from table called TB_Emloyee. There are 4 columns in table with C_ID, Name, Department, Count.

My table has following data

http://sqlfiddle.com/#!9/e74be

I would like to have following output.

C_ID   NAme    Department  Count
200    Max     IH          2
100    David   PR          1
101    Lex     PR          1
102    Alex    IT          2
103    Slava   IH          1
104    Tunja   PR          2

Until now I have tried the following, but I am not able to get the whole data.

http://sqlfiddle.com/#!9/e74be/2/0

I am not an expert with inner query so help me with situation.

Thanks.

Body:
Though I agree with @Kriz Poon in that you should normalize your tables. TO get the output you want there is no need to GROUP more columns. Just change the columns you actually want to select.

SELECT
    `c_ID`, `Name`, `department`, max(`Count`) AS `Count`
FROM
    Tb_Employee
GROUP BY
    C_ID
;


问:
Compiling OpenSSL 1.1.0f with SSLv3
I'm running Ubuntu 14.04.5 and have compiled from source OpenSSL 1.1.0f and Curl 7.54.1.  When I compile openssl I threw the enable-ssl2 and enable-ssl3 flags:

```<code>    vbetoglo@helios:~/Downloads/openssl-1.1.0f$ ./Configure enable-ssl2 enable-ssl3 linux-x86_64
Configuring OpenSSL version 1.1.0f (0x1010006fL)
    no-asan         [default]  OPENSSL_NO_ASAN
    no-crypto-mdebug [default]  OPENSSL_NO_CRYPTO_MDEBUG
    no-crypto-mdebug-backtrace [default]  OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
    no-ec_nistp_64_gcc_128 [default]  OPENSSL_NO_EC_NISTP_64_GCC_128
    no-egd          [default]  OPENSSL_NO_EGD
    no-fuzz-afl     [default]  OPENSSL_NO_FUZZ_AFL
    no-fuzz-libfuzzer [default]  OPENSSL_NO_FUZZ_LIBFUZZER
    no-heartbeats   [default]  OPENSSL_NO_HEARTBEATS
    no-md2          [default]  OPENSSL_NO_MD2 (skip dir)
    no-msan         [default]  OPENSSL_NO_MSAN
    no-rc5          [default]  OPENSSL_NO_RC5 (skip dir)
    no-sctp         [default]  OPENSSL_NO_SCTP
    no-ssl-trace    [default]  OPENSSL_NO_SSL_TRACE
    no-ssl3         [forced]   OPENSSL_NO_SSL3
    no-ssl3-method  [default]  OPENSSL_NO_SSL3_METHOD
    no-ubsan        [default]  OPENSSL_NO_UBSAN
    no-unit-test    [default]  OPENSSL_NO_UNIT_TEST
    no-weak-ssl-ciphers [default]  OPENSSL_NO_WEAK_SSL_CIPHERS
    no-zlib         [default]
    no-zlib-dynamic [default]
Configuring for linux-x86_64
CC            =gcc
CFLAG         =-Wall -O3 -pthread -m64 -DL_ENDIAN
SHARED_CFLAG  =-fPIC -DOPENSSL_USE_NODELETE
DEFINES       =DSO_DLFCN HAVE_DLFCN_H NDEBUG OPENSSL_THREADS OPENSSL_NO_STATIC_ENGINE OPENSSL_PIC OPENSSL_IA32_SSE2 OPENSSL_BN_ASM_MONT OPENSSL_BN_ASM_MONT5 OPENSSL_BN_ASM_GF2m SHA1_ASM SHA256_ASM SHA512_ASM RC4_ASM MD5_ASM AES_ASM VPAES_ASM BSAES_ASM GHASH_ASM ECP_NISTZ256_ASM PADLOCK_ASM POLY1305_ASM
LFLAG         =
PLIB_LFLAG    =
EX_LIBS       =-ldl
APPS_OBJ      =
CPUID_OBJ     =x86_64cpuid.o
UPLINK_OBJ    =
BN_ASM        =asm/x86_64-gcc.o x86_64-mont.o x86_64-mont5.o x86_64-gf2m.o rsaz_exp.o rsaz-x86_64.o rsaz-avx2.o
EC_ASM        =ecp_nistz256.o ecp_nistz256-x86_64.o
DES_ENC       =des_enc.o fcrypt_b.o
AES_ENC       =aes-x86_64.o vpaes-x86_64.o bsaes-x86_64.o aesni-x86_64.o aesni-sha1-x86_64.o aesni-sha256-x86_64.o aesni-mb-x86_64.o
BF_ENC        =bf_enc.o
CAST_ENC      =c_enc.o
RC4_ENC       =rc4-x86_64.o rc4-md5-x86_64.o
RC5_ENC       =rc5_enc.o
MD5_OBJ_ASM   =md5-x86_64.o
SHA1_OBJ_ASM  =sha1-x86_64.o sha256-x86_64.o sha512-x86_64.o sha1-mb-x86_64.o sha256-mb-x86_64.o
RMD160_OBJ_ASM=
CMLL_ENC      =cmll-x86_64.o cmll_misc.o
MODES_OBJ     =ghash-x86_64.o aesni-gcm-x86_64.o
PADLOCK_OBJ   =e_padlock-x86_64.o
CHACHA_ENC    =chacha-x86_64.o
POLY1305_OBJ  =poly1305-x86_64.o
BLAKE2_OBJ    =
PROCESSOR     =
RANLIB        =ranlib
ARFLAGS       =
PERL          =/usr/bin/perl

SIXTY_FOUR_BIT_LONG mode

Configured for linux-x86_64.
</code>```

I've compile and recompiled curl after having done this as well, but no matter what I do, it always comes back with:

```<code>vbetoglo@helios:~/Downloads$ curl --version
curl 7.54.1 (x86_64-pc-linux-gnu) libcurl/7.54.1 OpenSSL/1.1.0f zlib/1.2.8 nghttp2/1.12.0-DEV
Release-Date: 2017-06-14
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz TLS-SRP HTTP2 UnixSockets HTTPS-proxy
vbetoglo@helios:~/Downloads$ curl -3 https://www.google.com/
curl: (4) OpenSSL was built without SSLv3 support
</code>```

Can anyone hint at what I may be doing wrong?

答:
Try to add also the flag "enable-ssl3-method"

Your command becomes:

./Configure enable-ssl2 enable-ssl3 enable-ssl3-method linux-x86_64

Title: Compiling OpenSSL 1.1.0f with SSLv3

Body:
I'm running Ubuntu 14.04.5 and have compiled from source OpenSSL 1.1.0f and Curl 7.54.1.  When I compile openssl I threw the enable-ssl2 and enable-ssl3 flags:

    vbetoglo@helios:~/Downloads/openssl-1.1.0f$ ./Configure enable-ssl2 enable-ssl3 linux-x86_64
Configuring OpenSSL version 1.1.0f (0x1010006fL)
    no-asan         [default]  OPENSSL_NO_ASAN
    no-crypto-mdebug [default]  OPENSSL_NO_CRYPTO_MDEBUG
    no-crypto-mdebug-backtrace [default]  OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
    no-ec_nistp_64_gcc_128 [default]  OPENSSL_NO_EC_NISTP_64_GCC_128
    no-egd          [default]  OPENSSL_NO_EGD
    no-fuzz-afl     [default]  OPENSSL_NO_FUZZ_AFL
    no-fuzz-libfuzzer [default]  OPENSSL_NO_FUZZ_LIBFUZZER
    no-heartbeats   [default]  OPENSSL_NO_HEARTBEATS
    no-md2          [default]  OPENSSL_NO_MD2 (skip dir)
    no-msan         [default]  OPENSSL_NO_MSAN
    no-rc5          [default]  OPENSSL_NO_RC5 (skip dir)
    no-sctp         [default]  OPENSSL_NO_SCTP
    no-ssl-trace    [default]  OPENSSL_NO_SSL_TRACE
    no-ssl3         [forced]   OPENSSL_NO_SSL3
    no-ssl3-method  [default]  OPENSSL_NO_SSL3_METHOD
    no-ubsan        [default]  OPENSSL_NO_UBSAN
    no-unit-test    [default]  OPENSSL_NO_UNIT_TEST
    no-weak-ssl-ciphers [default]  OPENSSL_NO_WEAK_SSL_CIPHERS
    no-zlib         [default]
    no-zlib-dynamic [default]
Configuring for linux-x86_64
CC            =gcc
CFLAG         =-Wall -O3 -pthread -m64 -DL_ENDIAN
SHARED_CFLAG  =-fPIC -DOPENSSL_USE_NODELETE
DEFINES       =DSO_DLFCN HAVE_DLFCN_H NDEBUG OPENSSL_THREADS OPENSSL_NO_STATIC_ENGINE OPENSSL_PIC OPENSSL_IA32_SSE2 OPENSSL_BN_ASM_MONT OPENSSL_BN_ASM_MONT5 OPENSSL_BN_ASM_GF2m SHA1_ASM SHA256_ASM SHA512_ASM RC4_ASM MD5_ASM AES_ASM VPAES_ASM BSAES_ASM GHASH_ASM ECP_NISTZ256_ASM PADLOCK_ASM POLY1305_ASM
LFLAG         =
PLIB_LFLAG    =
EX_LIBS       =-ldl
APPS_OBJ      =
CPUID_OBJ     =x86_64cpuid.o
UPLINK_OBJ    =
BN_ASM        =asm/x86_64-gcc.o x86_64-mont.o x86_64-mont5.o x86_64-gf2m.o rsaz_exp.o rsaz-x86_64.o rsaz-avx2.o
EC_ASM        =ecp_nistz256.o ecp_nistz256-x86_64.o
DES_ENC       =des_enc.o fcrypt_b.o
AES_ENC       =aes-x86_64.o vpaes-x86_64.o bsaes-x86_64.o aesni-x86_64.o aesni-sha1-x86_64.o aesni-sha256-x86_64.o aesni-mb-x86_64.o
BF_ENC        =bf_enc.o
CAST_ENC      =c_enc.o
RC4_ENC       =rc4-x86_64.o rc4-md5-x86_64.o
RC5_ENC       =rc5_enc.o
MD5_OBJ_ASM   =md5-x86_64.o
SHA1_OBJ_ASM  =sha1-x86_64.o sha256-x86_64.o sha512-x86_64.o sha1-mb-x86_64.o sha256-mb-x86_64.o
RMD160_OBJ_ASM=
CMLL_ENC      =cmll-x86_64.o cmll_misc.o
MODES_OBJ     =ghash-x86_64.o aesni-gcm-x86_64.o
PADLOCK_OBJ   =e_padlock-x86_64.o
CHACHA_ENC    =chacha-x86_64.o
POLY1305_OBJ  =poly1305-x86_64.o
BLAKE2_OBJ    =
PROCESSOR     =
RANLIB        =ranlib
ARFLAGS       =
PERL          =/usr/bin/perl

SIXTY_FOUR_BIT_LONG mode

Configured for linux-x86_64.

I've compile and recompiled curl after having done this as well, but no matter what I do, it always comes back with:

vbetoglo@helios:~/Downloads$ curl --version
curl 7.54.1 (x86_64-pc-linux-gnu) libcurl/7.54.1 OpenSSL/1.1.0f zlib/1.2.8 nghttp2/1.12.0-DEV
Release-Date: 2017-06-14
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp
Features: IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz TLS-SRP HTTP2 UnixSockets HTTPS-proxy
vbetoglo@helios:~/Downloads$ curl -3 https://www.google.com/
curl: (4) OpenSSL was built without SSLv3 support

Can anyone hint at what I may be doing wrong?


问:
angular value is not reflecting from the function
I am trying to assign value to $scope variable from a controller function. I can see the value is assigned from console but it is not reflecting in html page.

my html

```<code><div id="NodeDetails" class="NodeDetails">{{NodeDetails}}</div>
</code>```

my controller function

```<code>$scope.ShowDetails = function() {
    $scope.NodeDetails = "in am called in function";
    console.log($scope.NodeDetails)
};
</code>```

i can see the data in console but same is not displayed in html.

it works when i put,

```<code>$scope.NodeDetails = "in am called in individual";
</code>```

is there any specific way to set variable in function. I have tried by return value also but that also didn't work.

```<code>$scope.NodeDetails = function() {
return "in am called in function";
};
</code>```

please suggest.

答:
It should work either way, here's an example of different type of setters

angular.module("app", []).controller("myCtrl", function($scope){
  $scope.val = "default value";

  $scope.change = function(){
    $scope.val = $scope.text;
    $scope.text ="";
  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
{{val}}
<input type="text" ng-model="text" placeholder="Add something"/>
<button ng-click="change()">Change</button>
</div></code>```

Body:
I am trying to assign value to $scope variable from a controller function. I can see the value is assigned from console but it is not reflecting in html page.

my html

{{NodeDetails}}

my controller function

$scope.ShowDetails = function() {
    $scope.NodeDetails = "in am called in function";
    console.log($scope.NodeDetails)
};

i can see the data in console but same is not displayed in html.

it works when i put,

$scope.NodeDetails = "in am called in individual";

is there any specific way to set variable in function. I have tried by return value also but that also didn't work.

$scope.NodeDetails = function() {
return "in am called in function";
};

please suggest.

Body:
It should work either way, here's an example of different type of setters

angular.module("app", []).controller("myCtrl", function($scope){
  $scope.val = "default value";

  $scope.change = function(){
    $scope.val = $scope.text;
    $scope.text ="";
  };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="myCtrl">
{{val}}
<input type="text" ng-model="text" placeholder="Add something"/>
<button ng-click="change()">Change</button>
</div>


答:
I would write the code like below.
$('img') will select all your images and apply the code to them on hover.

```<code>$('img').hover(function(){
    $(this).addClass('active');
},function(){
     $(this).removeClass('active');
});
</code>```

Title: To Compress my jQuery

Body:
How can I compress my jQuery useful? I want to add a function to show an element when I hover another one. The function below is exactly what I want, but I want it more dynamic. Maybe with an data attribute?

var item_first = $('.item_first');
var item_second = $('.item_second');
var item_third = $('.item_third');
var item_fourth = $('.item_fourth');

var image_first = $('.image_first');
var image_second = $('.image_second');
var image_third = $('.image_third');
var image_fourth = $('.image_fourth');

$(document).ready(function () {
    item_first.hover(function () {
        image_first.addClass('active');
    }, function () {
        image_first.removeClass('active');
    });

    item_second.hover(function () {
        image_second.addClass('active');
    }, function () {
        image_second.removeClass('active');
    });
    item_third.hover(function () {
        image_third.addClass('active');
    }, function () {
        image_third.removeClass('active');
    });

    item_fourth.hover(function () {
        image_fourth.addClass('active');
    }, function () {
        image_fourth.removeClass('active');
    });
});

https://jsfiddle.net/gt5kw00q/

Sorry for my bad English. I try to write so that you understand it.

Body:
I would write the code like below.
$('img') will select all your images and apply the code to them on hover.

$('img').hover(function(){
    $(this).addClass('active');
},function(){
     $(this).removeClass('active');
});


问:
no response from TCP socket in Apache Camel using Netty4
this is my route

```<code>from(Endpoints.login.inRoute())
    .process(new LoginRequestProcessor())
    .to("netty4:tcp://somehost:9001?textline=true")
    .process(new LoginResponseProcessor())
    .to(Endpoints.login.outRoute());
</code>```

I just want to communicate with a socket server running at somehost at port 9001 but I'm not getting any response.

However, I tested the socket server using telnet and it is alive and responding.

Also, I writed a simple TCP socket server using C and tested exactly the same Camel route but with the address of my local server (localhost) with its local port and everything works fine.

What could be happening?

Thanks!

答: Try pass the param synchronous=true, it will force your call be synchronous.</p>

Body:
this is my route

from(Endpoints.login.inRoute())
    .process(new LoginRequestProcessor())
    .to("netty4:tcp://somehost:9001?textline=true")
    .process(new LoginResponseProcessor())
    .to(Endpoints.login.outRoute());

I just want to communicate with a socket server running at somehost at port 9001 but I'm not getting any response.

However, I tested the socket server using telnet and it is alive and responding.

Also, I writed a simple TCP socket server using C and tested exactly the same Camel route but with the address of my local server (localhost) with its local port and everything works fine.

What could be happening?

Thanks!


问:
VBA interact with HTML: How to click a drop down when HTML tag have only HREF and CLASS name
Here I am trying to replicate one issue I am facing in my secured network using a live example so that some one can help me to find a solution for this.

In fact I open one question (VBA: How to click a drop down in a web page with the help of HREF and CLASS HTML tag avilable ) for the same issue but I cant find a solution yet.

Expected result:
The code which help me to open a web page (https://www.amazon.in/) and navigate to a dropdown (Today's Deal) from a menu bar using HTML tag CLASS and HREF only. [The sample (website) give here have "tabindex" as well but please dont use that as a solution because in my really scenario I dont have any other tags other than href & class (Please find the screen shot of HTML tags I have for the real webpage)]

 Img1: Real scenario, just keep it here to make you understand that I only have these two tags

The VBA code

```<code>Sub Click_aLinkorDropdown()

Dim MyHTML_Element As IHTMLElement
Dim MyURL As String

'On Error GoTo Err_Clear
MyURL = "https://www.amazon.in/"
Set MyBrowser = New InternetExplorerMedium
MyBrowser.Silent = True
MyBrowser.navigate MyURL
MyBrowser.Visible = True

For Each MyHTML_Element In HTMLDoc.getElementsByClassName("nav-a")
If InStr(MyHTML_Element.href, "/gp/goldbox/ref=nav_cs_gb") Then
MyHTML_Element.Click
Exit For
Next

'Err_Clear:
'If Err <> 0 Then
'Err.Clear
'Resume Next
'End If
End Sub
</code>```

HTML TAG

```<code>href='/gp/goldbox/ref=nav_cs_gb' class='nav-a' tabindex='22'>Today's Deals</a><a
</code>```

Issue I am facing by using this code
The web page open and when it reach to click the link I am getting two types of error 1: > Runtime error 438: Object does not support this property or method

2: > Runtime error 424: Object required

And i also tried one of the post available in StackOverflow but this is not working for me

答:
Use the following code and remember to enable the references Microsoft Internet Controls and Microsoft HTML Object Library:

```<code>#If VBA7 Then
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

Sub test()
Dim IE As Object
Dim HTMLDoc As Object
Dim sURL As String

' CREATING OBJECT
Set IE = CreateObject("internetexplorer.application")

sURL = "https://www.amazon.in/"
' WEBPAGE NAVIGATION
With IE
.Navigate (sURL)
.Visible = True
End With

WaitIE IE, 2000

' CLICK ON LOG IN
Set HTMLDoc = IE.Document
Set buttonclick = HTMLDoc.getElementsByClassName("nav-a")

For Each Element In buttonclick
    If Element.href = "https://www.amazon.in/gp/goldbox/ref=nav_cs_gb" Then Element.Click
Next Element
WaitIE IE, 5000

'IE.Quit
'Set IE = Nothing
End Sub

Sub WaitIE(IE As Object, Optional time As Long = 250)
'Code from: https://stackoverflow.com/questions/33808000/run-time-error-91-object-variable-or-with-block-variable-not-set
Dim i As Long
Do
    Sleep time
    Debug.Print CStr(i) & vbTab & "Ready: " & CStr(IE.READYSTATE = 4) & _
                vbCrLf & vbTab & "Busy: " & CStr(IE.Busy)
    i = i + 1
Loop Until IE.READYSTATE = 4 Or Not IE.Busy
End Sub
</code>```

You can refer to this answer for a similar answer code.

Body:
Here I am trying to replicate one issue I am facing in my secured network using a live example so that some one can help me to find a solution for this.

In fact I open one question (VBA: How to click a drop down in a web page with the help of HREF and CLASS HTML tag avilable ) for the same issue but I cant find a solution yet.

Expected result:
The code which help me to open a web page (https://www.amazon.in/) and navigate to a dropdown (Today's Deal) from a menu bar using HTML tag CLASS and HREF only. [The sample (website) give here have "tabindex" as well but please dont use that as a solution because in my really scenario I dont have any other tags other than href & class (Please find the screen shot of HTML tags I have for the real webpage)]

 Img1: Real scenario, just keep it here to make you understand that I only have these two tags

The VBA code

Sub Click_aLinkorDropdown()

Dim MyHTML_Element As IHTMLElement
Dim MyURL As String

'On Error GoTo Err_Clear
MyURL = "https://www.amazon.in/"
Set MyBrowser = New InternetExplorerMedium
MyBrowser.Silent = True
MyBrowser.navigate MyURL
MyBrowser.Visible = True

For Each MyHTML_Element In HTMLDoc.getElementsByClassName("nav-a")
If InStr(MyHTML_Element.href, "/gp/goldbox/ref=nav_cs_gb") Then
MyHTML_Element.Click
Exit For
Next

'Err_Clear:
'If Err <> 0 Then
'Err.Clear
'Resume Next
'End If
End Sub

HTML TAG

href='/gp/goldbox/ref=nav_cs_gb' class='nav-a' tabindex='22'>Today's Deals<a

Issue I am facing by using this code
The web page open and when it reach to click the link I am getting two types of error 1: > Runtime error 438: Object does not support this property or method

2: > Runtime error 424: Object required

And i also tried one of the post available in StackOverflow but this is not working for me

Body:
Use the following code and remember to enable the references Microsoft Internet Controls and Microsoft HTML Object Library:

#If VBA7 Then
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

Sub test()
Dim IE As Object
Dim HTMLDoc As Object
Dim sURL As String

' CREATING OBJECT
Set IE = CreateObject("internetexplorer.application")

sURL = "https://www.amazon.in/"
' WEBPAGE NAVIGATION
With IE
.Navigate (sURL)
.Visible = True
End With

WaitIE IE, 2000

' CLICK ON LOG IN
Set HTMLDoc = IE.Document
Set buttonclick = HTMLDoc.getElementsByClassName("nav-a")

For Each Element In buttonclick
    If Element.href = "https://www.amazon.in/gp/goldbox/ref=nav_cs_gb" Then Element.Click
Next Element
WaitIE IE, 5000

'IE.Quit
'Set IE = Nothing
End Sub

Sub WaitIE(IE As Object, Optional time As Long = 250)
'Code from: https://stackoverflow.com/questions/33808000/run-time-error-91-object-variable-or-with-block-variable-not-set
Dim i As Long
Do
    Sleep time
    Debug.Print CStr(i) & vbTab & "Ready: " & CStr(IE.READYSTATE = 4) & _
                vbCrLf & vbTab & "Busy: " & CStr(IE.Busy)
    i = i + 1
Loop Until IE.READYSTATE = 4 Or Not IE.Busy
End Sub

You can refer to this answer for a similar answer code.


问:
How to setup multiple Layouts in Zend Framework. Eg. Public/Logged in/Various combinations of modules
I know & used the very basic Zend Framework's Layouts where I used 1 layout throughout the whole site. But now I need a more intermediate/organized setup.

The public site layout will have the div#mainContent taking up the whole 12 columns (using 960gs)

The logged in site will have div#mainContent taking up 9 columns + side bar with 3 columns

In the sidebar of the logged in site, various pages may contain various modules (not Zend Framework's modules, more like "boxes/widgets")

They will have different nav menus too

I am thinking of using 1 base layout where the 2 sub layouts will "extend". The base layout will just contain the  declarations headScripts etc till the  then the sublayouts will contain definations for the wrapping divs div.grid_12, grid_9, grid_3. How can I implement this "extending", basically, I just want to reuse code

Also whats a good way to render sidebar boxes/widgets

答:
I'm switching between layouts depending on the subdomain of my website.

Here's the layout plugin I'm using...

```<code>class App_Layout_Controller_Plugin_Layout extends Zend_Layout_Controller_Plugin_Layout
{

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $layout = $this->getLayout();
        $filename = $layout->getLayoutPath() . '/' . $request->getModuleName() . '.' . $layout->getViewSuffix();

        //check if the layout template exists, if not use the default layout set in application.ini
        if (file_exists($filename))
        {
            $this->getLayout()->setLayout($request->getModuleName());
        }
    }

}
</code>```

Of course you can modify this for your own needs.

Make sure you set up you application.ini correctly too including elements like the following...

```<code>resources.layout.layout = "default"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.layout.pluginClass = "App_Layout_Controller_Plugin_Layout"
</code>```

In my case I have:

default.phtml, admin.phtml, clients.phtml

I hope this helps...

Angel

Body:
I'm switching between layouts depending on the subdomain of my website.

Here's the layout plugin I'm using...

class App_Layout_Controller_Plugin_Layout extends Zend_Layout_Controller_Plugin_Layout
{

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $layout = $this->getLayout();
        $filename = $layout->getLayoutPath() . '/' . $request->getModuleName() . '.' . $layout->getViewSuffix();

        //check if the layout template exists, if not use the default layout set in application.ini
        if (file_exists($filename))
        {
            $this->getLayout()->setLayout($request->getModuleName());
        }
    }

}

Of course you can modify this for your own needs.

Make sure you set up you application.ini correctly too including elements like the following...

resources.layout.layout = "default"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.layout.pluginClass = "App_Layout_Controller_Plugin_Layout"

In my case I have:

default.phtml, admin.phtml, clients.phtml

I hope this helps...

Angel


问:
Expert modeler for forecast in R like in SPSS
In SPSS, there is good feature for time series, which is called expert modeler
here the screen.

It chooses the best model,by it's R^2, Stationary R^2, RMSEA, MAE, MAPE in automatic mode.

Can R do that?

Here my data

```<code>          SERIES_G
JAN 1949    112
FEB 1949    118
MAR 1949    132
APR 1949    129
MAY 1949    121
JUN 1949    135
JUL 1949    148
AUG 1949    148
SEP 1949    136
OCT 1949    119
NOV 1949    104
DEC 1949    118
JAN 1950    115
FEB 1950    126
MAR 1950    141
APR 1950    135
MAY 1950    125
JUN 1950    149
JUL 1950    170
AUG 1950    170
SEP 1950    158
OCT 1950    133
NOV 1950    114
DEC 1950    140
JAN 1951    145
FEB 1951    150
</code>```

答:
The ets (for exponential smoothing models) and auto.arima (for ARIMA models) functions included in the forecast package come close to what you are looking for. You'll have to manually specify under which (if any) constraints the models are to be estimated, but these functions will automatically select the 'best' model based on AIC and BIC values.

For more information, have a look at the package documentation and this publication by two of the authors of the forecast package.

Body:
In SPSS, there is good feature for time series, which is called expert modeler
here the screen.

It chooses the best model,by it's R^2, Stationary R^2, RMSEA, MAE, MAPE in automatic mode.

Can R do that?

Here my data

          SERIES_G
JAN 1949    112
FEB 1949    118
MAR 1949    132
APR 1949    129
MAY 1949    121
JUN 1949    135
JUL 1949    148
AUG 1949    148
SEP 1949    136
OCT 1949    119
NOV 1949    104
DEC 1949    118
JAN 1950    115
FEB 1950    126
MAR 1950    141
APR 1950    135
MAY 1950    125
JUN 1950    149
JUL 1950    170
AUG 1950    170
SEP 1950    158
OCT 1950    133
NOV 1950    114
DEC 1950    140
JAN 1951    145
FEB 1951    150


问:
Change background color when button is active or selected
I have default  ._sideFolder  with background color of black

I want to change the bgcolor into blue when the button is selected

```<code>.zf-folder:active ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}
</code>```

The blue color only appears when clicked.

I am really confused with my pseudo CSS. Should I use JavaScript in here?

My JSFiddle

I want to display like in the picture on the left.

FYI: In my project I use ._sideFolder with background-color: red;

$(document).ready(function() {
  $('table.table').DataTable();
  $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>._sideFolder {
  background-color: black;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}</code>```

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

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

            Main Folder

            Second Folder

            Name
            Start Date
            End Date
            Operation

            ...
            ...
            ...

              <button class="btn btn-success btn-xs approve-off" type="submit" value="approve">
                 Approve
              </button>
              <button class="btn btn-danger btn-xs reject-off" type="submit" value="reject">
                 Reject
              </button>

            Name
            Start Date
            End Date
            Operation

            ...
            ...
            ...

              <input hidden="hidden" name="offId" />
              <button class="btn btn-danger btn-xs delete-ocoff" type="submit" value="delete">
                 Delete
              </button>

```

答:
A few things I'll try to summarise:

The html structure was invalid, unordered lists (ul) and ordered
lists (ol) should only contain list items (li) as direct
descendant elements.

The active class was not toggling off inactive list items
correctly - this behaviour was rectified by nesting .zf-folder inside of
the list items - which is valid html structuring anyway and was
addressed in the former point.

The styles you have declared for the elements in question for
:active pseudo-states should now be declared for .active list
items. You could probably do away with those :active styles
altogether now.

Updated JSFiddle

Adjusted Selectors:

```<code>.zf-folder:active ._sideFolder, li.active .zf-folder ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

._tabFolder:active, li.active ._tabFolder {
  background-color: rgba(29, 33, 41, 1)
}
</code>```

Code Snippet Demonstration:

$(document).ready(function() {
  $('table.table').DataTable();
  $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>._sideFolder {
  background-color: black;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder,
li.active .zf-folder ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active, li.active ._tabFolder {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}</code>```

<link rel="stylesheet" type="text/css" href="/css/result-light.css">

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

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">

            Main Folder

            Second Folder

            Name
            Start Date
            End Date
            Operation

            ...
            ...
            ...

              <button class="btn btn-success btn-xs approve-off" type="submit" value="approve">
                 Approve
              </button>
              <button class="btn btn-danger btn-xs reject-off" type="submit" value="reject">
                 Reject
              </button>

            Name
            Start Date
            End Date
            Operation

            ...
            ...
            ...

              <input hidden="hidden" name="offId" />
              <button class="btn btn-danger btn-xs delete-ocoff" type="submit" value="delete">
                 Delete
              </button>

```

Body:
I have default  ._sideFolder  with background color of black

I want to change the bgcolor into blue when the button is selected

.zf-folder:active ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

The blue color only appears when clicked.

I am really confused with my pseudo CSS. Should I use JavaScript in here?

My JSFiddle

I want to display like in the picture on the left.

FYI: In my project I use ._sideFolder with background-color: red;

$(document).ready(function() {
  $('table.table').DataTable();
  $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
  });
});

._sideFolder {
  background-color: black;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}

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

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

            Main Folder

            Second Folder

            Name
            Start Date
            End Date
            Operation

            ...
            ...
            ...

              <button class="btn btn-success btn-xs approve-off" type="submit" value="approve">
                 Approve
              </button>
              <button class="btn btn-danger btn-xs reject-off" type="submit" value="reject">
                 Reject
              </button>

            Name
            Start Date
            End Date
            Operation

            ...
            ...
            ...

              <input hidden="hidden" name="offId" />
              <button class="btn btn-danger btn-xs delete-ocoff" type="submit" value="delete">
                 Delete
              </button>

Body:
A few things I'll try to summarise:

The html structure was invalid, unordered lists (ul) and ordered
lists (ol) should only contain list items (li) as direct
descendant elements.

The active class was not toggling off inactive list items
correctly - this behaviour was rectified by nesting .zf-folder inside of
the list items - which is valid html structuring anyway and was
addressed in the former point.

The styles you have declared for the elements in question for
:active pseudo-states should now be declared for .active list
items. You could probably do away with those :active styles
altogether now.

Updated JSFiddle

Adjusted Selectors:

.zf-folder:active ._sideFolder, li.active .zf-folder ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

._tabFolder:active, li.active ._tabFolder {
  background-color: rgba(29, 33, 41, 1)
}

Code Snippet Demonstration:

$(document).ready(function() {
  $('table.table').DataTable();
  $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    $($.fn.dataTable.tables(true)).DataTable().columns.adjust();
  });
});

._sideFolder {
  background-color: black;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder,
li.active .zf-folder ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active, li.active ._tabFolder {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}

<script type="text/javascript" src="/js/lib/dummy.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<ul class="nav">

  <li class="active">
    <div class="zf-folder">
      <div id="tabFolder" class="_tabFolder _itemPosition" style="height: 40px;border-bottom:1px groove; user-select: none;">
        <div class="_sideFolder"></div>
        <div class="_iconText" style="width: 215px">
          <div class="ellipsis">
            <div class="_iconFolder">
              <div class="_icon-col">
              </div>
            </div>
            <a href="#mainFolder" aria-controls="mainFolder" data-toggle="tab">Main Folder<span class="hyperspan"></span></a>
          </div>
        </div>
      </div>
    </div>
  </li>

  <li>
    <div class="zf-folder">
      <div id="tabFolder2" class="_tabFolder _itemPosition" style="height: 40px;border-bottom:1px groove; user-select: none;">
        <div class="_sideFolder"></div>
        <div class="_iconText" style="width: 215px">
          <div class="ellipsis">
            <div class="_iconFolder">
              <div class="_icon-col">
              </div>
            </div>
            <a href="#secondFolder" aria-controls="secondFolder" data-toggle="tab">Second Folder<span class="hyperspan"></span></a>
          </div>
        </div>
      </div>
    </div>
  </li>

</ul>

<!-- CONTENT -->

<div class="tab-content">

  <div class="tab-pane fade in active" id="mainFolder">
    <div class="zf-table">
      <table class="table table-bordered table-hover table-striped">
        <thead>
          <tr>
            <th>Name</th>
            <th>Start Date</th>
            <th>End Date</th>
            <th>Operation</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>

              <button class="btn btn-success btn-xs approve-off" type="submit" value="approve">
                <span class="fa fa-check-square-o"></span> Approve
              </button>
              <button class="btn btn-danger btn-xs reject-off" type="submit" value="reject">
                <span class="fa fa-times"></span> Reject
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <div class="tab-pane fade in" id="secondFolder">
    <div class="zf-table">
      <table class="table table-bordered table-hover table-striped">
        <thead>
          <tr>
            <th>Name</th>
            <th>Start Date</th>
            <th>End Date</th>
            <th>Operation</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>...</td>
            <td>...</td>
            <td>...</td>
            <td>
              <input hidden="hidden" name="offId" />
              <button class="btn btn-danger btn-xs delete-ocoff" type="submit" value="delete">
                <span class="fa fa-times"></span> Delete
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

</div>


问:
Go: **Type pointer
In tutorial is written:

The type *T is a pointer to a T value. The & operator generates
  a pointer to its operand.

I am just playing around with pointers in Go and have following:

```<code>example := 42

p:=&example
fmt.Println(reflect.TypeOf(&p)) // **int
fmt.Println(reflect.TypeOf(*p)) // int
</code>```

So if I got it correctly, &p is a pointer to a pointer to an int value.

What is use of **Type in the Go language?

答:
Here's a simple demonstration of the concept of a chain of pointers:

```<code>package main

import "fmt"

func main() {
    i := 42
    fmt.Printf("i: %[1]T %[1]d\n", i)
    p := &i
    fmt.Printf("p: %[1]T %[1]p\n", p)
    j := *p
    fmt.Printf("j: %[1]T %[1]d\n", j)
    q := &p
    fmt.Printf("q: %[1]T %[1]p\n", q)
    k := **q
    fmt.Printf("k: %[1]T %[1]d\n", k)
}
</code>```

Playground: https://play.golang.org/p/WL2M1jp1T3

Output:

```<code>i: int 42
p: *int 0x10410020
j: int 42
q: **int 0x1040c130
k: int 42
</code>```

Title: Go: **Type pointer

Body:
In tutorial is written:

The type *T is a pointer to a T value. The & operator generates
  a pointer to its operand.

I am just playing around with pointers in Go and have following:

example := 42

p:=&example
fmt.Println(reflect.TypeOf(&p)) // **int
fmt.Println(reflect.TypeOf(*p)) // int

So if I got it correctly, &p is a pointer to a pointer to an int value.

What is use of **Type in the Go language?

Body:
Here's a simple demonstration of the concept of a chain of pointers:

package main

import "fmt"

func main() {
    i := 42
    fmt.Printf("i: %[1]T %[1]d\n", i)
    p := &i
    fmt.Printf("p: %[1]T %[1]p\n", p)
    j := *p
    fmt.Printf("j: %[1]T %[1]d\n", j)
    q := &p
    fmt.Printf("q: %[1]T %[1]p\n", q)
    k := **q
    fmt.Printf("k: %[1]T %[1]d\n", k)
}

Playground: https://play.golang.org/p/WL2M1jp1T3

Output:

i: int 42
p: *int 0x10410020
j: int 42
q: **int 0x1040c130
k: int 42


问:
Is the array structure redundant in json?
In https://www.json.org/, it said:

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

My question is:

Why json is designed to use two types of data structures instead of one ? (name/value pairs only)

For instance,

I use the following two methods to describe the School structure (School contains multiple Students):

1.

```<code>{
    "Student" : [
        { "Name" : "Peter", "Sex" : "Male" },
        { "Name" : "Linda", "Sex" : "Female" },
    ]
}
</code>```

2.

```<code>{
    "Student" : {
        "0" : { "Name" : "Peter", "Sex" : "Male" },
        "1" : { "Name" : "Linda", "Sex" : "Female" },
    }
}
</code>```

Which is better?

I like the second one.

Why?

Because in my opinion, the member "Student" is array or map, ordered or unordered, bounded or unbounded, should be defined in its meta data instead of instance data.

The two school json data above are both instance data! (note: the symbol '[]' represent "type infomation" which should be defined in meta data. It's redundant now...)

When I use XPath like syntax to access "Name" member in the example above, they are no different:

School.Student[0].Name  <---[0] as array index

School.Student[0].Name  <---[0] as map key

The same example in XML which has only one way to express:

```<code><School>
    <Student Name="Peter" Sex="Male"/>
    <Student Name="Linda" Sex="Female"/>
</School>
</code>```

I heard someone claiming that XML is redundant because of it's ending tags and attributes (relative to s-expression).

But I think the redundancy of XML is only in grammar, the redundancy of Json is in semantic.

Am I right?
Very thanks.

答:
Redundant for what?

Discussing the theories of data transfer? Then yes, it's redundant as the other structure it supports can represent arrays.

Balancing the concerns of sparseness, representational integrity, simplicity for human readers and writers, simplicity for software parsers and generators, speed of parsing and generating, simplicity of mapping to data structures and simplicity of validation — that is to say, the actual design goals — then no. Being able to directly encode arrays has benefits for the sparseness, simplicity of humans, simplicity of validation (if it's a valid array in syntax it's a valid array, which doesn't necessarily follow from maps that could omit indices without a separate application-specific rule to handle that) and speed of producing (if something maps on increasing indices then we are forced to potentially catch someone mixing them up). What is a redundancy in the sense of analysing what can be represented is not redundant in the sense of not offering a practical benefit.

In the second case of "beyond what we need or want" redundant has a rather pejorative connotation while in other cases redundant can be a positive thing (having redundancy gives you room to deal with loss, ability to catch errors and so on in different cases). The redundancy here is of the second sort; we could use a version of JSON that had no arrays, so we don't strictly need it, but life is a lot easier because we do have it and almost nobody is going to go to the effort of producing a horrible mapping of ascending integers to elements just to make the life of those parsing it harder.

Body:
In https://www.json.org/, it said:

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

My question is:

Why json is designed to use two types of data structures instead of one ? (name/value pairs only)

For instance,

I use the following two methods to describe the School structure (School contains multiple Students):

1.

{
    "Student" : [
        { "Name" : "Peter", "Sex" : "Male" },
        { "Name" : "Linda", "Sex" : "Female" },
    ]
}

2.

{
    "Student" : {
        "0" : { "Name" : "Peter", "Sex" : "Male" },
        "1" : { "Name" : "Linda", "Sex" : "Female" },
    }
}

Which is better?

I like the second one.

Why?

Because in my opinion, the member "Student" is array or map, ordered or unordered, bounded or unbounded, should be defined in its meta data instead of instance data.

The two school json data above are both instance data! (note: the symbol '[]' represent "type infomation" which should be defined in meta data. It's redundant now...)

When I use XPath like syntax to access "Name" member in the example above, they are no different:

School.Student[0].Name  <---[0] as array index

School.Student[0].Name  <---[0] as map key

The same example in XML which has only one way to express:

<School>
    <Student Name="Peter" Sex="Male"/>
    <Student Name="Linda" Sex="Female"/>
</School>

I heard someone claiming that XML is redundant because of it's ending tags and attributes (relative to s-expression).

But I think the redundancy of XML is only in grammar, the redundancy of Json is in semantic.

Am I right?
Very thanks.


问:
Desktop file for Flatpak app
I have created a Flatpak app but I don't know how to specify icons and launcher information for my package.

The application has a desktop file but get this error message:

"Not exporting share/applications/myapp.desktop, wrong prefix"

The file is located in myapp/files/share/applications/myapp.desktop

Please help

答: Desktop file and icons should be stored in myapp/export instead of myapp/files.

Title: Desktop file for Flatpak app


问:
Regex Python extract digits between two strings in a single expression
I want only digits existing between two characters in order to get an integer dollar value, e.g. from string:

"Advance [Extra Value of $1,730,555] in packages 2,3, and 5."

we want to obtain "1730555".

We can use \$(.*)\] to get "1,730,555", but how do we remove the commas in the same expression, while retaining the possibility of arbitrary many commas, ideally getting the number in a single capturing group?

答:
You can try like this</p>

```<code>import re
text = "Advance [Extra Value of $1,730,555] in packages 2,3, and 5."
match = re.findall(r'\$(.*)]',text)[0].replace(',','')
print match
</code>```

Body:
You can try like this

import re
text = "Advance [Extra Value of $1,730,555] in packages 2,3, and 5."
match = re.findall(r'\$(.*)]',text)[0].replace(',','')
print match


问:
Splunk - stop break-by by timestamp
Sorry new to Splunk...I've a single logfile with entries that look like this:

"15/11/2017 20:20:59","0","1803.xml","Copied to Amazon S3",5,"O"
"15/11/2017 20:21:00","0","1260.xml","Copied to Amazon S3",5,"O"
"15/11/2017 20:21:00","0","2415.xml","Copied to Amazon S3",5,"O"
"15/11/2017 20:21:01","0","134.xml","Copied to Amazon S3",5,"O"
"15/11/2017 20:21:01","0","808.xml","Copied to Amazon S3",5,"O"
"15/11/2017 20:21:02","0","261.xml","Copied to Amazon S3",5,"O"
"15/11/2017 20:21:02","0","646.xml","Copied to Amazon S3",5,"O"
"15/11/2017 20:21:03","0","1157.xml","Copied to Amazon S3",5,"O"

Splunk is breaking this into events by timestamp (field 1) but because the above entries have repeating timestamps I only get the first event for each date.

How can I insure that EACH line gets its own event?

答:
I had to create a new sourcetype with

1. SHOULD_LINEMERGE = false
2 removed BREAK_ONLY_BEFORE attribute

and point the data source to this

Title: Splunk - stop break-by by timestamp


问:
Java String.replaceAll() refer the latest found group
Javadoc says $1, $2, etc. can be used to reference the match groups, but how does one reference the latest found group in the replacement string when using String.replaceAll()?

I.e. there's a string "aaabbbaa" and a regex "a+", and I want to be able to do something like s.replaceAll("a+", "$\n") to get "aaa\nbbbaa\n", but Java gives me the Illegal group reference.

答:
s.replaceAll("(a+)", "$1\n") should work:

```<code>jshell> String s = "aaabbbaa"
s ==> "aaabbbaa"

jshell> s.replaceAll("(a+)", "$1\n")
$2 ==> "aaa\nbbbaa\n"
</code>```

As pointed out in the comments already, you'll have to mark the capture group in your regular expression. That's what the parentheses (...) do. Then you'll have to reference that capture group with $1, which is the first capture group. $0 would be the whole match (also pointed out in the comments), but just $ will not work.

Body:
s.replaceAll("(a+)", "$1\n") should work:

jshell> String s = "aaabbbaa"
s ==> "aaabbbaa"

jshell> s.replaceAll("(a+)", "$1\n")
$2 ==> "aaa\nbbbaa\n"

As pointed out in the comments already, you'll have to mark the capture group in your regular expression. That's what the parentheses (...) do. Then you'll have to reference that capture group with $1, which is the first capture group. $0 would be the whole match (also pointed out in the comments), but just $ will not work.


问:
Datatype of escape sequences in c++
I am still a beginner.

Some of my teachers say that escape sequences are characters while others say they are "special" strings.

What are they exactly?

答: Escape sequences are a set of characters. So the datatype simply depends on the way you use them.</p>

Title: Datatype of escape sequences in c++


问:
Writing Python lists to columns in csv
I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:

```<code>with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for val in test_list:
        writer.writerow([val])
</code>```

If I add another for loop, it just writes that list to the same column. Anyone know a good way to get five separate columns?

答:
The following code writes python lists into columns in csv

```<code>import csv
from itertools import zip_longest
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j']
d = [list1, list2]
export_data = zip_longest(*d, fillvalue = '')
with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
      wr = csv.writer(myfile)
      wr.writerow(("List1", "List2"))
      wr.writerows(export_data)
myfile.close()
</code>```

The output looks like this

Title: Writing Python lists to columns in csv

Body:
I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:

with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for val in test_list:
        writer.writerow([val])

If I add another for loop, it just writes that list to the same column. Anyone know a good way to get five separate columns?

Body:
The following code writes python lists into columns in csv

import csv
from itertools import zip_longest
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j']
d = [list1, list2]
export_data = zip_longest(*d, fillvalue = '')
with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
      wr = csv.writer(myfile)
      wr.writerow(("List1", "List2"))
      wr.writerows(export_data)
myfile.close()

The output looks like this