问:
embed PHP in react js
I'm adding react.js to a section of my app and am trying to embed some php code into react.js in order to not have to rewrite my whole backend which I had written in php. The idea would be something like the following:

```<code>...render(){
  return(
    <h1><?php echo "hello world"; ?></h1>
  )
}...
</code>```

Unfortunately, this does not compile. I have tried every possible permutation I can think of and nothing will work, yet I feel this must be possible. Thanks!

Felix

答:
You could have PHP output your JS but you absolutely positively shouldn't. You could also make ajax calls like everyone else to fetch data from external sources such as a PHP script.

Maybe something along the lines of:

```<code>...componentDidMount() {
    fetch("http://example.com/data.php")
    .then(response => response.json())
    .then(result => this.setState(result));
}...

...render() {
    return(
       <div>{this.state.result && this.state.result.foo}</div>
    );
}...
</code>```

You're going to need to rebuild your current HTML output from PHP as React components. PHP now becomes a web service that looks something like this:

<?php
// Business logic goes here:
$data=new stdClass();
$data->name="Uzebeckatrente";
$data->foo="bar";
echo json_encode($data);

Lumen/Laravel is my personal choice of PHP platforms for web services.

Title: embed PHP in react js

Body:
I'm adding react.js to a section of my app and am trying to embed some php code into react.js in order to not have to rewrite my whole backend which I had written in php. The idea would be something like the following:

...render(){
  return(

<?php echo "hello world"; ?>

  )
}...

Unfortunately, this does not compile. I have tried every possible permutation I can think of and nothing will work, yet I feel this must be possible. Thanks!

Felix

Body:
You could have PHP output your JS but you absolutely positively shouldn't. You could also make ajax calls like everyone else to fetch data from external sources such as a PHP script.

Maybe something along the lines of:

...componentDidMount() {
    fetch("http://example.com/data.php")
    .then(response => response.json())
    .then(result => this.setState(result));
}...

...render() {
    return(
       <div>{this.state.result && this.state.result.foo}</div>
    );
}...

You're going to need to rebuild your current HTML output from PHP as React components. PHP now becomes a web service that looks something like this:

<?php
// Business logic goes here:
$data=new stdClass();
$data->name="Uzebeckatrente";
$data->foo="bar";
echo json_encode($data);

Lumen/Laravel is my personal choice of PHP platforms for web services.


来源: stackexchange

问:
Shell - variable assign output failed with VOLUME="$(sox $1 -n stat -v)"?
I want to batch processing a bunch of wav files with SoX (to Adjust their volume). I face a problem with assign the Volume Adjustment output from sox file.wav -n stat -v. I tried with this:

I found there are many examples on web about this operation, but these examples are not so complex like data=$(data). I tried VOLUME_ADJUST="$(sox  $1 -n stat -v)" but the result output to my terminal not assign to the variable. When I echo it nothing shows up.

Thanks for your suggestion.
My code is as follows:

```<code>#!/bin/sh

RED='\033[0;31m'
NC='\033[0m'
BLUE='\033[0;34m'
GREEN='\033[0;32m'

Process () {
    printf "Process with ${RED}$1${NC}\n";
    printf "Volume up as high as possible?[y/n]";
    read PASS;
    if test "$PASS" = "y"; then
        a="$(date)"
        VOLUME="$(sox "$1" -n stat -v)"
        #echo $VOLUME
        # eval "sox -v $VOLUME_ADJUST $1 $1"
        #printf $?
    elif test "$PASS" = "n"; then
        printf "${GREEN}Volume up skipped.${NC}"
    fi
}

Process "test.wav"
</code>```

Here is a pastebin to all of my code

答:
Here is my understanding.

For some reason sox print data in the stderr but not stdout. When we get value from a command like var=$(date) the message from stdout is assigned to the variable but message from stderr will not be assigned to. In order to get the value, it is easy to redirect stderr to stdout: just add 2>&1 after the command. In addtion we can direct stdout to stderr, like var=$(date 1>&2) the result printed and nothing in $var if we echo it.

ContentLicense: CC BY-SA 3.0

Body:
I want to batch processing a bunch of wav files with SoX (to Adjust their volume). I face a problem with assign the Volume Adjustment output from sox file.wav -n stat -v. I tried with this:

I found there are many examples on web about this operation, but these examples are not so complex like data=$(data). I tried VOLUME_ADJUST="$(sox  $1 -n stat -v)" but the result output to my terminal not assign to the variable. When I echo it nothing shows up.

Thanks for your suggestion.
My code is as follows:

#!/bin/sh

RED='\033[0;31m'
NC='\033[0m'
BLUE='\033[0;34m'
GREEN='\033[0;32m'

Process () {
    printf "Process with ${RED}$1${NC}\n";
    printf "Volume up as high as possible?[y/n]";
    read PASS;
    if test "$PASS" = "y"; then
        a="$(date)"
        VOLUME="$(sox "$1" -n stat -v)"
        #echo $VOLUME
        # eval "sox -v $VOLUME_ADJUST $1 $1"
        #printf $?
    elif test "$PASS" = "n"; then
        printf "${GREEN}Volume up skipped.${NC}"
    fi
}

Process "test.wav"

Here is a pastebin to all of my code


问:
Where to change highlight color for selected occurrences in Eclipse?
When a method or variable is selected it is highlighted in Eclipse with some color. Can anyone advice where to change that color? I'm working under Windows OS.</p>

答:
If you're using eclipse with PHP package and want to change highlighted colour then there is slight difference to above answer.

Right click on highlighted word

Select 'Preferences'

Go to General > Editors > Text Editors > Annotations. Now look for "PHP elements 'read' occurrences" and "PHP elements 'write' occurrences". You can select your desired colour there.


问:
How to optimize code removing unwanted characters
This code is designed for a problem where the users computer has a bug where every time he/she hits the backspace button it displays a '<' symbol. The created program should fix this and output the intended string considering that '<' represents a backspace. The input string can be up to 10^6 characters long, and it only will include lowercase letters and '<'.

My code seems to be executing correctly but, when I submit it, the website says it exceeded the time limit for test 5/25. The amount of time given is 1 second. Also, if there are only '<' symbols it should produce no output.

For example,

```<code>"hellooo<< my name is matthe<<"
</code>```

would output

```<code>"hello my name is matt"
</code>```

and

```<code>"ssadfas<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
</code>```

would output nothing, etc.

Here is the code:

```<code>input = gets.chomp
while input[/[[:lower:]]</]
    input.gsub!(/[[:lower:]]</, "")
end
input.gsub!(/</, "")
puts"#{input}"
</code>```

In the code above I stay in the while loop if there are any instances where a lowercase letter is in front of a '<'. Anywhere a lowercase letter is followed by a '<' it is replaced with nothing. Once the while loop is exited if there are any '<' symbols left, they are replaced with nothing. Then the final string is displayed.

I created a test which I think is worst case scenario for my code:

```<code>input = ("a" + "<" + "a")*10000000

#input = gets.chomp
while input[/[[:lower:]]</]
    input.gsub!(/[[:lower:]]</, "")
end
input.gsub!(/</, "")
puts"#{input}"
</code>```

I made the program stop between the creation of the string and the execution of the while loop and then ran it completely to be able to eyeball if it was taking longer than a second. It seemed to take much longer than 1 second.

How can it be modified to be faster or is there a much better way to do this?

答:
```<code>def backspace(str)
  bs_count = 0
  str.reverse.each_char.with_object([]) do |s, arr|
    if s == '<'
      bs_count += 1
    else
      bs_count.zero? ? arr.unshift(s) : bs_count -= 1
    end
  end.join
end

backspace "Now is the<< tim<e fo<<<r every<<<one to chill ou<<<<t"
  #=> "Now is t tier evone to chilt"
</code>```

Body:
This code is designed for a problem where the users computer has a bug where every time he/she hits the backspace button it displays a '<' symbol. The created program should fix this and output the intended string considering that '<' represents a backspace. The input string can be up to 10^6 characters long, and it only will include lowercase letters and '<'.

My code seems to be executing correctly but, when I submit it, the website says it exceeded the time limit for test 5/25. The amount of time given is 1 second. Also, if there are only '<' symbols it should produce no output.

For example,

"hellooo<< my name is matthe<<"

would output

"hello my name is matt"

and

"ssadfas<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"

would output nothing, etc.

Here is the code:

input = gets.chomp
while input[/[[:lower:]]</]
    input.gsub!(/[[:lower:]]</, "")
end
input.gsub!(/</, "")
puts"#{input}"

In the code above I stay in the while loop if there are any instances where a lowercase letter is in front of a '<'. Anywhere a lowercase letter is followed by a '<' it is replaced with nothing. Once the while loop is exited if there are any '<' symbols left, they are replaced with nothing. Then the final string is displayed.

I created a test which I think is worst case scenario for my code:

input = ("a" + "<" + "a")*10000000

#input = gets.chomp
while input[/[[:lower:]]</]
    input.gsub!(/[[:lower:]]</, "")
end
input.gsub!(/</, "")
puts"#{input}"

I made the program stop between the creation of the string and the execution of the while loop and then ran it completely to be able to eyeball if it was taking longer than a second. It seemed to take much longer than 1 second.

How can it be modified to be faster or is there a much better way to do this?


问:
Mounting a local directory to remote docker container
I have a remote docker container which I pulled and is currently running using:

```<code>docker pull bamos/openface
docker run -p 9000:9000 -p 8000:8000 -t -i bamos/openface /bin/bash
</code>```

I also have a local directory at

```<code>/Users/name/Documents/my-project
</code>```

