问:
Ionic 3 app with cordova-plugin-chrome-apps-sockets-tcp. Livereload trouble
I am using cordova-plugin-chrome-apps-sockets-tcp in my android application. In this app I am trying to connect to TCP/IP server. Example of my code:

```<code>export class HomePage implements OnInit {
  constructor(public navCtrl: NavController) {}
  ngOnInit() {
    (<any>window).chrome.sockets.tcp.create({}, createInfo => {
      let socketTcpId = createInfo.socketId;
      (<any>window).chrome.sockets.tcp.connect(socketTcpId, "127.0.0.1", 12345, result => {
        console.log("Connected to server");
      });
    });
  } ...
</code>```

I uploaded this code to android emulator V 7.1.1 using command:

```<code>ionic cordova run android --prod --emulator --livereload --consolelogs
</code>```

During the first run my application succesfully connects to TCP/IP server. But if I will press CTRL-S and livereload process will starts, after reloading I see error and warn messages:

console.warn: Ionic Native: deviceready did not fire within 5000ms. This can happen when plugins are in an inconsistent state. Try removing plugins from plugins/ and reinstalling them.

Runtime Error

Uncaught (in promise): TypeError: Cannot read property 'sockets' of undefined at HomePage.ngOnInit

I tried to fix it with reinstalling of plugin, removed and added android platform, I tried to use window.plugins or window.cordova.plugins, but them are undefined and solved my problem. Can you help me, please?

After declaration of chrome variable, code:

```<code>import {
  Component,
  OnInit
} from '@angular/core';
import {
  NavController
} from 'ionic-angular';
declare var chrome;
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage implements OnInit {
  constructor(public navCtrl: NavController) {}
  ngOnInit() {
    chrome.sockets.tcp.create({}, createInfo => {
      let socketTcpId = createInfo.socketId;
      chrome.sockets.tcp.connect(socketTcpId, "127.0.0.1", 12345, result => {
        console.log("Connected to server");
      });
    });
  }...
</code>```

First run - all working. After livereload I see message: ReferenceError: chrome is not defined. After that if I will replace declaration of chrome:

```<code>} from 'ionic-angular';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
declare var chrome;
export class HomePage implements OnInit {
</code>```

it will call the Runtime error "'Home Page' declared by the module...", and after that if I will put declaration back and press CTRL-S - all will work again and I will connect to server, where am I wrong?

答:
You must call it with (<any>window)

Example:

```<code>(<any>window).chrome.sockets.tcpServer.create({}, function(createInfo) {
       alert('Created')
       this.listenAndAccept(createInfo.socketId);
});
</code>```

Body:
I am using cordova-plugin-chrome-apps-sockets-tcp in my android application. In this app I am trying to connect to TCP/IP server. Example of my code:

export class HomePage implements OnInit {
  constructor(public navCtrl: NavController) {}
  ngOnInit() {
    (<any>window).chrome.sockets.tcp.create({}, createInfo => {
      let socketTcpId = createInfo.socketId;
      (<any>window).chrome.sockets.tcp.connect(socketTcpId, "127.0.0.1", 12345, result => {
        console.log("Connected to server");
      });
    });
  } ...

I uploaded this code to android emulator V 7.1.1 using command:

ionic cordova run android --prod --emulator --livereload --consolelogs

During the first run my application succesfully connects to TCP/IP server. But if I will press CTRL-S and livereload process will starts, after reloading I see error and warn messages:

console.warn: Ionic Native: deviceready did not fire within 5000ms. This can happen when plugins are in an inconsistent state. Try removing plugins from plugins/ and reinstalling them.

Runtime Error

Uncaught (in promise): TypeError: Cannot read property 'sockets' of undefined at HomePage.ngOnInit

I tried to fix it with reinstalling of plugin, removed and added android platform, I tried to use window.plugins or window.cordova.plugins, but them are undefined and solved my problem. Can you help me, please?

After declaration of chrome variable, code:

import {
  Component,
  OnInit
} from '@angular/core';
import {
  NavController
} from 'ionic-angular';
declare var chrome;
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage implements OnInit {
  constructor(public navCtrl: NavController) {}
  ngOnInit() {
    chrome.sockets.tcp.create({}, createInfo => {
      let socketTcpId = createInfo.socketId;
      chrome.sockets.tcp.connect(socketTcpId, "127.0.0.1", 12345, result => {
        console.log("Connected to server");
      });
    });
  }...

First run - all working. After livereload I see message: ReferenceError: chrome is not defined. After that if I will replace declaration of chrome:

} from 'ionic-angular';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
declare var chrome;
export class HomePage implements OnInit {

it will call the Runtime error "'Home Page' declared by the module...", and after that if I will put declaration back and press CTRL-S - all will work again and I will connect to server, where am I wrong?

Body:
You must call it with (<any>window)

Example:

(<any>window).chrome.sockets.tcpServer.create({}, function(createInfo) {
       alert('Created')
       this.listenAndAccept(createInfo.socketId);
});


来源: stackexchange

问:
Change Button Font Style when it clicks
I want to change the button font style when it clicks how can i achieve am new in android please help </p>

```<code>   Button b1=(Button)findviewbyid(R.id.login);
</code>```

<p>how can i select from pre_installed fonts . studio 3.0 has preinstalled fonts </p>

答:
You can use this:</p>

```<code>Button b1 = (Button) findViewById( R.id.login );
b1.setOnClickListener( new OnClickListener() {

    @Override
    public void onClick(View v) {
        Typeface newFont = getResources().getFont(R.font.myfont);
        b1.setTypeface(newFont);
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Change Button Font Style when it clicks

Body:
I want to change the button font style when it clicks how can i achieve am new in android please help

   Button b1=(Button)findviewbyid(R.id.login);

how can i select from pre_installed fonts . studio 3.0 has preinstalled fonts

Body:
You can use this:

Button b1 = (Button) findViewById( R.id.login );
b1.setOnClickListener( new OnClickListener() {

    @Override
    public void onClick(View v) {
        Typeface newFont = getResources().getFont(R.font.myfont);
        b1.setTypeface(newFont);
    }
});


问:
Nativescript: how to programmatically disable / enable ScrollView scrolling?
Is there a way to programatically disable/enable ScrollView scrolling in NativeScript?</p>

答:
Angular 2 Version:

In your html:

```<code><ScrollView #scrollView >
  ...
</ScrollView>
</code>```

In your controller:

```<code>@ViewChild('scrollView') scrollView: ElementRef;

allowScrolling(e) {
    const scrollView: ScrollView = this.scrollView.nativeElement;
    if (platformModule.device.os === 'Android') {
        scrollView.nativeView.requestDisallowInterceptTouchEvent(e);
    }
    if (platformModule.device.os === 'iOS') {
        scrollView.ios.scrollEnabled = !e;
    }
}
</code>```

Body:
Angular 2 Version:

In your html:

<ScrollView #scrollView >
  ...
</ScrollView>

In your controller:

@ViewChild('scrollView') scrollView: ElementRef;

allowScrolling(e) {
    const scrollView: ScrollView = this.scrollView.nativeElement;
    if (platformModule.device.os === 'Android') {
        scrollView.nativeView.requestDisallowInterceptTouchEvent(e);
    }
    if (platformModule.device.os === 'iOS') {
        scrollView.ios.scrollEnabled = !e;
    }
}


问:
Docker with yarn
First time trying to get yarn and docker working together.
How can I stop yarn from installing the packages every single time I run docker build command?

I've found some solutions like storing node_modules in a temporary directory and then linking it, but with various packages installed I get too many errors to handle. Is there maybe a way to compare my yarn.lock with the one existing inside Docker or any other solutions?

Dockerfile:

```<code>FROM node:8.9.1-alpine

COPY package.json yarn.lock /usr/src/
RUN cd /usr/src \
    && yarn install --pure-lockfile

COPY . /usr/src
EXPOSE 3005
</code>```

With this setup I get a message saying Sending build context to Docker daemon  375.2MB, then the yarn install is run as usual, fetching the packages every single time.

答:
Definitely pay attention to docker caching. Basically you want to run the most stable instructions earlier than less stable ones. Instructions which would result in the same image changes as an earlier run should not be rerun (exluding issues with ENV/ARG instructions). But once an instruction does need to be run, all instructions following will be run regardless of what's in the cache.

.dockerignore will also help, but it can be easy for things to slip in. I've adopted the practice of inverting the file by ignoring everything and then specifying exactly what should be copied.

To minimise fetching from the web, I like using the yarn offline cache. This stores the tarballs of installed dependencies and reuses them for future installs. You get the benefit over npm rebuild of fresh installs every time (if the cache has been invalidated). You configure the offline cache with a .yarnrc file which could be in your home directory but for this purpose you keep one in your repo along with a directory to store the tarballs.

You have the option of checking-in the mirror directory to your repo. A typically large npm module install will still only be in the region of 20 megs.

If you use the files below, customised for your needs, and run yarn locally, the yarn-offline-mirror will contain the tarballs needed to install the app.

.dockerignore

```<code>*

!yarn-offline-mirror/
!src/
!package.json
!yarn.lock
!.yarnrc
</code>```

.yarnrc

```<code># THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1

yarn-offline-mirror "./yarn-offline-mirror"
</code>```

Dockerfile

```<code>ENV HOME /usr/src/
WORKDIR $HOME

# copy the tarballs
COPY ["yarn-offline-mirror", "$HOME/yarn-offline-mirror/"]

# copy files needed for the install
COPY ["package.json", "yarn.lock", ".yarnrc", "$HOME/"]

# the offline flag will mean that an error is raised if any
# module needs to be fetched remotely. It can be removed to allow
# yarn to fetch any missing modules if that was to happen.
RUN yarn --offline --frozen-lockfile --link-duplicates

# copy the rest.. could be further broken up into multiple instructions
# for cache optimisation
COPY . $HOME

CMD npm start
</code>```

Title: Docker with yarn

Body:
First time trying to get yarn and docker working together.
How can I stop yarn from installing the packages every single time I run docker build command?

I've found some solutions like storing node_modules in a temporary directory and then linking it, but with various packages installed I get too many errors to handle. Is there maybe a way to compare my yarn.lock with the one existing inside Docker or any other solutions?

Dockerfile:

FROM node:8.9.1-alpine

COPY package.json yarn.lock /usr/src/
RUN cd /usr/src \
    && yarn install --pure-lockfile

COPY . /usr/src
EXPOSE 3005

With this setup I get a message saying Sending build context to Docker daemon  375.2MB, then the yarn install is run as usual, fetching the packages every single time.

Body:
Definitely pay attention to docker caching. Basically you want to run the most stable instructions earlier than less stable ones. Instructions which would result in the same image changes as an earlier run should not be rerun (exluding issues with ENV/ARG instructions). But once an instruction does need to be run, all instructions following will be run regardless of what's in the cache.

.dockerignore will also help, but it can be easy for things to slip in. I've adopted the practice of inverting the file by ignoring everything and then specifying exactly what should be copied.

To minimise fetching from the web, I like using the yarn offline cache. This stores the tarballs of installed dependencies and reuses them for future installs. You get the benefit over npm rebuild of fresh installs every time (if the cache has been invalidated). You configure the offline cache with a .yarnrc file which could be in your home directory but for this purpose you keep one in your repo along with a directory to store the tarballs.

You have the option of checking-in the mirror directory to your repo. A typically large npm module install will still only be in the region of 20 megs.

If you use the files below, customised for your needs, and run yarn locally, the yarn-offline-mirror will contain the tarballs needed to install the app.

.dockerignore

*

!yarn-offline-mirror/
!src/
!package.json
!yarn.lock
!.yarnrc

.yarnrc

# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1

yarn-offline-mirror "./yarn-offline-mirror"

Dockerfile

ENV HOME /usr/src/
WORKDIR $HOME

# copy the tarballs
COPY ["yarn-offline-mirror", "$HOME/yarn-offline-mirror/"]

# copy files needed for the install
COPY ["package.json", "yarn.lock", ".yarnrc", "$HOME/"]

# the offline flag will mean that an error is raised if any
# module needs to be fetched remotely. It can be removed to allow
# yarn to fetch any missing modules if that was to happen.
RUN yarn --offline --frozen-lockfile --link-duplicates

# copy the rest.. could be further broken up into multiple instructions
# for cache optimisation
COPY . $HOME

CMD npm start


答:
Get the font you need as a .ttf  file and place it in your project's /assets/ directory.
Use this code to refer to the font and set it to your button:</p>

```<code>Typeface face= Typeface.createFromAsset(getAppContext().getAssets(), "LightBlueFont.ttf");
button.setTypeface(face);
</code>```

Title: Change Button Font Style when it clicks

Body:
Get the font you need as a .ttf  file and place it in your project's /assets/ directory.
Use this code to refer to the font and set it to your button:

Typeface face= Typeface.createFromAsset(getAppContext().getAssets(), "LightBlueFont.ttf");
button.setTypeface(face);


问:
using font awesome icons-navbar wont collapse
I am new to using bootstrap,I am trying to add a user icon that should collapse when a user clicks on it. when i try to add navbar-toggle to a class the user icon item disappears.If i remove it the icon appears but when i click on the icon it doesn't collapse.
what am i doing wrong? how do i get the icon to "open/collapse"

```<code><div class="navbar navbar-default navbar-inverse visible-sm" >
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand collapsed" data-toggle="collapse" data-target="#navbar-collapse-account" ><i class="fa fa-user" aria-hidden="true"></i></a> // i tried adding the class as "navbar-brand pull right navbar-toggle collapsed" but when i do this the user icon disappears
</div>
<div class="collapse navbar-collapse" id="navbar-collapse-account" data-text="Login" data-class="login"> // this part doesn't open
</div>

</div>
</div>
</div>
</code>```

答:
Hope this helps...

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>
      WebSiteName

Home

          Page 1

Page 1-1

Page 1-2

Page 1-3

Page 2

Page 3

 Sign Up

 Login

```

source: w3schools.com

Body:
I am new to using bootstrap,I am trying to add a user icon that should collapse when a user clicks on it. when i try to add navbar-toggle to a class the user icon item disappears.If i remove it the icon appears but when i click on the icon it doesn't collapse.
what am i doing wrong? how do i get the icon to "open/collapse"

