问:
Can’t login to MySQL/mariaDB - [Error] Failed to load resource: the server responded with a status of 500 (Internal Server Error) (get_data.php)
I am moving a stable Appache2/PHP/MysQL web service to a new machine and I have come across a problem which I am unable to resolve despite hours of searchng on the internet.  The old machine is Debian Weezy, the new machine is Debian Stretch.  Javascript running on the client calls a PHP script running on the server.  The PHP script should loggon to MySQL/mariaDB and retrieve the data which is returned to the client as a JSON string.  This has been working ok (with old MySQL) for the past four years.  But on the new machine I have encountered a problem logging onto the MySQL/mariaDB.  I have created a number of user accounts on Mysql/mariadb with different hostnames with no success.  All of the accounts work if the PHP script is run locally via the command line, none work via the web client.  If I replace all the code in the PHP script with just example data to be returned everything works from the client as expected.  e.g.

```<code><?PHP
      echo ‘{“k1”:”3.0”,”k2”:”4.2”,”k3”:”2.6”,”k4”:”1.9”}’;
?>
</code>```

The error is caused by the Mysql login failure. I feel sure the answer is a simple one but I just can’t find it.  Abbreviated code snippet follows:-

```<code> <?PHP
   $link = mysqli_connect(‘hostname’, ‘user’, ‘password’, ‘database’);
   if(!$link) {
       printf("Connection failed: %s\n");
       exit();
   }
   if($result = mysqli_query($link, "SELECT * FROM my_data ORDER BY id DESC LIMIT 1")) {
       $row = mysqli_fetch_assoc($result);
       $php_array = array('k1' => $row[“data0”],
                          'k2' => $row[“data1”],
                          'k3' => $row[“data2”],
                          'k4’ => $row["ldata3”]
       );
       echo json_encode($php_array);   // this returns the data
       mysqli_free_result($result);
       mysqli_close($link);
   }
 ?>
</code>```

I have tried hostname = ‘’, ‘%’ and ‘localhost’ - the old machine uses ‘localhost’.

all users have ALL PRIVILEGES on ‘database’.

Perhaps it is some OS permissions issue?

Many thanks

答: SOLVED - PHP7.0 and associated modules for Apache2 and MySQL no longer support mysqli-connect().  The solution was to delete all PHP7 replace it with PHP5.</p>

Body:
I am moving a stable Appache2/PHP/MysQL web service to a new machine and I have come across a problem which I am unable to resolve despite hours of searchng on the internet.  The old machine is Debian Weezy, the new machine is Debian Stretch.  Javascript running on the client calls a PHP script running on the server.  The PHP script should loggon to MySQL/mariaDB and retrieve the data which is returned to the client as a JSON string.  This has been working ok (with old MySQL) for the past four years.  But on the new machine I have encountered a problem logging onto the MySQL/mariaDB.  I have created a number of user accounts on Mysql/mariadb with different hostnames with no success.  All of the accounts work if the PHP script is run locally via the command line, none work via the web client.  If I replace all the code in the PHP script with just example data to be returned everything works from the client as expected.  e.g.

<?PHP
      echo ‘{“k1”:”3.0”,”k2”:”4.2”,”k3”:”2.6”,”k4”:”1.9”}’;
?>

The error is caused by the Mysql login failure. I feel sure the answer is a simple one but I just can’t find it.  Abbreviated code snippet follows:-

 <?PHP
   $link = mysqli_connect(‘hostname’, ‘user’, ‘password’, ‘database’);
   if(!$link) {
       printf("Connection failed: %s\n");
       exit();
   }
   if($result = mysqli_query($link, "SELECT * FROM my_data ORDER BY id DESC LIMIT 1")) {
       $row = mysqli_fetch_assoc($result);
       $php_array = array('k1' => $row[“data0”],
                          'k2' => $row[“data1”],
                          'k3' => $row[“data2”],
                          'k4’ => $row["ldata3”]
       );
       echo json_encode($php_array);   // this returns the data
       mysqli_free_result($result);
       mysqli_close($link);
   }
 ?>

I have tried hostname = ‘’, ‘%’ and ‘localhost’ - the old machine uses ‘localhost’.

all users have ALL PRIVILEGES on ‘database’.

Perhaps it is some OS permissions issue?

Many thanks


来源: stackexchange

问:
Read interactive input in Jenkins pipeline to a variable
In a Jenkins pipeline, I want to provide an option to the user to give an interactive input at run time. I want to understand how we can read the user input in the Groovy script.

I'm referring to this documentation.

After some trials I've got this working:

```<code> pipeline {
    agent any

    stages {

        stage("Interactive_Input") {
            steps {
                script {
                def userInput = input(
                 id: 'userInput', message: 'Enter path of test reports:?',
                 parameters: [
                 [$class: 'TextParameterDefinition', defaultValue: 'None', description: 'Path of config file', name: 'Config'],
                 [$class: 'TextParameterDefinition', defaultValue: 'None', description: 'Test Info file', name: 'Test']
                ])
                echo ("IQA Sheet Path: "+userInput['Config'])
                echo ("Test Info file path: "+userInput['Test'])

                }
            }
        }
    }
}
</code>```

In this example I'm able to echo (print) the user input parameters:

```<code>echo ("IQA Sheet Path: "+userInput['Config'])
echo ("Test Info file path: "+userInput['Test'])
</code>```

but I'm not able to write these parameters to a file or assign them to a variable. How can we achieve this?

答:
For saving to variables and a file, try something like this based on what you had:</p>

```<code>pipeline {

    agent any

    stages {

        stage("Interactive_Input") {
            steps {
                script {

                    // Variables for input
                    def inputConfig
                    def inputTest

                    // Get the input
                    def userInput = input(
                            id: 'userInput', message: 'Enter path of test reports:?',
                            parameters: [

                                    string(defaultValue: 'None',
                                            description: 'Path of config file',
                                            name: 'Config'),
                                    string(defaultValue: 'None',
                                            description: 'Test Info file',
                                            name: 'Test'),
                            ])

                    // Save to variables. Default to empty string if not found.
                    inputConfig = userInput.Config?:''
                    inputTest = userInput.Test?:''

                    // Echo to console
                    echo("IQA Sheet Path: ${inputConfig}")
                    echo("Test Info file path: ${inputTest}")

                    // Write to file
                    writeFile file: "inputData.txt", text: "Config=${inputConfig}\r\nTest=${inputTest}"

                    // Archive the file (or whatever you want to do with it)
                    archiveArtifacts 'inputData.txt'
                }
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In a Jenkins pipeline, I want to provide an option to the user to give an interactive input at run time. I want to understand how we can read the user input in the Groovy script.

I'm referring to this documentation.

After some trials I've got this working:

 pipeline {
    agent any

    stages {

        stage("Interactive_Input") {
            steps {
                script {
                def userInput = input(
                 id: 'userInput', message: 'Enter path of test reports:?',
                 parameters: [
                 [$class: 'TextParameterDefinition', defaultValue: 'None', description: 'Path of config file', name: 'Config'],
                 [$class: 'TextParameterDefinition', defaultValue: 'None', description: 'Test Info file', name: 'Test']
                ])
                echo ("IQA Sheet Path: "+userInput['Config'])
                echo ("Test Info file path: "+userInput['Test'])

                }
            }
        }
    }
}

In this example I'm able to echo (print) the user input parameters:

echo ("IQA Sheet Path: "+userInput['Config'])
echo ("Test Info file path: "+userInput['Test'])

but I'm not able to write these parameters to a file or assign them to a variable. How can we achieve this?

Body:
For saving to variables and a file, try something like this based on what you had:

pipeline {

    agent any

    stages {

        stage("Interactive_Input") {
            steps {
                script {

                    // Variables for input
                    def inputConfig
                    def inputTest

                    // Get the input
                    def userInput = input(
                            id: 'userInput', message: 'Enter path of test reports:?',
                            parameters: [

                                    string(defaultValue: 'None',
                                            description: 'Path of config file',
                                            name: 'Config'),
                                    string(defaultValue: 'None',
                                            description: 'Test Info file',
                                            name: 'Test'),
                            ])

                    // Save to variables. Default to empty string if not found.
                    inputConfig = userInput.Config?:''
                    inputTest = userInput.Test?:''

                    // Echo to console
                    echo("IQA Sheet Path: ${inputConfig}")
                    echo("Test Info file path: ${inputTest}")

                    // Write to file
                    writeFile file: "inputData.txt", text: "Config=${inputConfig}\r\nTest=${inputTest}"

                    // Archive the file (or whatever you want to do with it)
                    archiveArtifacts 'inputData.txt'
                }
            }
        }
    }
}

ContentLicense: CC BY-SA 3.0


问:
Making a countDownTimer pause on button presses
I'm trying to make a basic app where I can press a button to start a countdown, and the text on that same button changes between "START", "PAUSE", or "RESUME" depending on which state the button was in when pressed. Currently the pressing the button does nothing and I'm not sure why.

The button starts out with the text "start"

This is the code for the button listener in onCreate()

None of the 'if' statements seem to ever be true, even though the starting text on the button is "start"

```<code>clockText = findViewById(R.id.timer);
final Button startButton = findViewById(R.id.timerBtn);
    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(clockText.getText().toString().toLowerCase().equals("resume")) {
                startTimer(milliLeft);
                clock.start();
                startButton.setText("resume");
            }
            else if(clockText.getText().toString().toLowerCase().equals("pause")){
                clock.cancel();
                clockText.setText(formatTime);
                startButton.setText("resume");
            }
            else if(clockText.getText().toString().toLowerCase().equals("start")){
                startTimer(30000);
                startButton.setText("pause");
                clock.start();
            }

        }
    });