I need to import openface from scripts inside my-project while developing in ipython, but I do not know how to mount my-project onto openface, or should it be the other way around.

In general, I have been reading the docs here https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume, but am still very confused. I would greatly appreciated it if someone could

give the exact commands so that I can import openface from my-project

explain aspects of the command so I am less confused :D

Thank you!

==============================================================
EDIT:

right now I am doing:

```<code>docker run -v /Users/name/Documents/my-project:/root/my-project -p 9000:9000 -p 8000:8000 -t -i bamos/openface /bin/bash
</code>```

and it seems to be working.

答:
So, I will just point some topics you can study and give thoughts that I think can be useful for you.

As you are still learning, let's go through these topics:

Using a docker image

Custom a docker image

Integrate some docker images

Using a docker image

This is what you already know. Run docker run -v /Users/name/Documents/my-project:/root/my-project -p 9000:9000 -p 8000:8000 -t -i bamos/openface /bin/bash and start using it. Run some commands and see the capabilities of the image provided.

Use cases (for me):

Once, I needed test NoSQL Cassandra. I easily run docker run --name some-cassandra -d cassandra:latest and it is already working

I will make an Python/Flask app, so instead of making virtualenv, I prefer Docker.

Not so good for now, but it is interesting to use.

Custom a docker image

Instead of using ephemeral images, you can create your own. So, you need to learn about Dockerfile. Here is a simple example:

```<code>FROM bamos/openface

RUN pip install flask
COPY myentrypoint.sh

CMD ["myentrypoint.sh"]
</code>```

Fast explanation:

Start your own image from bamos/openface

Run a command that install python package flask

Copy your entrypoint (you need to create one)

Run this entrypoint when user use your container

With this image, just save with name Dockerfile and run docker build -t
chibro2/myopenface ., and then you have your own image with an extra package.

entrypoint is a default sh command that will start something (for example, a web server). If you have an online instance (AWS, for example) you can run your docker, and it will start your web service. If you tested locally, you should have the same results online. One common problem is testing with different versions (like python3 local, and python2 at the server).

Use cases:

Make versions of your infrastructure (you have at your git repository all packages required)

Make an image that will work easily on your server.

Check:
https://www.digitalocean.com/community/tutorials/docker-explained-using-dockerfiles-to-automate-building-of-images
https://docs.docker.com/engine/reference/builder/

Integrate some docker images

One thing that I really like at Docker, is the docker compose. You easily work with several docker images that work with each other. An example of docker-compose:

```<code>version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
</code>```

Fast explanation:

We create a container db, a postgres database

We create a webservice, build from Dockerfile (it is implicit in build), and run a server with command python3 manage.py runserver 0.0.0.0:8000.

Ps.: Yes, it use the code as a volume, but this something I don't recommend for production, but recommend for development (so, you easily change your code, and don't need to build the image).

With docker-compose, we easily integrate several projects and start all with a single command: docker-compose up

Use cases:

This is excelent for microservices

Services discovery is easy

Simple command for scale (docker-compose scale web=2 will create 2 instances of your web server).

Check this quickstart: https://docs.docker.com/compose/django/

Conclusion

There is too much to learn about docker. I can't give a very good answer on this, but I hope I could help a little.

Possible future steps is to use Docker Machine and Docker Swarm.

Body:
I have a remote docker container which I pulled and is currently running using:

docker pull bamos/openface
docker run -p 9000:9000 -p 8000:8000 -t -i bamos/openface /bin/bash

I also have a local directory at

/Users/name/Documents/my-project

I need to import openface from scripts inside my-project while developing in ipython, but I do not know how to mount my-project onto openface, or should it be the other way around.

In general, I have been reading the docs here https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume, but am still very confused. I would greatly appreciated it if someone could

give the exact commands so that I can import openface from my-project

explain aspects of the command so I am less confused :D

Thank you!

==============================================================
EDIT:

right now I am doing:

docker run -v /Users/name/Documents/my-project:/root/my-project -p 9000:9000 -p 8000:8000 -t -i bamos/openface /bin/bash

and it seems to be working.

Body:
So, I will just point some topics you can study and give thoughts that I think can be useful for you.

As you are still learning, let's go through these topics:

Using a docker image

Custom a docker image

Integrate some docker images

Using a docker image

This is what you already know. Run docker run -v /Users/name/Documents/my-project:/root/my-project -p 9000:9000 -p 8000:8000 -t -i bamos/openface /bin/bash and start using it. Run some commands and see the capabilities of the image provided.

Use cases (for me):

Once, I needed test NoSQL Cassandra. I easily run docker run --name some-cassandra -d cassandra:latest and it is already working

I will make an Python/Flask app, so instead of making virtualenv, I prefer Docker.

Not so good for now, but it is interesting to use.

Custom a docker image

Instead of using ephemeral images, you can create your own. So, you need to learn about Dockerfile. Here is a simple example:

FROM bamos/openface

RUN pip install flask
COPY myentrypoint.sh

CMD ["myentrypoint.sh"]

Fast explanation:

Start your own image from bamos/openface

Run a command that install python package flask

Copy your entrypoint (you need to create one)

Run this entrypoint when user use your container

With this image, just save with name Dockerfile and run docker build -t
chibro2/myopenface ., and then you have your own image with an extra package.

entrypoint is a default sh command that will start something (for example, a web server). If you have an online instance (AWS, for example) you can run your docker, and it will start your web service. If you tested locally, you should have the same results online. One common problem is testing with different versions (like python3 local, and python2 at the server).

Use cases:

Make versions of your infrastructure (you have at your git repository all packages required)

Make an image that will work easily on your server.

Check:
https://www.digitalocean.com/community/tutorials/docker-explained-using-dockerfiles-to-automate-building-of-images
https://docs.docker.com/engine/reference/builder/

Integrate some docker images

One thing that I really like at Docker, is the docker compose. You easily work with several docker images that work with each other. An example of docker-compose:

version: '3'

services:
  db:
    image: postgres
  web:
    build: .
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

Fast explanation:

We create a container db, a postgres database

We create a webservice, build from Dockerfile (it is implicit in build), and run a server with command python3 manage.py runserver 0.0.0.0:8000.

Ps.: Yes, it use the code as a volume, but this something I don't recommend for production, but recommend for development (so, you easily change your code, and don't need to build the image).

With docker-compose, we easily integrate several projects and start all with a single command: docker-compose up

Use cases:

This is excelent for microservices

Services discovery is easy

Simple command for scale (docker-compose scale web=2 will create 2 instances of your web server).

Check this quickstart: https://docs.docker.com/compose/django/

Conclusion

There is too much to learn about docker. I can't give a very good answer on this, but I hope I could help a little.

Possible future steps is to use Docker Machine and Docker Swarm.


问:
Calculating bytes needed to store a string using BinaryWriter
I'm using BinaryWriter to write a string to a file. For unrelated reasons I need to calculate how many bytes this will require but I'm seeing results that don't match the documentation.

With this test code:

```<code>using (var stream = new FileStream(filePath, FileMode.Create)) {
    using (var writer = new BinaryWriter(stream)) {
        writer.Write("Test");
    }
}
</code>```

I expect the file to be 8 bytes:

Using Encoding.UTF8.GetByteCount(str) (UTF-8 is the default used by BinaryWriter), it reports the string Test is 4 bytes.

According to the docs, BinaryWriter prefixes the output string with an "unsigned integer" which is 4 bytes.

However, the written file is only 5 bytes, and all of my file offset math works when I assume strings are always Encoding.UTF8.GetByteCount(str) + 1 bytes.

I'm not clear on where the difference is.

This is being tested in Unity 5.6, which uses Mono / .NET 2.0 and some Mono / .NET 3.5.

答:
I'm surprised that documentation says it writes size uncompressed. It is very wasteful and I expect compressed format for length provided by BinaryWriter.Write7BitEncodedInt which indeed requires 1 byte for integer below 127.

Reference code confirms that expectation:

```<code> public unsafe virtual void Write(String value)
 {
     ...
     int len = _encoding.GetByteCount(value);
     Write7BitEncodedInt(len);
</code>```

Body:
I'm using BinaryWriter to write a string to a file. For unrelated reasons I need to calculate how many bytes this will require but I'm seeing results that don't match the documentation.

With this test code:

using (var stream = new FileStream(filePath, FileMode.Create)) {
    using (var writer = new BinaryWriter(stream)) {
        writer.Write("Test");
    }
}

I expect the file to be 8 bytes:

Using Encoding.UTF8.GetByteCount(str) (UTF-8 is the default used by BinaryWriter), it reports the string Test is 4 bytes.

According to the docs, BinaryWriter prefixes the output string with an "unsigned integer" which is 4 bytes.

However, the written file is only 5 bytes, and all of my file offset math works when I assume strings are always Encoding.UTF8.GetByteCount(str) + 1 bytes.

I'm not clear on where the difference is.

This is being tested in Unity 5.6, which uses Mono / .NET 2.0 and some Mono / .NET 3.5.

Body:
I'm surprised that documentation says it writes size uncompressed. It is very wasteful and I expect compressed format for length provided by BinaryWriter.Write7BitEncodedInt which indeed requires 1 byte for integer below 127.