 // i tried adding the class as "navbar-brand pull right navbar-toggle collapsed" but when i do this the user icon disappears

 // this part doesn't open

Body:
Hope this helps...

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home</a></li>
        <li class="dropdown">
          <a class="dropdown-toggle" data-toggle="dropdown" href="#">Page 1 <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">Page 1-1</a></li>
            <li><a href="#">Page 1-2</a></li>
            <li><a href="#">Page 1-3</a></li>
          </ul>
        </li>
        <li><a href="#">Page 2</a></li>
        <li><a href="#">Page 3</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
        <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
      </ul>
    </div>
  </div>
</nav>

</body>
</html>

source: w3schools.com


问:
Git - Forking without Github
Is the function of "forking" specific to github? or is there a purely git process for creating "copied" child repositories that can pull updates from the parent? If so, how?

EDIT : I must be confused about what git clone does then.  It was my understanding that git clone is what I do on my machine to get a local copy of the repository to make changes to, commit, and push from.  We are currently hosting our repos with gitosis.  So if I wanted to accompish a 'fork' I would clone the repository on the gitosis server itself (at the origin)?  Would that create a new git address?

答: Forking on Github is the equivalent of a simple git clone, though in the case of the fork it's more like a git clone --mirror.

ContentLicense: CC BY-SA 2.5

Title: Git - Forking without Github


问:
What's the difference between git reset --mixed, --soft, and --hard?
I'm looking to split a commit up and not sure which reset option to use.

I was looking at the page In plain English, what does "git reset" do?, but I realized I don't really understand what the git index or staging area is and thus the explanations didn't help.

Also, the use cases for --mixed and --soft look the same to me in that answer (when you want to fix and recommit). Can someone break it down even more?  I realize --mixed is probably the option to go with, but I want to know why. Lastly, what about --hard?

Can someone give me a workflow example of how selecting the 3 options would happen?

答:
Before going into these three option one must understand 3 things.

1) History/HEAD

2) Stage/index

3) Working directory

reset --soft : History changed, HEAD changed, Working directory is not changed.

reset --mixed : History changed, HEAD changed, Working directory changed with unstaged data.

reset --hard : History changed, HEAD changed, Working directory is changed with lost data.

It is always safe to go with Git --soft. One should use other option in complex requirement.

ContentLicense: CC BY-SA 4.0


问:
How to add tomcat connection pool properties to custom DataSource in Spring?
I want to have multiple DataSource in my application. Therefore cannot rely on the datasource autoconfiguration of Spring and have to create my own, like this:

```<code>        @Bean
        @Primary
        @ConfigurationProperties("spring.datasource.custom")
        public DataSource primaryDataSource() {
            return DataSourceBuilder.create().build();
        }

spring.datasource.custom.url=jdbc:mysql://localhost/tablename
spring.datasource.custom.username=root
spring.datasource.custom.password=rootpw
spring.datasource.custom.driver-class-name=com.mysql.jdbc.Driver

#the important part:
spring.datasource.custom.tomcat.test-on-borrow=true
spring.datasource.custom.tomcat.validation-query=SELECT 1
</code>```

Problem: the .tomcat.* properties are not automatically picked up.

Question: how can I get them into the DataSource?

答:
You need to create multiple Datasource beans with one of them being @Primary and you can set tomcat connection pool properties like this

```<code>@Value("${spring.datasource.custom.tomcat.validation-query}")
private String validationQuery;

@Value("${spring.datasource.custom.tomcat.test-on-borrow}")
private boolean onBorrow;

    org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
    ds.setValidationQuery(validationQuery);
    ds.setTestOnBorrow(onBorrow);
</code>```

Instead of return DataSourceBuilder.create().build(); you need to return the datasource u created above

Body:
I want to have multiple DataSource in my application. Therefore cannot rely on the datasource autoconfiguration of Spring and have to create my own, like this:

        @Bean
        @Primary
        @ConfigurationProperties("spring.datasource.custom")
        public DataSource primaryDataSource() {
            return DataSourceBuilder.create().build();
        }

spring.datasource.custom.url=jdbc:mysql://localhost/tablename
spring.datasource.custom.username=root
spring.datasource.custom.password=rootpw
spring.datasource.custom.driver-class-name=com.mysql.jdbc.Driver

#the important part:
spring.datasource.custom.tomcat.test-on-borrow=true
spring.datasource.custom.tomcat.validation-query=SELECT 1

Problem: the .tomcat.* properties are not automatically picked up.

Question: how can I get them into the DataSource?

Body:
You need to create multiple Datasource beans with one of them being @Primary and you can set tomcat connection pool properties like this

@Value("${spring.datasource.custom.tomcat.validation-query}")
private String validationQuery;

@Value("${spring.datasource.custom.tomcat.test-on-borrow}")
private boolean onBorrow;

    org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
    ds.setValidationQuery(validationQuery);
    ds.setTestOnBorrow(onBorrow);

Instead of return DataSourceBuilder.create().build(); you need to return the datasource u created above


问:
How to access direct product URL with (Not Visible Individual) in magento1.9
I need a help in magento 1.9.x
I want access Product details page via URL but Product not visible in searching and Category so for that i use 'Not Visible Individual' in Visibility section when create product from backend.