</code>```

Here is the startTimer() method,

```<code>public int sec,min,fracSec;
public String formatTime;
public TextView clockText;
public CountDownTimer clock;
public long milliLeft;
public void startTimer(long time) {
    clock = new CountDownTimer(time, 100) {
        @Override
        public void onTick(long millisUntilFinished) {

                milliLeft = millisUntilFinished;
                min = (int) Math.floor(millisUntilFinished / 60000);
                sec = (int) (millisUntilFinished / 1000) % 60;
                fracSec = ((int) millisUntilFinished - sec * 1000) / 100;
                formatTime = min + ":" + sec + ":" + fracSec;
                clockText.setText(formatTime);

        }

        @Override
        public void onFinish() {
            clockText.setText("Finished");
        }
    };
}
</code>```

答:
The problem is because you are checking the text value of the wrong view. You are checking the text value of the clockText instead of the startButton, which is the view you are setting the text values of "resume", "pause","start" on. You need to change the code to:</p>

```<code>clockText = findViewById(R.id.timer);
final Button startButton = findViewById(R.id.timerBtn);
    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(startButton.getText().toString().toLowerCase().equals("resume")) {
                startTimer(milliLeft);
                clock.start();
                startButton.setText("resume");
            }
            else if(startButton.getText().toString().toLowerCase().equals("pause")){
                clock.cancel();
                clockText.setText(formatTime);
                startButton.setText("resume");
            }
            else if(startButton.getText().toString().toLowerCase().equals("start")){
                startTimer(30000);
                startButton.setText("pause");
                clock.start();
            }

        }
    });
</code>```

Body:
I'm trying to make a basic app where I can press a button to start a countdown, and the text on that same button changes between "START", "PAUSE", or "RESUME" depending on which state the button was in when pressed. Currently the pressing the button does nothing and I'm not sure why.

The button starts out with the text "start"

This is the code for the button listener in onCreate()

None of the 'if' statements seem to ever be true, even though the starting text on the button is "start"

clockText = findViewById(R.id.timer);
final Button startButton = findViewById(R.id.timerBtn);
    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(clockText.getText().toString().toLowerCase().equals("resume")) {
                startTimer(milliLeft);
                clock.start();
                startButton.setText("resume");
            }
            else if(clockText.getText().toString().toLowerCase().equals("pause")){
                clock.cancel();
                clockText.setText(formatTime);
                startButton.setText("resume");
            }
            else if(clockText.getText().toString().toLowerCase().equals("start")){
                startTimer(30000);
                startButton.setText("pause");
                clock.start();
            }

        }
    });

Here is the startTimer() method,

public int sec,min,fracSec;
public String formatTime;
public TextView clockText;
public CountDownTimer clock;
public long milliLeft;
public void startTimer(long time) {
    clock = new CountDownTimer(time, 100) {
        @Override
        public void onTick(long millisUntilFinished) {

                milliLeft = millisUntilFinished;
                min = (int) Math.floor(millisUntilFinished / 60000);
                sec = (int) (millisUntilFinished / 1000) % 60;
                fracSec = ((int) millisUntilFinished - sec * 1000) / 100;
                formatTime = min + ":" + sec + ":" + fracSec;
                clockText.setText(formatTime);

        }

        @Override
        public void onFinish() {
            clockText.setText("Finished");
        }
    };
}

Body:
The problem is because you are checking the text value of the wrong view. You are checking the text value of the clockText instead of the startButton, which is the view you are setting the text values of "resume", "pause","start" on. You need to change the code to:

clockText = findViewById(R.id.timer);
final Button startButton = findViewById(R.id.timerBtn);
    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(startButton.getText().toString().toLowerCase().equals("resume")) {
                startTimer(milliLeft);
                clock.start();
                startButton.setText("resume");
            }
            else if(startButton.getText().toString().toLowerCase().equals("pause")){
                clock.cancel();
                clockText.setText(formatTime);
                startButton.setText("resume");
            }
            else if(startButton.getText().toString().toLowerCase().equals("start")){
                startTimer(30000);
                startButton.setText("pause");
                clock.start();
            }

        }
    });


问:
Using event.client (x and y) to use for mouse coordinates to spawn a shape in HTML/JS
So I am trying to make a program where I click on the canvas it creates a shape in the position that I click. I am having trouble grabbing the mouse x and y coordinates and using for the x and y coordinates of my shape when I click

My HTML code:

```<code><!doctype html>
<html lang="en">
<canvas id = "drawBoard" height = '600' width = '1330' style="border:1px solid black";></canvas>
<head>
    <div id = "js">
    <script src = "functions.js"></script>
    </div>
    <div id = "css">
   <link rel = stylesheet type = "text/css" href = "main.css">
    </div>
  <meta charset="utf-8">
  <title> Shape Drawer </title>

  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

</head>
<body>

<div id="log"></div>

<script id = "jquery">
$( document ).on( "mousemove", function( event ) {
  $( "#log" ).text( "Coordinates: " + event.pageX + " , " + event.pageY );
});

    </script>
 <button id = "circle" onclick = "circleTrue()"> Circle </button>
 <button id = "square" onclick = "squareTrue()"> Square </button>
 <button id = "triangle" onclick = "triangleTrue()"> Triangle </button>
</body>
</html>
</code>```

My JavaScript Code:

```<code>var shape;
var circle = false;
var square = true;
var triangle = false;

function getCoord(event){
var x = event.clientX;
var y = event.clientY;
}

document.getElementById("drawBoard");

document.getElementById('drawBoard').onclick = function() {clickSpawn()};

function clickSpawn{
  fillRect(x, y, 50, 50 );
  fillStyle = "black";
}

function circleTrue() {
    circle = true;
    square = false;
    triangle = false;
}

function squareTrue() {
    circle = false;
    square = true;
    triangle = false;
}

function triangleTrue() {
    circle = false;
    square = false;
    triangle = true;
}
</code>```

I am trying to figure out if it is possible to use my mouse x and y coordinates for a spawn location for my shape. Any help would be appreciated. Thanks.

答:
Try the demo I made below :

```<code><!DOCTYPE html>
<html>
<body>

  <canvas id="canvas" width="500" height="500" onmousedown="draw(event)" style="border:1px solid black;">Your browser does not support HTML 5.</canvas>

  <script>

    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    var width = 100;
    var height = 100;

    function draw(event){
      var mousex = event.clientX;
      var mousey = event.clientY;
      ctx.fillRect(mousex - (width / 2), mousey - (height / 2), width, height);
    }

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

The program above gets your mouse x and the mouse y when you click the canvas. Then it makes a rectangle of the specified width and height and places the center of the rectangle on your mouse pointer.

Body:
So I am trying to make a program where I click on the canvas it creates a shape in the position that I click. I am having trouble grabbing the mouse x and y coordinates and using for the x and y coordinates of my shape when I click

My HTML code:

<!doctype html>

<canvas id = "drawBoard" height = '600' width = '1330' style="border:1px solid black";></canvas>

   <link rel = stylesheet type = "text/css" href = "main.css">

  <meta charset="utf-8">
  <title> Shape Drawer </title>

 <button id = "circle" onclick = "circleTrue()"> Circle </button>
 <button id = "square" onclick = "squareTrue()"> Square </button>
 <button id = "triangle" onclick = "triangleTrue()"> Triangle </button>

My JavaScript Code:

var shape;
var circle = false;
var square = true;
var triangle = false;

function getCoord(event){
var x = event.clientX;
var y = event.clientY;
}

document.getElementById("drawBoard");

document.getElementById('drawBoard').onclick = function() {clickSpawn()};

function clickSpawn{
  fillRect(x, y, 50, 50 );
  fillStyle = "black";
}

function circleTrue() {
    circle = true;
    square = false;
    triangle = false;
}

function squareTrue() {
    circle = false;
    square = true;
    triangle = false;
}

function triangleTrue() {
    circle = false;
    square = false;
    triangle = true;
}

I am trying to figure out if it is possible to use my mouse x and y coordinates for a spawn location for my shape. Any help would be appreciated. Thanks.

Body:
Try the demo I made below :

<!DOCTYPE html>
<html>
<body>

  <canvas id="canvas" width="500" height="500" onmousedown="draw(event)" style="border:1px solid black;">Your browser does not support HTML 5.</canvas>

  <script>

    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    var width = 100;
    var height = 100;

    function draw(event){
      var mousex = event.clientX;
      var mousey = event.clientY;
      ctx.fillRect(mousex - (width / 2), mousey - (height / 2), width, height);
    }

  </script>
</body>
</html>

The program above gets your mouse x and the mouse y when you click the canvas. Then it makes a rectangle of the specified width and height and places the center of the rectangle on your mouse pointer.


问:
How and When to use subscribe?
Im very new to typescript.
I'm trying to understand the Observables but I'm kinda lost here.
The function below searches for videos on Youtube API v3.
Is it a good approach?
Is subscribing inside a function which will be called many times a good idea?
This function is called whenever user types something.

Should I have an unsubscribe somewhere?

```<code>searchVideos(searchbar: any): void{
  const typedValue: string = searchbar.srcElement.value;

   if(typedValue.length > 2){
     this.videosList = this.youtubeProvider.searchVideos(typedValue);
     this.videosList.subscribe(data => {
       if( data.length == 0  ){
         this.notFoundAnyVideo = true;
       }else{
         this.notFoundAnyVideo = false;
       }
     })
   }
}
</code>```

答:
I suppose you could use RxJS all the way through, cause its reactive paradigm lends itself very well for search components. Take a look at the code below, I implemented variations of it in few applications.</p>