Reference code confirms that expectation:

 public unsafe virtual void Write(String value)
 {
     ...
     int len = _encoding.GetByteCount(value);
     Write7BitEncodedInt(len);


问:
How do I count the number of global variables in global scope?
I'm working on a project developed by someone else. I load the Chrome Developer Tool to check the status of a global variable. When I tick open Global under Scope, I see a colossal number of global variables. It takes me over 8 seconds to scroll through them. Having worked on this project for some time now, I know that global variables is a problem which we'll have to fix; but, *that is irrelevant to my question.

To communicate the scale of our global scope being flooded, I'd like to count the number of variables presently instantiated in the global scope

How do I do this?

I'm looking for an answer in JavaScript that I can execute immediately in my console. Basically something that may iterate over the global scope and count++.

答:
I'm not sure a count of global variables is, of itself, a useful indicator of anything. You should do some analysis to work out which are created by code, which are host specific and which are related to the environment (e.g. DOM).

In a browser, the window object is a synonym for the global object, hosts are allowed to add properties to it (e.g. window.name) as well as define properties on its prototype (if it has one).

Also, all element IDs are created as properties of window (you can blame Microsoft and IE for that), so if there are lots of element IDs then there'll be lots of global properties.

Anyway, below are two ways to count the own enumerable properties of the global (window) object. It uses an IIFE so it doesn't create any properties itself.

// Create 3 global properties
var x, y, z;

(function(global) {

  // for..in with hasOwnProperty check
  var count = 0;
  for (var prop in global) {
    if (global.hasOwnProperty(prop)) {
      count++;
    }
  }
  console.log('for..in count: ' + count +

            // Direct count using Object.keys
            '\nObject.keys  : ' + Object.keys(global).length);

// Pass global (window in a browser) object to function
}(this));```
</div>
</div>
</p>

<p>So an approach to testing for code-created variables in a browser may be to:</p>

<ol>
<li>Count the number of global properties in an "empty" document, that should be the default host-defined set</li>
<li>Count the total number of global properties in the suspect document</li>
<li>Count the number of elements in the document with an ID</li>
</ol>

<p>So the number of code-created globals should be the result of item 2 - (item 1 + item 3).</p>

<p>You can count the elements with an ID something like:</p>

```var allEls = document.getElementsByTagName('*');
var idCount = 0;

for (var i=0, iLen=allEls.length; i<iLen; i++) {
  if (allEls[i].id != '') {
    ++idCount;
  }
}
```

<p>or:</p>

```[].filter.call(document.getElementsByTagName('*'), function(el) {
  return el.id != '';
}).length;
```

Body:
I'm not sure a count of global variables is, of itself, a useful indicator of anything. You should do some analysis to work out which are created by code, which are host specific and which are related to the environment (e.g. DOM).

In a browser, the window object is a synonym for the global object, hosts are allowed to add properties to it (e.g. window.name) as well as define properties on its prototype (if it has one).

Also, all element IDs are created as properties of window (you can blame Microsoft and IE for that), so if there are lots of element IDs then there'll be lots of global properties.

Anyway, below are two ways to count the own enumerable properties of the global (window) object. It uses an IIFE so it doesn't create any properties itself.

// Create 3 global properties
var x, y, z;

(function(global) {

  // for..in with hasOwnProperty check
  var count = 0;
  for (var prop in global) {
    if (global.hasOwnProperty(prop)) {
      count++;
    }
  }
  console.log('for..in count: ' + count +

            // Direct count using Object.keys
            '\nObject.keys  : ' + Object.keys(global).length);

// Pass global (window in a browser) object to function
}(this));

So an approach to testing for code-created variables in a browser may be to:

Count the number of global properties in an "empty" document, that should be the default host-defined set

Count the total number of global properties in the suspect document

Count the number of elements in the document with an ID

So the number of code-created globals should be the result of item 2 - (item 1 + item 3).

You can count the elements with an ID something like:

var allEls = document.getElementsByTagName('*');
var idCount = 0;

for (var i=0, iLen=allEls.length; i<iLen; i++) {
  if (allEls[i].id != '') {
    ++idCount;
  }
}

or:

[].filter.call(document.getElementsByTagName('*'), function(el) {
  return el.id != '';
}).length;


问:
How to get SIZE_MAX in C89
I'm trying to get SIZE_MAX in C89.

I thought of the following way to find SIZE_MAX:

```<code>const size_t SIZE_MAX = -1;
</code>```

Since the standard (§6.2.1.2 ANSI C) says:

When a signed integer is converted to an unsigned integer with equal or greater size, if the value of the signed integer is nonnegative, its value is unchanged. Otherwise: if the unsigned integer has greater size, the signed integer is first promoted to the signed integer corresponding to the unsigned integer; the value is converted to unsigned by adding to it one greater than the largest number that can be represented in the unsigned integer type 28

With footnote 28:

In a two's-complement representation, there is no actual change in the bit pattern except filling the high-order bits with copies of the sign bit if the unsigned integer has greater size.

This seems like this has defined behavior, but I'm not quite sure if I understand the wording of that paragraph correctly.

Note that this question is explicitly about C89, so this doesn't answer my question because the standard has different wording.

If that doesn't work, the other way I came up with is:

```<code>size_t get_size_max() {
    static size_t max = 0;
    if (max == 0) {
        max -= 1U;
    }

    return max;
}
</code>```

But I couldn't find anything about unsigned integer underflow in the standard, so I'm poking in the dark here.

答:
You could use:

```<code>#ifndef SIZE_MAX
#define SIZE_MAX ((size_t)(-1))
#endif
</code>```

The behaviour of converting -1 to unsigned integer type is  defined under section C11 6.3.1.3  "Conversions - Signed and unsigned integers".  C89 had an equivalent definition, numbered 3.2.1.2.  In fact you quoted the ISO C90 definition 6.2.1.2 in your question (the difference between ANSI C89 and ISO C90 is that the sections are numbered differently).

I would not recommend using a const variable, since they cannot be used in constant expressions.

Note: This can't be used in C90 preprocessor arithmetic, which only works on integer constant expressions that contain no casts or words, so we can't use any sizeof tricks. In that case you might need a system-specific definition; there's no standard way for the preprocessor to detect a typedef.

Title: How to get SIZE_MAX in C89

Body:
I'm trying to get SIZE_MAX in C89.

I thought of the following way to find SIZE_MAX:

const size_t SIZE_MAX = -1;

Since the standard (§6.2.1.2 ANSI C) says:

When a signed integer is converted to an unsigned integer with equal or greater size, if the value of the signed integer is nonnegative, its value is unchanged. Otherwise: if the unsigned integer has greater size, the signed integer is first promoted to the signed integer corresponding to the unsigned integer; the value is converted to unsigned by adding to it one greater than the largest number that can be represented in the unsigned integer type 28

With footnote 28:

In a two's-complement representation, there is no actual change in the bit pattern except filling the high-order bits with copies of the sign bit if the unsigned integer has greater size.

This seems like this has defined behavior, but I'm not quite sure if I understand the wording of that paragraph correctly.

Note that this question is explicitly about C89, so this doesn't answer my question because the standard has different wording.

If that doesn't work, the other way I came up with is:

size_t get_size_max() {
    static size_t max = 0;
    if (max == 0) {
        max -= 1U;
    }

    return max;
}

But I couldn't find anything about unsigned integer underflow in the standard, so I'm poking in the dark here.

Body:
You could use:

#ifndef SIZE_MAX
#define SIZE_MAX ((size_t)(-1))
#endif

The behaviour of converting -1 to unsigned integer type is  defined under section C11 6.3.1.3  "Conversions - Signed and unsigned integers".  C89 had an equivalent definition, numbered 3.2.1.2.  In fact you quoted the ISO C90 definition 6.2.1.2 in your question (the difference between ANSI C89 and ISO C90 is that the sections are numbered differently).

I would not recommend using a const variable, since they cannot be used in constant expressions.

Note: This can't be used in C90 preprocessor arithmetic, which only works on integer constant expressions that contain no casts or words, so we can't use any sizeof tricks. In that case you might need a system-specific definition; there's no standard way for the preprocessor to detect a typedef.


问:
Ionic Cordova $http POST data works well in browser but does not work in my android phone
I am developing a hybrid application using Ionic Framework. I am using $http Restful web service to POST data into my server and get the response from server. When I test it in browser, it works well and I able to retrieve data from serve. But when I test it in my android device, it does not work at all. The following is my code.

Angularjs Code

```<code>  $scope.validateBorrower = function(){
    employeeNumber =  $scope.assetBorrowing.employeeNumber;
    employeeName = $scope.assetBorrowing.employeeName;
    employeeDeparment = $scope.assetBorrowing.employeeDepartment;

    if(employeeNumber == null && employeeName == null){
        alert("Please Enter Employee Number or Employee Name");
    }else{
        $http({
          url: "http://131.4.44.69/php3/validateBorrower.php",
                method: "POST",
                data: {
                    'employeeNumber': employeeNumber,
                    'employeeName' : employeeName
                },
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).success(function(response) {
                alert("Valid Employee");
                $scope.assetBorrowing.employeeNumber = response[0].employeeNumber;
                $scope.assetBorrowing.employeeName = response[0].employeeName;
                $scope.assetBorrowing.employeeDepartment =  response[0].employeeDepartment;
                $scope.borrowbtn  = false;

            }).error(function(response) {
                alert("error");
            });
            alert(employeeNumber);
    }
  }
</code>```

PHP Backend Code

```<code><?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Credentials: false");
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
    header('P3P: CP="CAO PSA OUR"');
    header("Content-Type: application/json; charset=utf-8");

    $postdata = file_get_contents("php://input");
    $employeeRequest = json_decode($postdata, true);
    @$employeeNumber =  $employeeRequest['employeeNumber'];
    @$employeeName =   $employeeRequest['employeeName'];

    if(empty($employeeNumber)){
        @$employeeName =   $employeeRequest['employeeName'];
    }else{
        @$employeeName = "";
    }

    $db_host = "localhost";
    $db_user = "jack";
    $db_password = "1234";
    $db_database = "daikin_asset_management";
    $conn = new mysqli($db_host, $db_user, $db_password, $db_database);

    if($conn->connect_error){
        echo "Connection Problem";
    }

    if(empty($employeeNumber) && empty($employeeName)){
        echo "Error";
    }else{
        $getUserQuery = "SELECT * FROM xpouser WHERE  (username='$employeeName') OR (employee_no = '$employeeNumber') ";
        $getUserRetval = $conn->query($getUserQuery);
        $userRow = mysqli_fetch_array($getUserRetval);

        $employeeName = $userRow['username'];
        $employeeNumber = $userRow['employee_no'];
        $employeeDepartment = $userRow['department'];
        $_arr = array();
        $array = array(
            'employeeNumber' => $employeeNumber,
            'employeeName' => $employeeName,
            'employeeDepartment' => $employeeDepartment
        );
        $jsonObjectChannel = json_encode($array);
        $jsonObjectChannel = "[" . $jsonObjectChannel . "]";

        echo $jsonObjectChannel;
    }
?>
</code>```

答:
I figure it out by myself. Is because of I never add few permissions in my android Manifest file. I have to include this 3 permissions in my android manifest.

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Next, I have to include cordova-whitelist plugin and add this into my config.xml

```<code><access origin = "http://example.com" />
<allow-navigation href = "*://*.example.com/*" />
</code>```

Body:
I am developing a hybrid application using Ionic Framework. I am using $http Restful web service to POST data into my server and get the response from server. When I test it in browser, it works well and I able to retrieve data from serve. But when I test it in my android device, it does not work at all. The following is my code.

Angularjs Code

  $scope.validateBorrower = function(){
    employeeNumber =  $scope.assetBorrowing.employeeNumber;
    employeeName = $scope.assetBorrowing.employeeName;
    employeeDeparment = $scope.assetBorrowing.employeeDepartment;

    if(employeeNumber == null && employeeName == null){
        alert("Please Enter Employee Number or Employee Name");
    }else{
        $http({
          url: "http://131.4.44.69/php3/validateBorrower.php",
                method: "POST",
                data: {
                    'employeeNumber': employeeNumber,
                    'employeeName' : employeeName
                },
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).success(function(response) {
                alert("Valid Employee");
                $scope.assetBorrowing.employeeNumber = response[0].employeeNumber;
                $scope.assetBorrowing.employeeName = response[0].employeeName;
                $scope.assetBorrowing.employeeDepartment =  response[0].employeeDepartment;
                $scope.borrowbtn  = false;

            }).error(function(response) {
                alert("error");
            });
            alert(employeeNumber);
    }
  }

PHP Backend Code

<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Credentials: false");
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
    header('P3P: CP="CAO PSA OUR"');
    header("Content-Type: application/json; charset=utf-8");

    $postdata = file_get_contents("php://input");
    $employeeRequest = json_decode($postdata, true);
    @$employeeNumber =  $employeeRequest['employeeNumber'];
    @$employeeName =   $employeeRequest['employeeName'];

    if(empty($employeeNumber)){
        @$employeeName =   $employeeRequest['employeeName'];
    }else{
        @$employeeName = "";
    }

    $db_host = "localhost";
    $db_user = "jack";
    $db_password = "1234";
    $db_database = "daikin_asset_management";
    $conn = new mysqli($db_host, $db_user, $db_password, $db_database);

    if($conn->connect_error){
        echo "Connection Problem";
    }

    if(empty($employeeNumber) && empty($employeeName)){
        echo "Error";
    }else{
        $getUserQuery = "SELECT * FROM xpouser WHERE  (username='$employeeName') OR (employee_no = '$employeeNumber') ";
        $getUserRetval = $conn->query($getUserQuery);
        $userRow = mysqli_fetch_array($getUserRetval);

        $employeeName = $userRow['username'];
        $employeeNumber = $userRow['employee_no'];
        $employeeDepartment = $userRow['department'];
        $_arr = array();
        $array = array(
            'employeeNumber' => $employeeNumber,
            'employeeName' => $employeeName,
            'employeeDepartment' => $employeeDepartment
        );
        $jsonObjectChannel = json_encode($array);
        $jsonObjectChannel = "[" . $jsonObjectChannel . "]";

        echo $jsonObjectChannel;
    }
?>

Body:
I figure it out by myself. Is because of I never add few permissions in my android Manifest file. I have to include this 3 permissions in my android manifest.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Next, I have to include cordova-whitelist plugin and add this into my config.xml

<access origin = "http://example.com" />
<allow-navigation href = "*://*.example.com/*" />


问:
App runs with --add-modules=java.se.ee in Eclipse but not on command line
I'm using Java 9-ea to both run an app built in Eclipse and to run a Ant-built jar of the same app on the commend line. In Eclipse everything works if I pass the --permit-illegal-access --add-modules=java.se.ee VM args but if I pass the same on the command line:

```<code>java --add-modules=java.se.ee --permit-illegal-access -jar swing/build/jar/OpenRocket.jar
</code>```

things fail at runtime:

```<code>java.lang.RuntimeException: Error starting OpenRocket
    at net.sf.openrocket.startup.jij.JarInJarStarter.runMain(JarInJarStarter.java:40)
    at net.sf.openrocket.startup.OpenRocket.main(OpenRocket.java:36)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:563)
    at net.sf.openrocket.startup.jij.JarInJarStarter.runMain(JarInJarStarter.java:38)
    ... 1 more
Caused by: java.lang.reflect.InvocationTargetException
    at java.desktop/java.awt.EventQueue.invokeAndWait(EventQueue.java:1323)
    at java.desktop/java.awt.EventQueue.invokeAndWait(EventQueue.java:1298)
    at java.desktop/javax.swing.SwingUtilities.invokeAndWait(SwingUtilities.java:1475)
    at net.sf.openrocket.startup.SwingStartup.main(SwingStartup.java:76)
    ... 6 more
Caused by: com.google.common.util.concurrent.ExecutionError: com.google.common.util.concurrent.ExecutionError: java.lang.NoClassDefFoundError: javax/script/ScriptEngineFactory
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2212)
    at com.google.common.cache.LocalCache.get(LocalCache.java:4053)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:4057)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4986)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4992)
    at com.google.inject.internal.FailableCache.get(FailableCache.java:48)
    at com.google.inject.internal.ConstructorInjectorStore.get(ConstructorInjectorStore.java:50)
    at com.google.inject.internal.ConstructorBindingImpl.initialize(ConstructorBindingImpl.java:138)
    at com.google.inject.internal.InjectorImpl.initializeJitBinding(InjectorImpl.java:550)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBinding(InjectorImpl.java:887)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBindingRecursive(InjectorImpl.java:808)
    at com.google.inject.internal.InjectorImpl.getJustInTimeBinding(InjectorImpl.java:285)
    at com.google.inject.internal.InjectorImpl.getBindingOrThrow(InjectorImpl.java:217)
    at com.google.inject.internal.InjectorImpl.getInternalFactory(InjectorImpl.java:893)
    at com.google.inject.internal.FactoryProxy.notify(FactoryProxy.java:46)
    at com.google.inject.internal.ProcessedBindingData.runCreationListeners(ProcessedBindingData.java:50)
    at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:134)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:107)
    at com.google.inject.Guice.createInjector(Guice.java:99)
    at com.google.inject.Guice.createInjector(Guice.java:73)
    at com.google.inject.Guice.createInjector(Guice.java:62)
    at net.sf.openrocket.startup.SwingStartup.runInEDT(SwingStartup.java:143)
    at net.sf.openrocket.startup.SwingStartup.access$000(SwingStartup.java:43)
    at net.sf.openrocket.startup.SwingStartup$1.run(SwingStartup.java:79)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:303)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:759)
    at java.desktop/java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.desktop/java.awt.EventQueue$3.run(EventQueue.java:712)
    at java.desktop/java.awt.EventQueue$3.run(EventQueue.java:706)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:88)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:729)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:199)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: com.google.common.util.concurrent.ExecutionError: java.lang.NoClassDefFoundError: javax/script/ScriptEngineFactory
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2212)
    at com.google.common.cache.LocalCache.get(LocalCache.java:4053)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:4057)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4986)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4992)
    at com.google.inject.internal.FailableCache.get(FailableCache.java:48)
    at com.google.inject.internal.MembersInjectorStore.get(MembersInjectorStore.java:68)
    at com.google.inject.internal.ConstructorInjectorStore.createConstructor(ConstructorInjectorStore.java:75)
    at com.google.inject.internal.ConstructorInjectorStore.access$000(ConstructorInjectorStore.java:29)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:37)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:33)
    at com.google.inject.internal.FailableCache$1.load(FailableCache.java:37)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3628)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2336)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2295)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2208)
    ... 37 more