So i can't understand what i do.

Please help me.

答: Either You have to change visibility to "Catalog Search" OR Add this simple product to any configurable product.</p>


问:
C# XPath help - Expression not working
Here is an example XML doc that matches the one I am getting info from:

```<code><?xml version="1.0" standalone="yes"?>
<Products xmlns="http://tempuri.org/Products.xsd">
  <Movies>
    <Title>Title1</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title2</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title3</Title>
    <Language>French</Language>
  </Movies>
  <Books>
    <Title>BTitle1</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle2</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle3</Title>
    <Genre>SciFi</Genre>
  </Books>
  <Books>
    <Title>BTitle4</Title>
    <Genre>SciFi</Genre>
  </Books>
</Products>
</code>```

Here is my code to get all books with the genre of Suspense:

```<code>//Get state list using XPath
XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
string booksQuery = "Books[Genre = \"Suspense\"]";
XPathNodeIterator xIter = xNav.Select(booksQuery);

while (xIter.MoveNext())
{
    //do stuff with xIter.Current
}
</code>```

I have tried several queries including Products/Books[Genre = \"Suspense\"], Products/Books, ./Books, and Books. My xIter always has zero items.

I'm new to XPath, so I'm sure it's a really simple error, but maybe not. I know I can get a DataSet with the tables [Movies] and [Books] out of this XML file using myDataSet.ReadXml(myXmlPathString); so the XML file is not corrupt. If that helps any.

So, my question ... what am I doing wrong?

答: You're looking for an element called Books which isn't in a namespace. The Products element is setting the default namespace for that element and all its descendants. You'll need to use a namespace in your XPath... or use a different approach for querying, such as LINQ to XML. (Personally I find LINQ to XML much easier to deal with than XPath - especially when you need to get namespaces involved.)

Title: C# XPath help - Expression not working

Body:
Here is an example XML doc that matches the one I am getting info from:

<?xml version="1.0" standalone="yes"?>
<Products xmlns="http://tempuri.org/Products.xsd">
  <Movies>
    <Title>Title1</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title2</Title>
    <Language>English</Language>
  </Movies>
  <Movies>
    <Title>Title3</Title>
    <Language>French</Language>
  </Movies>
  <Books>
    <Title>BTitle1</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle2</Title>
    <Genre>Suspense</Genre>
  </Books>
  <Books>
    <Title>BTitle3</Title>
    <Genre>SciFi</Genre>
  </Books>
  <Books>
    <Title>BTitle4</Title>
    <Genre>SciFi</Genre>
  </Books>
</Products>

Here is my code to get all books with the genre of Suspense:

//Get state list using XPath
XPathDocument xDoc = new XPathDocument(xmlPath); //Path to my file
XPathNavigator xNav = xDoc.CreateNavigator();
string booksQuery = "Books[Genre = \"Suspense\"]";
XPathNodeIterator xIter = xNav.Select(booksQuery);

while (xIter.MoveNext())
{
    //do stuff with xIter.Current
}

I have tried several queries including Products/Books[Genre = \"Suspense\"], Products/Books, ./Books, and Books. My xIter always has zero items.

I'm new to XPath, so I'm sure it's a really simple error, but maybe not. I know I can get a DataSet with the tables [Movies] and [Books] out of this XML file using myDataSet.ReadXml(myXmlPathString); so the XML file is not corrupt. If that helps any.

So, my question ... what am I doing wrong?


问:
Javascript sort algorithm for linked sections objects array
I have the following array of objects which need to be sorted in a special way:

```<code>var sections = [
    {begin:"test3", end:"test4"},
    {begin:"test5", end:"test2"},
    {begin:"test2", end:"test3"},
];
</code>```

All sections are linked together via sectionA.end == sectionB.begin so the result of the sort operation should be:

```<code>var sectionsSorted = [
    {begin:"test5", end:"test2"},
    {begin:"test2", end:"test3"},
    {begin:"test3", end:"test4"}
];
</code>```

I want to do this in the Array.prototype.sort() method. I realised that the beginning section could be found if the begin is not an end in any section but from there on I am lot. Has anybody an idea how to implement something like this?

I did a JSFiddle: https://jsfiddle.net/fxmnxh8L/1/

答:
You can not sort the array with Array#sort, because you need to have a stable sorting with defined predecessor, item and successor, which is not given, only if you view at two elements.

So you need a different approach by chaining all parts and get then the result out of the parts.

var sections = [{ begin: "test3", end: "test4" }, { begin: "test5", end: "test2" }, { begin: "test2", end: "test3" }],
    nodes = Object.create(null),
    begin = Object.create(null),
    end = Object.create(null),
    result;

sections.forEach(function (o) {
    nodes[o.begin] = o;
    begin[o.begin] = { a: [o.begin, o.end] };
    end[o.end] = begin[o.begin];

    if (begin[o.end]) {
        begin[o.end].a.unshift(o.begin);
        begin[o.begin] = begin[o.end];
        delete begin[o.end];
        delete end[o.end];
    }

    if (end[o.begin]) {
        Array.prototype.splice.apply(begin[o.begin].a, [0, 1].concat(end[o.begin].a));
        end[o.begin].a = begin[o.begin].a;
        delete begin[o.begin];
        delete end[o.end];
    }
    delete end[o.begin];
});

result = Object.keys(begin).map(function (k) {
    return begin[k].a.slice(0, -1).map(function (n) {
        return nodes[n];
    });
});

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have the following array of objects which need to be sorted in a special way:

var sections = [
    {begin:"test3", end:"test4"},
    {begin:"test5", end:"test2"},
    {begin:"test2", end:"test3"},
];

All sections are linked together via sectionA.end == sectionB.begin so the result of the sort operation should be:

var sectionsSorted = [
    {begin:"test5", end:"test2"},
    {begin:"test2", end:"test3"},
    {begin:"test3", end:"test4"}
];

I want to do this in the Array.prototype.sort() method. I realised that the beginning section could be found if the begin is not an end in any section but from there on I am lot. Has anybody an idea how to implement something like this?

I did a JSFiddle: https://jsfiddle.net/fxmnxh8L/1/

Body:
You can not sort the array with Array#sort, because you need to have a stable sorting with defined predecessor, item and successor, which is not given, only if you view at two elements.

So you need a different approach by chaining all parts and get then the result out of the parts.

var sections = [{ begin: "test3", end: "test4" }, { begin: "test5", end: "test2" }, { begin: "test2", end: "test3" }],
    nodes = Object.create(null),
    begin = Object.create(null),
    end = Object.create(null),
    result;

sections.forEach(function (o) {
    nodes[o.begin] = o;
    begin[o.begin] = { a: [o.begin, o.end] };
    end[o.end] = begin[o.begin];

    if (begin[o.end]) {
        begin[o.end].a.unshift(o.begin);
        begin[o.begin] = begin[o.end];
        delete begin[o.end];
        delete end[o.end];
    }

    if (end[o.begin]) {
        Array.prototype.splice.apply(begin[o.begin].a, [0, 1].concat(end[o.begin].a));
        end[o.begin].a = begin[o.begin].a;
        delete begin[o.begin];
        delete end[o.end];
    }
    delete end[o.begin];
});

result = Object.keys(begin).map(function (k) {
    return begin[k].a.slice(0, -1).map(function (n) {
        return nodes[n];
    });
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Packrat: Does the order of snapshotting vs. restoring matter?
Sometimes when working with packrat, one gets this kind of output whilst checking on the status of the packrat library:

```<code>> packrat::status()

The following packages are tracked by packrat, but are no longer available in the local library nor present in your code:
                _
    viridisLite   0.2.0

You can call packrat::snapshot() to remove these packages from the lockfile, or if you intend to use these packages, use packrat::restore() to restore them to your private library.

The following packages have been updated in your library, but have not been recorded in packrat:
              library   packrat
    RSQLite       2.0        NA
    blob        1.1.0        NA
    formatR       1.5        NA

Use packrat::snapshot() to record these packages in packrat.

The following packages are out of sync between packrat and your current library:
                  packrat    library
    BH           1.65.0-1   1.60.0-2
    R6              2.2.2      2.2.0
    Rcpp          0.12.13     0.12.7
    Rfacebook      0.6.17     0.6.15
    assertthat      0.2.0        0.1
    backports       1.1.1      1.0.5
    colorspace      1.3-2      1.2-6
    curl              3.0        2.1
    dplyr           0.7.4      0.5.0
    htmltools       0.3.6      0.3.5
    httr            1.3.1      1.2.1
    jsonlite          1.5        1.4
    lazyeval        0.2.1      0.2.0
    openssl         0.9.8      0.9.4
    reshape2        1.4.2      1.4.1
    scales          0.5.0      0.4.1
    stringi         1.1.5      1.1.2
    tibble          1.3.4        1.2
    yaml           2.1.14     2.1.13

Use packrat::snapshot() to set packrat to use the current library, or use
packrat::restore() to reset the library to the last snapshot.
</code>```

My question is: Which one should one run first, restore() or snapshot()? I have looked through the packrat documentation but there doesn't seem to be a way one could carry out parameterized updates i.e. to nitpick on packages.

UPDATE:

Following Alex's suggestion below, I received this prompt:

```<code>> packrat::restore()

Adding these packages to your library:
                _
    viridisLite   0.2.0

Removing these packages from your library:
            _
    RSQLite   2.0
    blob      1.1.0
    formatR   1.5
    memoise   1.1.0

Upgrading these packages in your library:
                     from         to
    BH           1.60.0-2   1.65.0-1
    R6              2.2.0      2.2.2
    Rcpp           0.12.7    0.12.13
    Rfacebook      0.6.15     0.6.17
    assertthat        0.1      0.2.0
    backports       1.0.5      1.1.1
    colorspace      1.2-6      1.3-2
    curl              2.1        3.0
    dplyr           0.5.0      0.7.4
    glue            1.1.1      1.2.0
    htmltools       0.3.5      0.3.6
    httr            1.2.1      1.3.1
    jsonlite          1.4        1.5
    lazyeval        0.2.0      0.2.1
    openssl         0.9.4      0.9.8
    reshape2        1.4.1      1.4.2
    rlang           0.1.1      0.1.4
    scales          0.4.1      0.5.0
    stringi         1.1.2      1.1.5
    tibble            1.2      1.3.4
    yaml           2.1.13     2.1.14

Do you want to continue? [Y/n]:
</code>```

The answer is No.

What I want to do is to remove viridislite, not add it, and I want to add RSQLite, blob and formatR as suggested.

And now I'm also wondering how memoise came into the picture...

答: It depends on what do you want from packrat. If you want to load the last snapshot, use restore(). If you update a package that's used in project, and want to make new snapshot, use snapshot().

Body:
Sometimes when working with packrat, one gets this kind of output whilst checking on the status of the packrat library:

> packrat::status()

The following packages are tracked by packrat, but are no longer available in the local library nor present in your code:
                _
    viridisLite   0.2.0

You can call packrat::snapshot() to remove these packages from the lockfile, or if you intend to use these packages, use packrat::restore() to restore them to your private library.

The following packages have been updated in your library, but have not been recorded in packrat:
              library   packrat
    RSQLite       2.0        NA
    blob        1.1.0        NA
    formatR       1.5        NA

Use packrat::snapshot() to record these packages in packrat.

The following packages are out of sync between packrat and your current library:
                  packrat    library
    BH           1.65.0-1   1.60.0-2
    R6              2.2.2      2.2.0
    Rcpp          0.12.13     0.12.7
    Rfacebook      0.6.17     0.6.15
    assertthat      0.2.0        0.1
    backports       1.1.1      1.0.5
    colorspace      1.3-2      1.2-6
    curl              3.0        2.1
    dplyr           0.7.4      0.5.0
    htmltools       0.3.6      0.3.5
    httr            1.3.1      1.2.1
    jsonlite          1.5        1.4
    lazyeval        0.2.1      0.2.0
    openssl         0.9.8      0.9.4
    reshape2        1.4.2      1.4.1
    scales          0.5.0      0.4.1
    stringi         1.1.5      1.1.2
    tibble          1.3.4        1.2
    yaml           2.1.14     2.1.13

Use packrat::snapshot() to set packrat to use the current library, or use
packrat::restore() to reset the library to the last snapshot.

My question is: Which one should one run first, restore() or snapshot()? I have looked through the packrat documentation but there doesn't seem to be a way one could carry out parameterized updates i.e. to nitpick on packages.

UPDATE:

Following Alex's suggestion below, I received this prompt:

> packrat::restore()

Adding these packages to your library:
                _
    viridisLite   0.2.0

Removing these packages from your library:
            _
    RSQLite   2.0
    blob      1.1.0
    formatR   1.5
    memoise   1.1.0

Upgrading these packages in your library:
                     from         to
    BH           1.60.0-2   1.65.0-1
    R6              2.2.0      2.2.2
    Rcpp           0.12.7    0.12.13
    Rfacebook      0.6.15     0.6.17
    assertthat        0.1      0.2.0
    backports       1.0.5      1.1.1
    colorspace      1.2-6      1.3-2
    curl              2.1        3.0
    dplyr           0.5.0      0.7.4
    glue            1.1.1      1.2.0
    htmltools       0.3.5      0.3.6
    httr            1.2.1      1.3.1
    jsonlite          1.4        1.5
    lazyeval        0.2.0      0.2.1
    openssl         0.9.4      0.9.8
    reshape2        1.4.1      1.4.2
    rlang           0.1.1      0.1.4
    scales          0.4.1      0.5.0
    stringi         1.1.2      1.1.5
    tibble            1.2      1.3.4
    yaml           2.1.13     2.1.14

Do you want to continue? [Y/n]:

The answer is No.

What I want to do is to remove viridislite, not add it, and I want to add RSQLite, blob and formatR as suggested.

And now I'm also wondering how memoise came into the picture...


问:
Using application.caller to change other cells
If I for example have this in the code of a function:

```<code>If TypeOf Application.Caller Is Range Then
    Rng = Application.Caller
    With Rng
        With .Offset(0, -4)
            .Value = 0
        End With
        With .Offset(0, -6)
            .Value = 0
        End With
    End With
End If
</code>```

It returns error.

How would I go about changing the value of other cells using Application.Caller.Offset when calling a function?

答:
According to your comments, you want to use Offset with Row parameter, not column.

If you send Range("B8") to your current code, using With .Offset(0, -4) will result in an error !  Since you have 2 (for column "B") and you use Offset of -4 >> 2 - 4 = -2

= Run-Time Error

change:

```<code>With .Offset(0, -4)
</code>```

To:

```<code>With .Offset(-4, 0)
</code>```

And also:

```<code>With .Offset(0, -6)
</code>```

To:

```<code>With .Offset(-6, 0)
</code>```

You could use the code below to get the result you want:

```<code>Sub ChangeOffsetCells(Rng As Range)

With Rng
    With .Offset(-4, 0)
        .Value = 0
    End With
    With .Offset(-6, 0)
        .Value = 0
    End With
End With

End Sub
</code>```

and use the little Test sub below to test it:

```<code>Sub Test()

ChangeOffsetCells Range("B8")

End Sub
</code>```

Body:
If I for example have this in the code of a function:

If TypeOf Application.Caller Is Range Then
    Rng = Application.Caller
    With Rng
        With .Offset(0, -4)
            .Value = 0
        End With
        With .Offset(0, -6)
            .Value = 0
        End With
    End With
End If

It returns error.

How would I go about changing the value of other cells using Application.Caller.Offset when calling a function?

Body:
According to your comments, you want to use Offset with Row parameter, not column.

If you send Range("B8") to your current code, using With .Offset(0, -4) will result in an error !  Since you have 2 (for column "B") and you use Offset of -4 >> 2 - 4 = -2

= Run-Time Error

change:

With .Offset(0, -4)

To:

With .Offset(-4, 0)

And also:

With .Offset(0, -6)

To:

With .Offset(-6, 0)

You could use the code below to get the result you want:

Sub ChangeOffsetCells(Rng As Range)

With Rng
    With .Offset(-4, 0)
        .Value = 0
    End With
    With .Offset(-6, 0)
        .Value = 0
    End With
End With

End Sub

and use the little Test sub below to test it:

Sub Test()

ChangeOffsetCells Range("B8")

End Sub


问:
Pin encryption 4 digit number to hexadecimal
These are the steps the program must follow:

Request user input for 4 digit pin. [done]

Convert 4 digit pin to hexadecimal. [?]

Generate two random numbers greater than 1000 and convert to hexadecimal.[?]

Sandwich the converted pin between the two random converted numbers. [can be done]

So far the code I have is:

```<code>public static void main(String[] args)
{
    int digit = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a four digit pin:");
    digit = scan.nextInt(); // scanning for user input

    String Hexpin =Integer.toHexString(digit);
    System.out.println(Hexpin);
}
</code>```

I currently need help converting the pin to hexadecimal and generating two random numbers greater than 1000 and converting them to hexadecimal also. I can then however do the sandwich easily. I tried searching for an answer before this and cant find anything other than:

C# convert integer to hex and back again

This article however converts the int to a hex string not a decimal.

答:
Use Integer.valueOf(String.valueOf(digit), 16) to do the conversion. If you change your digitand make it String, you don't need to do the String.valueOf(...)

Result:

```<code>In: 1234
Out(hex): 4660
</code>```

Body:
These are the steps the program must follow:

Request user input for 4 digit pin. [done]

Convert 4 digit pin to hexadecimal. [?]

Generate two random numbers greater than 1000 and convert to hexadecimal.[?]

Sandwich the converted pin between the two random converted numbers. [can be done]

So far the code I have is:

public static void main(String[] args)
{
    int digit = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a four digit pin:");
    digit = scan.nextInt(); // scanning for user input

    String Hexpin =Integer.toHexString(digit);
    System.out.println(Hexpin);
}

I currently need help converting the pin to hexadecimal and generating two random numbers greater than 1000 and converting them to hexadecimal also. I can then however do the sandwich easily. I tried searching for an answer before this and cant find anything other than:

C# convert integer to hex and back again

This article however converts the int to a hex string not a decimal.

Body:
Use Integer.valueOf(String.valueOf(digit), 16) to do the conversion. If you change your digitand make it String, you don't need to do the String.valueOf(...)

Result:

In: 1234
Out(hex): 4660


问:
Since which version of GCC is C++14 supported?
I was investigating why this piece of code compiles on my PC that has GCC v7.2, but doesn't compile with our toolchain's GCC v5.4, depsite -std=c++14 -Wpedantic -pedantic-errors being passed:

```<code>#include <array>
#include <vector>
#include <tuple>
typedef std::tuple<const char *, const char *, bool> StrStrBool;

const std::vector<StrStrBool> cApIDValidTestValues {
{
    {"str1", "str2", true },
    { "str3", "str4",  false }
}
};
</code>```

The error is:

<source>:12:1: error: converting to 'std::tuple<const char*, const char*, bool>' from initializer list would use explicit constructor 'constexpr std::tuple< <template-parameter-1-1> >::tuple(_UElements&& ...) [with _UElements = {const char (&)[5], const char (&)[5], bool}; <template-parameter-2-2> = void; _Elements = {const char*, const char*, bool}]'
 };
 ^

This code is C++14 valid (explanation), so according to GCC's Standards Support page--which shows full C++14 support since GCC v5--I expected GCC v5.4 to be able to compile it.

But I was told online that it looks like the compiler of this GCC version supports C++14, but the accompanying libstdc++ is not C++14 compliant.

My related questions are:

What is the earliest GCC version that provides a C++14 compliant libstdc++ ? How do I find this out for other standards too?

Why would GCC advertise that it has C++14 support for a gcc version, but the libstdc++ shipped with it does not?

Does this indicate the gcc compiler can be used with other stdlib implementations?

答:
This code is C++14 valid (explanation),

No it isn't (that "explanation" is completely unrelated).

so according to GCC's Standards Support page--which shows full C++14 support since GCC v5

That page clearly says "For information about the status of the library implementation, please see this page." However ...

--I expected GCC v5.4 to be able to compile it.

No, because 5.4 doesn't have C++17 support, and specifically doesn't have support for the "Improving pair and tuple" feature that was added to the draft C++ standard after C++14 was released. The feature was approved by the C++ committee at the May 2015 meeting, and GCC 5.1 was released in April 2015, and the changes for the feature are far too invasive to backport to a stable release branch of GCC.  The library support page shows that libstdc++ supports it from GCC 6.1 onwards.

Body:
I was investigating why this piece of code compiles on my PC that has GCC v7.2, but doesn't compile with our toolchain's GCC v5.4, depsite -std=c++14 -Wpedantic -pedantic-errors being passed:

#include <array>
#include <vector>
#include <tuple>
typedef std::tuple<const char *, const char *, bool> StrStrBool;

const std::vector<StrStrBool> cApIDValidTestValues {
{
    {"str1", "str2", true },
    { "str3", "str4",  false }
}
};

The error is:

<source>:12:1: error: converting to 'std::tuple<const char*, const char*, bool>' from initializer list would use explicit constructor 'constexpr std::tuple< <template-parameter-1-1> >::tuple(_UElements&& ...) [with _UElements = {const char (&)[5], const char (&)[5], bool}; <template-parameter-2-2> = void; _Elements = {const char*, const char*, bool}]'
 };
 ^

This code is C++14 valid (explanation), so according to GCC's Standards Support page--which shows full C++14 support since GCC v5--I expected GCC v5.4 to be able to compile it.

But I was told online that it looks like the compiler of this GCC version supports C++14, but the accompanying libstdc++ is not C++14 compliant.

My related questions are:

What is the earliest GCC version that provides a C++14 compliant libstdc++ ? How do I find this out for other standards too?

Why would GCC advertise that it has C++14 support for a gcc version, but the libstdc++ shipped with it does not?

Does this indicate the gcc compiler can be used with other stdlib implementations?


问:
Recurrence relations in Maple using Matrices
So like the title suggests I'm doing a Project in maple that involves using recurrence.

As an ex. suppose we have an 3x3 matrix called A and we multiply it by a 3x1(B) and then add it to a 3x1(C) and the resulting matrix is used as the new B and we do the same operation over. How would I go about doing this in maple?

答:
You can do it with a procedure:

```<code>recurrence := proc(A,b,c,n)
    ## A is a k x k matrix
    ## b is a 1 x k vector
    ## c is a 1 x k vector
    ## n is the number of iterations

    local btemp, i;

    btemp := b;

    for i to n do
        btemp := A.btemp+c;
    end do;
end proc:
</code>```

Example of use:

```<code>A:= <<1,4,7>|<2,5,8>|<3,6,9>>;
b:=<1/10,1/10,1/10>;
c:=<-1,2,-2>;
seq(recurrence(A,b,c,n),n = 1..3);  ## Output the recurrence for 1,2 and 3 iterations
</code>```

Body:
You can do it with a procedure:

recurrence := proc(A,b,c,n)
    ## A is a k x k matrix
    ## b is a 1 x k vector
    ## c is a 1 x k vector
    ## n is the number of iterations

    local btemp, i;

    btemp := b;

    for i to n do
        btemp := A.btemp+c;
    end do;
end proc:

Example of use:

A:= <<1,4,7>|<2,5,8>|<3,6,9>>;
b:=<1/10,1/10,1/10>;
c:=<-1,2,-2>;
seq(recurrence(A,b,c,n),n = 1..3);  ## Output the recurrence for 1,2 and 3 iterations


问:
PayPal subscription api has stopped working
My site has been creating subscription payments for years using the classic form-post method to PayPal's cgi-bin/webscr URL.

Suddenly this has stopped working. The webscr page is called but just displays blank. Is something broken, or have PayPal changed something? There's no info to suggest the API is deprecated or anything.

I tried the "create a button" method, and using the generated html (which also calls webscr) it works. I can't use this live because some of the parameters are calculated by JS on my page, a standard button is too simplistic.

Does anyone know what's going on?

Thanks

答:
To round this off, I have discovered the cause, and it's ultimately mea culpa. I went through my code with a fine tooth comb, and for some reason the following line appeared twice in my button form html:

```<code><input type="hidden" name="cmd" value="_xclick-subscriptions">
</code>```

Probably an ancient copy-paste error. This never caused any problem until recently, but obviously there's been some tightening of validation by PayPal.

Removing the duplicate line has restored the original functionality.
Sometimes the simplest things can be the hardest to find!

Body:
To round this off, I have discovered the cause, and it's ultimately mea culpa. I went through my code with a fine tooth comb, and for some reason the following line appeared twice in my button form html:

<input type="hidden" name="cmd" value="_xclick-subscriptions">

Probably an ancient copy-paste error. This never caused any problem until recently, but obviously there's been some tightening of validation by PayPal.

Removing the duplicate line has restored the original functionality.
Sometimes the simplest things can be the hardest to find!


答:
To convert to Hexadecimal use:

```<code>String Hexpin = Integer.toHexString(digit);
</code>```

To convert back to integer use:

```<code>int numberFromHex = Integer.parseInt(Hexpin, 16);
</code>```

Be clear on what you call unusual result in your code comment.

Title: Pin encryption 4 digit number to hexadecimal

Body:
To convert to Hexadecimal use:

String Hexpin = Integer.toHexString(digit);

To convert back to integer use:

int numberFromHex = Integer.parseInt(Hexpin, 16);

Be clear on what you call unusual result in your code comment.


问:
What's the difference of <T>(a: T) => U and  => U in TypeScript
As stated in the title, if I have a function declared as below:

```<code>applyTo<T, U>(a: T): (a: T) => U
</code>```

Call the function:

```<code>applyTo(1)(x => x + '2')
</code>```

The TypeScript will show you an error:

```<code>TS2345:Argument of type '(b: number) => number' is not assignable to parameter of type 'number'.
</code>```

Change the declare of applyTo function as below code which will fix the error:

```<code>applyTo<T, U>(a: T): <T>(a: T) => U
</code>```

I dont't know why? Can you tell me their differences?

答:
The missing implementation would make things more clear but the signature ...

```<code>applyTo<T, U>(a: T): (a: T) => U
</code>```

says: "Give me some T and I'll give you back a function that takes some other T as parameter and returns some U." so you are supposed to pass as argument something of the same type T, like in:

```<code>applyTo(1)(2) // -> the result must be some U
</code>```

Since in the first call a number were passed as argument, the compiler expected another number and not a function from (x: whatever) => x + '2'.

The second signature ...

```<code>applyTo<T, U>(a: T): <T>(a: T) => U
</code>```

can be confusing just because naming, T in (a: T) => U is not necessarily the same type T in (a: T): ..., so would be better if each parameter and type parameter had a distinct name:

```<code>applyTo<T, U>(a: T): (b: T) => U
applyTo<T, U>(a: T): <S>(b: S) => U
</code>```

Now the second signature say's: "Give me some T and I'll give back a function that takes some S as parameter and returns some U"

So depending on the implementation this would be valid:

```<code>applyTo(1)        (x => x + '2')  =   ...
//  ^^^^^^        ^^^^^^^^^^^^^^
//  T is number   S is function       U is whatever;
//                from whatever to
//                string
</code>```

Title: What's the difference of <T>(a: T) => U and <a: T> => U in TypeScript

Body:
As stated in the title, if I have a function declared as below:

applyTo<T, U>(a: T): (a: T) => U

Call the function:

applyTo(1)(x => x + '2')

The TypeScript will show you an error:

TS2345:Argument of type '(b: number) => number' is not assignable to parameter of type 'number'.

Change the declare of applyTo function as below code which will fix the error:

applyTo<T, U>(a: T): <T>(a: T) => U

I dont't know why? Can you tell me their differences?

Body:
The missing implementation would make things more clear but the signature ...

applyTo<T, U>(a: T): (a: T) => U

says: "Give me some T and I'll give you back a function that takes some other T as parameter and returns some U." so you are supposed to pass as argument something of the same type T, like in:

applyTo(1)(2) // -> the result must be some U

Since in the first call a number were passed as argument, the compiler expected another number and not a function from (x: whatever) => x + '2'.

The second signature ...

applyTo<T, U>(a: T): <T>(a: T) => U

can be confusing just because naming, T in (a: T) => U is not necessarily the same type T in (a: T): ..., so would be better if each parameter and type parameter had a distinct name:

applyTo<T, U>(a: T): (b: T) => U
applyTo<T, U>(a: T): <S>(b: S) => U

Now the second signature say's: "Give me some T and I'll give back a function that takes some S as parameter and returns some U"

So depending on the implementation this would be valid:

applyTo(1)        (x => x + '2')  =   ...
//  ^^^^^^        ^^^^^^^^^^^^^^
//  T is number   S is function       U is whatever;
//                from whatever to
//                string


问:
Django QuerySet chaining, subset and caching
I know that QuerySets are lazy and they are evaluated only on certain conditions to avoid hitting the databases all the times.

What I don't know is if given a generic query set (retrieving all the items) and then using it to construct a more refined queryset (adding a filter for example) would lead to multiple sql queries or not?

Example:

```<code>all_items = MyModel.objects.all()
subset1 = all_items.filter(**some_conditions)
subset2 = subset1.filter(**other_condition)
</code>```

1) Would this create 3 different sql queries?
Or it all depends if the 3 variable are evaluated (for example iterating over them)?

2) Is this efficient or would it be better to fetch all the items, then convert them into a list and filter them in python?

