问:
Semantic-ui-react: How do I trigger a Popup without it being click/hover?
When submitting a form, I wish to show a small popup for 2.5 seconds if the server sends back a bad response.

The logic is fairly simple, however, I cannot figure out how to make this popup listen to a boolean somewhere in the state management(MobX in my case). I can get the content into the Popup just fine, however, the trigger is a button(and the content will show, if you click it) - But how do I make it listen to a boolean value somewhere?

Fairly simple class here:

```<code>import React from "react";
import { Popup, Button } from "semantic-ui-react";
import { inject } from "mobx-react";
const timeoutLength = 2500;

@inject("store")
export default class ErrorPopup extends React.Component {

    state = {
        isOpen: false
    };

    handleOpen = () => {
        this.setState({
            isOpen: true
        });

        this.timeout = setTimeout(() => {
            this.setState({
                isOpen: false
            })
        }, timeoutLength)
    };

    handleClose = () => {
        this.setState({
            isOpen: false
        });
        clearTimeout(this.timeout)
    };

    render () {

        const errorContent = this.props.data;

        if(errorContent){
            return(
                <Popup
                    trigger={<Button content='Open controlled popup' />}
                    content={errorContent}
                    on='click'
                    open={this.state.isOpen}
                    onClose={this.handleClose}
                    onOpen={this.handleOpen}
                    position='top center'
                />
            )
        }
    }
}
</code>```

However, the trigger value is a button which is rendered if this.props.data is present. But that's not the behavior I wish; I simply want the popup to render(and thus trigger) if this.props.data is there; alternatively, I can provide a true value with props if need be.

But how do I make this component trigger without it being a hover/button?

答:
How about passing in the isOpen prop? Then you could add some logic onto the componentWillReceiveProps hook:

```<code>import React from "react";
import { Popup, Button } from "semantic-ui-react";
import { inject } from "mobx-react";
const timeoutLength = 2500;

@inject("store")
export default class ErrorPopup extends React.Component {

 constructor(props) {
   super(props);
   this.state = {
     isOpen: false,
   }
 };

  //This is where you trigger your methods
  componentWillReceiveProps(nextProps){
    if(true === nextProps.isOpen){
      this.handleOpen();
    } else {
      this.handleClose();
    }
  }

  handleOpen = () => {

    this.setState({
      isOpen: true
    });

    this.timeout = setTimeout(() => {
      //No need to repeat yourself - use the existing method here
      this.handleClose();
    }, timeoutLength)
  };

  handleClose = () => {
    this.setState({
      isOpen: false
    });
    clearTimeout(this.timeout)
  };

  render () {

    const errorContent = this.props.data;

    if(errorContent){
      return(
        <Popup
          trigger={<Button content='Open controlled popup' />}
          content={errorContent}
          on='click'
          open={this.state.isOpen}
          position='top center'
        />
      )
    }
  }
}
</code>```

Without a need of handling delay - you could simply pass in the isOpen prop and that would do the trick.

And here what it could look like in your parent component's render:

```<code>let isOpen = this.state.isOpen;
<ErrorPopup isOpen={isOpen}/>
</code>```

Set this value to control the popup, ideally, this should be a part of your parent component's state. Having a stateful component as a parent is important to make the popup re-rendered

Body:
When submitting a form, I wish to show a small popup for 2.5 seconds if the server sends back a bad response.

The logic is fairly simple, however, I cannot figure out how to make this popup listen to a boolean somewhere in the state management(MobX in my case). I can get the content into the Popup just fine, however, the trigger is a button(and the content will show, if you click it) - But how do I make it listen to a boolean value somewhere?

Fairly simple class here:

import React from "react";
import { Popup, Button } from "semantic-ui-react";
import { inject } from "mobx-react";
const timeoutLength = 2500;

@inject("store")
export default class ErrorPopup extends React.Component {

    state = {
        isOpen: false
    };

    handleOpen = () => {
        this.setState({
            isOpen: true
        });

        this.timeout = setTimeout(() => {
            this.setState({
                isOpen: false
            })
        }, timeoutLength)
    };

    handleClose = () => {
        this.setState({
            isOpen: false
        });
        clearTimeout(this.timeout)
    };

    render () {

        const errorContent = this.props.data;

        if(errorContent){
            return(
                <Popup
                    trigger={<Button content='Open controlled popup' />}
                    content={errorContent}
                    on='click'
                    open={this.state.isOpen}
                    onClose={this.handleClose}
                    onOpen={this.handleOpen}
                    position='top center'
                />
            )
        }
    }
}

However, the trigger value is a button which is rendered if this.props.data is present. But that's not the behavior I wish; I simply want the popup to render(and thus trigger) if this.props.data is there; alternatively, I can provide a true value with props if need be.

But how do I make this component trigger without it being a hover/button?

Body:
How about passing in the isOpen prop? Then you could add some logic onto the componentWillReceiveProps hook:

import React from "react";
import { Popup, Button } from "semantic-ui-react";
import { inject } from "mobx-react";
const timeoutLength = 2500;

@inject("store")
export default class ErrorPopup extends React.Component {

 constructor(props) {
   super(props);
   this.state = {
     isOpen: false,
   }
 };

  //This is where you trigger your methods
  componentWillReceiveProps(nextProps){
    if(true === nextProps.isOpen){
      this.handleOpen();
    } else {
      this.handleClose();
    }
  }

  handleOpen = () => {

    this.setState({
      isOpen: true
    });

    this.timeout = setTimeout(() => {
      //No need to repeat yourself - use the existing method here
      this.handleClose();
    }, timeoutLength)
  };

  handleClose = () => {
    this.setState({
      isOpen: false
    });
    clearTimeout(this.timeout)
  };

  render () {

    const errorContent = this.props.data;

    if(errorContent){
      return(
        <Popup
          trigger={<Button content='Open controlled popup' />}
          content={errorContent}
          on='click'
          open={this.state.isOpen}
          position='top center'
        />
      )
    }
  }
}

Without a need of handling delay - you could simply pass in the isOpen prop and that would do the trick.

And here what it could look like in your parent component's render:

let isOpen = this.state.isOpen;
<ErrorPopup isOpen={isOpen}/>

Set this value to control the popup, ideally, this should be a part of your parent component's state. Having a stateful component as a parent is important to make the popup re-rendered


来源: stackexchange

问:
Facebook Graph API in workplace: group post with mentioning users
How do I mention a user in a post in the 2.8 version Graph API in Facebook Workplace?</p>

```<code>https://graph.facebook.com/{group_id}/feed
params: message=test
</code>```

答:
Use:

```<code>https://graph.facebook.com/{group_id}/feed
</code>```

Parameters: message=test and tag=userid of the person you want to tag.

ContentLicense: CC BY-SA 3.0

Body:
How do I mention a user in a post in the 2.8 version Graph API in Facebook Workplace?

https://graph.facebook.com/{group_id}/feed
params: message=test

Body:
Use:

https://graph.facebook.com/{group_id}/feed

Parameters: message=test and tag=userid of the person you want to tag.


问:
Is there a windows utility similar to HTML Tidy for Javascript?
I want to cleanup some javascript files and reformat them with nice indents, etc,
Are there recommendations for utilities to do this under Windows?</p>

答: This page on about.com has a tool where you paste in your script and it cleans it up for you.</p>

OwnerDisplayName: Noah

LastEditorDisplayName: Noah

OwnerDisplayName: Diodeus

ContentLicense: CC BY-SA 2.5


问:
jQuery UI Autocomplete: Triggering a Search From outside of autocomplete
I would like to trigger some jQuery autocomplete events from outside of autocomplete but I don't know how to. i.e.

```<code>$("something").autocomplete({select:function(event,ui){do x},
                                search:function(event,ui){do y}});

$("something else").keypress(function(eventobject){*trigger autocomplete "select"*});
</code>```

What code do I put in trigger autocomplete "select"

答:
Use the "Search" method: http://api.jqueryui.com/autocomplete/#method-search</p>

```<code>$("something").autocomplete(/* options */);
$("somethingelse").click(function () {
    $("something").autocomplete('search', 'demo-value');
});
</code>```

Body:
I would like to trigger some jQuery autocomplete events from outside of autocomplete but I don't know how to. i.e.

$("something").autocomplete({select:function(event,ui){do x},
                                search:function(event,ui){do y}});

$("something else").keypress(function(eventobject){*trigger autocomplete "select"*});

What code do I put in trigger autocomplete "select"

Body:
Use the "Search" method: http://api.jqueryui.com/autocomplete/#method-search

$("something").autocomplete(/* options */);
$("somethingelse").click(function () {
    $("something").autocomplete('search', 'demo-value');
});


问:
How to define a variable in Logback with a default value and override it?
I would like to define a property/variable in Logback (1.2.1) that:

Has a default value

Can be overriden via a Java command-line option

Basically, during development, I would like Maven to be invoking the maven-surefire-plugin with something like this:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <systemPropertyVariables>
            <log.dir>${project.build.directory}/logs</log.dir>
        </systemPropertyVariables>
    </configuration>
</plugin>
</code>```

(I am sure that the above is working fine, because I have other properties being passed in for the tests this way and those work as expected).

At the moment, I have the following logback.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration scan="true" scanPeriod="30 seconds" debug="false">

    <property name="log.dir" value="."/>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.dir}/logs/my.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>strongbox_%d{yyyy-MM-dd}.%i.log</fileNamePattern>

            <fileNamePattern>strongbox-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>128MB</maxFileSize>
            <maxHistory>31</maxHistory>
            <totalSizeCap>1GB</totalSizeCap>

            <maxHistory>30</maxHistory>
        </rollingPolicy>

        <encoder>
            <charset>UTF-8</charset>
            <pattern>%d{HH:mm:ss.SSS dd-MM-yyyy} | %-5.5p | %-20.20t | %-50.50logger{50} | %m%n</pattern>
        </encoder>
    </appender>
    ...
</configuration>
</code>```

The -Dlog.dir=foo/logs, it is simply being ignored and the log file is being produced in the current directory. What am I doing wrong here? Does it need a scope? Does it need an if condition to be set up?

答:
You specify the property for the maven-surefire-plugin.

So the property will be bound only for this plugin execution :

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <systemPropertyVariables>
            <log.dir>${project.build.directory}/logs</log.dir>
        </systemPropertyVariables>
    </configuration>