Caused by: java.lang.NoClassDefFoundError: javax/script/ScriptEngineFactory
    at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3134)
    at java.base/java.lang.Class.getDeclaredMethods(Class.java:2285)
    at com.google.inject.spi.InjectionPoint.getInjectionPoints(InjectionPoint.java:688)
    at com.google.inject.spi.InjectionPoint.forInstanceMethodsAndFields(InjectionPoint.java:380)
    at com.google.inject.internal.ConstructorBindingImpl.getInternalDependencies(ConstructorBindingImpl.java:165)
    at com.google.inject.internal.InjectorImpl.getInternalDependencies(InjectorImpl.java:616)
    at com.google.inject.internal.InjectorImpl.cleanup(InjectorImpl.java:572)
    at com.google.inject.internal.InjectorImpl.initializeJitBinding(InjectorImpl.java:558)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBinding(InjectorImpl.java:887)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBindingRecursive(InjectorImpl.java:808)
    at com.google.inject.internal.InjectorImpl.getJustInTimeBinding(InjectorImpl.java:285)
    at com.google.inject.internal.InjectorImpl.getBindingOrThrow(InjectorImpl.java:217)
    at com.google.inject.internal.SingleFieldInjector.<init>(SingleFieldInjector.java:42)
    at com.google.inject.internal.MembersInjectorStore.getInjectors(MembersInjectorStore.java:131)
    at com.google.inject.internal.MembersInjectorStore.createWithListeners(MembersInjectorStore.java:98)
    at com.google.inject.internal.MembersInjectorStore.access$000(MembersInjectorStore.java:37)
    at com.google.inject.internal.MembersInjectorStore$1.create(MembersInjectorStore.java:45)
    at com.google.inject.internal.MembersInjectorStore$1.create(MembersInjectorStore.java:42)
    at com.google.inject.internal.FailableCache$1.load(FailableCache.java:37)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3628)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2336)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2295)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2208)
    ... 52 more