答:
1) If you enumerate only the final query set subset2 then only one database query request is executed, that is optimal.

2) Avoid premature optimization (before measurement on appropriate amount of data after most of application code is written.). You never know what will be finally the most important problem if the database gets bigger. E.g. if you ask for a subset then the query is usually faster thanks to caching in the database. The amount of memory is in opposition to other optimizations. Maybe you can't hold later all data in the memory and users will access them only by a page of data. A clean readable code is more important for a later possible optimization than an optimization by 20% that must be removed later to can continue.

Other important paragraphs about (lazy) evaluation of queries:

When QuerySets are evaluated

QuerySets are lazy

Laziness in Django

Body:
I know that QuerySets are lazy and they are evaluated only on certain conditions to avoid hitting the databases all the times.

What I don't know is if given a generic query set (retrieving all the items) and then using it to construct a more refined queryset (adding a filter for example) would lead to multiple sql queries or not?

Example:

all_items = MyModel.objects.all()
subset1 = all_items.filter(**some_conditions)
subset2 = subset1.filter(**other_condition)

1) Would this create 3 different sql queries?
Or it all depends if the 3 variable are evaluated (for example iterating over them)?

2) Is this efficient or would it be better to fetch all the items, then convert them into a list and filter them in python?


问:
tmux and macOS Clipboard
Is there a reliable way to make tmux 2.5 to work with macOS clipboard?