</plugin>
</code>```

In your case, you want that the property be bound whatever the executed plugin.
Not only for test executions.

So you should use properties declared in the  <build> tag of the pom.

```<code><build>
      ...
  <properties>
     <log.dir>${project.build.directory}/logs</log.dir>
  </properties>
      ...
</build>
</code>```

In order that the Maven property used in the logback configuration be replaced by the actual value computed from the pom, you have to enable the Maven resources filtering :

```<code>  ...
  <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
  </resource>
  ...
</code>```

And the Logback configuration has to be located inside the src/main/resources folder of course (this folder or a child).

Body:
I would like to define a property/variable in Logback (1.2.1) that:

Has a default value

Can be overriden via a Java command-line option

Basically, during development, I would like Maven to be invoking the maven-surefire-plugin with something like this:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <systemPropertyVariables>
            <log.dir>${project.build.directory}/logs</log.dir>
        </systemPropertyVariables>
    </configuration>
</plugin>

(I am sure that the above is working fine, because I have other properties being passed in for the tests this way and those work as expected).

At the moment, I have the following logback.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration scan="true" scanPeriod="30 seconds" debug="false">

    <property name="log.dir" value="."/>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.dir}/logs/my.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>strongbox_%d{yyyy-MM-dd}.%i.log</fileNamePattern>

            <fileNamePattern>strongbox-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <maxFileSize>128MB</maxFileSize>
            <maxHistory>31</maxHistory>
            <totalSizeCap>1GB</totalSizeCap>

            <maxHistory>30</maxHistory>
        </rollingPolicy>

        <encoder>
            <charset>UTF-8</charset>
            <pattern>%d{HH:mm:ss.SSS dd-MM-yyyy} | %-5.5p | %-20.20t | %-50.50logger{50} | %m%n</pattern>
        </encoder>
    </appender>
    ...
</configuration>

The -Dlog.dir=foo/logs, it is simply being ignored and the log file is being produced in the current directory. What am I doing wrong here? Does it need a scope? Does it need an if condition to be set up?

Body:
You specify the property for the maven-surefire-plugin.

So the property will be bound only for this plugin execution :

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <systemPropertyVariables>
            <log.dir>${project.build.directory}/logs</log.dir>
        </systemPropertyVariables>
    </configuration>
</plugin>

In your case, you want that the property be bound whatever the executed plugin.
Not only for test executions.

So you should use properties declared in the  <build> tag of the pom.

<build>
      ...
  <properties>
     <log.dir>${project.build.directory}/logs</log.dir>
  </properties>
      ...
</build>

In order that the Maven property used in the logback configuration be replaced by the actual value computed from the pom, you have to enable the Maven resources filtering :

  ...
  <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
  </resource>
  ...

And the Logback configuration has to be located inside the src/main/resources folder of course (this folder or a child).


问:
Logcat shows random/irrelevant errors
It's so annoying when logcat shows errors which are not related to my app at all. I turned off my app in the emulator and still this error will print after every 15-20 seconds

```<code>06-08 18:22:50.685 2350-14664/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
                                                                                com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
                                                                                Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
                                                                                at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
                                                                                at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
                                                                                at java.io.InputStream.read(InputStream.java:101)
                                                                                at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
                                                                                at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
</code>```

It makes debugging a bit tedious and I really want to do something about it.

EDIT-Even after using the filter I get random googlequicksearchbox errors

```<code>06-08 18:20:34.728 2350-14241/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -1
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -1.
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-08 18:20:39.760 1306-3296/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
06-08 18:20:39.762 1306-1691/? E/AudioFlinger: openRecord() permission denied: recording not allowed
</code>```

PS: I am not using any voice related stuff in my app.

答:
You Go To File menu on Android studio they have a option invalidate cache and restart and press this option .
when You invalidate cache and restart then . Approx Your Problem solved</p>

Title: Logcat shows random/irrelevant errors

Body:
It's so annoying when logcat shows errors which are not related to my app at all. I turned off my app in the emulator and still this error will print after every 15-20 seconds

06-08 18:22:50.685 2350-14664/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
                                                                                com.google.android.apps.gsa.shared.speech.a.g: Error reading from input stream
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a.a(SourceFile:342)
                                                                                at com.google.android.apps.gsa.staticplugins.recognizer.i.a$1.run(SourceFile:1367)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)
                                                                                Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
                                                                                at com.google.android.apps.gsa.speech.audio.Tee.g(SourceFile:2531)
                                                                                at com.google.android.apps.gsa.speech.audio.ap.read(SourceFile:555)
                                                                                at java.io.InputStream.read(InputStream.java:101)
                                                                                at com.google.android.apps.gsa.speech.audio.al.run(SourceFile:362)
                                                                                at com.google.android.apps.gsa.speech.audio.ak$1.run(SourceFile:471)
                                                                                at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ak.run(SourceFile:66)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ax.run(SourceFile:139)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)
                                                                                at com.google.android.apps.gsa.shared.util.concurrent.a.ad$1.run(SourceFile:85)

It makes debugging a bit tedious and I really want to do something about it.

EDIT-Even after using the filter I get random googlequicksearchbox errors

06-08 18:20:34.728 2350-14241/com.google.android.googlequicksearchbox:search E/AudioRecord: AudioFlinger could not create record track, status: -1
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -1.
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
06-08 18:20:34.732 2350-14241/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
06-08 18:20:39.760 1306-3296/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
06-08 18:20:39.762 1306-1691/? E/AudioFlinger: openRecord() permission denied: recording not allowed

PS: I am not using any voice related stuff in my app.


问:
Folders missing in project pane in Webstorm
I've built a project in WebStorm and then submitted the project to GitHub.

When I rebooted the computer and relaunched WebStorm (and the project), all I can see in the project pane is the root files, and none of the folders (yes the folders are there)

See the image below for reference.

Does anyone know how I can get those folders to re-appear in the project pane of Webstorm?

答:
You do not need to delete whole .idea folder and reconfigure your whole project, just

delete the .idea/modules.xml

restart the IDE and your folders are there again!


问:
Error while deploying my Spring Angular2 application in Heroku
I have built a spring application with angular 2 for the front end and a cloud hosted database at mlab. It works perfectly fine on development enviroment but now I'm trying to deploy it in Heroku. I've managed to do so but it doesn't seem to be receiving data needed from the database.

This is the error that appears in console:

```<code>Mixed Content: The page at 'https://myappname.herokuapp.com/list' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint 'http://myappname.herokuapp.com/security/login'.
This request has been blocked; the content must be served over HTTPS.
</code>```

I have tried to redirect my urls to the https equivalent as shown in this post Angular 2+Heroku , always redirect to https:// instead of using http:// but it didn't work.

http://myappname.herokuapp.com/security/login is the url where you are redirected when spring security intercepts a request when you have no access to a resource so maybe the problem is there? Do I have to change the spring security config file for deployment or is it something else?.

答:
After looking around a little more I found this post which gives a solution to my problem: http://www.learningthegoodstuff.com/2015/08/mixed-http-error-with-spring-security.html

All the details are explained there, basically all I had to do was add this two lines to my application.properties file:

```<code>server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto
</code>```

Body:
I have built a spring application with angular 2 for the front end and a cloud hosted database at mlab. It works perfectly fine on development enviroment but now I'm trying to deploy it in Heroku. I've managed to do so but it doesn't seem to be receiving data needed from the database.

This is the error that appears in console:

Mixed Content: The page at 'https://myappname.herokuapp.com/list' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint 'http://myappname.herokuapp.com/security/login'.
This request has been blocked; the content must be served over HTTPS.

I have tried to redirect my urls to the https equivalent as shown in this post Angular 2+Heroku , always redirect to https:// instead of using http:// but it didn't work.

http://myappname.herokuapp.com/security/login is the url where you are redirected when spring security intercepts a request when you have no access to a resource so maybe the problem is there? Do I have to change the spring security config file for deployment or is it something else?.

Body:
After looking around a little more I found this post which gives a solution to my problem: http://www.learningthegoodstuff.com/2015/08/mixed-http-error-with-spring-security.html

All the details are explained there, basically all I had to do was add this two lines to my application.properties file:

server.tomcat.remote_ip_header=x-forwarded-for
server.tomcat.protocol_header=x-forwarded-proto


问:
Windows Forms input /save to FilePath issue using excel
I have a simple windows form with person details input.I am using a filepath to save entry (mydocuments/.csv file) My display on WF is a label

Issue: each entry I make is saved to csv/excel doc in one continous line and also on the label when i click "show data"
I want each entry line to be seperated in label display
Any help would be much appreciated ,new to this game.
Thanks
G
My code :

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

 namespace StringFilePath
 {
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   string FilePath = Environment.GetFolderPath      (Environment.SpecialFolder.MyDocuments) +    Path.DirectorySeparatorChar+ "mestring.csv";
    private void btnAdd_Click(object sender, EventArgs e)
    {
        int id = int.Parse(txtID.Text);
        string fname = TXTfNAME.Text;
        string lname = txtLname.Text;
        string phone = txtPhone.Text;
        string email = txtEmail.Text;

        StreamWriter sw = File.AppendText(FilePath);
        sw.Write(id + ",");
        sw.Write(fname + ",");
        sw.Write(lname + ",");
        sw.Write(phone + ",");
        sw.Write(email + ",");

        sw.Close();

        txtID.Clear();
        TXTfNAME.Clear();
        txtLname.Clear();
        txtPhone.Clear();
        txtEmail.Clear();

    }

    private void isplay_Click(object sender, EventArgs e)
    {
        string content = File.ReadAllText(FilePath);
        lblDisplay.Text = content;
    }
</code>```

答:
You need to add an Environment.NewLine to your text. You can do that explicitly or just using sw.WriteLine on the last input

```<code>string line = $"{id},{fname},{lname},{phone},{email}";
using(StreamWriter sw = new StreamWriter(FilePath))
   sw.WriteLine(line);
</code>```

Or more concise with

```<code>string line = $"{id},{fname},{lname},{phone},{email}{Environment.NewLine}";
File.AppendAllText(FilePath, line);
</code>```

For the label you should be able to set simply its text with the data loaded from the file, but, of course, the label should have enough Height to show the lines loaded

Body:
I have a simple windows form with person details input.I am using a filepath to save entry (mydocuments/.csv file) My display on WF is a label