Caused by: java.lang.ClassNotFoundException: javax.script.ScriptEngineFactory
    at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:466)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:553)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:486)
    ... 76 more
</code>```

The failure comes down to

```<code>java.lang.NoClassDefFoundError: javax/script/ScriptEngineFactory
</code>```

but --add-modules=java.se.ee is supposed to expose that class so it can be found (and that seemingly works in Eclipse).

What could be wrong?

答: The problem seems specific to my app. I noticed that it does shady things at startup: https://github.com/openrocket/openrocket/blob/master/swing/src/net/sf/openrocket/startup/jij/JarInJarStarter.java</p>

Body:
I'm using Java 9-ea to both run an app built in Eclipse and to run a Ant-built jar of the same app on the commend line. In Eclipse everything works if I pass the --permit-illegal-access --add-modules=java.se.ee VM args but if I pass the same on the command line:

java --add-modules=java.se.ee --permit-illegal-access -jar swing/build/jar/OpenRocket.jar

things fail at runtime:

java.lang.RuntimeException: Error starting OpenRocket
    at net.sf.openrocket.startup.jij.JarInJarStarter.runMain(JarInJarStarter.java:40)
    at net.sf.openrocket.startup.OpenRocket.main(OpenRocket.java:36)
Caused by: java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:563)
    at net.sf.openrocket.startup.jij.JarInJarStarter.runMain(JarInJarStarter.java:38)
    ... 1 more
Caused by: java.lang.reflect.InvocationTargetException
    at java.desktop/java.awt.EventQueue.invokeAndWait(EventQueue.java:1323)
    at java.desktop/java.awt.EventQueue.invokeAndWait(EventQueue.java:1298)
    at java.desktop/javax.swing.SwingUtilities.invokeAndWait(SwingUtilities.java:1475)
    at net.sf.openrocket.startup.SwingStartup.main(SwingStartup.java:76)
    ... 6 more
Caused by: com.google.common.util.concurrent.ExecutionError: com.google.common.util.concurrent.ExecutionError: java.lang.NoClassDefFoundError: javax/script/ScriptEngineFactory
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2212)
    at com.google.common.cache.LocalCache.get(LocalCache.java:4053)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:4057)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4986)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4992)
    at com.google.inject.internal.FailableCache.get(FailableCache.java:48)
    at com.google.inject.internal.ConstructorInjectorStore.get(ConstructorInjectorStore.java:50)
    at com.google.inject.internal.ConstructorBindingImpl.initialize(ConstructorBindingImpl.java:138)
    at com.google.inject.internal.InjectorImpl.initializeJitBinding(InjectorImpl.java:550)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBinding(InjectorImpl.java:887)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBindingRecursive(InjectorImpl.java:808)
    at com.google.inject.internal.InjectorImpl.getJustInTimeBinding(InjectorImpl.java:285)
    at com.google.inject.internal.InjectorImpl.getBindingOrThrow(InjectorImpl.java:217)
    at com.google.inject.internal.InjectorImpl.getInternalFactory(InjectorImpl.java:893)
    at com.google.inject.internal.FactoryProxy.notify(FactoryProxy.java:46)
    at com.google.inject.internal.ProcessedBindingData.runCreationListeners(ProcessedBindingData.java:50)
    at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:134)
    at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:107)
    at com.google.inject.Guice.createInjector(Guice.java:99)
    at com.google.inject.Guice.createInjector(Guice.java:73)
    at com.google.inject.Guice.createInjector(Guice.java:62)
    at net.sf.openrocket.startup.SwingStartup.runInEDT(SwingStartup.java:143)
    at net.sf.openrocket.startup.SwingStartup.access$000(SwingStartup.java:43)
    at net.sf.openrocket.startup.SwingStartup$1.run(SwingStartup.java:79)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:303)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:759)
    at java.desktop/java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.desktop/java.awt.EventQueue$3.run(EventQueue.java:712)
    at java.desktop/java.awt.EventQueue$3.run(EventQueue.java:706)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:88)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:729)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:199)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: com.google.common.util.concurrent.ExecutionError: java.lang.NoClassDefFoundError: javax/script/ScriptEngineFactory
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2212)
    at com.google.common.cache.LocalCache.get(LocalCache.java:4053)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:4057)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4986)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4992)
    at com.google.inject.internal.FailableCache.get(FailableCache.java:48)
    at com.google.inject.internal.MembersInjectorStore.get(MembersInjectorStore.java:68)
    at com.google.inject.internal.ConstructorInjectorStore.createConstructor(ConstructorInjectorStore.java:75)
    at com.google.inject.internal.ConstructorInjectorStore.access$000(ConstructorInjectorStore.java:29)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:37)
    at com.google.inject.internal.ConstructorInjectorStore$1.create(ConstructorInjectorStore.java:33)
    at com.google.inject.internal.FailableCache$1.load(FailableCache.java:37)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3628)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2336)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2295)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2208)
    ... 37 more
Caused by: java.lang.NoClassDefFoundError: javax/script/ScriptEngineFactory
    at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3134)
    at java.base/java.lang.Class.getDeclaredMethods(Class.java:2285)
    at com.google.inject.spi.InjectionPoint.getInjectionPoints(InjectionPoint.java:688)
    at com.google.inject.spi.InjectionPoint.forInstanceMethodsAndFields(InjectionPoint.java:380)
    at com.google.inject.internal.ConstructorBindingImpl.getInternalDependencies(ConstructorBindingImpl.java:165)
    at com.google.inject.internal.InjectorImpl.getInternalDependencies(InjectorImpl.java:616)
    at com.google.inject.internal.InjectorImpl.cleanup(InjectorImpl.java:572)
    at com.google.inject.internal.InjectorImpl.initializeJitBinding(InjectorImpl.java:558)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBinding(InjectorImpl.java:887)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBindingRecursive(InjectorImpl.java:808)
    at com.google.inject.internal.InjectorImpl.getJustInTimeBinding(InjectorImpl.java:285)
    at com.google.inject.internal.InjectorImpl.getBindingOrThrow(InjectorImpl.java:217)
    at com.google.inject.internal.SingleFieldInjector.<init>(SingleFieldInjector.java:42)
    at com.google.inject.internal.MembersInjectorStore.getInjectors(MembersInjectorStore.java:131)
    at com.google.inject.internal.MembersInjectorStore.createWithListeners(MembersInjectorStore.java:98)
    at com.google.inject.internal.MembersInjectorStore.access$000(MembersInjectorStore.java:37)
    at com.google.inject.internal.MembersInjectorStore$1.create(MembersInjectorStore.java:45)
    at com.google.inject.internal.MembersInjectorStore$1.create(MembersInjectorStore.java:42)
    at com.google.inject.internal.FailableCache$1.load(FailableCache.java:37)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3628)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2336)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2295)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2208)
    ... 52 more
Caused by: java.lang.ClassNotFoundException: javax.script.ScriptEngineFactory
    at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:466)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:553)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:486)
    ... 76 more

The failure comes down to

java.lang.NoClassDefFoundError: javax/script/ScriptEngineFactory

but --add-modules=java.se.ee is supposed to expose that class so it can be found (and that seemingly works in Eclipse).

What could be wrong?


问:
Mips program doesnt print anything
I have a program in MIPS assembly thats is supposed to swap a char in my message.

If the char is 'a', it swaps by the char 'b'.

So i have:"holla" and it must print "hollb".

There's what i have:

```<code>.data
string: .asciiz "holla"
a: .ascii "a"
a1: .ascii "b"
tam: .word 5

.text

main:
lw $t6, tam #string length
lb $t1, string($t0) #read bit by bit

lb $s0, a #save in register the char that we want to search
lb $s1, a1 #save in register the char that we want to replace

beq $t0, $t6, done

beq $t1, $s0, continua #if the char of (bit by bit) its like the char of chars, swap it
bne $t1, $s0, store #if not, saves

continua:
sb $s1, string($t0) #do the swap
addi $t0, $t0, 1 #+1 in the index
j main

store:
    sb $t1, string($t0) #saves
    addi $t0, $t0, 1 #+1 in the index
    j main
done:
    li $v0, 4
    li $v0, 10
    syscall