After upgrading to 2.5 everything went downhill. I have tried every solution I have found and nothing works. Could anybody please provide me with a working sample of tmux.conf that will make it work?

I can copy from neovim inside tmux just fine. I can't copy the text using tmux itself.

Here is what I have in .tmux.conf:

```<code>setw -g mode-keys vi
bind-key -T copy-mode-vi 'v' begin-selection
bind-key -T copy-mode-vi 'y' copy-pipe-and-cancel "reattach-to-user-namespace pbcopy" \; display-message "copied to system clipboard"
</code>```

These are the errors that appear every time the session is started:

```<code>.tmux.conf:95: unknown command: begin-selection
.tmux.conf:96: unknown command: copy-pipe-and-cancel
</code>```

I have tried the following:

```<code>set-window-option -g mode-keys vi
bind-key -Tcopy-mode-vi 'v' send -X begin-selection
bind-key -Tcopy-mode-vi 'y' send -X copy-pipe-and-cancel pbcopy
</code>```

I have also tried:

```<code>bind-key -Tcopy-mode-vi 'y' send -X copy-pipe-and-cancel
</code>```

Nothing.

答:
Had a problem similar to yours.
Try reinstalling reattach-to-user-namespace

```<code>brew uninstall --force reattach-to-user-namespace
brew install reattach-to-user-namespace --with-wrap-pbcopy-and-pbpaste
</code>```