Issue: each entry I make is saved to csv/excel doc in one continous line and also on the label when i click "show data"
I want each entry line to be seperated in label display
Any help would be much appreciated ,new to this game.
Thanks
G
My code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

 namespace StringFilePath
 {
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
   string FilePath = Environment.GetFolderPath      (Environment.SpecialFolder.MyDocuments) +    Path.DirectorySeparatorChar+ "mestring.csv";
    private void btnAdd_Click(object sender, EventArgs e)
    {
        int id = int.Parse(txtID.Text);
        string fname = TXTfNAME.Text;
        string lname = txtLname.Text;
        string phone = txtPhone.Text;
        string email = txtEmail.Text;

        StreamWriter sw = File.AppendText(FilePath);
        sw.Write(id + ",");
        sw.Write(fname + ",");
        sw.Write(lname + ",");
        sw.Write(phone + ",");
        sw.Write(email + ",");

        sw.Close();

        txtID.Clear();
        TXTfNAME.Clear();
        txtLname.Clear();
        txtPhone.Clear();
        txtEmail.Clear();

    }

    private void isplay_Click(object sender, EventArgs e)
    {
        string content = File.ReadAllText(FilePath);
        lblDisplay.Text = content;
    }

Body:
You need to add an Environment.NewLine to your text. You can do that explicitly or just using sw.WriteLine on the last input

string line = $"{id},{fname},{lname},{phone},{email}";
using(StreamWriter sw = new StreamWriter(FilePath))
   sw.WriteLine(line);

Or more concise with

string line = $"{id},{fname},{lname},{phone},{email}{Environment.NewLine}";
File.AppendAllText(FilePath, line);

For the label you should be able to set simply its text with the data loaded from the file, but, of course, the label should have enough Height to show the lines loaded


问:
Kotlin constructor reference with generics
I have this code in (Rx)Java:

```<code>Observable.fromArray(1, 2, 3)
    .flatMap(this::intToBooleanObservable, Pair::new)
    .....
</code>```

I would expect to corresponding Kotlin code to look like:

```<code>Observable.fromArray(1, 2, 3)
    .flatMap(::intToBooleanObservable, ::Pair)
    .....
</code>```

However the compiler cannot infer the generic type of Pair, so the best I can do right now is:

```<code>.flatMap(::intToBooleanObservable, { a, b -> a to b })
</code>```

Which isn't as concise as I would like it to be.

Is there a way to achieve this without declaring the variables a and b?

答:
Same trouble here. A few other workarounds (in the order I used them), you may like one of those.

1) Writing your own operator:

```<code>fun <T, U> Single<T>.flatMapPair(func: (T) -> Single<U>) : Single<Pair<T, U>> {
    return this.flatMap { t -> func.invoke(t).map { u -> t to u } }
}
</code>```

2) Move the wrapping to the conditional Observable (here intToBooleanObservable), returning the result as a Pair or a more explicit and custom type (sealed class with 2 childs, like Success and Failure). This enable more explicit code :

```<code> when(it) {
   is Success -> ...
   is Failure -> ...
}
</code>```

3) Depending on intToBooleanObservable result you have now 2 different scenario (I imagine). Usually one is a sort of failure/denial, quick to resolve. For this matter write a filter with side effect where the predicate is an Observable, thus avoiding the problem :

```<code>fun <T> Observable<T>.filterSingle(predicate: (T) -> Single<Boolean>, rejectionFunction: (T) -> Unit): Observable<T> = ... //filter with the given predicate, and call rejectionFunction if item doesn't pass
</code>```

4) The last method work only with boolean result. What if I am interested by the reason behind failure/refusal to give a meaningful message ? For the sake of homogeneous code, I dropped this operator. Inspired by other functionals languages, I defined a Either type and defined generic Either+RxJava operators; mapRight, flatMapRight and more important dropLeft. dropLeft is like a generalization of filterSingle.

```<code>inline fun <L, R> Observable<Either<L, R>>.dropLeft(crossinline sideEffect: (L) -> Unit): Observable<R> = this.lift { downObserver ->
    object: Observer<Either<L, R>> {
        override fun onError(throwable: Throwable?) = downObserver.onError(throwable)

        override fun onSubscribe(disposable: Disposable?) = downObserver.onSubscribe(disposable)

        override fun onComplete() = downObserver.onComplete()

        override fun onNext(either: Either<L, R>) = when (either) {
            is Right -> downObserver.onNext(either.value)
            is Left -> sideEffect(either.value)
        }
    }
}
</code>```

Hope it could help.

Body:
I have this code in (Rx)Java:

Observable.fromArray(1, 2, 3)
    .flatMap(this::intToBooleanObservable, Pair::new)
    .....

I would expect to corresponding Kotlin code to look like:

Observable.fromArray(1, 2, 3)
    .flatMap(::intToBooleanObservable, ::Pair)
    .....

However the compiler cannot infer the generic type of Pair, so the best I can do right now is:

.flatMap(::intToBooleanObservable, { a, b -> a to b })

Which isn't as concise as I would like it to be.

Is there a way to achieve this without declaring the variables a and b?

Body:
Same trouble here. A few other workarounds (in the order I used them), you may like one of those.

1) Writing your own operator:

fun <T, U> Single<T>.flatMapPair(func: (T) -> Single<U>) : Single<Pair<T, U>> {
    return this.flatMap { t -> func.invoke(t).map { u -> t to u } }
}

2) Move the wrapping to the conditional Observable (here intToBooleanObservable), returning the result as a Pair or a more explicit and custom type (sealed class with 2 childs, like Success and Failure). This enable more explicit code :

 when(it) {
   is Success -> ...
   is Failure -> ...
}

3) Depending on intToBooleanObservable result you have now 2 different scenario (I imagine). Usually one is a sort of failure/denial, quick to resolve. For this matter write a filter with side effect where the predicate is an Observable, thus avoiding the problem :

fun <T> Observable<T>.filterSingle(predicate: (T) -> Single<Boolean>, rejectionFunction: (T) -> Unit): Observable<T> = ... //filter with the given predicate, and call rejectionFunction if item doesn't pass

4) The last method work only with boolean result. What if I am interested by the reason behind failure/refusal to give a meaningful message ? For the sake of homogeneous code, I dropped this operator. Inspired by other functionals languages, I defined a Either type and defined generic Either+RxJava operators; mapRight, flatMapRight and more important dropLeft. dropLeft is like a generalization of filterSingle.

inline fun <L, R> Observable<Either<L, R>>.dropLeft(crossinline sideEffect: (L) -> Unit): Observable<R> = this.lift { downObserver ->
    object: Observer<Either<L, R>> {
        override fun onError(throwable: Throwable?) = downObserver.onError(throwable)

        override fun onSubscribe(disposable: Disposable?) = downObserver.onSubscribe(disposable)

        override fun onComplete() = downObserver.onComplete()

        override fun onNext(either: Either<L, R>) = when (either) {
            is Right -> downObserver.onNext(either.value)
            is Left -> sideEffect(either.value)
        }
    }
}

Hope it could help.


问:
Vue binding overrides element attribute
I have a component that renders a HTML input:

```<code><input
    :placeholder="placeholder"
    v-model="value"
    type="text"
    :disabled="disabled"
    :readOnly="readOnly"
    @focus="onFocus"
/>
</code>```

Note that the type is not binded/reactive.

When I put this component inside another, and bind a object to it, the type gets overrided.

```<code> <my-input v-bind="{type: 'foobar'}"></my-input>
</code>```

Is this a by design or a bug?

Example (check the input[type] in the HTML):