```<code>import {Component, ViewChild, ElementRef} from "@angular/core";

@Component({
      selector: 'search',
      styleUrls: ['./search.component.scss'],
      template: `
        <form #searchBoxEl action="" class="search-form" [formGroup]="form">
          <fieldset>
            <input #searchBoxEl type="text" placeholder='Search for Youtube videos'
            autocomplete="off" />

            <nwum-list (itemSelected)="onItemSelect($event)"></nwum-list>

          </fieldset>
        </form>
      `,
      changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class SearchComponent implements OnInit {
        @ViewChild('searchBoxEl') searchBoxEl: ElementRef;
        componentDestroyed$: Subject<void> = new Subject<void>();
        videosList: Video[];

      constructor(public videoService: VideoService){}

        ngOnInit(){
          subscribeToSearchQueryChanges();
        }

        subscribeToSearchQueryChanges(){
            const minNumOfChars = 2;

            Observable.fromEvent(this.searchBoxEl.nativeElement, 'keyup')
                .debounceTime(300)
                .pluck('target', 'value')
                .map(value => value.trim())
                // .map(() => this.searchBoxEl.nativeElement.value.trim())
                .filter(value => value.length >= minNumOfChars)
                .takeUntil(this.componentDestroyed$)
                .switchMap(value => this.videoService.fetchVideos(value))
                .subscribe((videos: Video[]) => {
                    //show videos, etc
                    this.videosList = this.videoService.groupSuggestions(suggestions);
                }, err => {
                    console.error('failed fetching videos', err);
                    this.removeAllSubscriptions();
                    this.subscribeToSearchQueryChanges();
                });

            this.addSubscription(sub);
        }

        ngOnDestroy() {
          this.removeAllSubscriptions();
        }

        removeAllSubscriptions(){
            this.componentDestroyed$.next();
            this.componentDestroyed$.complete();
        }
    }
</code>```

Title: How and When to use subscribe?

Body:
Im very new to typescript.
I'm trying to understand the Observables but I'm kinda lost here.
The function below searches for videos on Youtube API v3.
Is it a good approach?
Is subscribing inside a function which will be called many times a good idea?
This function is called whenever user types something.

Should I have an unsubscribe somewhere?

searchVideos(searchbar: any): void{
  const typedValue: string = searchbar.srcElement.value;

   if(typedValue.length > 2){
     this.videosList = this.youtubeProvider.searchVideos(typedValue);
     this.videosList.subscribe(data => {
       if( data.length == 0  ){
         this.notFoundAnyVideo = true;
       }else{
         this.notFoundAnyVideo = false;
       }
     })
   }
}

Body:
I suppose you could use RxJS all the way through, cause its reactive paradigm lends itself very well for search components. Take a look at the code below, I implemented variations of it in few applications.

import {Component, ViewChild, ElementRef} from "@angular/core";