the following works for me

```<code>set-window-option -g mode-keys vi
bind-key -T copy-mode-vi 'v' send -X begin-selection
bind-key -T copy-mode-vi 'y' send -X copy-pipe-and-cancel "reattach-to-user-namespace pbcopy"
</code>```

Title: tmux and macOS Clipboard

Body:
Is there a reliable way to make tmux 2.5 to work with macOS clipboard?

After upgrading to 2.5 everything went downhill. I have tried every solution I have found and nothing works. Could anybody please provide me with a working sample of tmux.conf that will make it work?

I can copy from neovim inside tmux just fine. I can't copy the text using tmux itself.

Here is what I have in .tmux.conf:

setw -g mode-keys vi
bind-key -T copy-mode-vi 'v' begin-selection
bind-key -T copy-mode-vi 'y' copy-pipe-and-cancel "reattach-to-user-namespace pbcopy" \; display-message "copied to system clipboard"

These are the errors that appear every time the session is started:

.tmux.conf:95: unknown command: begin-selection
.tmux.conf:96: unknown command: copy-pipe-and-cancel

I have tried the following:

set-window-option -g mode-keys vi
bind-key -Tcopy-mode-vi 'v' send -X begin-selection
bind-key -Tcopy-mode-vi 'y' send -X copy-pipe-and-cancel pbcopy

I have also tried:

bind-key -Tcopy-mode-vi 'y' send -X copy-pipe-and-cancel

Nothing.

Body:
Had a problem similar to yours.
Try reinstalling reattach-to-user-namespace

brew uninstall --force reattach-to-user-namespace
brew install reattach-to-user-namespace --with-wrap-pbcopy-and-pbpaste

the following works for me

set-window-option -g mode-keys vi
bind-key -T copy-mode-vi 'v' send -X begin-selection
bind-key -T copy-mode-vi 'y' send -X copy-pipe-and-cancel "reattach-to-user-namespace pbcopy"


问:
Undertow Routing Format using Wildcards
My requirement is to serve "index.html" irrespective of what route is being set in the request. I have referenced Routing template format for undertow but to no avail. It seems to work for people. The handler looks like

```<code>PathHandler path1 = Handlers.path()
            .addPrefixPath("/*", new ResourceHandler(new FileResourceManager(new File(System.getProperty("user.dir")+"ed.jpg"), 100 * 1024)).setWelcomeFiles("index.html") );
</code>```

And the handler is being added like

```<code>server = Undertow
                    .builder()
                    .addHttpListener(serverConfig.getHttpPort(), serverConfig.getHost())
                    .addAjpListener(serverConfig.getAjpPort(), serverConfig.getHost())
                    .setHandler(path1)
                    .build();
</code>```

I have tried using PathResourceManager as well. That doesn't work. The handler is able to match paths without wildcards perfectly. Only cases with wildcard character seems to fail.

Any help on this would be appreciated.

答:
You do not want to use a PathHandler.

Instead, serve your HTML file with a ResourceManager directly from a custom handler, like this:

```<code>ResourceManager rm = new PathResourceManager(Paths.get("/path/to/your/folder"));
Resource r = rm.getResource("index.html");
Undertow.builder()
    .addHttpListener(8080, "0.0.0.0")
    .setHandler(Handlers.predicate(
        ex -> ex.getRequestMethod().equals(Methods.GET),
        ex -> r.serve(ex.getResponseSender(), ex, IoCallback.END_EXCHANGE),
        ResponseCodeHandler.HANDLE_405)
    ).build().start();
</code>```

Note1: I have added a simple check to the request verb/method with a predicate, to only allow GET requests and fallback to a simple 405 response.

Note2: you might want to dispatch the handler that serves the HTML file to a worker thread.

Title: Undertow Routing Format using Wildcards

Body:
My requirement is to serve "index.html" irrespective of what route is being set in the request. I have referenced Routing template format for undertow but to no avail. It seems to work for people. The handler looks like

PathHandler path1 = Handlers.path()
            .addPrefixPath("/*", new ResourceHandler(new FileResourceManager(new File(System.getProperty("user.dir")+"ed.jpg"), 100 * 1024)).setWelcomeFiles("index.html") );

And the handler is being added like

server = Undertow
                    .builder()
                    .addHttpListener(serverConfig.getHttpPort(), serverConfig.getHost())
                    .addAjpListener(serverConfig.getAjpPort(), serverConfig.getHost())
                    .setHandler(path1)
                    .build();

I have tried using PathResourceManager as well. That doesn't work. The handler is able to match paths without wildcards perfectly. Only cases with wildcard character seems to fail.

Any help on this would be appreciated.

Body:
You do not want to use a PathHandler.

Instead, serve your HTML file with a ResourceManager directly from a custom handler, like this:

ResourceManager rm = new PathResourceManager(Paths.get("/path/to/your/folder"));
Resource r = rm.getResource("index.html");
Undertow.builder()
    .addHttpListener(8080, "0.0.0.0")
    .setHandler(Handlers.predicate(
        ex -> ex.getRequestMethod().equals(Methods.GET),
        ex -> r.serve(ex.getResponseSender(), ex, IoCallback.END_EXCHANGE),
        ResponseCodeHandler.HANDLE_405)
    ).build().start();

Note1: I have added a simple check to the request verb/method with a predicate, to only allow GET requests and fallback to a simple 405 response.

Note2: you might want to dispatch the handler that serves the HTML file to a worker thread.


问:
Server load Database vs. File Operation
I am trying to figure out which bears a heavier load on a system:

A database operation

OR a File operation (AKA reading an XML file)

Thanks in advance!

答: Could be either, it depends on so many things. Is the database in-memory or not? When you say "file operation" do you mean just reading the raw bytes from the file or do you include parsing through those raw bytes for the data? There's just not enough data to go on.</p>

Title: Server load Database vs. File Operation


问:
Connection between programs over the network
I want to dive into the whole diversity of tools which provide connection between programs over the network.

To clarify the question, I divide it on subquestions:

Why some groups of programs (or specific tools/frameworks/approaches with programming languages where this frameworks can be used) were popular in each period of time? (I expect description of problems which were solved, description of tools, why those tools are considered as best solution to those problems at that time, why some tools lost popularity)

What is the entire history of software communication over the network? (tools/approaches popularity precisely to decades)