const Input = {
    template: '<input type="text"/>'
    //                      ^^^^ "text" gets overriden to "foobar"
}
new Vue({
    el: '#demo',
    components: {
        'my-input': Input
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://vuejs.org/js/vue.min.js"></script>
<div id="demo">
    <my-input v-bind="{type: 'foobar'}"></my-input>
</div></code>```

答:
I answered this in an issue, this is expected

https://github.com/vuejs/vue/issues/5846#issuecomment-307098682

You can, however, disregard attrs by adding them as props and ignore them

```<code>const Input = {
    props: ['type'],
    template: '<input type="text"/>'
    //                      ^^^^ "text" won't get overriden
}
new Vue({
    el: '#demo',
    components: {
        'my-input': Input
    }
});
</code>```

Other attributes like class get merged but type can only be overriden

Title: Vue binding overrides element attribute

Body:
I have a component that renders a HTML input:

<input
    :placeholder="placeholder"
    v-model="value"
    type="text"
    :disabled="disabled"
    :readOnly="readOnly"
    @focus="onFocus"
/>

Note that the type is not binded/reactive.

When I put this component inside another, and bind a object to it, the type gets overrided.

 <my-input v-bind="{type: 'foobar'}"></my-input>

Is this a by design or a bug?

Example (check the input[type] in the HTML):

const Input = {
    template: '<input type="text"/>'
    //                      ^^^^ "text" gets overriden to "foobar"
}
new Vue({
    el: '#demo',
    components: {
        'my-input': Input
    }
});

    <my-input v-bind="{type: 'foobar'}"></my-input>

Body:
I answered this in an issue, this is expected

https://github.com/vuejs/vue/issues/5846#issuecomment-307098682

You can, however, disregard attrs by adding them as props and ignore them

const Input = {
    props: ['type'],
    template: '<input type="text"/>'
    //                      ^^^^ "text" won't get overriden
}
new Vue({
    el: '#demo',
    components: {
        'my-input': Input
    }
});

Other attributes like class get merged but type can only be overriden


问:
How to avoid Warning when accessing an Interface ByRef
i want to access a element in a dictionary of interfaces:

```<code>Public Interface IWorker
    Sub doSomething()
End Interface

Private Sub Test()

    Dim MyDict As New Dictionary(Of Integer, IWorker)()
    Dim Worker As IWorker

    If MyDict.TryGetValue(0, Worker) Then
        Worker.doSomething()
    End If

End Sub
</code>```

It works but i get a Warning: "Variable 'Worker' is used before it has been assigned a value"

I found this Question: VB.NET: Null reference with an Interface but for the solution i had to change the "TryGetValue" Function.

What is the best way to get rid of the warning?

答:
The best way to get rid of this is to assign it a value, the value doesn't have to be an actual object, it can just be nothing

This should work:

Dim Worker As IWorker = Nothing

Hope this helps!

Body:
i want to access a element in a dictionary of interfaces:

Public Interface IWorker
    Sub doSomething()
End Interface

Private Sub Test()

    Dim MyDict As New Dictionary(Of Integer, IWorker)()
    Dim Worker As IWorker

    If MyDict.TryGetValue(0, Worker) Then
        Worker.doSomething()
    End If

End Sub

It works but i get a Warning: "Variable 'Worker' is used before it has been assigned a value"

I found this Question: VB.NET: Null reference with an Interface but for the solution i had to change the "TryGetValue" Function.

What is the best way to get rid of the warning?


问:
How to use hapi js on Firebase Cloud Function?
I try to learn from an example to use express together with  handlebars on firebase.

For the express way, we can send the "app" instance directly to the "functions.https.onRequest" like...

```<code>const app = express();
...
app.get('/', (req, res) => {
    ...
});

exports.app = functions.https.onRequest(app);
</code>```

See live functions

As my understanding it's working because "express"  act like http-node, so it can respond "http plain".

Comparing to hapi, here is hello-world

```<code>const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 8000
});

server.route({
    method: 'GET',
    path:'/hello',
    handler: function (request, reply) {
        return reply('hello world');
    }
});

server.start((err) => {
    console.log('Server running at:', server.info.uri);
});
</code>```

From the hapi example, is it possible to use hapi on firebase cloud function?

Can I use hapi without starting a server like express?

答:
Have a look at the inject method (last code example): http://www.carbonatethis.com/hosting-a-serverless-hapi-js-api-with-aws-lambda/

However, I don't think that this is feasible, because you would still need to hold onto the response object of the express app instance Google Cloud Functions provide to http triggered functions, as only send(), redirect() or end() will work to respond to the incoming request and not hapi's methods (see https://firebase.google.com/docs/functions/http-events).

Body:
I try to learn from an example to use express together with  handlebars on firebase.

For the express way, we can send the "app" instance directly to the "functions.https.onRequest" like...

const app = express();
...
app.get('/', (req, res) => {
    ...
});

exports.app = functions.https.onRequest(app);

See live functions

As my understanding it's working because "express"  act like http-node, so it can respond "http plain".

Comparing to hapi, here is hello-world

const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 8000
});

server.route({
    method: 'GET',
    path:'/hello',
    handler: function (request, reply) {
        return reply('hello world');
    }
});

server.start((err) => {
    console.log('Server running at:', server.info.uri);
});

From the hapi example, is it possible to use hapi on firebase cloud function?

Can I use hapi without starting a server like express?


问:
why DataOutputStream is preferred in Server Client program
Why DataInputStream/DataOutputStream is used or preferred over any other stream of java like BufferedInputStream/BufferedOutputStream , BufferedReader/BufferedWriter in Socket programming like Server Client program ?

Please explain the difference between them ??

Give the detailed feature of DataOutputStream (like what it does).

And explain explicitly why & when do we need DataInputStream/DataOutputStream  ??

Thanks in Advance.

答:
I got all the answer , thanks to Roman Puchkovskiy . And I also found that DataInputStream/DataOutputStream and BufferedReader/BufferedWriter both can be used in Socket programming , but using DataInputStream/DataOutputStream is preferred , cause

" It is very convenient if you have to read/write data in some
  primitives (short/int/utf8 string/...) and not just bytes. " as Roman Puchkovskiy said.

And thanks to you all of you for coming forward to help me.


问:
mysql select only groups having certain length
Lets say, i have a table like this:

table1

```<code>  id | val
_____________
   1 | a
   2 | b
   3 | b
   4 | a
   5 | b
   6 | a
   7 | c
</code>```

and i want to have all rows grouped by val but only if the size of the group is 3. So intended result is:

```<code>[1, a], [4, a], [6, a]
[2, b], [3, b], [5, b]
</code>```

[7, c] should be ignored cause the size of it's group is less than 3.

Note, the solution with having will return one row for each group and i want to see them all.

答:
Use a subquery to identify the id values whose groups have three or more members, and then join this to the original table to restrict to the records you want in your result set.

```<code>SELECT t1.*
FROM table1 t1
INNER JOIN
(
    SELECT val
    FROM table1
    GROUP BY val
    HAVING COUNT(*) >= 3
) t2
    ON t1.val = t2.val
</code>```

Output:

Demo here:

Rextester

Body:
Lets say, i have a table like this:

table1

  id | val
_____________
   1 | a
   2 | b
   3 | b
   4 | a
   5 | b
   6 | a
   7 | c

and i want to have all rows grouped by val but only if the size of the group is 3. So intended result is:

[1, a], [4, a], [6, a]
[2, b], [3, b], [5, b]

[7, c] should be ignored cause the size of it's group is less than 3.

Note, the solution with having will return one row for each group and i want to see them all.

Body:
Use a subquery to identify the id values whose groups have three or more members, and then join this to the original table to restrict to the records you want in your result set.

SELECT t1.*
FROM table1 t1
INNER JOIN
(
    SELECT val
    FROM table1
    GROUP BY val
    HAVING COUNT(*) >= 3
) t2
    ON t1.val = t2.val

Output:

Demo here:

Rextester


答:
GROUP_CONCAT with HAVING should give yu the requested result:

```<code>select Group_concat(id), value from table group by value having Count(*)>=3
</code>```

Title: mysql select only groups having certain length

Body:
GROUP_CONCAT with HAVING should give yu the requested result:

select Group_concat(id), value from table group by value having Count(*)>=3


答:
Have a sub-query that returns all val's that occur at least 3 times:</p>

```<code>select id, val
from tablename
where val in (select val
              from tablename
              group by val
              having count(*) >= 3)
</code>```

Body:
Have a sub-query that returns all val's that occur at least 3 times:

select id, val
from tablename
where val in (select val
              from tablename
              group by val
              having count(*) >= 3)


问:
Python requests dict as form-data
I have a python dict

```<code>x = {'id': 123, 'data': {'param1': 'hello', 'param2': 'world'}}
</code>```

I'm trying to get my form-data to be

```<code>id=123
data[param1]=hello
data[param2]=world
</code>```

I cannot pass it as a json, because the API receiving it won't accept json objects

I've tried passing it like this

```<code>requests.post(url, data=x, headers={'content-type': 'application/x-www-form-urlencoded'})
</code>```

The request goes out with form data looking like this

```<code>id=123
data=param1
data=param2
</code>```

Is there a way to get around this?

答:
You can flatten-out the first level:

```<code>x = {'data': {'param1': 'hello', 'param2': 'world'}}

x_flattened = {"{}[{}]".format(e, s) if type(: x[e][s] for e in x for s in x[e]}

requests.post(url, data=x_flattened)
</code>```

edit - you've added more info to your original object in the meantime. If you want to preserve the top level singular parameters as well, you can do it in two steps (you can do it in single dict comprehension but it gets ugly quickly):

```<code>x_flattened = {}
for e in x:
    if isinstance(x[e], (list, dict)):
        x_flattened.update({"{}[{}]".format(e, s): x[e][s] for s in x[e]})
    else:
        x_flattened[e] = x[e]

requests.post(url, data=x_flattened)
</code>```

Title: Python requests dict as form-data

Body:
I have a python dict

x = {'id': 123, 'data': {'param1': 'hello', 'param2': 'world'}}

I'm trying to get my form-data to be

id=123
data[param1]=hello
data[param2]=world

I cannot pass it as a json, because the API receiving it won't accept json objects

I've tried passing it like this

requests.post(url, data=x, headers={'content-type': 'application/x-www-form-urlencoded'})

The request goes out with form data looking like this

id=123
data=param1
data=param2

Is there a way to get around this?

Body:
You can flatten-out the first level:

x = {'data': {'param1': 'hello', 'param2': 'world'}}

x_flattened = {"{}[{}]".format(e, s) if type(: x[e][s] for e in x for s in x[e]}

requests.post(url, data=x_flattened)

edit - you've added more info to your original object in the meantime. If you want to preserve the top level singular parameters as well, you can do it in two steps (you can do it in single dict comprehension but it gets ugly quickly):

x_flattened = {}
for e in x:
    if isinstance(x[e], (list, dict)):
        x_flattened.update({"{}[{}]".format(e, s): x[e][s] for s in x[e]})
    else:
        x_flattened[e] = x[e]

requests.post(url, data=x_flattened)


问:
Why are my UTF-8 filenames in bugzilla downloading as quoted-printable filenames?
I have a bugzilla install set up with English and Japanese templates to support our users in the US and Japan.  My users are having a problem with attachments that have Japanese characters in the filename; English filenames are OK.

Say I upload a file called "Blah操作手.doc".  When I go to download the file, I get a prompt asking me to save it as "=_UTF-8_Q_Blah=E6=93=8D=E4=BD=9C=E6=89=8B_=.doc".  All of the data in the file is preserved, but the filename appears to not be decoded properly.  Often, the filename ends up so long that it loses the original extension, and the user gets a page filled with garbage if they try to open the attachment in their browser.  This is happening even though the database "filename" field displays the original characters correctly.

This is happening with all types of files that contain non-ASCII characters - doc, xls, pdf, png, txt, etc.  I was able to reproduce this on the default templates for Bugzilla 3.6.3, regardless of regional settings or template language.

This is primarily a problem for Internet Explorer.  Chrome and Safari have similar problems, but I don't really have any users that use either.  Firefox works fine and returns the original filename as expected.

Is there a way I can fix this?

答: There's a very long answer to this question that somebody else may give you, but the basic problem is that there is no reasonable method of encoding UTF-8 filenames that all browsers support. I suspect that you're using IE, and it doesn't support the standard encoding method that we're using. More or less, this is something that can be worked around in Bugzilla, but we haven't done it yet. There's a bug filed for it at bugzilla.mozilla.org, but I'm not finding it at the moment.</p>


问:
PHP check payment method in returned object
I'm not so good in PHP because of the way it prints arrays. I return a var called $order, and I get the following:

```<code>{
    "id":14770,
    "parent_id":0,
    "status":"on-hold",
    "currency":"EUR",
    "version":"3.0.7",
    "prices_include_tax":true,
    "date_created":{
        "date":"2017-06-08 12:11:24.000000",
        "timezone_type":1,
        "timezone":"+00:00"
    },
    "date_modified":{
        "date":"2017-06-08 12:11:24.000000",
        "timezone_type":1,
        "timezone":"+00:00"
    },
    "discount_total":"0",
    "discount_tax":"0",
    "shipping_total":"4.09",
    "shipping_tax":"0.8589",
    "cart_tax":"1.1107",
    "total":"11.35",
    "total_tax":"1.9696",
    "customer_id":8,
    "order_key":"wc_order_59393eec03f4a",
    "payment_method":"bacs",
    "payment_method_title":"Bankoverschrijving",
    "transaction_id":"",
    "customer_user_agent":"mozilla\/5.0 (windows nt 10.0; win64; x64) applewebkit\/537.36 (khtml, like gecko) chrome\/58.0.3029.110 safari\/537.36",
    "created_via":"checkout",
    "customer_note":"",
    "date_completed":null,
    "date_paid":null,
    "cart_hash":"c517e3080e56d6d341bc93d4ff219b31",
    "number":"14770",
    "meta_data":[
        {
            "id":257891,
            "key":"_wc_customer_order_xml_export_suite_is_exported",
            "value":"0"
        },
        {
            "id":257892,
            "key":"_wc_customer_order_xml_export_suite_customer_is_exported",
            "value":"0"
        },
        {
            "id":257938,
            "key":"_billing_email-2"
        },
        {
            "id":257939,
            "key":"vat_number",
            "value":"NL234077232B02"
        },
        {
            "id":257940,
            "key":"_vat_country",
            "value":"NL"
        },
        {
            "id":257941,
            "key":"_vat_number_validated",
            "value":"valid"
        },
        {
            "id":257942,
            "key":"_customer_location_self_certified",
            "value":"no"
        },
        {
            "id":257943,
            "key":"_eu_vat_data",
            "value":{
                "eu_vat_assistant_version":"1.7.8.170421",
                "exchange_rates_provider_label":"BitPay",
                "invoice_currency":"EUR",
                "taxes":{
                    "25":{
                        "label":"21% NL BTW",
                        "vat_rate":"21.0000",
                        "country":"NL",
                        "tax_rate_class":"",
                        "tax_payable_to_country":"NL",
                        "amounts":{
                            "items_total":1.1107,
                            "shipping_total":0.8589
                        }
                    }
                },
                "vat_currency":"EUR",
                "vat_currency_exchange_rate":1,
                "vat_currency_exchange_rate_timestamp":1493135026
            }
        },
        {
            "id":257944,
            "key":"_eu_vat_evidence",
            "value":{
                "eu_vat_assistant_version":"1.7.8.170421",
                "location":{
                    "is_eu_country":1,
                    "billing_country":"NL",
                    "shipping_country":"NL",
                    "self_certified":"no"
                },
                "exemption":{
                    "vat_country":"NL",
                    "vat_number_validated":"valid"
                }
            }
        },
        {
            "id":257947,
            "key":"_wcpdf_proforma_date",
            "value":"2017-06-08 14:11:25"
        },
        {
            "id":257948,
            "key":"_wcpdf_proforma_number",
            "value":"513"
        },
        {
            "id":257949,
            "key":"_wcpdf_formatted_proforma_number",
            "value":"89000513"
        },
        {
            "id":257951,
            "key":"_order_stock_reduced",
            "value":"yes"
        }
    ],
    "line_items":{
        "17631":{

        }
    },
    "tax_lines":{
        "17633":{

        }
    },
    "shipping_lines":{
        "17632":{

        }
    },
    "fee_lines":[

    ],
    "coupon_lines":[

    ]
}
</code>```

I would like to do a check on the payment method, so I can create arguments based on that. Right now, the payment method is bacs, but how can I check that?
Any idea what I need to return for that?

答:
First of all: You have a JSON encoded object. If you want to access it, you have to decode it via json_decode():

```<code>$array = json_decode($order, true);
// If you pass true as second parameter,
// you will get an associative array instead of an object.
</code>```

What you are looking for is then

```<code>$payment_method = $array['payment_method'];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm not so good in PHP because of the way it prints arrays. I return a var called $order, and I get the following:

{
    "id":14770,
    "parent_id":0,
    "status":"on-hold",
    "currency":"EUR",
    "version":"3.0.7",
    "prices_include_tax":true,
    "date_created":{
        "date":"2017-06-08 12:11:24.000000",
        "timezone_type":1,
        "timezone":"+00:00"
    },
    "date_modified":{
        "date":"2017-06-08 12:11:24.000000",
        "timezone_type":1,
        "timezone":"+00:00"
    },
    "discount_total":"0",
    "discount_tax":"0",
    "shipping_total":"4.09",
    "shipping_tax":"0.8589",
    "cart_tax":"1.1107",
    "total":"11.35",
    "total_tax":"1.9696",
    "customer_id":8,
    "order_key":"wc_order_59393eec03f4a",
    "payment_method":"bacs",
    "payment_method_title":"Bankoverschrijving",
    "transaction_id":"",
    "customer_user_agent":"mozilla\/5.0 (windows nt 10.0; win64; x64) applewebkit\/537.36 (khtml, like gecko) chrome\/58.0.3029.110 safari\/537.36",
    "created_via":"checkout",
    "customer_note":"",
    "date_completed":null,
    "date_paid":null,
    "cart_hash":"c517e3080e56d6d341bc93d4ff219b31",
    "number":"14770",
    "meta_data":[
        {
            "id":257891,
            "key":"_wc_customer_order_xml_export_suite_is_exported",
            "value":"0"
        },
        {
            "id":257892,
            "key":"_wc_customer_order_xml_export_suite_customer_is_exported",
            "value":"0"
        },
        {
            "id":257938,
            "key":"_billing_email-2"
        },
        {
            "id":257939,
            "key":"vat_number",
            "value":"NL234077232B02"
        },
        {
            "id":257940,
            "key":"_vat_country",
            "value":"NL"
        },
        {
            "id":257941,
            "key":"_vat_number_validated",
            "value":"valid"
        },
        {
            "id":257942,
            "key":"_customer_location_self_certified",
            "value":"no"
        },
        {
            "id":257943,
            "key":"_eu_vat_data",
            "value":{
                "eu_vat_assistant_version":"1.7.8.170421",
                "exchange_rates_provider_label":"BitPay",
                "invoice_currency":"EUR",
                "taxes":{
                    "25":{
                        "label":"21% NL BTW",
                        "vat_rate":"21.0000",
                        "country":"NL",
                        "tax_rate_class":"",
                        "tax_payable_to_country":"NL",
                        "amounts":{
                            "items_total":1.1107,
                            "shipping_total":0.8589
                        }
                    }
                },
                "vat_currency":"EUR",
                "vat_currency_exchange_rate":1,
                "vat_currency_exchange_rate_timestamp":1493135026
            }
        },
        {
            "id":257944,
            "key":"_eu_vat_evidence",
            "value":{
                "eu_vat_assistant_version":"1.7.8.170421",
                "location":{
                    "is_eu_country":1,
                    "billing_country":"NL",
                    "shipping_country":"NL",
                    "self_certified":"no"
                },
                "exemption":{
                    "vat_country":"NL",
                    "vat_number_validated":"valid"
                }
            }
        },
        {
            "id":257947,
            "key":"_wcpdf_proforma_date",
            "value":"2017-06-08 14:11:25"
        },
        {
            "id":257948,
            "key":"_wcpdf_proforma_number",
            "value":"513"
        },
        {
            "id":257949,
            "key":"_wcpdf_formatted_proforma_number",
            "value":"89000513"
        },
        {
            "id":257951,
            "key":"_order_stock_reduced",
            "value":"yes"
        }
    ],
    "line_items":{
        "17631":{

        }
    },
    "tax_lines":{
        "17633":{

        }
    },
    "shipping_lines":{
        "17632":{

        }
    },
    "fee_lines":[

    ],
    "coupon_lines":[

    ]
}

I would like to do a check on the payment method, so I can create arguments based on that. Right now, the payment method is bacs, but how can I check that?
Any idea what I need to return for that?

Body:
First of all: You have a JSON encoded object. If you want to access it, you have to decode it via json_decode():

$array = json_decode($order, true);
// If you pass true as second parameter,
// you will get an associative array instead of an object.

What you are looking for is then

$payment_method = $array['payment_method'];


问:
laravel 5.0 delete and edit in database
How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?

This is my library, here I want to delete or update something from my database

```<code>@foreach ($allJobs as $job)
    <tr>
        <td><img src="{{$job->selected_icon}}" width="50" /> </td>
        <td>{{$job->jobtitle_de}}</td>
        <td>{{$job->location}}</td>
        <td><img src="{{$job->selected_image}}" width="100" /></td>
        <td>{{$job->workinghours}}</td>
        <td>{{$job->grey_header_de}}</td>
        <td>{{$job->date}}</td>
        <td>
            <a href=""><button>Edit</button></a> <a href="/delete">
            <button>Delete</button></a></td>
            <!--<td> <button type="delete" name="button"></button>-->
        <td>
        </td>
    </tr>
@endforeach
</code>```

答:
my Controller:</p>
```<code><?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use App\Jobs;

class JobController extends Controller {

/**
 * Display a listing of the resource.
 *
 * @return Response
 */
public function index()
{
    return view('library',['allJobs' => Jobs::all()]);
}

//my create function
public function create()
{
    return view('add');
}
/**
 * Store a newly created resource in storage.
 *
 * @return Response
 */
public function store(Request $request)
{
    $job = new Jobs();

    $job->jobtitle_de = array_key_exists('jobtitle_de',$_POST) ?
$_POST['jobtitle_de'] : '';
    $job->jobtitle_en = array_key_exists('jobtitle_en',$_POST) ?
$_POST['jobt'] : '';

    if (array_key_exists('place', $_POST)) {
        $places = $_POST['place'];
        $placesString = "";
        foreach ($places as $p) {
            $placesString .= $p.',';
        }
        $job->location = $placesString;
    }

    $job->workinghours = array_key_exists('workinghours',$_POST) ?
    $_POST['workinghours'] : '';
    $job->workinghours_de = array_key_exists('workinghours',$_POST) ?
    $_POST['workinghours'] : '';
    $job->selected_image= array_key_exists('selected_image',$_POST) ?
    $_POST['selected_image'] : '';
    $job->grey_header_de = array_key_exists('grey_header_de',$_POST) ?
    $_POST['grey_header_de'] : '';

    $job->selected_icon = array_key_exists('selected_icon',$_POST) ?
    $_POST['selected_icon'] : '';
    $job->selected_icon = array_key_exists('selected_icon',$_POST) ?
    $_POST['selected_icon'] : '';
    $job->selected_icon = array_key_exists('selected_icon',$_POST) ?
    $_POST['selected_icon'] : '';
    $job->selected_icon = array_key_exists('selected_icon',$_POST) ?
    $_POST['selected_icon'] : '';

    $job->date;

    if (array_key_exists('date',$_POST) && !empty($_POST['date'])) {
        $date = $_POST['date'];
        $date = explode('/',$_POST['date']);
        $newdate = $date[2]."-".$date[0]."-".$date[1];
        $job->date = $newdate;
    }

    $job->grey_header_de =  $_POST['grey_header_de'];

    if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
 === "full-time") {
        $job->workinghours = $_POST['workinghours'];
        $job->workinghours_de = "Vollzeit";
    }
    if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
 === "part-time"){
        $job->workinghours = $_POST['workinghours'];
        $job->workinghours_de = "Teilzeit";
    }
    try {
        $job->save();
    }
    catch (Exceptions $e) {
        echo $e->getMessage();
    }

    return redirect()->action('JobController@index');
}

//my edit function
public function edit($id)
{
     $job = Job::find($id);

     return view('jobs.edit', [
         'job' => $job
    ]);
}

//destroy function
public function destroy($id)
{
     Job::find($id)->delete();

    return redirect()->route('jobs');
}
</code>```

Title: laravel 5.0 delete and edit in database

Body:
How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?

This is my library, here I want to delete or update something from my database

@foreach ($allJobs as $job)

        selected_icon}}" width="50" />
        {{$job->jobtitle_de}}
        {{$job->location}}
        selected_image}}" width="100" />
        {{$job->workinghours}}
        {{$job->grey_header_de}}
        {{$job->date}}

            <button>Edit</button>
            <button>Delete</button>