@Component({
      selector: 'search',
      styleUrls: ['./search.component.scss'],
      template: `
        <form #searchBoxEl action="" class="search-form" [formGroup]="form">
          <fieldset>
            <input #searchBoxEl type="text" placeholder='Search for Youtube videos'
            autocomplete="off" />

            <nwum-list (itemSelected)="onItemSelect($event)"></nwum-list>

          </fieldset>
        </form>
      `,
      changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class SearchComponent implements OnInit {
        @ViewChild('searchBoxEl') searchBoxEl: ElementRef;
        componentDestroyed$: Subject<void> = new Subject<void>();
        videosList: Video[];

      constructor(public videoService: VideoService){}

        ngOnInit(){
          subscribeToSearchQueryChanges();
        }

        subscribeToSearchQueryChanges(){
            const minNumOfChars = 2;

            Observable.fromEvent(this.searchBoxEl.nativeElement, 'keyup')
                .debounceTime(300)
                .pluck('target', 'value')
                .map(value => value.trim())
                // .map(() => this.searchBoxEl.nativeElement.value.trim())
                .filter(value => value.length >= minNumOfChars)
                .takeUntil(this.componentDestroyed$)
                .switchMap(value => this.videoService.fetchVideos(value))
                .subscribe((videos: Video[]) => {
                    //show videos, etc
                    this.videosList = this.videoService.groupSuggestions(suggestions);
                }, err => {
                    console.error('failed fetching videos', err);
                    this.removeAllSubscriptions();
                    this.subscribeToSearchQueryChanges();
                });

            this.addSubscription(sub);
        }

        ngOnDestroy() {
          this.removeAllSubscriptions();
        }

        removeAllSubscriptions(){
            this.componentDestroyed$.next();
            this.componentDestroyed$.complete();
        }
    }


问:
How can I set different font size between letter and number in UILabel
I want to make the letter font size bigger and number font size smaller in UILabel's text. How can I do?

I tried to use NSAttributedString, but it seems to receive a confirmed range to change. This can not meet my needs。

Thanks a lot

答: In that case you could use a regular expression to get ranges of numbers to retrieve their ranges and set their attributes accordingly.</p>


问:
Mock Notification Api
I have this code:

```<code>const browserNotification = new Notification(title, options);

browserNotification.onshow = () => this.props.sendTracking('in-app-chat-notification-start');

browserNotification.onclick = event => {
  const notification = event.target;

  this.props.router.push(notification.data.url.split('.com')[1]);
  this.props.sendTracking('in-app-chat-notification-complete');

  notification.close();
};
</code>```

I'm trying to mock window Notification because I need to call these two methods (onshow and onclick):

```<code>it('should call onshow method', () => {
  window.Notification = () => ({
    onshow: jest.fn(),
    onclick: jest.fn()
  });
  const instance = shallow(<MyComponent />).instance();

  instance.myMethod();

  //window.Notification.onShow();

  expect(sendTracking).toHaveBeenCalledTimes(1);
});
</code>```

I know that if I do that, I'm losing the original method but, since tests does not have window and Notification, I have to mock it.

How can do it properly with Jest in order to pass this code?

I have tried also mocking with global, but at the end, is the same as window.

The coverage:

Thanks

答:
Finally I suceded to test those two methods by splitting the code that I showed in my question.

This is it:

```<code>handleNewFirebaseNotification = notification => {
  const title = notification.data.title || 'letgo';
  const options = {
    body: notification.data.body,
    icon: notification.data.icon || 'https://static.letgo.com/site-images/logo_letgo_share_fb.jpg',
    data: {
      url: notification.data.url
    }
  };

  this.handleNotifications(title, options);
};

handleNotifications = (title, options) => {
  const browserNotification = new Notification(title, options);

  browserNotification.onshow = this.onShowNotification;
  browserNotification.onClick = this.onClickNotification;
}

onShowNotification = () => {
  this.props.sendTracking('in-app-chat-notification-start')
}

onClickNotification = event => {
  const notification = event.target;

  this.props.router.push(notification.data.url.split('.com')[1]);
  this.props.sendTracking('in-app-chat-notification-complete');

  notification.close();
}
</code>```

And then I can test with enzyme all this new methods. For example:

```<code>it('should call handleNewFirebaseNotification and then call handleNotifications with title and icon', () => {
  window.Notification = () => ({
    onshow: jest.fn(),
    onclick: jest.fn()
  });
  const instance = shallow(mockComponent()).instance();
  const notificationMock = {
    data: {
      title: 'test',
      body: 'test',
      icon: 'test',
      url: 'test'
    }
  };

  instance.handleNewFirebaseNotification(notificationMock);

  expect(window.Notification()).toEqual(expect.objectContaining({
    onshow: expect.any(Function),
    onclick: expect.any(Function)
  }));
});
</code>```

And one of the new methods:

```<code>it('should call onShowNotification', () => {
  const instance = shallow(mockComponent()).instance();

  instance.onShowNotification();

  expect(sendTrackingSpy).toHaveBeenCalledTimes(1);
});
</code>```

Title: Mock Notification Api

Body:
I have this code:

const browserNotification = new Notification(title, options);

browserNotification.onshow = () => this.props.sendTracking('in-app-chat-notification-start');

browserNotification.onclick = event => {
  const notification = event.target;

  this.props.router.push(notification.data.url.split('.com')[1]);
  this.props.sendTracking('in-app-chat-notification-complete');

  notification.close();
};

I'm trying to mock window Notification because I need to call these two methods (onshow and onclick):

it('should call onshow method', () => {
  window.Notification = () => ({
    onshow: jest.fn(),
    onclick: jest.fn()
  });
  const instance = shallow(<MyComponent />).instance();

  instance.myMethod();

  //window.Notification.onShow();

  expect(sendTracking).toHaveBeenCalledTimes(1);
});

I know that if I do that, I'm losing the original method but, since tests does not have window and Notification, I have to mock it.

How can do it properly with Jest in order to pass this code?

I have tried also mocking with global, but at the end, is the same as window.

The coverage:

Thanks

Body:
Finally I suceded to test those two methods by splitting the code that I showed in my question.

This is it:

handleNewFirebaseNotification = notification => {
  const title = notification.data.title || 'letgo';
  const options = {
    body: notification.data.body,
    icon: notification.data.icon || 'https://static.letgo.com/site-images/logo_letgo_share_fb.jpg',
    data: {
      url: notification.data.url
    }
  };

  this.handleNotifications(title, options);
};

handleNotifications = (title, options) => {
  const browserNotification = new Notification(title, options);

  browserNotification.onshow = this.onShowNotification;
  browserNotification.onClick = this.onClickNotification;
}

onShowNotification = () => {
  this.props.sendTracking('in-app-chat-notification-start')
}

onClickNotification = event => {
  const notification = event.target;

  this.props.router.push(notification.data.url.split('.com')[1]);
  this.props.sendTracking('in-app-chat-notification-complete');

  notification.close();
}

And then I can test with enzyme all this new methods. For example:

it('should call handleNewFirebaseNotification and then call handleNotifications with title and icon', () => {
  window.Notification = () => ({
    onshow: jest.fn(),
    onclick: jest.fn()
  });
  const instance = shallow(mockComponent()).instance();
  const notificationMock = {
    data: {
      title: 'test',
      body: 'test',
      icon: 'test',
      url: 'test'
    }
  };

  instance.handleNewFirebaseNotification(notificationMock);

  expect(window.Notification()).toEqual(expect.objectContaining({
    onshow: expect.any(Function),
    onclick: expect.any(Function)
  }));
});

And one of the new methods:

it('should call onShowNotification', () => {
  const instance = shallow(mockComponent()).instance();

  instance.onShowNotification();

  expect(sendTrackingSpy).toHaveBeenCalledTimes(1);
});


问:
Using interval in PostgreSQL with Ruby on Rails
I want to save durations (2 days, 5 years, ...) as intervals in PostgreSQL from my Rails application.

Both duration_min and duration_max are values like "2 days" or "5 years", so each of them is an interval by itself:

```<code>  def change
    create_table :times do |t|
      t.interval  :duration_min
      t.interval  :duration_max
      t.timestamps
    end
  end
</code>```

but the DB migration fails when setting the data type to "interval" and rake returns:

```<code>undefined method 'interval' for #<ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition:0x007f8615694360>
</code>```

How do I define the table for it to accept (and understand) an input like "2 days"?

答:
We have an implementation of interval for Rails 5.1 that you can try.

https://gist.github.com/vollnhals/a7d2ce1c077ae2289056afdf7bba094a

Body:
I want to save durations (2 days, 5 years, ...) as intervals in PostgreSQL from my Rails application.

Both duration_min and duration_max are values like "2 days" or "5 years", so each of them is an interval by itself:

  def change
    create_table :times do |t|
      t.interval  :duration_min
      t.interval  :duration_max
      t.timestamps
    end
  end

but the DB migration fails when setting the data type to "interval" and rake returns:

undefined method 'interval' for #<ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition:0x007f8615694360>

How do I define the table for it to accept (and understand) an input like "2 days"?


问:
Are there MapReduce implementations on GPUs (CUDA)?
So far, I'm aware of the Mars, though what about alternatives?</p>

答:
Years ago I have implemented cumar.

As I was using Mac OS X and 'nvcc' compiler was not happy with Apple's 'clang', I designed this library pure C++ ( and a flavor of lambda ).

A typical map operation looks like this:

```<code>//A = B + C, all of length 'n'
cumar::map()("[](double a&, double b, double c){ a = b+c; }" )(A, A+n, B, C);
</code>```

For reduce operation, it looks like this:

```<code>// x = min(A), A of size 'n'
cumar::reduce()( "[](double a, double b){ return a < b ? a : b; }" )(A, A+n);
</code>```

Body:
Years ago I have implemented cumar.

As I was using Mac OS X and 'nvcc' compiler was not happy with Apple's 'clang', I designed this library pure C++ ( and a flavor of lambda ).

A typical map operation looks like this:

//A = B + C, all of length 'n'
cumar::map()("[](double a&, double b, double c){ a = b+c; }" )(A, A+n, B, C);

For reduce operation, it looks like this:

// x = min(A), A of size 'n'
cumar::reduce()( "[](double a, double b){ return a < b ? a : b; }" )(A, A+n);


问:
How can this way exclusion of files be achieved in PowerShell?
I have a PowerShell script on a production server to show me the list of database backup files that are older than 30 days.

I need to see only the files that have the extension of ".bak". However, in my script there is no matching syntax or regular expression, so I am also getting to see a list of files which have an extension like "filename.foo.bak". These files may be text files or other configuration files on the server for which backups have been taken automatically by the program that uses these files.

How do I enable a match filter so that I see only "*.bak" and not other files as mentioned above?

As mentioned by mjolinor, I have used this script to do the exclusion.

```<code>gci $paths -recurse -filter *.bak -exclude *.*.bak | ?{!$_.psiscontainer}
</code>```

However, I have learnt that I need to exclude some system folders such as C:\Windows.
How can this be accomplished as well?

答:
Try this:

```<code>gci *.bak -exclude *.*.bak
</code>```

I tried to reply to your comment, but the code doesn't show up right.  -exclude takes a string[] argument, so:

```<code>gci -recurse -filter *.bak -exclude *.*.bak,windows |? {!$_.psiscontainer}
</code>```

Body:
I have a PowerShell script on a production server to show me the list of database backup files that are older than 30 days.

I need to see only the files that have the extension of ".bak". However, in my script there is no matching syntax or regular expression, so I am also getting to see a list of files which have an extension like "filename.foo.bak". These files may be text files or other configuration files on the server for which backups have been taken automatically by the program that uses these files.

How do I enable a match filter so that I see only "*.bak" and not other files as mentioned above?

As mentioned by mjolinor, I have used this script to do the exclusion.

gci $paths -recurse -filter *.bak -exclude *.*.bak | ?{!$_.psiscontainer}

However, I have learnt that I need to exclude some system folders such as C:\Windows.
How can this be accomplished as well?

Body:
Try this:

gci *.bak -exclude *.*.bak

I tried to reply to your comment, but the code doesn't show up right.  -exclude takes a string[] argument, so:

gci -recurse -filter *.bak -exclude *.*.bak,windows |? {!$_.psiscontainer}

ContentLicense: CC BY-SA 2.5


问:
How do I get the border the move up and down when "Up" and "Down" button is clicked?
I would just like the border to move up and down when I click the up or down button.

$(document).ready(function() {
  $("#up").click(function() {
    $("#up").prev().css("border", "2px solid blue");
  });
});

$(document).ready(function() {
  $("#down").click(function() {
    $("p").next().css("border", "2px solid blue");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">paragraph 1</p>
<p id="two">paragraph 2</p>
<p id="three">paragraph 3</p>
<p id="four">paragraph 4</p>

<button id="up">Up</button>
<button id="down">Down</button></code>```

How can I achieve this using jQuery?

答:
You can try something like this:

$(document).ready(function() {
  $("#up").click(function() {
    if ($("p.with-border").prev("p").length > 0) { // is there prev paragraph?
      $("p.with-border").prev("p").addClass("with-border");
      $("p.with-border").last().removeClass("with-border");
    }
  });
  $("#down").click(function() {
    if ($("p.with-border").next("p").length > 0) { // is there next paragraph?
      $("p.with-border").next("p").addClass("with-border");
      $("p.with-border").first().removeClass("with-border");
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.with-border {
  border: 2px solid blue;
}</code>```

paragraph 1

paragraph 2

paragraph 3

paragraph 4

<button id="up">Up</button>
<button id="down">Down</button>```

Body:
I would just like the border to move up and down when I click the up or down button.

$(document).ready(function() {
  $("#up").click(function() {
    $("#up").prev().css("border", "2px solid blue");
  });
});

$(document).ready(function() {
  $("#down").click(function() {
    $("p").next().css("border", "2px solid blue");
  });
});

paragraph 1

paragraph 2

paragraph 3

paragraph 4

<button id="up">Up</button>
<button id="down">Down</button>

How can I achieve this using jQuery?

Body:
You can try something like this:

$(document).ready(function() {
  $("#up").click(function() {
    if ($("p.with-border").prev("p").length > 0) { // is there prev paragraph?
      $("p.with-border").prev("p").addClass("with-border");
      $("p.with-border").last().removeClass("with-border");
    }
  });
  $("#down").click(function() {
    if ($("p.with-border").next("p").length > 0) { // is there next paragraph?
      $("p.with-border").next("p").addClass("with-border");
      $("p.with-border").first().removeClass("with-border");
    }
  });
});

.with-border {
  border: 2px solid blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">paragraph 1</p>
<p id="two">paragraph 2</p>
<p id="three">paragraph 3</p>
<p id="four" class="with-border">paragraph 4</p>

<button id="up">Up</button>
<button id="down">Down</button>


问:
Docker Terminal connection refused
I've also asked this question over at the Docker boards but got no response there. If someone knows a solution for the issue it might be helpful to post the answer in the Docker boards as well. Here is a link to the question.

My task is to create a Docker image from a Tomcat web app that I’ve developed. I’ve set up Docker on my Windows 7 machine and I think I got it almost working. After several configuration attempts, I managed to get a connection to the docker repository. To get that working I had add the proxy server which I extracted from the PAC file (more on that later) to the config.json file:

My understanding is that for creating an image from my web app I need to use the Docker terminal to access the default VM hosts file system to get the packaged war file and the Dockerfile to create an image. For that the terminal sends an HTTP Post request to the Docker default VM that then creates the Docker image.

Here is where I get an error message. Apparently when firing the HTTP request to the IP of the default VM (168.192.99.100) the Docker terminal sends it in a way that routes the request over the corporate proxy resulting in an error:

I thought I would have this issue covered since I added the default VMs IP address to the NP_PROXY variable in the config.json file. This doesn’t seem to have the desired effect. If I use curl to do an HTTP Get to the default VM I get the same connection error that I get when I browse the Internet and encounter a site that is blocked by the firewall.

As a related note, I also have the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables set directly in Windows.

I’ve talked to one of our network guys who told me that the NO_PROXY variable has no influence on the HTTP requests because the corporate network uses a PAC file for the proxy configuration. Apparently the Docker terminal uses the proxy configuration from the PAC file to route its requests thus the NO_PROXY settings have not effect on the requests.

His advise would be to find a way to start the Docker terminal without the proxy configuration. I’ve looked at the start.sh script that is responsible for starting the Docker terminal and tried to determine how to achieve this but had no success.

Has anyone encountered this situation before and knows hot to resolve the issue?

Any help is appreciated.

答:
After tinkering around with some settings I found a workaround for this problem that might be helpful to other.

Apparently the Docker quickstart terminal ignores the NO_PROXY environment variable. As soon as I removed the HTTP_PROXY and HTTPS_PROXY environment variables the terminal worked as expected.

Title: Docker Terminal connection refused


问:
Javascript Modular Arithmetic
Javascript evaluates the following code snippet to -1.

```
-5 % 4
```

I understand that the remainder theorem states a = bq + r such that 0 ≤ r < b.
Given the definition above should the answer not be 3? Why does JavaScript return -1?

答:
Most programming languages use a symmetric modulo which is different than the mathematical one for negative values.

The mathematical modulo can be computed using the symmetric modulo like this:

```<code>a mod b = ((a % b) + b) % b
</code>```

mod mathematical modulo

% symmetric modulo

Title: Javascript Modular Arithmetic

Body:
Javascript evaluates the following code snippet to -1.

-5 % 4

I understand that the remainder theorem states a = bq + r such that 0 ≤ r < b.
Given the definition above should the answer not be 3? Why does JavaScript return -1?

Body:
Most programming languages use a symmetric modulo which is different than the mathematical one for negative values.

The mathematical modulo can be computed using the symmetric modulo like this:

a mod b = ((a % b) + b) % b

mod mathematical modulo

% symmetric modulo


问:
How do I limit the number of rows in a datatable?
I generate a DataTable (from non-SQL data) and then use a DataView to filter the records.

I want to limit the number of records in the final record set but can't do this when I generate the DataTable.

I've resorted to deleting rows from the final result set, as per:

```<code>                DataView dataView = new DataView(dataTable);
                dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
                dataView.Sort = "EventDate";
                dataTable = dataView.ToTable();

                 while (dataTable.Rows.Count > _rowLimit)
                    dataTable.Rows[dataTable.Rows.Count - 1].Delete();

                 return dataTable;
</code>```

Is there a more efficient way to limit the results?

答:
You can use Linq:

Try changing your code to the following:

```<code>DataView dataView = new DataView(dataTable);
dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
dataView.Sort = "EventDate";
dataTable = dataView.ToTable();
while (dataTable.Rows.Count > _rowLimit)
{
    dataTable = dataTable.AsEnumerable().Skip(0).Take(50).CopyToDataTable();
}
return dataTable;
</code>```

You'll need namespace: System.Linq and System.Data

Body:
I generate a DataTable (from non-SQL data) and then use a DataView to filter the records.

I want to limit the number of records in the final record set but can't do this when I generate the DataTable.

I've resorted to deleting rows from the final result set, as per:

                DataView dataView = new DataView(dataTable);
                dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
                dataView.Sort = "EventDate";
                dataTable = dataView.ToTable();

                 while (dataTable.Rows.Count > _rowLimit)
                    dataTable.Rows[dataTable.Rows.Count - 1].Delete();

                 return dataTable;

Is there a more efficient way to limit the results?

Body:
You can use Linq:

Try changing your code to the following:

DataView dataView = new DataView(dataTable);
dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
dataView.Sort = "EventDate";
dataTable = dataView.ToTable();
while (dataTable.Rows.Count > _rowLimit)
{
    dataTable = dataTable.AsEnumerable().Skip(0).Take(50).CopyToDataTable();
}
return dataTable;

You'll need namespace: System.Linq and System.Data


问:
Bash - heredoc with variable expansion, preserving newlines
I am trying to generate the mail text for the send mail client ssmtp within a bash script (instead of putting it in a file).

Using heredocs I came up with this:

```<code>MAILTO=me@mydomain.com
FROM=admin@mydomain.com
SUBJ="$HOSTNAME: Daemon not running"

read -d '' msg <<EOF
    To: $MAILTO
    From: $FROM
    Subject: $SUBJ

    Please check $HOSTNAME.
    Daemon has stopped running.

    -Admin
EOF

echo $msg | ssmtp $MAILTO
</code>```

(This does not work. ssmtp does not send the mail, because the text does not preserve the newlines.)

If I echo $msg, then I see that the newlines in the heredoc are not preserved. How can I accomplish that?

Also: Where is the difference btw this

```<code>{
  echo "To: $MAILTO"
  echo "From: $FROM"
  echo "Subject: $SUBJ"
  echo
  echo "Please check $HOSTNAME"
} | ssmtp $MAILTO
</code>```

and the first example? Are all echo commands executed and the result piped to ssmtp? Isn't this working in my first example? Can't I echo a text and pipe echo's output to a command?

答:
Your second example uses Command Grouping. So your assumption, that all echo commands are executed and piped to ssmtp is correct.

From the manual:

Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created.

Regarding your first example. This is not the heredoc's fault. Try to enclose msg in quotes:

```<code>echo "$msg" | ssmtp "$MAILTO"
</code>```

Body:
I am trying to generate the mail text for the send mail client ssmtp within a bash script (instead of putting it in a file).

Using heredocs I came up with this:

MAILTO=me@mydomain.com
FROM=admin@mydomain.com
SUBJ="$HOSTNAME: Daemon not running"

read -d '' msg <<EOF
    To: $MAILTO
    From: $FROM
    Subject: $SUBJ

    Please check $HOSTNAME.
    Daemon has stopped running.

    -Admin
EOF

echo $msg | ssmtp $MAILTO

(This does not work. ssmtp does not send the mail, because the text does not preserve the newlines.)

If I echo $msg, then I see that the newlines in the heredoc are not preserved. How can I accomplish that?

Also: Where is the difference btw this

{
  echo "To: $MAILTO"
  echo "From: $FROM"
  echo "Subject: $SUBJ"
  echo
  echo "Please check $HOSTNAME"
} | ssmtp $MAILTO

and the first example? Are all echo commands executed and the result piped to ssmtp? Isn't this working in my first example? Can't I echo a text and pipe echo's output to a command?

Body:
Your second example uses Command Grouping. So your assumption, that all echo commands are executed and piped to ssmtp is correct.

From the manual:

Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created.

Regarding your first example. This is not the heredoc's fault. Try to enclose msg in quotes:

echo "$msg" | ssmtp "$MAILTO"


问:
Print whole result in interactive Scala console
When I type something into the Scala interactive console, the console prints the result of the statement.  If the result is too long, the console crops it (scroll right to see it):

```<code>scala> Array.fill[Byte](5)(0)
res1: Array[Byte] = Array(0, 0, 0, 0, 0)

scala> Array.fill[Byte](500)(0)
res2: Array[Byte] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...

scala> "a"*5000
res3: String = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
</code>```

How can I print the same or equivalent output, for any given object (not just a collection or array) without the cropping occurring?

答:
try this </p>

```<code>scala> :power
Power mode enabled. :phase is at typer.
import scala.tools.nsc._, intp.global._, definitions._
Try :help or completions for vals._ and power._

scala> vals.isettings.maxPrintString
res9: Int = 800

scala> vals.isettings.maxPrintString = 10000
vals.isettings.maxPrintString: Int = 10000
</code>```

Body:
When I type something into the Scala interactive console, the console prints the result of the statement.  If the result is too long, the console crops it (scroll right to see it):

scala> Array.fill[Byte](5)(0)
res1: Array[Byte] = Array(0, 0, 0, 0, 0)

scala> Array.fill[Byte](500)(0)
res2: Array[Byte] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...

scala> "a"*5000
res3: String = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...

How can I print the same or equivalent output, for any given object (not just a collection or array) without the cropping occurring?

Body:
try this

scala> :power
Power mode enabled. :phase is at typer.
import scala.tools.nsc._, intp.global._, definitions._
Try :help or completions for vals._ and power._

scala> vals.isettings.maxPrintString
res9: Int = 800

scala> vals.isettings.maxPrintString = 10000
vals.isettings.maxPrintString: Int = 10000


问:
unexpected token '=' on array initialization
I'm attempting to create a new array var class = [] based off an array of arrays and comparing the indices within those. when i run the test it's telling me that the = in the var class = [] is a syntax error. Not sure exactly what i'm doing wrong.

function list(names) {
  var class = [];
  var array = names.map(function(obj) {
    for (var i = 0; i < obj.length; i++) {
      if (obj[0] > 55 && obj[1] > 7) {
        class.push("Name1")
      } else {
        class.push("Name2")
      }
      return class;
    }
  });
};
console.log(
list([
[18, 20],
[45, 2],
[61, 12],
[37, 6],
[21, 21],
[78, 9]
])
)```

答: class is a reserved word in javascript.  Change it to something else, you should be good.


问:
Glassfish cannot find imported class
I have a small webservice program in which I need to import JSONObject from external jar. While trying to deploy the webservice, the Glassfish couldn't find the imported class (from external jar), but things look fine in IDE.

I tried to look into the log and found this :

[2017-11-17T16:22:49.429+0100] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=30 _ThreadName=http-listener-1(1)] [timeMillis: 1510932169429] [levelValue: 900] [[
    StandardWrapperValve[MyApplication]: Servlet.service() for servlet MyApplication threw exception
  java.lang.ClassNotFoundException: org.json.simple.JSONObject

Can someone help me ?

答:
You have to add the library to your Glassfish directory too. Otherwise Glassfish will not find it.

Add the .jar file to <GLASSFISH_DIR>\glassfish\domain\domain1\lib and then restart your Glassfish.

Title: Glassfish cannot find imported class


问:
Responsive Angled CSS Triangles with Percentages
So I've got an odd responsive design - I'm trying to recreate 2 triangles (white & pink) via CSS that overlay a photo without having to use an image. See photo:
Responsive/Percentage CSS triangles

So far, I've got a pretty good idea of how to create the white triangle that overlays the photo and blends in with the background.. but the pink triangle is where i'm stuck and not sure how to program it.

#triangleWrapper {
  background-color: red;
  height: 80px;
  position: relative;
  width: 100%;
}

.triangle {
  background: linear-gradient(to right bottom, white 50%, transparent 50%);
  height: 100%;
  left: 0px;
  top: 0px;
  transform: scaleY(-1);
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="triangleWrapper">
    <div class="triangle"></div>
</div></code>```

答:
You can use borders to create triangles. Border width is what you have to play with to make the size how you want it (I just went with full-screen width).

body {
  margin: 0;
  background: #333;
}

.overlay {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: calc(50vw/6) 50vw;
  border-color: rgba(237, 75, 98, 0.4) rgba(237, 75, 98, 0.4) #fff #ed4b62;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="overlay"></div></code>```

EDIT:

Here is a responsive example

body {
  margin: 0;
  background: #333;
}

.image-tri {
  position: relative;
}

.image-tri .overlay {
  position: absolute;
  top: 0;
  width: 0;
  height: 0;
  border-style: solid;
  border-color: rgba(237, 75, 98, 0.4) rgba(237, 75, 98, 0.4) #fff #ed4b62;
}

@media (min-width: 80px) {
  .image-tri .overlay {
    border-width: 12.5px 40px;
  }
  .image-tri img {
    width: 80px;
    height: 25px;
  }
}

@media (min-width: 320px) {
  .image-tri .overlay {
    border-width: 50px 160px;
  }
  .image-tri img {
    width: 320px;
    height: 100px;
  }
}

@media (min-width: 960px) {
  .image-tri .overlay {
    border-width: 150px 480px;
  }
  .image-tri img {
    width: 960px;
    height: 300px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-tri">
  <img src="http://fiatifta.org/wp-content/uploads/2016/01/rio-de-janeiro-banner.jpg">
  <div class="overlay"></div>
</div></code>```

Hope this helps.

Body:
You can use borders to create triangles. Border width is what you have to play with to make the size how you want it (I just went with full-screen width).

body {
  margin: 0;
  background: #333;
}

.overlay {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: calc(50vw/6) 50vw;
  border-color: rgba(237, 75, 98, 0.4) rgba(237, 75, 98, 0.4) #fff #ed4b62;
}

<div class="overlay"></div>

EDIT:

Here is a responsive example

body {
  margin: 0;
  background: #333;
}

.image-tri {
  position: relative;
}

.image-tri .overlay {
  position: absolute;
  top: 0;
  width: 0;
  height: 0;
  border-style: solid;
  border-color: rgba(237, 75, 98, 0.4) rgba(237, 75, 98, 0.4) #fff #ed4b62;
}

@media (min-width: 80px) {
  .image-tri .overlay {
    border-width: 12.5px 40px;
  }
  .image-tri img {
    width: 80px;
    height: 25px;
  }
}

@media (min-width: 320px) {
  .image-tri .overlay {
    border-width: 50px 160px;
  }
  .image-tri img {
    width: 320px;
    height: 100px;
  }
}

@media (min-width: 960px) {
  .image-tri .overlay {
    border-width: 150px 480px;
  }
  .image-tri img {
    width: 960px;
    height: 300px;
  }
}

<div class="image-tri">
  <img src="http://fiatifta.org/wp-content/uploads/2016/01/rio-de-janeiro-banner.jpg">
  <div class="overlay"></div>
</div>

Hope this helps.


问:
Microsoft Windows Python-3.6 PyCrypto installation error
pip install pycrypto works fine with python3.5.2 but fails with python3.6 with the following error:

inttypes.h(26): error C2061: syntax error: identifier 'intmax_t'

答: Use PyCryptodome instead of pycrypto. pycrypto is discontinued and is no longer actively supported. PyCryptodome exposes almost the same API as pycrypto (source).


答:
you can't use reserved words for variables..class is reserved here is the link for reserved words
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar

Title: unexpected token '=' on array initialization

Body:
I'm attempting to create a new array var class = [] based off an array of arrays and comparing the indices within those. when i run the test it's telling me that the = in the var class = [] is a syntax error. Not sure exactly what i'm doing wrong.

function list(names) {
  var class = [];
  var array = names.map(function(obj) {
    for (var i = 0; i < obj.length; i++) {
      if (obj[0] > 55 && obj[1] > 7) {
        class.push("Name1")
      } else {
        class.push("Name2")
      }
      return class;
    }
  });
};
console.log(
list([
[18, 20],
[45, 2],
[61, 12],
[37, 6],
[21, 21],
[78, 9]
])
)


问:
prevent system from getting locked
How can we prevent system from getting locked, There are group of systems in our office which needs to run 24/7 with getting locked, these are lab machines.

I do have admin rights but group policies apply preventing from changing registry and windows updates options

looking for a best and easy way for preventing system getting locked

答: Probably not the best solution but you can download software to fake mouse inputs to stop the computers falling asleep. I personaly use this one : https://mousejiggler.codeplex.com/</p>

Title: prevent system from getting locked


问:
I want to include a certain div from another url into my site
I have this

```<code><div>
  <object type="text/html" data="https://www.urlIWantTheDivFrom.com"
   width="800px" height="600px">
  </object>
/div>
</code>```

However this gives me the whole webpage. I want to copy a certain div. I also tried some js. However I cannot find out how to copy the exact div as well

```<code>document.getElementById("div").innerHTML='<object type="text/html" data="https://www.urlIWantTheDivFrom.com" ></object>';
</code>```

答:
Embedding another webpage content is not allowed by default, but here is a thing which you may try using jQuery ajax:

```<code>$.get('https://www.urlIWantTheDivFrom.com', function(pageText){
 // Appends to your div
 $('#myDiv').append(
   $(pageText) // parses returned html
     .find('#externalDiv') // gets it div
 );
})
</code>```

But remember that online content publisher still has rights over his content, also remember that some tags link may be broken after importing.

Body:
I have this

  <object type="text/html" data="https://www.urlIWantTheDivFrom.com"
   width="800px" height="600px">
  </object>
/div>

However this gives me the whole webpage. I want to copy a certain div. I also tried some js. However I cannot find out how to copy the exact div as well

document.getElementById("div").innerHTML='<object type="text/html" data="https://www.urlIWantTheDivFrom.com" ></object>';

Body:
Embedding another webpage content is not allowed by default, but here is a thing which you may try using jQuery ajax:

$.get('https://www.urlIWantTheDivFrom.com', function(pageText){
 // Appends to your div
 $('#myDiv').append(
   $(pageText) // parses returned html
     .find('#externalDiv') // gets it div
 );
})

But remember that online content publisher still has rights over his content, also remember that some tags link may be broken after importing.


问:
SQL - select muliple rows if search criteria matches one of the Values
Apologies if already asked but not too sure what to search for. I want to select muliple LocaleIds if search criterial matches one of the Values.

Currently I am doing simple search like this:

```<code>SELECT *
   FROM [dbo].[Localizations]
   WHERE Value like 'task switching' OR ResourceId like 'task switching'
   ORDER BY LocaleId, ResourceId
</code>```

This results in:

```<code>Id      ResourceId                      Value            LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching
</code>```

However this is missing the associated rows for the Other LocaleIds (English LocaleId is blank ' '). For example, I require:

```<code>Id      ResourceId                      Value                  LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching
42257   AssessmentType_Description_21   Aufgabenwechsel         de
42839   Attribute_Description_1         Aufgabenwechsel         de
42876   Attribute_Description_132       Aufgabenwechsel         de
45864   AssessmentType_Description_21   Changement de tâches    fr
46446   Attribute_Description_1         Changement de tâches    fr
46483   Attribute_Description_132       Changement de tâches    fr
</code>```

How can I get the full results set for all LocaleIds? Any help appreciated.

Edit:
Sorry I want all the records that match 'Task switching' and their corresponding values in other languages. Will only ever be searching in 1 language.

答:
I would recommend EXISTS here, instead of IN:

```<code>SELECT *
FROM dbo.Localizations loc
WHERE EXISTS
(SELECT 1
 FROM dbo.Localizations loc2
 WHERE value LIKE 'task switching'
 AND loc.resourceID = loc2.resourceid)
ORDER BY localeid, resourceid
</code>```

This way should run faster.

Body:
Apologies if already asked but not too sure what to search for. I want to select muliple LocaleIds if search criterial matches one of the Values.

Currently I am doing simple search like this:

SELECT *
   FROM [dbo].[Localizations]
   WHERE Value like 'task switching' OR ResourceId like 'task switching'
   ORDER BY LocaleId, ResourceId

This results in:

Id      ResourceId                      Value            LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching

However this is missing the associated rows for the Other LocaleIds (English LocaleId is blank ' '). For example, I require:

Id      ResourceId                      Value                  LocaleId
53591   AssessmentType_Description_21   Task Switching
53247   Attribute_Description_1         Task Switching
53378   Attribute_Description_132       Task Switching
42257   AssessmentType_Description_21   Aufgabenwechsel         de
42839   Attribute_Description_1         Aufgabenwechsel         de
42876   Attribute_Description_132       Aufgabenwechsel         de
45864   AssessmentType_Description_21   Changement de tâches    fr
46446   Attribute_Description_1         Changement de tâches    fr
46483   Attribute_Description_132       Changement de tâches    fr

How can I get the full results set for all LocaleIds? Any help appreciated.

Edit:
Sorry I want all the records that match 'Task switching' and their corresponding values in other languages. Will only ever be searching in 1 language.

Body:
I would recommend EXISTS here, instead of IN:

SELECT *
FROM dbo.Localizations loc
WHERE EXISTS
(SELECT 1
 FROM dbo.Localizations loc2
 WHERE value LIKE 'task switching'
 AND loc.resourceID = loc2.resourceid)
ORDER BY localeid, resourceid

This way should run faster.


问:
sed unix error: unterminated 's' command
Executing this command:

```<code>sed -e 's/á/\á/g' ./source_file > ./destiny_file
</code>```

Shows this error:

```<code>sed: -e expression #1, char 14: unterminated `s' command
</code>```

Sentence is a part of an .sh file.

I had tried on several shells: sh/bash/sch

And the result is the same.

答:
The solution was to codify "á" as "xE1":

```<code>sed -e 's/\xE1/\&#225\x3B/g'
</code>```

This works ok!

Body:
Executing this command:

sed -e 's/á/\á/g' ./source_file > ./destiny_file

Shows this error:

sed: -e expression #1, char 14: unterminated `s' command

Sentence is a part of an .sh file.

I had tried on several shells: sh/bash/sch

And the result is the same.

Body:
The solution was to codify "á" as "xE1":

sed -e 's/\xE1/\&#225\x3B/g'

This works ok!


问:
How to revoke Google API refresh token in Java?
I'm integrating Google Calendar in my Android application. I followed the example explained on http://code.google.com/apis/calendar/v3/using.html#client for authorizing and retreiving access token and refresh token. Everything works fine as everything is explained quite well in the documentation. However, I couldn't find an example code on how to programmatically revert the refresh token. Does anyone know how to revert the refresh token? I'm programming in Java. </p>

<p>-Ali</p>

答:
First, use the API to revoke the token, using the token itself.

```<code>String url = String.format(
    "https://accounts.google.com/o/oauth2/revoke?token=%s",token);

get(url, token);  // An example helper that adds the token to the request.
</code>```

Also, remove the token from the DataStore (or other storage mechanism) if the refresh token or access token was cached by your application.

```<code>dataStoreFactory.getDataStore<StoredCredential>("theUserId").clear();
</code>```

Body:
I'm integrating Google Calendar in my Android application. I followed the example explained on http://code.google.com/apis/calendar/v3/using.html#client for authorizing and retreiving access token and refresh token. Everything works fine as everything is explained quite well in the documentation. However, I couldn't find an example code on how to programmatically revert the refresh token. Does anyone know how to revert the refresh token? I'm programming in Java.

-Ali

Body:
First, use the API to revoke the token, using the token itself.

String url = String.format(
    "https://accounts.google.com/o/oauth2/revoke?token=%s",token);

get(url, token);  // An example helper that adds the token to the request.

Also, remove the token from the DataStore (or other storage mechanism) if the refresh token or access token was cached by your application.

dataStoreFactory.getDataStore<StoredCredential>("theUserId").clear();


问:
Xcode Debugger: view value of variable
My code in a UITableViewController:

```<code>delegate.myData = [myData objectAtIndex:indexPath.row];
</code>```

How can I see the values of delegate.myData or indexPath.row in the Debugger? delegate.myData should be an array and indexPath.row an int. I can only see memory addresses of the objects delegate and indexPath but where are myData and row?

答:
This gets a little complicated. These objects are custom classes or structs, and looking inside them is not as easy on Xcode as in other development environments.

If I were you, I'd NSLog the values you want to see, with some description.

i.e:

```<code>NSLog(@"Description of object & time: %i", indexPath.row);</code>```

Title: Xcode Debugger: view value of variable

Body:
My code in a UITableViewController:

delegate.myData = [myData objectAtIndex:indexPath.row];

How can I see the values of delegate.myData or indexPath.row in the Debugger? delegate.myData should be an array and indexPath.row an int. I can only see memory addresses of the objects delegate and indexPath but where are myData and row?

Body:
This gets a little complicated. These objects are custom classes or structs, and looking inside them is not as easy on Xcode as in other development environments.

If I were you, I'd NSLog the values you want to see, with some description.

i.e:

NSLog(@"Description of object & time: %i", indexPath.row);


问:
how to change joomla basic url update in joomla 3.6.4?
how to change joomla basic url update in joomla 3.6.4 ?

for example:
https://update.joomla.org/core/extensions/com_joomlaupdate.xml

change to:
http://update.myWeb.net/core/extensions/com_joomlaupdate.xml

image for this question

答:
You can change that thru your database:

In the table (dbprefix)_update_sites, the location url.


问:
Mysql - PDO Error - Invalid catalog name: 1046 No database selected
I have a problem with PDO, and I see absolutely no where he come. I can not question my MySQL database. Just to test I used the following code (having quite sour previously configured the parameters for the connection:

```<code>$dbh= new PDO('mysql:host=serverName;dbname=Mydatabase','user','password');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

var_dump($dbh);    // gives : object(PDO)#1 (0) { }

$res=$dbh->query('SELECT * FROM table');
</code>```

The connection is made correctly with MySQL but after query I get this error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in /home/outout/public_html/file.php:16 Stack trace: #0 /home/outout/public_html/file.php(16): PDO->query('select * from t...') #1 {main} thrown in /home/outout/public_html/file.php on line 16.

The code works on a local machine, but as soon as I put it online (cPanel) it shows me this error. Do I have to configure PDO in .htaccess?

I absolutely do not understand where the problem come. Someone would have an idea?

答:
Use

```<code>$database -> query(' SELECT * FROM "database_name"."table_name" ');
</code>```

instead of

```<code>$database -> query(' SELECT * FROM "table_name" ');
</code>```

Body:
I have a problem with PDO, and I see absolutely no where he come. I can not question my MySQL database. Just to test I used the following code (having quite sour previously configured the parameters for the connection:

$dbh= new PDO('mysql:host=serverName;dbname=Mydatabase','user','password');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

var_dump($dbh);    // gives : object(PDO)#1 (0) { }

$res=$dbh->query('SELECT * FROM table');

The connection is made correctly with MySQL but after query I get this error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in /home/outout/public_html/file.php:16 Stack trace: #0 /home/outout/public_html/file.php(16): PDO->query('select * from t...') #1 {main} thrown in /home/outout/public_html/file.php on line 16.

The code works on a local machine, but as soon as I put it online (cPanel) it shows me this error. Do I have to configure PDO in .htaccess?

I absolutely do not understand where the problem come. Someone would have an idea?

Body:
Use

$database -> query(' SELECT * FROM "database_name"."table_name" ');

instead of

$database -> query(' SELECT * FROM "table_name" ');


问:
CollapsingToolBarLayout Animation Stops
Is there a way to disable the interruption of the animation of a CollapsingToolBarLayout ?

We have a collapsing tool bar with an image that we are programmatically collapsing with animation by calling method
app_bar.setExpanded(false, true)
on the enclosing AppBarLayout object. This is done by attaching an onClickListener on a button that triggers the setExpanded(false,true) method .

The problem we are encountering is that the animation gets interrupted if we tap the screen more than once fast enough. The taps can be on the triggering button, which is wrapped in a debouncer; or on the button once and anywhere on the screen for the additional times. When that happens, the image view gets stuck, the tool bar doesn't collapse, and it is not possible to manually complete the animation. The back button needs to be pressed to bring the view to the its original state.

Below is an except of the layout:

```<code><android.support.design.widget.CoordinatorLayout
    android:id="@+id/coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:elevation="@dimen/rc_tab_elevation">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/image_placeholder_text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"/>

                <ImageView
                    android:id="@+id/image_pic"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:clickable="false"/>
            </FrameLayout>
        </android.support.design.widget.CollapsingToolbarLayout>

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                style="@style/Tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabMode="scrollable"/>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

The excerpt code for the listener called in a fragment.java subclass:

```<code>app_bar.setExpanded(expanded, true);
tab_layout.setVisibility(View.GONE);
</code>```

Any help, tips, or hints are welcome.

Thank you in advance.

答:
I was able to work something out and i'm posting the solution here. Hopefully, it'll be of use to someone.

The root of the problem is the nature of CollapsingToolBarLayout widget that always responds to touch events. Therefore, the solution consists of ignoring touch events once the collapsing animation is triggered.

Below is the method that collapses the toolbar and a boolean instance variable, collapseTriggered,  is created in order hold the state that a collapse is triggered.

```<code>public void collapseToolBar(){
    collapseTriggered = true;
    app_bar.setExpanded(expanded, true);
    tab_layout.setVisibility(View.GONE);
}
</code>```

Override the touch event listener in the activity. This is crucial so that the animation doesn't get interrupted mid execution in case of a touch event.The method in question is dispatchTouchEvent(MovtionEvent).

```<code>@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if( collapseTriggered == true){
       return true;     //if collapsed is triggered ignore all touch events
    }
    return super.disptachTouchEvent(ev); //otherwise, dispatch as usual
}
</code>```

Once collapse animation is done, change collapseTriggered variable to false. This is needed so that regular processing of touch events can resume after collapse animation is done -- in other words, once toolbar is fully collapsed. To do so,  an onOffSetListener() was added to the toolbar and detects when toolbard is fully collpased.

```<code> private void addFullyCollapsedListener() {
    app_bar.addOnOffSetChangedListener(
        new AppBarLayout.OnOffsetChangedListener() {
        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
            showMapSelected = false;
            }
        }
 });
</code>```

Watch Out For Remember to account for odd scenarios in which collapseTriggered doesn't get set to false after being set to true. In such cases, touch events can ignored and this can potentially signal to the user that the app has frozen. In my case, collapsedTriggered gets set to false as part of the onResume() method.

Title: CollapsingToolBarLayout Animation Stops

Body:
Is there a way to disable the interruption of the animation of a CollapsingToolBarLayout ?

We have a collapsing tool bar with an image that we are programmatically collapsing with animation by calling method
app_bar.setExpanded(false, true)
on the enclosing AppBarLayout object. This is done by attaching an onClickListener on a button that triggers the setExpanded(false,true) method .

The problem we are encountering is that the animation gets interrupted if we tap the screen more than once fast enough. The taps can be on the triggering button, which is wrapped in a debouncer; or on the button once and anywhere on the screen for the additional times. When that happens, the image view gets stuck, the tool bar doesn't collapse, and it is not possible to manually complete the animation. The back button needs to be pressed to bring the view to the its original state.

Below is an except of the layout:

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:elevation="@dimen/rc_tab_elevation">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll">

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/image_placeholder_text"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"/>

                <ImageView
                    android:id="@+id/image_pic"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center"
                    android:clickable="false"/>
            </FrameLayout>
        </android.support.design.widget.CollapsingToolbarLayout>

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                style="@style/Tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabMode="scrollable"/>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

The excerpt code for the listener called in a fragment.java subclass:

app_bar.setExpanded(expanded, true);
tab_layout.setVisibility(View.GONE);

Any help, tips, or hints are welcome.

Thank you in advance.

Body:
I was able to work something out and i'm posting the solution here. Hopefully, it'll be of use to someone.

The root of the problem is the nature of CollapsingToolBarLayout widget that always responds to touch events. Therefore, the solution consists of ignoring touch events once the collapsing animation is triggered.

Below is the method that collapses the toolbar and a boolean instance variable, collapseTriggered,  is created in order hold the state that a collapse is triggered.

public void collapseToolBar(){
    collapseTriggered = true;
    app_bar.setExpanded(expanded, true);
    tab_layout.setVisibility(View.GONE);
}

Override the touch event listener in the activity. This is crucial so that the animation doesn't get interrupted mid execution in case of a touch event.The method in question is dispatchTouchEvent(MovtionEvent).

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if( collapseTriggered == true){
       return true;     //if collapsed is triggered ignore all touch events
    }
    return super.disptachTouchEvent(ev); //otherwise, dispatch as usual
}

Once collapse animation is done, change collapseTriggered variable to false. This is needed so that regular processing of touch events can resume after collapse animation is done -- in other words, once toolbar is fully collapsed. To do so,  an onOffSetListener() was added to the toolbar and detects when toolbard is fully collpased.

 private void addFullyCollapsedListener() {
    app_bar.addOnOffSetChangedListener(
        new AppBarLayout.OnOffsetChangedListener() {
        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
            showMapSelected = false;
            }
        }
 });

Watch Out For Remember to account for odd scenarios in which collapseTriggered doesn't get set to false after being set to true. In such cases, touch events can ignored and this can potentially signal to the user that the app has frozen. In my case, collapsedTriggered gets set to false as part of the onResume() method.


问:
Making an elegant bash script
I have a windows application and i am using WineHQ on my mac to run this app. The application is a specific numerical solver for physics. Everytime a physics problem is to be solved, certain initial conditions are to be given.

The idea is to develop a bash script that can INSTALL or RUN this numerical solver for the initial condition.

INSTALL:
When this app was developed the developer forgot to embed certain files into the app. The app hence requires certain CUSTOM FILES which are to be copy-pasted once the application is installed. [Its not a CRACK].

RUN:
Now that the app is installed, everytime i run the solver, i have to specify an initial condition. The initial condition is in INIT_FOLDER. I intend to copy this folder to /APP and then run the APP.exe.

I am writing a bash script for the same.

```<code>#! /bin/bash
if [ $1 = "INSTALL" ]; then
    wine [APP MAC PATH] APP.exe
    cp [CUSTOM FILES PATH]/ ~/.wine.../APP
    cd ~/.wine.../APP
else
    if [ $1="RUN" ];  then
        cp $2 ~/.wine.../APP
        cd ~/.wine.../APP
        wine APP.exe
    fi
fi
</code>```

The end goal is to run the following commands,

```<code>>>./scriptname INSTALL
>>./scriptname RUN INIT_FOLDER_PATH
</code>```

INSTALL:
Of course when i run the command to install the application, i do not come accross any problems. HOWEVER, I want to improve the following script (to educate myself). Suppose the application does not install I.E.

```<code>wine [APP MAC PATH] APP.exe
</code>```

"fails". How to prevent the subsequent operation from being executed?

Also, I dont want to type the wine folder location. Is their some way to make this easier, like representing the "wine app path" as an equivalent word (say FOO)

RUN:
I would like to get some validation on this. If i type,

```<code>>>./scriptname RUN INIT_FOLDER_PATH/
</code>```

Am I write to assume $2 is INIT_FOLDER_PATH. Also is the following command the write way,

```<code>cp $2 ~/.wine.../APPFOLDERNAME
</code>```

答:
To keep from specifying the path to your wine executable, insure that the path is in your computer's PATH environment variable. See here on how to do that on a mac. Once done, you can run it simply by specifying the program name.

I'm not sure on the error capturing. You will be running a windows executable inside of your wineHQ environment, so you have two layers of errors. 1) the windows executable and 2) Errors within Wine. You can check out the section talking about environment variables in the wine user guide. Specifically the WineDebug channel option. I'm not sure if that will solve for errors within the windows executable, but it seems like a good place to start. You could also check the return code after running the wine line by checking the return  return=$? which will be a code 0-255. 0 being A-OK and any thing else being "Something bad happened on that last command".

I'm not entirely sure what you are asking on the last part of your question. $2 in your case would refer to the string "INIT_FOLDER_PATH/" So your cp $2 ... line would copy whatever is in that folder called "INIT_FOLDER_PATH/" to your ~/.wine... path.

Title: Making an elegant bash script

Body:
I have a windows application and i am using WineHQ on my mac to run this app. The application is a specific numerical solver for physics. Everytime a physics problem is to be solved, certain initial conditions are to be given.

The idea is to develop a bash script that can INSTALL or RUN this numerical solver for the initial condition.

INSTALL:
When this app was developed the developer forgot to embed certain files into the app. The app hence requires certain CUSTOM FILES which are to be copy-pasted once the application is installed. [Its not a CRACK].

RUN:
Now that the app is installed, everytime i run the solver, i have to specify an initial condition. The initial condition is in INIT_FOLDER. I intend to copy this folder to /APP and then run the APP.exe.

I am writing a bash script for the same.

#! /bin/bash
if [ $1 = "INSTALL" ]; then
    wine [APP MAC PATH] APP.exe
    cp [CUSTOM FILES PATH]/ ~/.wine.../APP
    cd ~/.wine.../APP
else
    if [ $1="RUN" ];  then
        cp $2 ~/.wine.../APP
        cd ~/.wine.../APP
        wine APP.exe
    fi
fi

The end goal is to run the following commands,

>>./scriptname INSTALL
>>./scriptname RUN INIT_FOLDER_PATH

INSTALL:
Of course when i run the command to install the application, i do not come accross any problems. HOWEVER, I want to improve the following script (to educate myself). Suppose the application does not install I.E.

wine [APP MAC PATH] APP.exe

"fails". How to prevent the subsequent operation from being executed?

Also, I dont want to type the wine folder location. Is their some way to make this easier, like representing the "wine app path" as an equivalent word (say FOO)

RUN:
I would like to get some validation on this. If i type,

>>./scriptname RUN INIT_FOLDER_PATH/

Am I write to assume $2 is INIT_FOLDER_PATH. Also is the following command the write way,

cp $2 ~/.wine.../APPFOLDERNAME


问:
Java current machine name and logged in user?
Is it possible to get the name of the currently logged in user (Windows/Unix) and the hostname of the machine?

I assume it's just a property of some static environment class.

I've found this for the user name

```<code>com.sun.security.auth.module.NTSystem NTSystem = new
        com.sun.security.auth.module.NTSystem();
System.out.println(NTSystem.getName());
</code>```

and this for the machine name:

```<code>import java.net.InetAddress;
...
String computerName;
...
try {
    computerName = InetAddress.getLocalHost().getHostName();
}

catch(Exception ex) {
    ...
}
</code>```

Is the first one just for Windows?

And what will the second one do, if you don't have a hostname set?

答:
To get the currently logged in user:

```<code>System.getProperty("user.name");
</code>```

To get the host name of the machine:

```<code>InetAddress.getLocalHost().getHostName();
</code>```

To answer the last part of your question, the Java API says that getHostName() will return

the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.

OwnerDisplayName: Omar Kooheji

Body:
Is it possible to get the name of the currently logged in user (Windows/Unix) and the hostname of the machine?

I assume it's just a property of some static environment class.

I've found this for the user name

com.sun.security.auth.module.NTSystem NTSystem = new
        com.sun.security.auth.module.NTSystem();
System.out.println(NTSystem.getName());

and this for the machine name:

import java.net.InetAddress;
...
String computerName;
...
try {
    computerName = InetAddress.getLocalHost().getHostName();
}

catch(Exception ex) {
    ...
}

Is the first one just for Windows?

And what will the second one do, if you don't have a hostname set?

LastEditorDisplayName: Omar Kooheji

Body:
To get the currently logged in user:

System.getProperty("user.name");

To get the host name of the machine:

InetAddress.getLocalHost().getHostName();

To answer the last part of your question, the Java API says that getHostName() will return

the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.

OwnerDisplayName: Bill the Lizard