</code>```

But the code doesnt print me anything in mars.

答:
You may have wrote li $v0, 4 but this in not excaclty how print in MIPS works. Here's how it should have been:

```<code>li $v0, 4       # to print a string
la $a0, string  # load string's address
syscall
</code>```

And then

```<code>li $v0, 10
syscall
</code>```

to terminate the program.

Title: Mips program doesnt print anything

Body:
I have a program in MIPS assembly thats is supposed to swap a char in my message.

If the char is 'a', it swaps by the char 'b'.

So i have:"holla" and it must print "hollb".

There's what i have:

.data
string: .asciiz "holla"
a: .ascii "a"
a1: .ascii "b"
tam: .word 5

.text

main:
lw $t6, tam #string length
lb $t1, string($t0) #read bit by bit

lb $s0, a #save in register the char that we want to search
lb $s1, a1 #save in register the char that we want to replace

beq $t0, $t6, done

beq $t1, $s0, continua #if the char of (bit by bit) its like the char of chars, swap it
bne $t1, $s0, store #if not, saves

continua:
sb $s1, string($t0) #do the swap
addi $t0, $t0, 1 #+1 in the index
j main

store:
    sb $t1, string($t0) #saves
    addi $t0, $t0, 1 #+1 in the index
    j main
done:
    li $v0, 4
    li $v0, 10
    syscall

But the code doesnt print me anything in mars.

Body:
You may have wrote li $v0, 4 but this in not excaclty how print in MIPS works. Here's how it should have been:

li $v0, 4       # to print a string
la $a0, string  # load string's address
syscall

And then

li $v0, 10
syscall

to terminate the program.

ContentLicense: CC BY-SA 4.0


问:
R - Apply a function based on logical vector
I have the following code, but it throws the following error:

```<code>the condition has length > 1 and only the first element will be used
</code>```

Obviously this means that I am misusing the if (condition) {action} construction, so I'm looking for a more elegant way to do this:

```<code>if (grepl("Spring", data$Survey)) {data["Season"] <- "Spring"}
if (grepl("Summer", data$Survey)) {data["Season"] <- "Summer"}
if (grepl("Fall", data$Survey)) {data["Season"] <- "Fall"}
</code>```

Basically, I would like to input a logical vector, and for every TRUE, apply a function to a data set of the same length (in this case, assigning a string value to that row of a dataframe).

答:
You can use ifelse which is vectorial instead of if:

```<code>data$Season <- ifelse(grepl("Spring", data$Survey),
                         "Spring",
                         ifelse(grepl("Summer", data$Survey),
                                "Summer",
                                ifelse(grepl("Fall", data$Survey),
                                       "Fall",
                                       "Winter")))
</code>```

For each element of data$Survey : First ifelse will check if it contains "Spring" , then assign it to the corresponding item in data$Season, otherwise second ifelse will check if it contains "Summer"...

Body:
I have the following code, but it throws the following error:

the condition has length > 1 and only the first element will be used

Obviously this means that I am misusing the if (condition) {action} construction, so I'm looking for a more elegant way to do this:

if (grepl("Spring", data$Survey)) {data["Season"] <- "Spring"}
if (grepl("Summer", data$Survey)) {data["Season"] <- "Summer"}
if (grepl("Fall", data$Survey)) {data["Season"] <- "Fall"}

Basically, I would like to input a logical vector, and for every TRUE, apply a function to a data set of the same length (in this case, assigning a string value to that row of a dataframe).

Body:
You can use ifelse which is vectorial instead of if:

data$Season <- ifelse(grepl("Spring", data$Survey),
                         "Spring",
                         ifelse(grepl("Summer", data$Survey),
                                "Summer",
                                ifelse(grepl("Fall", data$Survey),
                                       "Fall",
                                       "Winter")))

For each element of data$Survey : First ifelse will check if it contains "Spring" , then assign it to the corresponding item in data$Season, otherwise second ifelse will check if it contains "Summer"...


问:
How many variables are too much for a class?
I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

Total Number of Files

Total Size of Files

Number of Office Files

Size of Office Files

Number of Exe Files

Size of Exe Files

etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

答:
Whenever I see more than 5 or 6 non-final variables in a class I get antsy.

Chances are that they should probably be placed in a smaller class as suggested by Outlaw Programmer. There's also a good chance it could just be placed in a hashtable.

Here's a good rule of thumb: If you have a variable that has nothing but a setter and a getter, you have DATA, not code--get it out of your class and place it into a collection or something.

Having a variable with a setter and a getter just means that either you never do anything with it (it's data) or the code that manipulates it is in another class (terrible OO design, move the variable to the other class).

Remember--every piece of data that is a class member is something you will have to write specific code to access; for instance, when you transfer it from your object to a control on a GUI.

I often tag GUI controls with a name so I can iterate over a collection and automatically transfer data from the collection to the screen and back, significantly reducing boilerplate code; storing the data as member variables makes this process much more complicated (requires reflection).

OwnerDisplayName: Ben

LastEditorDisplayName: mmyers

OwnerDisplayName: Bill K


问:
POST 404 Error (Component not found) in Joomla
I am running some custom php file that contains some javascript code within a Joomla website through an extension called sourcerer. Everything works as expected from the php side of things however I am experiencing an issue with a call to another php file made from within a javascript.  Here is the javascript code in question and on the second line is the "suburb.php" file that is called from within this code that is causing the issue.

```<code>$.ajax({
 url : 'suburb.php',
 dataType: "json",
 method: 'post',
 data: {
     name_startsWith: request.term,
     type: 'suburb_table',
     row_num : 1
 },
 success: function( data ) {
     response( $.map( data, function( item ) {
         var code = item.split("|");
         return {
             label: code[0],
             value: code[0],
             data : item
         }
     }));
 }
});
</code>```

The problem I am having is that even though the originating php file that contains this javascript is in the same directory as the suburb.php file, Joomla seems to change the URL call to "localhost/index.php/menu_alias/suburb.php" and this causes a POST error 404 (Component non found).

I have tried using many variation of the url path in that second line of the code, but all have failed. Can somebody tell me what my url path should look like for this to work?

Thank you,
Adri

答:
Thank you for your feedback. I tried with absolute urls with the standard format, but it gave some sort of restricted error. Somebody then suggested this option, which has worked and solved my problem

```<code>url : "<?php echo Juri::base(); ?>directory/etc/suburb.php",
</code>```

Thanks, Adri

Body:
I am running some custom php file that contains some javascript code within a Joomla website through an extension called sourcerer. Everything works as expected from the php side of things however I am experiencing an issue with a call to another php file made from within a javascript.  Here is the javascript code in question and on the second line is the "suburb.php" file that is called from within this code that is causing the issue.

$.ajax({
 url : 'suburb.php',
 dataType: "json",
 method: 'post',
 data: {
     name_startsWith: request.term,
     type: 'suburb_table',
     row_num : 1
 },
 success: function( data ) {
     response( $.map( data, function( item ) {
         var code = item.split("|");
         return {
             label: code[0],
             value: code[0],
             data : item
         }
     }));
 }
});

The problem I am having is that even though the originating php file that contains this javascript is in the same directory as the suburb.php file, Joomla seems to change the URL call to "localhost/index.php/menu_alias/suburb.php" and this causes a POST error 404 (Component non found).

I have tried using many variation of the url path in that second line of the code, but all have failed. Can somebody tell me what my url path should look like for this to work?

Thank you,
Adri

Body:
Thank you for your feedback. I tried with absolute urls with the standard format, but it gave some sort of restricted error. Somebody then suggested this option, which has worked and solved my problem

url : "<?php echo Juri::base(); ?>directory/etc/suburb.php",

Thanks, Adri


问:
Minikube with Istio Gateway Connection Refused
I'm trying to get a local kubernetes cluster running with Minikube and Istio. I followed the instructions found in the istio docs here: https://istio.io/docs/tasks/installing-istio.html

Then I followed the steps to install the sample BookInfo sample here: https://istio.io/docs/samples/bookinfo.html

However when I try and curl the Gateway URL, I get a connection refused error. All my pods and services appear to be running. Here is the result of the kubectl get pods command:

```<code>NAME                             READY     STATUS    RESTARTS   AGE
details-v1-1932527472-ggpf1      2/2       Running   0          8m
grafana-1261931457-d7wwx         1/1       Running   0          12m
istio-ca-3887035158-hnmkr        1/1       Running   0          12m
istio-egress-1920226302-vx1ml    1/1       Running   0          12m
istio-ingress-2112208289-kkblh   1/1       Running   0          12m
istio-manager-2910860705-qj8wv   2/2       Running   0          12m
istio-mixer-2335471611-hnnsz     1/1       Running   0          12m
productpage-v1-241699992-kl5mt   2/2       Running   0          8m
prometheus-3067433533-mdmp5      1/1       Running   0          12m
ratings-v1-2565146534-112g5      2/2       Running   0          8m
reviews-v1-2536835021-fp16t      2/2       Running   0          8m
reviews-v2-3299280847-x687f      2/2       Running   0          8m
reviews-v3-4061726673-6f4gb      2/2       Running   0          8m
servicegraph-3127588006-zc1w4    1/1       Running   0          12m
</code>```

Here is the result of the kubectl get services command:

```<code>NAME            CLUSTER-IP   EXTERNAL-IP   PORT(S)
AGE
details         10.0.0.151   <none>        9080/TCP                      10m
grafana         10.0.0.243   <pending>     3000:32076/TCP                14m
istio-egress    10.0.0.22    <none>        80/TCP                        14m
istio-ingress   10.0.0.96    <pending>     80:31126/TCP,443:30916/TCP    14m
istio-manager   10.0.0.90    <none>        8080/TCP,8081/TCP             14m
istio-mixer     10.0.0.68    <none>        9091/TCP,9094/TCP,42422/TCP   14m
kubernetes      10.0.0.1     <none>        443/TCP                       14m
productpage     10.0.0.139   <none>        9080/TCP                      10m
prometheus      10.0.0.95    <pending>     9090:32474/TCP                14m
ratings         10.0.0.110   <none>        9080/TCP                      10m
reviews         10.0.0.197   <none>        9080/TCP                      10m
servicegraph    10.0.0.230   <pending>     8088:32648/TCP                14m
</code>```

Then I run these commands:

```<code>export GATEWAY_URL=$(kubectl get po -l istio=ingress -o 'jsonpath={.items[0].status.hostIP}'):$(kubectl get svc istio-ingress -o 'jsonpath={.spec.ports[0].nodePort}')
curl -o /dev/null -s -w "%{http_code}\n" http://${GATEWAY_URL}/productpage
</code>```

The response I get is 000. Hitting the endpoint with my browser gives me a connection refused error. I had this working at some point, and I have no idea where it broke down the line. Any help would be greatly appreciated!

Version Information

Minikube

minikube version: v0.19.0

Kubectl

```<code>Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T20:41:07Z", GoVersion:"go1.8.1", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.0", GitCommit:"fff5156092b56e6bd60fff75aad4dc9de6b6ef37", GitTreeState:"clean", BuildDate:"2017-05-09T23:22:45Z", GoVersion:"go1.7.3", Compiler:"gc", Platform:"linux/amd64"}
</code>```

Istio

```<code>istioctl version:

Version: 0.1.5
GitRevision: 21f4cb4
GitBranch: master
User: jenkins@ubuntu-16-04-build-de3bbfab70500
GolangVersion: go1.8
KubeInjectHub: docker.io/istio
KubeInjectTag: 0.1

apiserver version:

Version: 0.1.5
GitRevision: 21f4cb4
GitBranch: master
User: jenkins@ubuntu-16-04-build-de3bbfab70500
GolangVersion: go1.8.1
</code>```

答:
This is more a support/troubleshooting question

Can you link this question in https://github.com/istio/issues/issues
and click "New Issue", link the great details you already did put here but also add the value of GATEWAY_URL and/or the full output of

```<code>curl -v http://${GATEWAY_URL}/productpage
</code>```

there. thanks !

Also Minikube v0.19.0 has known issues, please upgrade to v0.19.1 and try again to see if this alone solves your problem?

Body:
I'm trying to get a local kubernetes cluster running with Minikube and Istio. I followed the instructions found in the istio docs here: https://istio.io/docs/tasks/installing-istio.html

Then I followed the steps to install the sample BookInfo sample here: https://istio.io/docs/samples/bookinfo.html

However when I try and curl the Gateway URL, I get a connection refused error. All my pods and services appear to be running. Here is the result of the kubectl get pods command:

NAME                             READY     STATUS    RESTARTS   AGE
details-v1-1932527472-ggpf1      2/2       Running   0          8m
grafana-1261931457-d7wwx         1/1       Running   0          12m
istio-ca-3887035158-hnmkr        1/1       Running   0          12m
istio-egress-1920226302-vx1ml    1/1       Running   0          12m
istio-ingress-2112208289-kkblh   1/1       Running   0          12m
istio-manager-2910860705-qj8wv   2/2       Running   0          12m
istio-mixer-2335471611-hnnsz     1/1       Running   0          12m
productpage-v1-241699992-kl5mt   2/2       Running   0          8m
prometheus-3067433533-mdmp5      1/1       Running   0          12m
ratings-v1-2565146534-112g5      2/2       Running   0          8m
reviews-v1-2536835021-fp16t      2/2       Running   0          8m
reviews-v2-3299280847-x687f      2/2       Running   0          8m
reviews-v3-4061726673-6f4gb      2/2       Running   0          8m
servicegraph-3127588006-zc1w4    1/1       Running   0          12m

Here is the result of the kubectl get services command:

NAME            CLUSTER-IP   EXTERNAL-IP   PORT(S)
AGE
details         10.0.0.151   <none>        9080/TCP                      10m
grafana         10.0.0.243   <pending>     3000:32076/TCP                14m
istio-egress    10.0.0.22    <none>        80/TCP                        14m
istio-ingress   10.0.0.96    <pending>     80:31126/TCP,443:30916/TCP    14m
istio-manager   10.0.0.90    <none>        8080/TCP,8081/TCP             14m
istio-mixer     10.0.0.68    <none>        9091/TCP,9094/TCP,42422/TCP   14m
kubernetes      10.0.0.1     <none>        443/TCP                       14m
productpage     10.0.0.139   <none>        9080/TCP                      10m
prometheus      10.0.0.95    <pending>     9090:32474/TCP                14m
ratings         10.0.0.110   <none>        9080/TCP                      10m
reviews         10.0.0.197   <none>        9080/TCP                      10m
servicegraph    10.0.0.230   <pending>     8088:32648/TCP                14m

Then I run these commands:

export GATEWAY_URL=$(kubectl get po -l istio=ingress -o 'jsonpath={.items[0].status.hostIP}'):$(kubectl get svc istio-ingress -o 'jsonpath={.spec.ports[0].nodePort}')
curl -o /dev/null -s -w "%{http_code}\n" http://${GATEWAY_URL}/productpage

The response I get is 000. Hitting the endpoint with my browser gives me a connection refused error. I had this working at some point, and I have no idea where it broke down the line. Any help would be greatly appreciated!

Version Information

Minikube

minikube version: v0.19.0

Kubectl

Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T20:41:07Z", GoVersion:"go1.8.1", Compiler:"gc", Platform:"darwin/amd64"}
Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.0", GitCommit:"fff5156092b56e6bd60fff75aad4dc9de6b6ef37", GitTreeState:"clean", BuildDate:"2017-05-09T23:22:45Z", GoVersion:"go1.7.3", Compiler:"gc", Platform:"linux/amd64"}

Istio

istioctl version:

Version: 0.1.5
GitRevision: 21f4cb4
GitBranch: master
User: jenkins@ubuntu-16-04-build-de3bbfab70500
GolangVersion: go1.8
KubeInjectHub: docker.io/istio
KubeInjectTag: 0.1

apiserver version:

Version: 0.1.5
GitRevision: 21f4cb4
GitBranch: master
User: jenkins@ubuntu-16-04-build-de3bbfab70500
GolangVersion: go1.8.1

Body:
This is more a support/troubleshooting question

Can you link this question in https://github.com/istio/issues/issues
and click "New Issue", link the great details you already did put here but also add the value of GATEWAY_URL and/or the full output of

curl -v http://${GATEWAY_URL}/productpage

there. thanks !

Also Minikube v0.19.0 has known issues, please upgrade to v0.19.1 and try again to see if this alone solves your problem?


问:
trying to decode data (exporting Abs to MySQL)
I have database table:

```<code>DROP TABLE translation_en_lt;
CREATE TABLE translation_en_lt (
  id INTEGER,
  lt_translation WIDEMEMO BLOBBlockSize 102400 BLOBCompressionAlgorithm ZLIB BLOBCompressionMode 9
);
</code>```

Which was generated using AbsManager (Absolute database manager, Delphi). It seem to be outdated however, and syntax is invalid for current MySQL. Then I have this data entry:

```<code>INSERT INTO translation_en_lt (lt_translation) values (MimeToBin('cABhAHMAaQBzAGw='));
</code>```

The value for this row, as displayed correctly in the AbsManager, is pasislinkti. However, base64_decode('cABhAHMAaQBzAGw=') returns p�a�s�i�s�l [base64_encode('pasislinkti') returns cGFzaXNsaW5rdGk=].

How do I get 'pasislinkti' from MimeToBin('cABhAHMAaQBzAGw=')? Does it have anything to do with the encoding, zlib (WIDEMEMO BLOBBlockSize 102400 BLOBCompressionAlgorithm ZLIB BLOBCompressionMode 9)?

I got comment saying:

14:24 VoVo64: guy: looks as if the
  base64 encoded data is actually UCS-2
  little endian. decoding
  cABhAHMAaQBzAGw= to HEX results in 70
  00 61 00 73 00 69 00 73 00 6c

But I have already tried iconv('UTF-16', 'UTF-8', base64_decode('cABhAHMAaQBzAGw=')) which resulted in:

```<code>Notice: iconv(): Detected an incomplete multibyte character in input string in /var/www/ssl/pp.php on line 2 pasis
</code>```

I have also tried: mb_convert_encoding($u, 'UCS-2LE', 'UTF-8'), mb_convert_encoding($u, 'UCS-2', 'UTF-8'); neither didn't work.

答:
These are Base64 strings:

```<code>cABhAHMAaQBzAGw= -> pasisl
cGFzaXNsaW5rdGk= -> pasislinkti
</code>```

I think your data is being truncated somewhere.  You should look for a MimeToText() function in your database system.  I'd try to dump the data out to CSV and load that in MySQL using LOAD DATA INFILE.  You will probably have to rewrite the table schemas by hand.   The BLOBBlockSize.... appears to be for compression of this data. Your new table will take a little more space or you can look into using MySQL's Compress() function.

Something like this should work:

```<code>CREATE TABLE translation_en_lt (
  id INTEGER,
  lt_translation MEDIUMTEXT,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have database table:

DROP TABLE translation_en_lt;
CREATE TABLE translation_en_lt (
  id INTEGER,
  lt_translation WIDEMEMO BLOBBlockSize 102400 BLOBCompressionAlgorithm ZLIB BLOBCompressionMode 9
);

Which was generated using AbsManager (Absolute database manager, Delphi). It seem to be outdated however, and syntax is invalid for current MySQL. Then I have this data entry:

INSERT INTO translation_en_lt (lt_translation) values (MimeToBin('cABhAHMAaQBzAGw='));

The value for this row, as displayed correctly in the AbsManager, is pasislinkti. However, base64_decode('cABhAHMAaQBzAGw=') returns p�a�s�i�s�l [base64_encode('pasislinkti') returns cGFzaXNsaW5rdGk=].

How do I get 'pasislinkti' from MimeToBin('cABhAHMAaQBzAGw=')? Does it have anything to do with the encoding, zlib (WIDEMEMO BLOBBlockSize 102400 BLOBCompressionAlgorithm ZLIB BLOBCompressionMode 9)?

I got comment saying:

14:24 VoVo64: guy: looks as if the
  base64 encoded data is actually UCS-2
  little endian. decoding
  cABhAHMAaQBzAGw= to HEX results in 70
  00 61 00 73 00 69 00 73 00 6c

But I have already tried iconv('UTF-16', 'UTF-8', base64_decode('cABhAHMAaQBzAGw=')) which resulted in:

Notice: iconv(): Detected an incomplete multibyte character in input string in /var/www/ssl/pp.php on line 2 pasis

I have also tried: mb_convert_encoding($u, 'UCS-2LE', 'UTF-8'), mb_convert_encoding($u, 'UCS-2', 'UTF-8'); neither didn't work.

Body:
These are Base64 strings:

cABhAHMAaQBzAGw= -> pasisl
cGFzaXNsaW5rdGk= -> pasislinkti

I think your data is being truncated somewhere.  You should look for a MimeToText() function in your database system.  I'd try to dump the data out to CSV and load that in MySQL using LOAD DATA INFILE.  You will probably have to rewrite the table schemas by hand.   The BLOBBlockSize.... appears to be for compression of this data. Your new table will take a little more space or you can look into using MySQL's Compress() function.

Something like this should work:

CREATE TABLE translation_en_lt (
  id INTEGER,
  lt_translation MEDIUMTEXT,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8


问:
Reset increment when counter reaches specific # after AJAX response in Wordpress
I am having trouble with getting a counter to reset when it reaches a specific number.  I understand how to do this with a while-loop, but I can't seem to reset the counter properly and have the "loop" reset itself after a certain number of AJAX requests.

The full scope of my goal is to query a category of posts in wordpress via AJAX.  Each time a counter will increment which is then used as the value for 'offset' in the WP_Query(array()).  This portion I have working fine.  The trouble I am having is in having the offset variable reset back to 1 and start over... so as to create a loop of the posts.  I am not posting the portion that goes in functions.php because I don't believe I have any problems there, but if you think it will help, just ask and I will gladly add it.  See code below.

```<code>jQuery('#more_posts').click(nextTestimonial);
var page = 1; // What page we are on.
var ppp = 1; // Post per page
function nextTestimonial(){

    jQuery("#more_posts").attr("disabled",true); // Disable the

    jQuery.post(
        'http://localhost/kw/wp-admin/admin-ajax.php',
        {
        'action': 'next_testimonial',
        'page': page,
        'ppp': ppp
        },
        function(response){
            //page++; This works to increment fine if enabled
            if (page==3){ page = 1; } else {page++;} // <-- Trouble Here
            jQuery("#testimonial_box").html(response);
            jQuery("#more_posts").attr("disabled",false);
            jQuery('#more_posts').click(nextTestimonial);

        }
        );
 }
</code>```

答:
```<code> var page = 1; // What page we are on.
 var ppp = 1; // Post per page
</code>```

The counter variables have to be outside your click function or it will not update. Or you have to have some sort of loop going on inside the function.

Body:
I am having trouble with getting a counter to reset when it reaches a specific number.  I understand how to do this with a while-loop, but I can't seem to reset the counter properly and have the "loop" reset itself after a certain number of AJAX requests.

The full scope of my goal is to query a category of posts in wordpress via AJAX.  Each time a counter will increment which is then used as the value for 'offset' in the WP_Query(array()).  This portion I have working fine.  The trouble I am having is in having the offset variable reset back to 1 and start over... so as to create a loop of the posts.  I am not posting the portion that goes in functions.php because I don't believe I have any problems there, but if you think it will help, just ask and I will gladly add it.  See code below.

jQuery('#more_posts').click(nextTestimonial);
var page = 1; // What page we are on.
var ppp = 1; // Post per page
function nextTestimonial(){

    jQuery("#more_posts").attr("disabled",true); // Disable the

    jQuery.post(
        'http://localhost/kw/wp-admin/admin-ajax.php',
        {
        'action': 'next_testimonial',
        'page': page,
        'ppp': ppp
        },
        function(response){
            //page++; This works to increment fine if enabled
            if (page==3){ page = 1; } else {page++;} // <-- Trouble Here
            jQuery("#testimonial_box").html(response);
            jQuery("#more_posts").attr("disabled",false);
            jQuery('#more_posts').click(nextTestimonial);

        }
        );
 }

Body:
 var page = 1; // What page we are on.
 var ppp = 1; // Post per page

The counter variables have to be outside your click function or it will not update. Or you have to have some sort of loop going on inside the function.


问:
How to migrate NSWorkspace notifications to Swift 4?
In Swift 3 I registered for sleep and wake notifications with this code:

```<code>let notificationCenter = NSWorkspace.shared.notificationCenter
notificationCenter.addObserver(self, selector: #selector(AppDelegate.sleepListener), name: NSNotification.Name.NSWorkspaceWillSleep, object: nil)
notificationCenter.addObserver(self, selector: #selector(AppDelegate.wakeUpListener), name: NSNotification.Name.NSWorkspaceDidWake, object: nil)
</code>```

but after migrating to Swift 4, I get this error after applying the suggested fixes:

```<code>Type 'NSNotification.Name' has no member 'NSWorkspace'
</code>```

How do I do this in Swift 4?

答:
To fix this, you need to adjust the code referencing the notification's name from NSNotification.Name.NSWorkspaceWillSleep to NSWorkspace.willSleepNotification. The Swift 4 version is:

```<code>let notificationCenter = NSWorkspace.shared.notificationCenter
notificationCenter.addObserver(self, selector: #selector(AppDelegate.sleepListener), name: NSWorkspace.willSleepNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(AppDelegate.wakeUpListener), name: NSWorkspace.didWakeNotification, object: nil)
</code>```

You can see Apple's API diffs for this change here.

Body:
In Swift 3 I registered for sleep and wake notifications with this code:

let notificationCenter = NSWorkspace.shared.notificationCenter
notificationCenter.addObserver(self, selector: #selector(AppDelegate.sleepListener), name: NSNotification.Name.NSWorkspaceWillSleep, object: nil)
notificationCenter.addObserver(self, selector: #selector(AppDelegate.wakeUpListener), name: NSNotification.Name.NSWorkspaceDidWake, object: nil)

but after migrating to Swift 4, I get this error after applying the suggested fixes:

Type 'NSNotification.Name' has no member 'NSWorkspace'

How do I do this in Swift 4?

Body:
To fix this, you need to adjust the code referencing the notification's name from NSNotification.Name.NSWorkspaceWillSleep to NSWorkspace.willSleepNotification. The Swift 4 version is:

let notificationCenter = NSWorkspace.shared.notificationCenter
notificationCenter.addObserver(self, selector: #selector(AppDelegate.sleepListener), name: NSWorkspace.willSleepNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(AppDelegate.wakeUpListener), name: NSWorkspace.didWakeNotification, object: nil)

You can see Apple's API diffs for this change here.


问:
Using Simulink from c++ application
I would like to know if there is a way to use/communicate with Simulink from a c++ program. In this case Simulink is performing a real-time-simulation an should get its input data during simulation from the c++ controll-program. Also the simulation-data (output of blocks) from simulink should be accessible from the c++ program during simulation. Is this possible?

答:
For real-time processing you need to convert your Simulink model to C code using Simulink Coder.

Being C code, the code resulting from the model can then be used any way you want (within your larger C application).

Title: Using Simulink from c++ application


问:
Exrin: Database Models, Services, and MainModels
From an Exrin design standpoint, should each database model have their own Service?

I find that I may need to check the same thing within the database in multiple MainModels. I figured I would create a Service for these database models to do these repeated operations and have the a service for a MainModel not only implement its own IService interface but also inherit from these database model services.

答:
Each Database should have it's own repository class, but the service can cover many repositories.

I like to think of Services as an Aggregate Repository Layer, where you provide control logic on how the app interacts with the repositories.

If the repositories are extremely large, or it makes no sense to put them together in the same service, then by all means, split them.

However as an example, say I have a Database and an API repository. I have one service, that will retrieve data from the API or repository depending on what I am getting, and provide the information back to the app.

The premise here, is to ensure that the App doesn't concern itself
  with how it gets the information. The service layer is an abstraction layer on top of the repositories.


问:
I want to open a program by JavaScript on the clients computer? (WScript.shell)
I tried to open a program using this code:

```<code><head>
<title></title>
<script language="javascript" type="text/javascript">
    function run() {
        var shell = new ActiveXObject("WScript.shell");
        if (shell) {
            shell.run('"C:\\Program Files (x86)\\BitTorrent\\BitTorrent.exe"', 1);
        }
        else
        { alert("BitTorrent is not installed on your system."); }
    }
</script>
</head>
<body onload="run()">

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

But it doesn't work.
Any help, please?

答: It is because browser block creation of ActiveX controls, for security reasons. Moreover, ActiveX is supported only in IE; IE has options to allow run ActiveX in browser, but I have doubts that many users have this feature enabled.</p>

Body:
I tried to open a program using this code:

<title></title>

But it doesn't work.
Any help, please?