@endforeach

Body:
my Controller:

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use App\Jobs;

class JobController extends Controller {

/**
 * Display a listing of the resource.
 *
 * @return Response
 */
public function index()
{
    return view('library',['allJobs' => Jobs::all()]);
}

//my create function
public function create()
{
    return view('add');
}
/**
 * Store a newly created resource in storage.
 *
 * @return Response
 */
public function store(Request $request)
{
    $job = new Jobs();

    $job->jobtitle_de = array_key_exists('jobtitle_de',$_POST) ?
$_POST['jobtitle_de'] : '';
    $job->jobtitle_en = array_key_exists('jobtitle_en',$_POST) ?
$_POST['jobt'] : '';

    if (array_key_exists('place', $_POST)) {
        $places = $_POST['place'];
        $placesString = "";
        foreach ($places as $p) {
            $placesString .= $p.',';
        }
        $job->location = $placesString;
    }

    $job->workinghours = array_key_exists('workinghours',$_POST) ?
    $_POST['workinghours'] : '';
    $job->workinghours_de = array_key_exists('workinghours',$_POST) ?
    $_POST['workinghours'] : '';
    $job->selected_image= array_key_exists('selected_image',$_POST) ?
    $_POST['selected_image'] : '';
    $job->grey_header_de = array_key_exists('grey_header_de',$_POST) ?
    $_POST['grey_header_de'] : '';

    $job->selected_icon = array_key_exists('selected_icon',$_POST) ?
    $_POST['selected_icon'] : '';
    $job->selected_icon = array_key_exists('selected_icon',$_POST) ?
    $_POST['selected_icon'] : '';
    $job->selected_icon = array_key_exists('selected_icon',$_POST) ?
    $_POST['selected_icon'] : '';
    $job->selected_icon = array_key_exists('selected_icon',$_POST) ?
    $_POST['selected_icon'] : '';

    $job->date;

    if (array_key_exists('date',$_POST) && !empty($_POST['date'])) {
        $date = $_POST['date'];
        $date = explode('/',$_POST['date']);
        $newdate = $date[2]."-".$date[0]."-".$date[1];
        $job->date = $newdate;
    }

    $job->grey_header_de =  $_POST['grey_header_de'];

    if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
 === "full-time") {
        $job->workinghours = $_POST['workinghours'];
        $job->workinghours_de = "Vollzeit";
    }
    if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
 === "part-time"){
        $job->workinghours = $_POST['workinghours'];
        $job->workinghours_de = "Teilzeit";
    }
    try {
        $job->save();
    }
    catch (Exceptions $e) {
        echo $e->getMessage();
    }

    return redirect()->action('JobController@index');
}