What are the modern solutions to this problem?

I can distinguish only two significant approaches.

RPC, RMI and their implementations (I saw this, but it is about concrete problem and specific tools to solve this problem, I want to see the place of this problem in the whole picture of interconnection programs over the network. I heard about implementations: ONC RPC, XML-RPC, CORBA, DCOM, gRPC, but which are active now? which are reasonable to use? which are preferable and why? I want answers not to be opinion based, so I accept answers like "technology A better than technology B for problem X because ..." only if there is reliable research/statistics or facts). I heard that RPC and RMI were popular 10 years ago. Are they still?

Web services: REST, SOAP.

Am I miss something? Maybe there are some technologies which solve problem completely new way? Maybe there are technologies which can be treated as replacement to RPC(RMI) and Web Services? Can we replace RPC(RMI) by REST for any task? Can we replace RPC(RMI) by REST only for modern tasks? Should I separate technologies not as RPC and Web Services, but in some other manner?

答:
As a partial answer, I can give you my feedback on the use of RabbitMQ.
As explain here, it provides a lot of different ways to use it :

RPC by implementing a "callback" queue

One to one, one to many routing strategy to propagate your events through your whole infrastructure and target the right destination.

It comes with the ability to persist messages to avoid loosing data when a crash appears but also with some plugins to increase possibilities (e.g x-delayed plugin)

This technologie written in Erlang is powerful and is a must try in term of communication between programs.


问:
Error in initialization of custom array adapter

I am trying to make a custom listview. The list is declared as below

```<code>List<DocRow> doctors = new ArrayList<>();
</code>```

This list is then being populated.

My custom array adapter is in a separate class with its constructor declared as below.

```<code>public class DocAdapter extends ArrayAdapter<DocRow>{
    Context context;
    int resource;
    ArrayList<DocRow> doctors;
    private LayoutInflater inflater;

    public DocAdapter(@NonNull Context context, @LayoutRes int resource, ArrayList<DocRow> doctors) {
        super(context, resource, doctors);
        this.context = context;
        this.resource = resource;
        this.doctors = doctors;
        inflater = LayoutInflater.from(context);
    }
</code>```

Now in my main activity, I am trying to create a new custom array adapter by passing off my list (which is a valid parameter), it isn't accepted. The code for creation and setting of adapter for linking the listview with the list is below.

```<code>DocAdapter adapter = new DocAdapter(getApplicationContext(), R.layout.doc_row, doctors);
docList.setAdapter(adapter);
</code>```

Can anyone explain what is the issue? The link for error screenshot is above. I tried searching for this specific issue, but haven't been able to find a solution that works.

答:
Change your constructor argument to List instead of ArrayList as you are passing list in it.

```<code> List<DocRow> doctors;

 public DocAdapter(@NonNull Context context, @LayoutRes int resource, List<DocRow> doctors) {
        super(context, resource, doctors);
        this.context = context;
        this.resource = resource;
        this.doctors = doctors;
        inflater = LayoutInflater.from(context);
    }
</code>```

As pointed by @Tim, here is a little detail about why this is needed.

When an instance is initialized, it may be initialized with one of its child classes but the object remains an instance of Super class only(Due to runtime polymorphism) and therefore the methods that consume this instance either expect super class or the instance should be casted to superclass before passing it on.

The easiest way to identify is to always look at the type on the left-hand side instead.

```<code>List a=new ArrayList();
</code>```

In above example, the instance is actually an arraylist but it is of Type List.

Body:
I am trying to make a custom listview. The list is declared as below

List<DocRow> doctors = new ArrayList<>();

This list is then being populated.

My custom array adapter is in a separate class with its constructor declared as below.

public class DocAdapter extends ArrayAdapter<DocRow>{
    Context context;
    int resource;
    ArrayList<DocRow> doctors;
    private LayoutInflater inflater;

    public DocAdapter(@NonNull Context context, @LayoutRes int resource, ArrayList<DocRow> doctors) {
        super(context, resource, doctors);
        this.context = context;
        this.resource = resource;
        this.doctors = doctors;
        inflater = LayoutInflater.from(context);
    }

Now in my main activity, I am trying to create a new custom array adapter by passing off my list (which is a valid parameter), it isn't accepted. The code for creation and setting of adapter for linking the listview with the list is below.

DocAdapter adapter = new DocAdapter(getApplicationContext(), R.layout.doc_row, doctors);
docList.setAdapter(adapter);

Can anyone explain what is the issue? The link for error screenshot is above. I tried searching for this specific issue, but haven't been able to find a solution that works.

Body:
Change your constructor argument to List instead of ArrayList as you are passing list in it.

 List<DocRow> doctors;

 public DocAdapter(@NonNull Context context, @LayoutRes int resource, List<DocRow> doctors) {
        super(context, resource, doctors);
        this.context = context;
        this.resource = resource;
        this.doctors = doctors;
        inflater = LayoutInflater.from(context);
    }

As pointed by @Tim, here is a little detail about why this is needed.

When an instance is initialized, it may be initialized with one of its child classes but the object remains an instance of Super class only(Due to runtime polymorphism) and therefore the methods that consume this instance either expect super class or the instance should be casted to superclass before passing it on.

The easiest way to identify is to always look at the type on the left-hand side instead.

List a=new ArrayList();

In above example, the instance is actually an arraylist but it is of Type List.


问:
UINavigation controller: present and dismiss programmatically
I have a TableViewController which I want to present modally and I need it to have a NavigationBar.

To get that navbar, I have an embedded UINavigationController and as far as I know, that UINavigationController is what I have to present modally, so that's what I've done.

Everything works just fine, but I can't manage to dismiss that controller properly. Here is what I've got so far:

```<code>func presentErrorMessages(errorMessages: [String]) {
    let storyBoard: UIStoryboard = UIStoryboard(name: "Message", bundle: nil)

    let infoMessagesNavigationViewController = storyBoard.instantiateViewController(withIdentifier: "InfoMessagesNavigation") as! ModalNavigationController

    let infoMessagesTableViewController = infoMessagesNavigationViewController.viewControllers[0] as! InfoMessagesTableViewController
    infoMessagesTableViewController.errorMessages = errorMessages

    self.navigationController?.present(infoMessagesNavigationViewController, animated: true)
}
</code>```

I use that to present ModalNavigationController, and this to dismiss it:

```<code>class ModalNavigationController: BaseNavigationController {

    var backNavItem = UINavigationItem()
    var okNavItem = UINavigationItem()

    override func viewDidLoad() {
        super.viewDidLoad()

        let backButton = UIBarButtonItem(title: "Back", style: .plain, target: self, action:  #selector(dismissModal))
        backNavItem.leftBarButtonItem = backButton

        ...

        var items = [UINavigationItem]()
        items.append(backNavItem)

        self.navigationBar.items = items
    }

    @objc func dismissModal() {
        self.dismiss(animated: true)
    }
}
</code>```

When I press that back button, there is no change but the navbar which gets blank (with no title). I have the feeling that the application just 'forgets' what is the NavigationController used before the new one is presented.

How can I solve this?

答:
I managed to solve the problem by placing and invoking the dismissfunction on my TableViewController rather than my NavigationController:

```<code>...
public func setBackButton(){
    if self.navigationController != nil {
        let item = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(dismissModal))
        self.navigationItem.leftBarButtonItem = item
    }
}

@objc func dismissModal() {
    self.dismiss(animated: true)
}
</code>```

Body:
I have a TableViewController which I want to present modally and I need it to have a NavigationBar.

To get that navbar, I have an embedded UINavigationController and as far as I know, that UINavigationController is what I have to present modally, so that's what I've done.

Everything works just fine, but I can't manage to dismiss that controller properly. Here is what I've got so far:

func presentErrorMessages(errorMessages: [String]) {
    let storyBoard: UIStoryboard = UIStoryboard(name: "Message", bundle: nil)

    let infoMessagesNavigationViewController = storyBoard.instantiateViewController(withIdentifier: "InfoMessagesNavigation") as! ModalNavigationController

    let infoMessagesTableViewController = infoMessagesNavigationViewController.viewControllers[0] as! InfoMessagesTableViewController
    infoMessagesTableViewController.errorMessages = errorMessages

    self.navigationController?.present(infoMessagesNavigationViewController, animated: true)
}

I use that to present ModalNavigationController, and this to dismiss it:

class ModalNavigationController: BaseNavigationController {

    var backNavItem = UINavigationItem()
    var okNavItem = UINavigationItem()