//my edit function
public function edit($id)
{
     $job = Job::find($id);

     return view('jobs.edit', [
         'job' => $job
    ]);
}

//destroy function
public function destroy($id)
{
     Job::find($id)->delete();

    return redirect()->route('jobs');
}


问:
Recreate the default website in IIS
I've accidentally deleted the default website in IIS; It no longer shows up in the tree of IIS manager and browsing "localhost" returns a 404 error.

I've re-installed IIS, but the default website still doesn't exist... Is it possible to recreate the default website so I can create my folder inside?

答:
Check out this answer on SuperUser:

In short: Reinstall both IIS and WAS.

In details -

Step 1

Go to "Add remove programs"
  "Turn windows features on or off"
  Remove both IIS and WAS (Windows Process Activation Service)
  Restart the PC
  Step 2

Go to "Add remove programs"
  "Turn windows features on or off"
  Turn on both IIS and WAS (Windows Process Activation Service)
  Note: Reinstalling IIS alone won't help. You have to reinstall both IIS and WAS

This approach fixed the problem for me.

OwnerDisplayName: ciclyng

Title: Recreate the default website in IIS


问:
Exception Message: Some kind of disk I/O error occurred
I am getting this error when I try to run a update query on a SQLite database. This only happens on XP (on Vista works fine). The database is created without any issue, insert also works fine.
I also checked and I have permissions and disk space available (as sqlite.org says these are possible causes).</p>

答:
One answer that has worked for me is to use the PRAGMA statement to set the journal_mode value to something other than "DELETE". You do this by issuing a PRAGMA statement such as PRAGMA journal_mode = OFF in the same way you would issue a query statement. I posted an example of this using c# at: http://www.stevemcarthur.co.uk/blog/post/some-kind-of-disk-io-error-occurred-sqlite/

Edit

Probably a better PRAGMA statement to issue is PRAGMA journal_mode = TRUNCATE rather than "OFF" as a couple of the others have suggested.


问:
Set precision for all big decimals in Ruby on Rails
Is there any way of defining a precision for all the BigDecimal numbers in Ruby or Ruby on Rails?

I setted the precision using the limit method, but that didn't seem to work out:

```<code>irb(main):003:0> BigDecimal.limit
=> 25

irb(main):004:0> num = '0.' + 0.to_s * 30 + '1'
=> "0.0000000000000000000000000000001"

irb(main):005:0> decimal = BigDecimal(num)
=> #<BigDecimal:9614780,'0.1E-30',9(45)>

irb(main):006:0> puts decimal.to_s
0.0000000000000000000000000000001
=> nil

irb(main):007:0> BigDecimal.limit
=> 25
</code>```

Did I misunderstand the usage of the limit method? Is there any other that can achieve what I want?

The app uses Ruby 2.3.4 and Rails 4.2.8

Disclaimer: I already know how to truncate and how to only set the precision for individual values. I really need a way to set this "globally" (I mean, for all the new Big Decimals I instantiate or manipulate).

Body:
Is there any way of defining a precision for all the BigDecimal numbers in Ruby or Ruby on Rails?

I setted the precision using the limit method, but that didn't seem to work out:

irb(main):003:0> BigDecimal.limit
=> 25

irb(main):004:0> num = '0.' + 0.to_s * 30 + '1'
=> "0.0000000000000000000000000000001"

irb(main):005:0> decimal = BigDecimal(num)
=> #<BigDecimal:9614780,'0.1E-30',9(45)>

irb(main):006:0> puts decimal.to_s
0.0000000000000000000000000000001
=> nil

irb(main):007:0> BigDecimal.limit
=> 25

Did I misunderstand the usage of the limit method? Is there any other that can achieve what I want?

The app uses Ruby 2.3.4 and Rails 4.2.8

Disclaimer: I already know how to truncate and how to only set the precision for individual values. I really need a way to set this "globally" (I mean, for all the new Big Decimals I instantiate or manipulate).

Body:
You can try

 2.1.7 :056 > num = '0.' + 0.to_s * 30 + '1'
 => "0.0000000000000000000000000000001"
2.1.7 :057 > decimal = BigDecimal(num)
 => #<BigDecimal:7be2178,'0.1E-30',9(45)>
2.1.7 :058 > puts decimal.to_s
0.0000000000000000000000000000001
 => nil
2.1.7 :059 > '%.2f' % decimal
 => "0.00"


问:
Class object is initialised without defining member variables
I am learning C++ and came across this code where the constructor is initialised without declaring member variables. Also, the object is created without any parameters. Wouldn't a default constructor be called instead?

Also, if this class is inherited, will the derived class have access to x and y?

// Example program

```<code>#include <iostream>
#include <string>

class game
{
public:
    game(int x = 0, int y = 100); // Do they get defined as members?
    int z;
};

game::game(int x, int y) : z(x)
{
    std::cout << x;
}

int main()
{
    game g; // passed w/o parameters.
    return 0;
}
</code>```

答:
Also the object is created without any parameters. Wouldn't a default constructor be called instead?

You declare your constructor as follows:

```<code>game(int x = 0, int y = 100);
</code>```

And the implementation:

```<code>game::game(int x, int y) : z(x)
{
    std::cout << x;
}
</code>```

Since you have specified default arguments for the constructor, when you call:

```<code>game g;
</code>```

It is the same as calling:

```<code>game g {0, 100};
</code>```

Since the default arguments are provided for the constructor.

game(int x = 0, int y = 100); // Do they get defined as members.

They don't get defined as members, unless you set their values to members in the class. x and y both go out of scope at the end of the constructor.

Also, if this class is inherited will the derived class have access to x and y?

Not directly, which you can see as follows:

```<code>class Derived : public game
{
public:
    Derived();
};

Derived::Derived() : game(100, 100) //Or whatever arguments
{
    //...
}
</code>```

Body:
I am learning C++ and came across this code where the constructor is initialised without declaring member variables. Also, the object is created without any parameters. Wouldn't a default constructor be called instead?

Also, if this class is inherited, will the derived class have access to x and y?

// Example program

#include <iostream>
#include <string>

class game
{
public:
    game(int x = 0, int y = 100); // Do they get defined as members?
    int z;
};

game::game(int x, int y) : z(x)
{
    std::cout << x;
}

int main()
{
    game g; // passed w/o parameters.
    return 0;
}

Body:
Also the object is created without any parameters. Wouldn't a default constructor be called instead?

You declare your constructor as follows:

game(int x = 0, int y = 100);

And the implementation:

game::game(int x, int y) : z(x)
{
    std::cout << x;
}

Since you have specified default arguments for the constructor, when you call:

game g;

It is the same as calling:

game g {0, 100};

Since the default arguments are provided for the constructor.

game(int x = 0, int y = 100); // Do they get defined as members.

They don't get defined as members, unless you set their values to members in the class. x and y both go out of scope at the end of the constructor.

Also, if this class is inherited will the derived class have access to x and y?

Not directly, which you can see as follows:

class Derived : public game
{
public:
    Derived();
};

Derived::Derived() : game(100, 100) //Or whatever arguments
{
    //...
}


问:
How to start Virtual Machine by command line in Ubuntu server with VMWare
I have a server with Ubuntu 16.04.2 (no UI).

I want to start a Virtual Machine inside this server. In my Windows PC I start it with VMWare UI, but I do not know how to do this via command line (I also do not know what packages are required to install in linux to achieve this). Any ideas if this is possible and how?

答:
I did not find a way to do this with VMWare, but I managed to achieve it with VirtualBox. I describe here the steps needed:

1. Convert from VMWare to VirtualBox image

Open VirtualBox. Create a new Virtual Machine and select to use an existing virtual hard drive disk. Specify the image that works for VMWare.
Once the Virtual Machine is ready select File -> Export Appliance to export the image as an ova file (in my case benchmark.ova). The next step is to upload this file to the server.

2. Install VirtualBox

```<code>sudo apt-get install virtualbox
</code>```

3. Start the Virtual Machine

```<code>VBoxManage import benchmark.ova
VBoxManage startvm "benchmark" --type headless
</code>```

(you can close it with VBoxManage controlvm "benchmark" poweroff)

Body:
I did not find a way to do this with VMWare, but I managed to achieve it with VirtualBox. I describe here the steps needed:

1. Convert from VMWare to VirtualBox image

Open VirtualBox. Create a new Virtual Machine and select to use an existing virtual hard drive disk. Specify the image that works for VMWare.
Once the Virtual Machine is ready select File -> Export Appliance to export the image as an ova file (in my case benchmark.ova). The next step is to upload this file to the server.

2. Install VirtualBox

sudo apt-get install virtualbox

3. Start the Virtual Machine

VBoxManage import benchmark.ova
VBoxManage startvm "benchmark" --type headless

(you can close it with VBoxManage controlvm "benchmark" poweroff)


问:
Bash - print all seuqential lines from file and ignore non-sequential ones
I need to extract all sequential lines from a text file based on the sequence in the 4th column. This sequence is the current time, and there is only one entry for each second (so only one line). Sometimes in the file the sequence will break, because something has slowed down the script that creates it and it has skipped a second or two. As in the below example:

```<code>Thu Jun  8 14:17:31 CEST 2017 sync:1
Thu Jun  8 14:17:32 CEST 2017 sync:1
Thu Jun  8 14:17:33 CEST 2017 sync:1
Thu Jun  8 14:17:37 CEST 2017 sync:1 <--
Thu Jun  8 14:17:38 CEST 2017 sync:1
Thu Jun  8 14:17:39 CEST 2017 sync:1
Thu Jun  8 14:17:40 CEST 2017 sync:1
</code>```

I need bash to ignore this line and continue without printing it, but still print everything before and after it. How should I go about that?

答:
If you only care about the seconds field (eg, 14:17:39 -> 15:22:40 is clearly not sequential, but this code will think it is; if your data is sufficiently simple this may be fine):

```<code>awk 'NR==1 || $6 == (p + 1)%60 ; {p=$6}' FS=':\| *' input
</code>```

To check the hour and minute, you could simply convert to seconds from midnight or add logic to compare the hours and minutes.  Something like:

```<code>awk '{s=$4 * 3600 + $5 * 60 + $6} NR==1 || s == (p + 1)%86400 ; {p=s}' FS=':\| *' input
</code>```

Body:
I need to extract all sequential lines from a text file based on the sequence in the 4th column. This sequence is the current time, and there is only one entry for each second (so only one line). Sometimes in the file the sequence will break, because something has slowed down the script that creates it and it has skipped a second or two. As in the below example:

Thu Jun  8 14:17:31 CEST 2017 sync:1
Thu Jun  8 14:17:32 CEST 2017 sync:1
Thu Jun  8 14:17:33 CEST 2017 sync:1
Thu Jun  8 14:17:37 CEST 2017 sync:1 <--
Thu Jun  8 14:17:38 CEST 2017 sync:1
Thu Jun  8 14:17:39 CEST 2017 sync:1
Thu Jun  8 14:17:40 CEST 2017 sync:1

I need bash to ignore this line and continue without printing it, but still print everything before and after it. How should I go about that?

Body:
If you only care about the seconds field (eg, 14:17:39 -> 15:22:40 is clearly not sequential, but this code will think it is; if your data is sufficiently simple this may be fine):

awk 'NR==1 || $6 == (p + 1)%60 ; {p=$6}' FS=':\| *' input

To check the hour and minute, you could simply convert to seconds from midnight or add logic to compare the hours and minutes.  Something like:

awk '{s=$4 * 3600 + $5 * 60 + $6} NR==1 || s == (p + 1)%86400 ; {p=s}' FS=':\| *' input


问:
How to disable smooth scrolling in Chrome
I'm creating a web app (that's mostly focused on usage in Chrome), but the 'smooth scrolling' (I guess that's what it's called, the 'extra' scrolling like on IOS) of Chrome (when on mac) gets in the way.

Is there any way to disable this via javascript?

答:
I was able to mitigate some rendering issues I was having with smooth scrolling by intercepting wheel events and moving the scrollTop/scrollLeft pixel positions "by hand":

```<code>function wheeled(event) {
  event.preventDefault()

  container.scrollTop += event.deltaY
  container.scrollLeft += event.deltaX
}

container.addEventListener('wheel', wheeled, { passive: false, capture: true })
// actual render code is in the `scrolled` handler because
// there are other wheel events in the code that adjust the scroll position
container.addEventListener('scroll', scrolled, { passive: true })
</code>```

Body:
I was able to mitigate some rendering issues I was having with smooth scrolling by intercepting wheel events and moving the scrollTop/scrollLeft pixel positions "by hand":

function wheeled(event) {
  event.preventDefault()

  container.scrollTop += event.deltaY
  container.scrollLeft += event.deltaX
}

container.addEventListener('wheel', wheeled, { passive: false, capture: true })
// actual render code is in the `scrolled` handler because
// there are other wheel events in the code that adjust the scroll position
container.addEventListener('scroll', scrolled, { passive: true })


问:
Create Object from non-existing Type. Understanding ChangeType/Activator
Is it possible to pass an object and it's Type parameter to an application that does not have the Type and create an instance of it?

For instance

```<code>Application A
</code>```

Has Type Foo

We instantiate it and send the value as Object and the Type to Application B

```<code>Application B
</code>```

Has no References to the type Foo

So is it possible to say System.Convert.ChangeType(object, Type) and be able to convert the object or CreateInstance to be able to make a new instance of the type?

If that is confusing then lets say, I am unsure if the ChangeType uses the Type Information to convert the type or if it does a DLL lookup for short.

答:
.NET uses type metadata from .DLL to do something with types, including object creation. So, no, .NET can't create the instance without this metadata.

Also you can't send any complex data between applications. You can only serialize the data to binary/XML/JSON/something-else format and then deserialize it.

.NET applications can serialize and deserialize standard .NET types, f.e. integers, floats, strings, dates and times, time spans, IP addressed, exceptions and so on.

If you want to support your own type, you should share it between applications. First, you can implement it in source code and plug your project to both solutions. Second, you can share DLL. At least you can pack your assembly to NuGet packet and install this packet to both solutions.

Of course you should make your type serializable.

Body:
Is it possible to pass an object and it's Type parameter to an application that does not have the Type and create an instance of it?

For instance

Application A

Has Type Foo

We instantiate it and send the value as Object and the Type to Application B

Application B

Has no References to the type Foo

So is it possible to say System.Convert.ChangeType(object, Type) and be able to convert the object or CreateInstance to be able to make a new instance of the type?

If that is confusing then lets say, I am unsure if the ChangeType uses the Type Information to convert the type or if it does a DLL lookup for short.


问:
Can't pickup all dates between two datetimepicker C# Win Forms
Have a problem with my soft... There is two datetimepickers in my app, i should make a list of dates between selected dates in my app. Also, i need to add them to Access datebase.

```<code>        DateTime start = new DateTime();
        start = dateTimePicker1.Value;
        DateTime end = new DateTime();
        end = dateTimePicker2.Value;

        Enumerable.Range(0, 1 + end.Subtract(start).Days)
        .Select(offset => start.AddDays(offset))
        .ToArray();

        var dates = new List<DateTime>();

        for (var dt = start; dt <= end; dt = dt.AddDays(1))
        {
            dates.Add(dt);
            richTextBox1.Text = dt.ToString();

        }
</code>```

Thaks a lot!
UPDATED!

答:
Change the code to:</p>

```<code>    DateTime start = new DateTime();
    start = dateTimePicker1.Value;
    DateTime end = new DateTime();
    end = dateTimePicker2.Value;

    var dates = new List<DateTime>();
    richTextBox1.Text = "";
    for (var dt = start; dt <= end; dt = dt.AddDays(1))
    {
        dates.Add(dt);
        richTextBox1.Text += dt.ToString();

    }
</code>```

Body:
Have a problem with my soft... There is two datetimepickers in my app, i should make a list of dates between selected dates in my app. Also, i need to add them to Access datebase.

        DateTime start = new DateTime();
        start = dateTimePicker1.Value;
        DateTime end = new DateTime();
        end = dateTimePicker2.Value;

        Enumerable.Range(0, 1 + end.Subtract(start).Days)
        .Select(offset => start.AddDays(offset))
        .ToArray();

        var dates = new List<DateTime>();

        for (var dt = start; dt <= end; dt = dt.AddDays(1))
        {
            dates.Add(dt);
            richTextBox1.Text = dt.ToString();

        }

Thaks a lot!
UPDATED!

Body:
Change the code to:

    DateTime start = new DateTime();
    start = dateTimePicker1.Value;
    DateTime end = new DateTime();
    end = dateTimePicker2.Value;

    var dates = new List<DateTime>();
    richTextBox1.Text = "";
    for (var dt = start; dt <= end; dt = dt.AddDays(1))
    {
        dates.Add(dt);
        richTextBox1.Text += dt.ToString();

    }


问:
Converting Every Child Tags in to a Single Column with multiple Delimiters (SQL Server)
This is my XML

```<code><plan>
  <prescription>
    <name>ABC</name>
    <frequency>Daily</frequency>
    <dailyfrequency>
       <morning>2</morning>
       <afternoon></afternoon>
       <night>1</night>
    </dailyfrequency>
  </prescription>
  <prescription>
    <name>EDF</name>
    <frequency>Daily</frequency>
    <dailyfrequency>
      <morning>5</morning>
      <afternoon>5</afternoon>
      <evening>4</evening>
      <night>1</night>
   </dailyfrequency>
   <dayfrequency></dayfrequency>
  </prescription>
  <prescription>
    <name>YTER</name>
    <frequency>Weekly</frequency>
    <dailyfrequency>
      <morning>5</morning>
      <afternoon>5</afternoon>
      <evening>4</evening>
      <night>1</night>
    </dailyfrequency>
    <dayfrequency>Monday,Tuesday,Wednesday</dayfrequency>
  </prescription>
</plan>
</code>```

I queried like the below using the Cross Join

```<code>PLAN=    STUFF(XMLData.query('for $a in
    (*:ClinicalDocuments/Visits/Visit/prescriptions/prescription)

return <a>{concat("$", $a)}</a>').value('.', 'NVARCHAR(MAX)'), 1, 1, '')
</code>```

But i result will display like this

```<code>**PLAN**
ABCDaily21$EDFDaily5541$YTERWeekly5541Monday,Tuesday,Wednesday
</code>```

But i really want to be like the below(Assume $-Column delimiter for every tag inside the prescription ,!-Column Delimiter for Each Prescription itself)

```<code>**PLAN**
ABC$Daily$2$0$0$1$0!EDF$Daily$5$5$4$1$0!YTER$Weekly$5$5$4$1$Monday,Tuesday,Wednesday
</code>```

Please anyone helps me here !

(Note:Some child tags mayn't be present i.e, indicates it dosen't have values)

Thanks Very much in advance,Jayendran

答:
The following could be what you need, but I do not really know, how you want to handle elements not present. In your sample you placed 0 instead, but this is not a missing value but a dedicated default. This would need some knowlegde about the underlying data type...

Try this:

```<code>DECLARE @xml XML=
N'<plan>
  <prescription>
    <name>ABC</name>
    <frequency>Daily</frequency>
    <dailyfrequency>
       <morning>2</morning>
       <afternoon></afternoon>
       <night>1</night>
    </dailyfrequency>
  </prescription>
  <prescription>
    <name>EDF</name>
    <frequency>Daily</frequency>
    <dailyfrequency>
      <morning>5</morning>
      <afternoon>5</afternoon>
      <evening>4</evening>
      <night>1</night>
   </dailyfrequency>
   <dayfrequency></dayfrequency>
  </prescription>
  <prescription>
    <name>YTER</name>
    <frequency>Weekly</frequency>
    <dailyfrequency>
      <morning>5</morning>
      <afternoon>5</afternoon>
      <evening>4</evening>
      <night>1</night>
    </dailyfrequency>
    <dayfrequency>Monday,Tuesday,Wednesday</dayfrequency>
  </prescription>
</plan>';
</code>```

update: added a predicate to exclude <dailyfrequence>

```<code>SELECT STUFF(
(
    SELECT '!' + STUFF(p.query(N'for $n in .//*[local-name()!="dailyfrequency"]
                           return <a>{concat("$",($n/text())[1])}</a>'
                        ).value(N'.',N'nvarchar(max)'),1,1,'')
    FROM @xml.nodes(N'/plan/prescription') AS A(p)
    FOR XML PATH(''),TYPE).value(N'.',N'nvarchar(max)'),1,1,'')
</code>```

The result

```<code>ABC$Daily$2$$1!EDF$Daily$5$5$4$1$!YTER$Weekly$5$5$4$1$Monday,Tuesday,Wednesday
</code>```

Missing values are indicated by no value.

Body:
This is my XML

<plan>
  <prescription>
    <name>ABC</name>
    <frequency>Daily</frequency>
    <dailyfrequency>
       <morning>2</morning>
       <afternoon></afternoon>
       <night>1</night>
    </dailyfrequency>
  </prescription>
  <prescription>
    <name>EDF</name>
    <frequency>Daily</frequency>
    <dailyfrequency>
      <morning>5</morning>
      <afternoon>5</afternoon>
      <evening>4</evening>
      <night>1</night>
   </dailyfrequency>
   <dayfrequency></dayfrequency>
  </prescription>
  <prescription>
    <name>YTER</name>
    <frequency>Weekly</frequency>
    <dailyfrequency>
      <morning>5</morning>
      <afternoon>5</afternoon>
      <evening>4</evening>
      <night>1</night>
    </dailyfrequency>
    <dayfrequency>Monday,Tuesday,Wednesday</dayfrequency>
  </prescription>
</plan>

I queried like the below using the Cross Join

PLAN=    STUFF(XMLData.query('for $a in
    (*:ClinicalDocuments/Visits/Visit/prescriptions/prescription)

return {concat("$", $a)}').value('.', 'NVARCHAR(MAX)'), 1, 1, '')

But i result will display like this

**PLAN**
ABCDaily21$EDFDaily5541$YTERWeekly5541Monday,Tuesday,Wednesday

But i really want to be like the below(Assume $-Column delimiter for every tag inside the prescription ,!-Column Delimiter for Each Prescription itself)

**PLAN**
ABC$Daily$2$0$0$1$0!EDF$Daily$5$5$4$1$0!YTER$Weekly$5$5$4$1$Monday,Tuesday,Wednesday

Please anyone helps me here !

(Note:Some child tags mayn't be present i.e, indicates it dosen't have values)

Thanks Very much in advance,Jayendran

Body:
The following could be what you need, but I do not really know, how you want to handle elements not present. In your sample you placed 0 instead, but this is not a missing value but a dedicated default. This would need some knowlegde about the underlying data type...

Try this:

DECLARE @xml XML=
N'<plan>
  <prescription>
    <name>ABC</name>
    <frequency>Daily</frequency>
    <dailyfrequency>
       <morning>2</morning>
       <afternoon></afternoon>
       <night>1</night>
    </dailyfrequency>
  </prescription>
  <prescription>
    <name>EDF</name>
    <frequency>Daily</frequency>
    <dailyfrequency>
      <morning>5</morning>
      <afternoon>5</afternoon>
      <evening>4</evening>
      <night>1</night>
   </dailyfrequency>
   <dayfrequency></dayfrequency>
  </prescription>
  <prescription>
    <name>YTER</name>
    <frequency>Weekly</frequency>
    <dailyfrequency>
      <morning>5</morning>
      <afternoon>5</afternoon>
      <evening>4</evening>
      <night>1</night>
    </dailyfrequency>
    <dayfrequency>Monday,Tuesday,Wednesday</dayfrequency>
  </prescription>
</plan>';

update: added a predicate to exclude <dailyfrequence>

SELECT STUFF(
(
    SELECT '!' + STUFF(p.query(N'for $n in .//*[local-name()!="dailyfrequency"]
                           return <a>{concat("$",($n/text())[1])}</a>'
                        ).value(N'.',N'nvarchar(max)'),1,1,'')
    FROM @xml.nodes(N'/plan/prescription') AS A(p)
    FOR XML PATH(''),TYPE).value(N'.',N'nvarchar(max)'),1,1,'')

The result

ABC$Daily$2$$1!EDF$Daily$5$5$4$1$!YTER$Weekly$5$5$4$1$Monday,Tuesday,Wednesday

Missing values are indicated by no value.


问:
Passing two models to the Authorize middleware (also called can)
I am trying to pass two models to the Authorize middleware, used under the name can.

routes/api.php

```<code>Route::middleware('can:reach,profile,photo')->resource('users/{user}/profiles/{profile}/photos', 'PhotoController');
</code>```

Then I try to retrieve arguments like so:

app/Policies/PhotoPolicy.php

```<code>public function reach(User $user, Profile $profile, Photo $photo)
{
    return $profile->id === $photo->profile->id;
}
</code>```

But the middleware is totally ignored. I checked the definition of the middleware and I cannot see why this would not work.

Thanks in advance.

答:
I think you have to add the middleware to the resource, not the opposite. Or, you can create a group.

Example:

```<code>Route::group(['middleware' => 'can:reach,profile,photo'], function($router){
  $router->resource('users/{user}/profiles/{profile}/photos', 'PhotoController');
});
</code>```

Body:
I am trying to pass two models to the Authorize middleware, used under the name can.

routes/api.php

Route::middleware('can:reach,profile,photo')->resource('users/{user}/profiles/{profile}/photos', 'PhotoController');

Then I try to retrieve arguments like so:

app/Policies/PhotoPolicy.php

public function reach(User $user, Profile $profile, Photo $photo)
{
    return $profile->id === $photo->profile->id;
}

But the middleware is totally ignored. I checked the definition of the middleware and I cannot see why this would not work.

Thanks in advance.

Body:
I think you have to add the middleware to the resource, not the opposite. Or, you can create a group.

Example:

Route::group(['middleware' => 'can:reach,profile,photo'], function($router){
  $router->resource('users/{user}/profiles/{profile}/photos', 'PhotoController');
});