    override func viewDidLoad() {
        super.viewDidLoad()

        let backButton = UIBarButtonItem(title: "Back", style: .plain, target: self, action:  #selector(dismissModal))
        backNavItem.leftBarButtonItem = backButton

        ...

        var items = [UINavigationItem]()
        items.append(backNavItem)

        self.navigationBar.items = items
    }

    @objc func dismissModal() {
        self.dismiss(animated: true)
    }
}

When I press that back button, there is no change but the navbar which gets blank (with no title). I have the feeling that the application just 'forgets' what is the NavigationController used before the new one is presented.

How can I solve this?

Body:
I managed to solve the problem by placing and invoking the dismissfunction on my TableViewController rather than my NavigationController:

...
public func setBackButton(){
    if self.navigationController != nil {
        let item = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(dismissModal))
        self.navigationItem.leftBarButtonItem = item
    }
}

@objc func dismissModal() {
    self.dismiss(animated: true)
}


问:
message queue thinking
We have implemented a message queue by using C# Queue. We know we only have ONE consumer to take available message out from the queue for processing with a while loop. We also know there is only ONE producer to put message onto the queue.

We have a lock on above message queue to make sure the consumer and producer cannot access the queue simultaneously.

My question is is that lock necessary? If the Queue increase its Count property AFTER an item is actually added and if the consumer check the Count before retrieve, the consumer should get a complete message item even we don't have that lock. Right? So we will not face a partial message item issue. Then we can get rid of that lock?

That lock will slow down the system and occasionally we can see the retrieve thread is blocked for a while because we have a very heavy producer.

EDIT:

Unfortunately we are using .Net 3.5.

答: See ConcurrentQueue.</p>

Title: message queue thinking

Body: See ConcurrentQueue.


问:
How to pass the values from one activity to previous activity
How do I pass a value from one screen to its previous screen?

Consider this case: I have two activities. The first screen has one TextView and a button and the second activity has one EditText and a button.

If I click the first button then it has to move to second activity and here user has to type something in the text box. If he presses the button from the second screen then the values from the text box should move to the first activity and that should be displayed in the first activity TextView.

答:
The best way to do here is to put variable to a common class which is defined outside the scope

```<code>public class Utils
{
    public static String mPosition;
}
</code>```

inside your code (e.g. OnButtonClick etc...)

```<code>Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
Utils.mPosition = mViewData.mPosition + "";
LogHelper.e(TAG, "before intent: " + Utils.mPosition);
startActivityForResult(intent, Keys.PICK_CONTACT);
</code>```

inside the code of

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == Keys.PICK_CONTACT)
        {
            if (resultCode == Activity.RESULT_OK)
            {
                Uri contactData = data.getData();

```<code>            //you may use the variable here after intent result
            LogHelper.e(TAG, "after intent: " + Utils.mPosition);
....
</code>```

Body:
The best way to do here is to put variable to a common class which is defined outside the scope

public class Utils
{
    public static String mPosition;
}

inside your code (e.g. OnButtonClick etc...)

Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
Utils.mPosition = mViewData.mPosition + "";
LogHelper.e(TAG, "before intent: " + Utils.mPosition);
startActivityForResult(intent, Keys.PICK_CONTACT);

inside the code of

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == Keys.PICK_CONTACT)
        {
            if (resultCode == Activity.RESULT_OK)
            {
                Uri contactData = data.getData();

            //you may use the variable here after intent result
            LogHelper.e(TAG, "after intent: " + Utils.mPosition);
....


问:
could not deserialize] with root cause java.io.EOFException: null
I have seen some questions on this subject but I have not got any valid solution for my case

I'm having an exception with jason serialization I have the following classes

when I do a GET Pacientes I have an exception of the serialization privilege type

```<code>2017-11-14 08:54:35.039  INFO 8724 --- [nio-8080-exec-1] o.h.e.internal.DefaultLoadEventListener  : HHH000327: Error performing load command : org.hibernate.type.SerializationException: could not deserialize
2017-11-14 08:54:35.047 ERROR 8724 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause

    java.io.EOFException: null
        at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream.readStreamHeader(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream.<init>(Unknown Source) ~[na:1.8.0_144]
        at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
</code>```

I'm using framwork Spring boot with spring data jpa

class Paciente

```<code>import java.io.Serializable;
import java.math.BigInteger;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import digifred.model.global.Entidades;
import digifred.model.global.IdentidadesGenero;
import digifred.model.global.OrientacoesSexuais;
import digifred.model.global.Pessoas;

@Entity
@Table(name = "pacientes", schema = "sau")
public class Pacientes implements Serializable  {

    private static final long serialVersionUID = 5776384003601026304L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idPaciente")
    private Long idPaciente;

    @JoinColumn(name="id_entidade")
    @ManyToOne(cascade = CascadeType.ALL)
    private Entidades entidade;

    @Basic(optional = false)
    @JoinColumn(name="idPessoa")
    @ManyToOne(cascade = CascadeType.ALL)
    private Pessoas pessoa;

    @Column(name = "idResponsavel_familiar")
    private BigInteger responsavelFamiliar;

    @Column(name = "nomeResponsavel")
    private String nomeResponsavel;

    @Column(name = "cpfResponsavel")
    private String cpfResponsavel;

    @Column(name = "cnsResponsavel")
    private String cnsResponsavel;

    @Column(name = "flagAlergico")
    private Integer flagAlergico;

    @Column(name = "observacoesAlergias")
    private String observacoesAlergias;

    @Column(name = "microarea")
    private String microarea;

    @Column(name = "idDomicilio")
    private Long idDomicilio;

    @JoinColumn(name="idOrientacaoSexual")
    @ManyToOne
    private OrientacoesSexuais orientacaoSexual;

    @JoinColumn(name="idIdentidadeGenero", insertable=false, updatable=false)
    @ManyToOne
    private IdentidadesGenero identidadeGenero;

    @Basic(optional = false)
    @Column(name = "flag_ativo")
    private int flagAtivo;

    @JoinColumn(name="idArea")
    @ManyToOne
    private Areas area;

    @JoinColumn(name="idFamilia")
    @ManyToOne
    private Familias familia;

    public Pacientes() {
    }

 getters and setters
}
</code>```

答: You can’t simply transfer database entities over a REST interface, you have to create DTOs and transfer them instead of your entities.</p>

Body:
I have seen some questions on this subject but I have not got any valid solution for my case

I'm having an exception with jason serialization I have the following classes

when I do a GET Pacientes I have an exception of the serialization privilege type

2017-11-14 08:54:35.039  INFO 8724 --- [nio-8080-exec-1] o.h.e.internal.DefaultLoadEventListener  : HHH000327: Error performing load command : org.hibernate.type.SerializationException: could not deserialize
2017-11-14 08:54:35.047 ERROR 8724 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause

    java.io.EOFException: null
        at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream.readStreamHeader(Unknown Source) ~[na:1.8.0_144]
        at java.io.ObjectInputStream.<init>(Unknown Source) ~[na:1.8.0_144]
        at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
        at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]

I'm using framwork Spring boot with spring data jpa

class Paciente

import java.io.Serializable;
import java.math.BigInteger;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import digifred.model.global.Entidades;
import digifred.model.global.IdentidadesGenero;
import digifred.model.global.OrientacoesSexuais;
import digifred.model.global.Pessoas;

@Entity
@Table(name = "pacientes", schema = "sau")
public class Pacientes implements Serializable  {

    private static final long serialVersionUID = 5776384003601026304L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idPaciente")
    private Long idPaciente;

    @JoinColumn(name="id_entidade")
    @ManyToOne(cascade = CascadeType.ALL)
    private Entidades entidade;

    @Basic(optional = false)
    @JoinColumn(name="idPessoa")
    @ManyToOne(cascade = CascadeType.ALL)
    private Pessoas pessoa;

    @Column(name = "idResponsavel_familiar")
    private BigInteger responsavelFamiliar;

    @Column(name = "nomeResponsavel")
    private String nomeResponsavel;

    @Column(name = "cpfResponsavel")
    private String cpfResponsavel;

    @Column(name = "cnsResponsavel")
    private String cnsResponsavel;

    @Column(name = "flagAlergico")
    private Integer flagAlergico;

    @Column(name = "observacoesAlergias")
    private String observacoesAlergias;

    @Column(name = "microarea")
    private String microarea;

    @Column(name = "idDomicilio")
    private Long idDomicilio;

    @JoinColumn(name="idOrientacaoSexual")
    @ManyToOne
    private OrientacoesSexuais orientacaoSexual;

    @JoinColumn(name="idIdentidadeGenero", insertable=false, updatable=false)
    @ManyToOne
    private IdentidadesGenero identidadeGenero;

    @Basic(optional = false)
    @Column(name = "flag_ativo")
    private int flagAtivo;

    @JoinColumn(name="idArea")
    @ManyToOne
    private Areas area;

    @JoinColumn(name="idFamilia")
    @ManyToOne
    private Familias familia;

    public Pacientes() {
    }

 getters and setters
}


问:
Application-Integrated "Send Feedback"
I'm looking for an .jar or library project that will allow users of my application to easily send feedback from inside the application about their experience.

As asked in this question, I am looking for something similar to the crash reporting tool used in Google Plus, that allows the user to get in contact with me, besides leaving bad reviews.

Some not-quite there solutions that came up in answers to other questions:

ACRA : Application Crash Report for Android (functions as a crash reporting tool)

Hockey Kit: Helps distribute betas, nothing related to send feedback to developer.

Does a library like this exist? Is there an easy way to gather user feedback from within the application?

答: i think you need to use a tool like instabug it provides you a way for collecting bug reports and feedbacks about user experience and also you can talk back to them  </p>

Title: Application-Integrated "Send Feedback"


问:
Prototype Events: Use Input Value From When Event is Created
I have recently read how to do this but cannot for the life of me find it again!

Basically, I'm creating some events that listen to form inputs and update their values when triggered. How do I pass the initial input value (the value of the input when the event is created) to the event so that I can compare it with the current value?

答:
Just store it in a variable outside the event handling closure, like this:

```<code>var original = $('someinput').getValue();
$('someinput').observe('whatever_event', function(ev) {
    $('someinput').getValue(); // contains current value
    original; // contains original value
});
</code>```

UPDATE: Replaced the above code with Prototype. jQuery version below for reference.

```<code>var original = $('#someinput').val();
$('#someinput').whatever_event(function(ev) {
    this.val(); // contains current value
    original; // contains original value
});
</code>```

Body:
Just store it in a variable outside the event handling closure, like this:

var original = $('someinput').getValue();
$('someinput').observe('whatever_event', function(ev) {
    $('someinput').getValue(); // contains current value
    original; // contains original value
});

UPDATE: Replaced the above code with Prototype. jQuery version below for reference.

var original = $('#someinput').val();
$('#someinput').whatever_event(function(ev) {
    this.val(); // contains current value
    original; // contains original value
});