问:
Density plot with ggplot
I am interested in comparison of visualization of dataset: histogram and density. I used dataset below for example only, however the idea is the same and it is for Poisson distribution:
Could anyone help me to plot display this with ggplot2?</p>

```<code>example <- read.csv(file=url('http://www.math.uah.edu/stat/data/HorseKicks.csv'),header=T)
summary(example)

hist(example$C14,prob=T)
summary(glm(C14~1,family=poisson(link='log'),data=example))
lines(x=0:4,y=dpois(0:4,lambda=exp(0.1823)),col='red',lwd=1)
</code>```

答:
May be not that nice but for example like this:</p>

```<code>library(ggplot2)

ggplot(example) + geom_histogram(aes(x = C14,y = ..density..),binwidth = 1) +
stat_function(fun = function(x) dpois(x,lambda=exp(0.1823)),
color = "red", size = 1, n = 5)
</code>```

Title: Density plot with ggplot

Body:
I am interested in comparison of visualization of dataset: histogram and density. I used dataset below for example only, however the idea is the same and it is for Poisson distribution:
Could anyone help me to plot display this with ggplot2?

example <- read.csv(file=url('http://www.math.uah.edu/stat/data/HorseKicks.csv'),header=T)
summary(example)

hist(example$C14,prob=T)
summary(glm(C14~1,family=poisson(link='log'),data=example))
lines(x=0:4,y=dpois(0:4,lambda=exp(0.1823)),col='red',lwd=1)

Body:
May be not that nice but for example like this:

library(ggplot2)

ggplot(example) + geom_histogram(aes(x = C14,y = ..density..),binwidth = 1) +
stat_function(fun = function(x) dpois(x,lambda=exp(0.1823)),
color = "red", size = 1, n = 5)


来源: stackexchange

问:
What to set for Spring's @PropertySource when using spring.config.location command line arg?
I have defined a @Config class like so:

```<code>@Config
@PropertySource(value = "")
public class Foo {
...
}
</code>```

I run my program by including the following:

```<code> --spring.config.location=file:///Users/dev/workspace/application.yml
</code>```

The problem is that I cannot omit the 'value' attribute of the PropertySource annotation. Why do you need to set that? Will that overwrite what I have set in --spring.config.location? Should I use SimpleCommandLinePropertySource instead of --spring.config.location?

答:
When you use external property file using spring.config.location you just have to set for value in your configuration class:</p>

```<code>@Config
@PropertySource(value = "${spring.config.location}")
public class Foo {
...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have defined a @Config class like so:

@Config
@PropertySource(value = "")
public class Foo {
...
}

I run my program by including the following:

 --spring.config.location=file:///Users/dev/workspace/application.yml

The problem is that I cannot omit the 'value' attribute of the PropertySource annotation. Why do you need to set that? Will that overwrite what I have set in --spring.config.location? Should I use SimpleCommandLinePropertySource instead of --spring.config.location?

Body:
When you use external property file using spring.config.location you just have to set for value in your configuration class:

@Config
@PropertySource(value = "${spring.config.location}")
public class Foo {
...
}


问:
Swift 3 - Reduce a collection of objects by an Int property
I have an array containing 3 objects like so:

```<code>class AClass {
    var distance: Int?
}

let obj0 = AClass()
obj0.distance = 0

let obj1 = AClass()
obj1.distance = 1

let obj2 = AClass()
obj2.distance = 2

let arr = [obj0, obj1, obj2]
</code>```

When I reduce the array and assign it to a variable, I can only sum the last element in the array.

```<code>let total = arr.reduce(0, {$1.distance! + $1.distance!})  //returns 4
</code>```

If I try $0.distance! it errors with "expression is ambiguous without more context".

I tried being more explicit:

```<code>var total = arr.reduce(0, {(first: AClass, second: AClass) -> Int in
    return first.distance! + second.distance!
})
</code>```

But this errors with "'Int' is incompatible with contextual type '_'"
How do I reduce it to the sum of the distances?

答:
```<code>var total = arr.reduce(0, {$0 + $1.distance!})
</code>```

The first argument is the accumulator, it is already an integer.

Note that this will crash on elements without distance. You could fix that e.g. using:

```<code>let total = arr.reduce(0, {$0 + ($1.distance ?? 0)})
</code>```

or

```<code>let total = arr.compactMap { $0.distance }.reduce(0, +)
</code>```

Body:
I have an array containing 3 objects like so:

class AClass {
    var distance: Int?
}

let obj0 = AClass()
obj0.distance = 0

let obj1 = AClass()
obj1.distance = 1

let obj2 = AClass()
obj2.distance = 2

let arr = [obj0, obj1, obj2]

When I reduce the array and assign it to a variable, I can only sum the last element in the array.

let total = arr.reduce(0, {$1.distance! + $1.distance!})  //returns 4

If I try $0.distance! it errors with "expression is ambiguous without more context".

I tried being more explicit:

var total = arr.reduce(0, {(first: AClass, second: AClass) -> Int in
    return first.distance! + second.distance!
})

But this errors with "'Int' is incompatible with contextual type '_'"
How do I reduce it to the sum of the distances?

Body:
var total = arr.reduce(0, {$0 + $1.distance!})

The first argument is the accumulator, it is already an integer.

Note that this will crash on elements without distance. You could fix that e.g. using:

let total = arr.reduce(0, {$0 + ($1.distance ?? 0)})

or

let total = arr.compactMap { $0.distance }.reduce(0, +)

ContentLicense: CC BY-SA 4.0


问:
Reverse for 'x' with arguments '(1,)' not found. 1 pattern(s) tried: ['grupe/(?P<grupa_id>[0-9]+)/(?P<elev_id>[0-9]+)/$']
I was trying to build a django app which would let me access some groups that contain student(elev) objects. I can't make Elev objects show, tho.

Elevi urls.py

```<code>from django.conf.urls import url
from . import views

app_name = 'elevi'

urlpatterns = [
    #/
    url(r'^$', views.index, name = 'index'),
    #/Grupe/id
    url(r'^grupe/(?P<grupa_id>[0-9]+)/$', views.connect, name="connect"),
    #/Grupe/id/elevi_id
    url(r'^grupe/(?P<grupa_id>[0-9]+)/(?P<elev_id>[0-9]+)/$', views.elev_individual, name="elev_individual")
    ]
</code>```

Elevi views.py

```<code>from django.shortcuts import render,get_object_or_404
from .models import Grupa,Elev

def index(request):
    toate_grupele = Grupa.objects.all()
    context = {"toate_grupele" : toate_grupele}
    return render(request,'Elevi/test.html',context)

def connect(request,grupa_id):
    grupa = get_object_or_404(Grupa, pk = grupa_id)
    return render(request,'Elevi/connect.html',{'grupa':grupa})

def elev_individual(request,elev_id):
    elev = get_object_or_404(Elev, pk = elev_id)
    return render(request,'Elevi/elev_individual.html',{'elev':elev})
</code>```

test.html

```<code>{% if toate_grupele %}
<ul>
    {% for grupa in toate_grupele %}
         <li><a href ="{% url 'elevi:connect' grupa.id %}">{{ grupa.nume_grupa }}</a></li>
    {% endfor %}
</ul>
{% else %}
    <p>Nu sunt grupe salvate</p>
{% endif %}
</code>```

connect.html

```<code><h1>{{ grupa.nume_grupa }}</h1>
<h3>Lista Elevi:</h3>

<ul>
    {% for elev in grupa.elev_set.all %}
        <li><a href="{% url 'elevi:elev_individual' elev.id %}">{{ elev.nume_elev }} {{ elev.prenume_elev }}</a></li>
    {% endfor %}
</ul>
</code>```

elev_individual.html

```<code><p>{{ elev.nume_elev }} {{ elev.prenume_elev }}</p>
</code>```

答:
The url pattern doesn't match the view arguments

view

```<code>def index(request): #url pattern don't need any argument
def connect(request,grupa_id): #url pattern needs one argument
def elev_individual(request,elev_id): #requires one argument
</code>```

url

```<code>url(r'^$', views.index, name = 'index'), # good
url(r'^grupe/(?P<grupa_id>[0-9]+)/$', views.connect, name="connect") #good
</code>```

If you look at the error message, elev_individual requires two argument in the def elev_individual(request,elev_id): view method. To fix this, either remove the second argument so that

```<code>['grupe/(?P<grupa_id>[0-9]+)/(?P<elev_id>[0-9]+)/$']
</code>```

becomes

```<code>['grupe/(?P<elev_id>[0-9]+)/$']
</code>```

or add another argument elev_id as the second argument to your view so it becomes

```<code>def elev_individual(request,grupa_id, elev_id):
</code>```

and filter as necessary

Body:
I was trying to build a django app which would let me access some groups that contain student(elev) objects. I can't make Elev objects show, tho.

Elevi urls.py

from django.conf.urls import url
from . import views

app_name = 'elevi'

urlpatterns = [
    #/
    url(r'^$', views.index, name = 'index'),
    #/Grupe/id
    url(r'^grupe/(?P<grupa_id>[0-9]+)/$', views.connect, name="connect"),
    #/Grupe/id/elevi_id
    url(r'^grupe/(?P<grupa_id>[0-9]+)/(?P<elev_id>[0-9]+)/$', views.elev_individual, name="elev_individual")
    ]

Elevi views.py

from django.shortcuts import render,get_object_or_404
from .models import Grupa,Elev

def index(request):
    toate_grupele = Grupa.objects.all()
    context = {"toate_grupele" : toate_grupele}
    return render(request,'Elevi/test.html',context)

def connect(request,grupa_id):
    grupa = get_object_or_404(Grupa, pk = grupa_id)
    return render(request,'Elevi/connect.html',{'grupa':grupa})

def elev_individual(request,elev_id):
    elev = get_object_or_404(Elev, pk = elev_id)
    return render(request,'Elevi/elev_individual.html',{'elev':elev})

test.html

{% if toate_grupele %}

    {% for grupa in toate_grupele %}

{{ grupa.nume_grupa }}

    {% endfor %}

{% else %}

Nu sunt grupe salvate

{% endif %}

connect.html

{{ grupa.nume_grupa }}

Lista Elevi:

    {% for elev in grupa.elev_set.all %}

{{ elev.nume_elev }} {{ elev.prenume_elev }}

    {% endfor %}

elev_individual.html

{{ elev.nume_elev }} {{ elev.prenume_elev }}

Body:
The url pattern doesn't match the view arguments

view

def index(request): #url pattern don't need any argument
def connect(request,grupa_id): #url pattern needs one argument
def elev_individual(request,elev_id): #requires one argument

url

url(r'^$', views.index, name = 'index'), # good
url(r'^grupe/(?P<grupa_id>[0-9]+)/$', views.connect, name="connect") #good

If you look at the error message, elev_individual requires two argument in the def elev_individual(request,elev_id): view method. To fix this, either remove the second argument so that

['grupe/(?P<grupa_id>[0-9]+)/(?P<elev_id>[0-9]+)/$']

becomes

['grupe/(?P<elev_id>[0-9]+)/$']

or add another argument elev_id as the second argument to your view so it becomes

def elev_individual(request,grupa_id, elev_id):

and filter as necessary


问:
Typescript/ES6: import src files with absolute path
in one of my files I import another commonjs module with

```<code>import * as at from '../../../at-angular'
</code>```

I would much rather do

```<code>import * as at from 'fv/at-angular'
</code>```

with fv being my src directory. So my app folder structure looks like this:

```<code>- src
  - at-angular.ts
  - core
    - services
  ....
</code>```

Can I somehow enable typescript to have fv point to src?

答:
I've created a gist for the source code to use absolute path names or any other paths deifned in the tsconfig.json
It works well with Browserify+Watchify+Tsify also works with Gulp-typescript.

https://gist.github.com/azarus/f369ee2ab0283ba0793b0ccf0e9ec590

It transforms path names & baseUrl defined in the tsconfig.json to their relative path names.
Enjoy!

Body:
in one of my files I import another commonjs module with

import * as at from '../../../at-angular'

I would much rather do

import * as at from 'fv/at-angular'

with fv being my src directory. So my app folder structure looks like this:

- src
  - at-angular.ts
  - core
    - services
  ....

Can I somehow enable typescript to have fv point to src?


问:
Imagick not enough processor power?
I'm trying to do crop animated gif on VDS with this configuration:

~800MHz and 256 RAM

And it's not working. It just eats memory and processor and after a ~minute returns no responce.

http://i192.photobucket.com/albums/z228/Somebi/no-responce.jpg

http://imm.io/1OID

On local machine i'v created a virtual machine with 256 RAM.
Everything works fine, but a bit slow i must admit...
But i have Duo Core 7400 on local machine.

I have tried to limit memory usage on VDS with these settings:

```<code>$gif = new Imagick($s['src']);

set_time_limit(0);
$gif->setResourceLimit(Imagick::RESOURCETYPE_MEMORY,32);
$gif->setResourceLimit(Imagick::RESOURCETYPE_MAP,64);

// echo $gif->getResourceLimit(Imagick::RESOURCETYPE_MEMORY);
// echo $gif->getResourceLimit(Imagick::RESOURCETYPE_MAP);
// echo $gif->getResourceLimit(Imagick::RESOURCETYPE_FILE);
// echo $gif->getResourceLimit(Imagick::RESOURCETYPE_DISK);
// echo $gif->getResourceLimit(Imagick::RESOURCETYPE_AREA);
// exit;

$gif = $gif->coalesceImages();

foreach($gif as $frame){
    $frame->cropImage($s['params']['w'], $s['params']['h'], $s['params']['x'], $s['params']['y']);
    $frame->setImagePage($s['params']['w'], $s['params']['h'], 0, 0);
}

$gif->writeImages($s['dest_path'] .'/'. $fullname,true);
</code>```

But can i limit processor usage?

And is there any solution for slow VDS? :|

Thanks everyone!

update:

```<code>   print_r(getimagesize($s['src']));
   exit;

   $gif = new Imagick($s['src']);
   etc...

    Array
(
    [0] => 530
    [1] => 150
    [2] => 1
    [3] => width="530" height="150"
    [bits] => 8
    [channels] => 3
    [mime] => image/gif
)
</code>```

update2:

```<code>pathinfo($s['src'])

(
    [dirname] => images/tmp
    [basename] => 43138a0723d6ae0799564bd6acb8c7b83c8df483.gif
    [extension] => gif
    [filename] => 43138a0723d6ae0799564bd6acb8c7b83c8df483
)
</code>```

update3:
How to debug imagick extension? :(

Have found this package:
http://fr2.rpmfind.net/linux/RPM/fedora/updates/testing/13/i386/debug/php-pecl-imagick-debuginfo-3.0.0-5.fc13.i686.html

Have anyone tried it?

答:
Try running your php script on command line to see whether it has anything to do with execution time.

```<code>shell> php <your-script-name>
</code>```

You may have to replace full path to php if it's not in your PATH environment variable.

Keep in mind that ImageMagick is optimized for quality; not for speed. There's a similar library called GraphicsMagick which (they say) is running well with low resources. You may consider trying it if you still experience resource issue.

ContentLicense: CC BY-SA 2.5

Title: Imagick not enough processor power?

Body:
I'm trying to do crop animated gif on VDS with this configuration:

~800MHz and 256 RAM

And it's not working. It just eats memory and processor and after a ~minute returns no responce.

http://i192.photobucket.com/albums/z228/Somebi/no-responce.jpg

http://imm.io/1OID

On local machine i'v created a virtual machine with 256 RAM.
Everything works fine, but a bit slow i must admit...
But i have Duo Core 7400 on local machine.

I have tried to limit memory usage on VDS with these settings:

$gif = new Imagick($s['src']);

set_time_limit(0);
$gif->setResourceLimit(Imagick::RESOURCETYPE_MEMORY,32);
$gif->setResourceLimit(Imagick::RESOURCETYPE_MAP,64);

// echo $gif->getResourceLimit(Imagick::RESOURCETYPE_MEMORY);
// echo $gif->getResourceLimit(Imagick::RESOURCETYPE_MAP);
// echo $gif->getResourceLimit(Imagick::RESOURCETYPE_FILE);
// echo $gif->getResourceLimit(Imagick::RESOURCETYPE_DISK);
// echo $gif->getResourceLimit(Imagick::RESOURCETYPE_AREA);
// exit;

$gif = $gif->coalesceImages();

foreach($gif as $frame){
    $frame->cropImage($s['params']['w'], $s['params']['h'], $s['params']['x'], $s['params']['y']);
    $frame->setImagePage($s['params']['w'], $s['params']['h'], 0, 0);
}

$gif->writeImages($s['dest_path'] .'/'. $fullname,true);

But can i limit processor usage?

And is there any solution for slow VDS? :|

Thanks everyone!

update:

   print_r(getimagesize($s['src']));
   exit;

   $gif = new Imagick($s['src']);
   etc...

    Array
(
    [0] => 530
    [1] => 150
    [2] => 1
    [3] => width="530" height="150"
    [bits] => 8
    [channels] => 3
    [mime] => image/gif
)

update2:

pathinfo($s['src'])

(
    [dirname] => images/tmp
    [basename] => 43138a0723d6ae0799564bd6acb8c7b83c8df483.gif
    [extension] => gif
    [filename] => 43138a0723d6ae0799564bd6acb8c7b83c8df483
)

update3:
How to debug imagick extension? :(

Have found this package:
http://fr2.rpmfind.net/linux/RPM/fedora/updates/testing/13/i386/debug/php-pecl-imagick-debuginfo-3.0.0-5.fc13.i686.html

Have anyone tried it?

Body:
Try running your php script on command line to see whether it has anything to do with execution time.

shell> php <your-script-name>

You may have to replace full path to php if it's not in your PATH environment variable.

Keep in mind that ImageMagick is optimized for quality; not for speed. There's a similar library called GraphicsMagick which (they say) is running well with low resources. You may consider trying it if you still experience resource issue.


问:
Content alignment inside wrapper
I'm reaching this sketch:

how I can push image towards bottom, then I can align content noramally. For some unknown reason for me, content reacting like a row, not a column

```<code><div class="d-flex flex-wrap">
    <div class="premises">
        <div class="left-wrapper">
            <img class="img-responsive" src="http://i.imgur.com/riJ1LKY.jpg" />
        </div>
        <div class="right-wrapper align-self-end">
            <div class="title">
                <p class="">Title text</p>
            </div>
            <div class="ordered-data d-inline-flex justify-content-between">
                <p class="">**.**.**</p>
                <p class="">**:** - **:**</p>
            </div>   <div class="destination d-inline-flex justify-content-start">
                <p class="">Destination</p>
            </div>
            <div class="footer-options d-inline-flex justify-content-between">
                <p class="">Submit</p>
                <p class="">Cancel</p>
            </div>
        </div>
    </div>
</div>
</code>```

Fiddle

答:
First off, your .premises should have flex-direction: row; (or remove it for default behaviour) to get closer to the result in your original image.
Then you should set a min-height: 0; to your left and right wrappers to counter flex's min-height: auto; behaviour, and remove the height: 100%; as the value isn't explicitly set in the parent. I also recommend setting vertical-align: bottom; to your image tag.

Here is an updated, working fiddle: https://jsfiddle.net/ybxbx55m/

Title: Content alignment inside wrapper

Body:
I'm reaching this sketch:

how I can push image towards bottom, then I can align content noramally. For some unknown reason for me, content reacting like a row, not a column

Title text

**.**.**

**:** - **:**

Destination

Submit

Cancel

Fiddle


问:
adapter getFilter not filtering
I'm at a loss on this one, after reading several posts I still have no clue what to do with my current situation. But when I filter my Cursor Adapter the list will not update or filter anything, it is like nothing happens at all.

here is the activity where i view a list of clients

```<code>public class ViewClientActivity extends Activity
{

EditText inputSearch;

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewclient_activity);

    inputSearch = (EditText) findViewById(R.id.search_view);

    DBHandler handler = new DBHandler(this, null, null, 1);
    SQLiteDatabase db = handler.getReadableDatabase();
    final Cursor ClientCursor = db.rawQuery("SELECT  * FROM clients", null);
    final ListView allClients = (ListView) findViewById(R.id.allClients);
    final ClientCursorAdapter clientAdapter = new ClientCursorAdapter(this, ClientCursor);

    allClients.setAdapter(clientAdapter);

    allClients.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Cursor cur = (Cursor) parent.getItemAtPosition(position);
            int clientIdint = cur.getInt(cur.getColumnIndex("_id"));
            String clientId = Integer.toString(clientIdint);
            Intent AddClientIntent = new Intent(getApplicationContext(), AddClientActivity.class);
            AddClientIntent.putExtra("CLIENT_IDINT", clientIdint);
            AddClientIntent.putExtra("CLIENT_ID", clientId);
            startActivity(AddClientIntent);
        }
    });

    inputSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3)
        {
            // When user changed the Text
            clientAdapter.getFilter().filter(cs.toString());
            allClients.setAdapter(clientAdapter);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }
    });

}
}
</code>```

and here is my cursor class

```<code>public class ClientCursorAdapter extends CursorAdapter
{

public ClientCursorAdapter(Context context, Cursor cursor) {
    super(context, cursor, 0);
}

// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.display_client_row, parent, false);
}

// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
@Override
public void bindView(View view, Context context, Cursor cursor) {
    // Find fields to populate in inflated template
    TextView txtViewName = (TextView) view.findViewById(R.id.txtViewName);
    TextView txtViewAddress = (TextView) view.findViewById(R.id.txtViewAddress);
    TextView txtViewPhoneNum = (TextView) view.findViewById(R.id.txtViewPhoneNum);
    // Extract properties from cursor
    String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
    String address = cursor.getString(cursor.getColumnIndexOrThrow("address"));
    String homenum = cursor.getString(cursor.getColumnIndexOrThrow("homenum"));
    String cellnum = cursor.getString(cursor.getColumnIndexOrThrow("cellnum"));
    String worknum = cursor.getString(cursor.getColumnIndexOrThrow("worknum"));
    // Populate fields with extracted properties
    txtViewName.setText(name);
    txtViewAddress.setText(address);

    if (!cellnum.equals("") && !cellnum.equalsIgnoreCase("cell phone"))
    {
        txtViewPhoneNum.setText(String.valueOf(cellnum));
    }
    else if (!homenum.equals("") && !homenum.equalsIgnoreCase("home phone"))
    {
        txtViewPhoneNum.setText(String.valueOf(homenum));
    }
    else if (!worknum.equals("") && !worknum.equalsIgnoreCase("work phone"))
    {
        txtViewPhoneNum.setText(String.valueOf(worknum));
    }
    else
    {
        txtViewPhoneNum.setText("No phone listed.");
    }

}

}
</code>```

thanks for your time and let me know if you need any other information!

答:
To filter CursorAdapter or SimpleCursorAdapter you have to use clientAdapter.setFilterQueryProvider than you can filter your content.

```<code>  clientAdapter .setFilterQueryProvider(new FilterQueryProvider() {
   public Cursor runQuery(CharSequence constraint) {
  //your code here
    }

 });
</code>```

You can see here for more detailed explanation: How to set Filter to ListView with CursorAdapter?
Also you don't have to setup adapter twice remove allClients.setAdapter(clientAdapter); from your addTextChangedListener method. If needed you can call notifyDataSetChanged();

Title: adapter getFilter not filtering

Body:
I'm at a loss on this one, after reading several posts I still have no clue what to do with my current situation. But when I filter my Cursor Adapter the list will not update or filter anything, it is like nothing happens at all.

here is the activity where i view a list of clients

public class ViewClientActivity extends Activity
{

EditText inputSearch;

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewclient_activity);

    inputSearch = (EditText) findViewById(R.id.search_view);

    DBHandler handler = new DBHandler(this, null, null, 1);
    SQLiteDatabase db = handler.getReadableDatabase();
    final Cursor ClientCursor = db.rawQuery("SELECT  * FROM clients", null);
    final ListView allClients = (ListView) findViewById(R.id.allClients);
    final ClientCursorAdapter clientAdapter = new ClientCursorAdapter(this, ClientCursor);

    allClients.setAdapter(clientAdapter);

    allClients.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Cursor cur = (Cursor) parent.getItemAtPosition(position);
            int clientIdint = cur.getInt(cur.getColumnIndex("_id"));
            String clientId = Integer.toString(clientIdint);
            Intent AddClientIntent = new Intent(getApplicationContext(), AddClientActivity.class);
            AddClientIntent.putExtra("CLIENT_IDINT", clientIdint);
            AddClientIntent.putExtra("CLIENT_ID", clientId);
            startActivity(AddClientIntent);
        }
    });

    inputSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3)
        {
            // When user changed the Text
            clientAdapter.getFilter().filter(cs.toString());
            allClients.setAdapter(clientAdapter);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }
    });

}
}

and here is my cursor class

public class ClientCursorAdapter extends CursorAdapter
{

public ClientCursorAdapter(Context context, Cursor cursor) {
    super(context, cursor, 0);
}

// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.display_client_row, parent, false);
}

// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
@Override
public void bindView(View view, Context context, Cursor cursor) {
    // Find fields to populate in inflated template
    TextView txtViewName = (TextView) view.findViewById(R.id.txtViewName);
    TextView txtViewAddress = (TextView) view.findViewById(R.id.txtViewAddress);
    TextView txtViewPhoneNum = (TextView) view.findViewById(R.id.txtViewPhoneNum);
    // Extract properties from cursor
    String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
    String address = cursor.getString(cursor.getColumnIndexOrThrow("address"));
    String homenum = cursor.getString(cursor.getColumnIndexOrThrow("homenum"));
    String cellnum = cursor.getString(cursor.getColumnIndexOrThrow("cellnum"));
    String worknum = cursor.getString(cursor.getColumnIndexOrThrow("worknum"));
    // Populate fields with extracted properties
    txtViewName.setText(name);
    txtViewAddress.setText(address);

    if (!cellnum.equals("") && !cellnum.equalsIgnoreCase("cell phone"))
    {
        txtViewPhoneNum.setText(String.valueOf(cellnum));
    }
    else if (!homenum.equals("") && !homenum.equalsIgnoreCase("home phone"))
    {
        txtViewPhoneNum.setText(String.valueOf(homenum));
    }
    else if (!worknum.equals("") && !worknum.equalsIgnoreCase("work phone"))
    {
        txtViewPhoneNum.setText(String.valueOf(worknum));
    }
    else
    {
        txtViewPhoneNum.setText("No phone listed.");
    }

}

}

thanks for your time and let me know if you need any other information!

Body:
To filter CursorAdapter or SimpleCursorAdapter you have to use clientAdapter.setFilterQueryProvider than you can filter your content.

  clientAdapter .setFilterQueryProvider(new FilterQueryProvider() {
   public Cursor runQuery(CharSequence constraint) {
  //your code here
    }

 });

You can see here for more detailed explanation: How to set Filter to ListView with CursorAdapter?
Also you don't have to setup adapter twice remove allClients.setAdapter(clientAdapter); from your addTextChangedListener method. If needed you can call notifyDataSetChanged();


问:
Fetch IP Address
I want to get ip address of client machine Like I opened website on my machine which is hosted on any server So i need IP address of my machine not hosted server IP.</p>

答:
    ''# VB
    HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")
```

<pre class="lang-cs prettyprint-override"><code>    // C#
    HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
</code>```

This will get the PUBLIC ip address of the client computer. It will NOT get the LAN IP (192.168...)

Title: Fetch IP Address

Body:
    ''# VB
    HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")

    // C#
    HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]

This will get the PUBLIC ip address of the client computer. It will NOT get the LAN IP (192.168...)


问:
How do I implement native FB login in a hybrid Phonegap app?
I've been searching and trying things for a few days
I'm making an app with Phonegap for both Android and IOS. The app will have both a facebook login and a normal registration.
Using OpenFB I can do everything I wanted except logging in with the facebook app.
Basically I want to know how I can, in both Android and IOS, use the facebook app (if it's available) to sign my user in without him having to write his user and password. Skip that step and ask the permissions right away, sign him in right away.
Literally all I need is to have my user login and get his name, picture and email; without him having to write his credentials (if he is logged in to the facebook app).</p>

答:
From what I've seen lately it doesn't seem possible, but I might be wrong. Phonegap and it's plugins are old, some do some things, others don't even seem to work anymore. Not sure if there is a way to do it now with Phonegap. OpenFB works well but it doesn't login automatically the first time, although after you log in you can save the token so you don't have to write your email and password again. Try it, that might be the best you can do. Uncomment the following line:
openFB.init({appId: YOUR_APP_ID, tokenStore: window.localStorage});`</p>


问:
setText in PostExecute gives me error
I was trying to setText for two views while parsing JSON from server but it gives me error when run.
Here is my code:

```<code>protected void onPostExecute(String result) {
            super.onPostExecute(result);
            textView.setText(result);
            newTextView.setText(result);
        }
</code>```

Here is my error:

```<code>FATAL EXCEPTION: main
    java.lang.NullPointerException
    at com.musicianfocus.ben.wordedfm.MainActivity$JSONTask.onPostExecute(MainActivity.java:254)
    at com.musicianfocus.ben.wordedfm.MainActivity$JSONTask.onPostExecute(MainActivity.java:208)
    at android.os.AsyncTask.finish(AsyncTask.java:631)
    at android.os.AsyncTask.access$600(AsyncTask.java:177)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)
    06
</code>```

答:
It is bad practice to access views from an AsyncTask. Thing is, by the time that AsyncTask is finished, your activity might be dead and you would try to access inexisting views. Instead, I would suggest that you use a library called EventBus from here: https://github.com/greenrobot/EventBus

The idea is the following: You post an event in onPostExecute with the correct values to set. Then you catch that event in your activity or fragment and update your views from there. This is an architecturally much better solution.

Title: setText in PostExecute gives me error

Body:
I was trying to setText for two views while parsing JSON from server but it gives me error when run.
Here is my code:

protected void onPostExecute(String result) {
            super.onPostExecute(result);
            textView.setText(result);
            newTextView.setText(result);
        }

Here is my error:

FATAL EXCEPTION: main
    java.lang.NullPointerException
    at com.musicianfocus.ben.wordedfm.MainActivity$JSONTask.onPostExecute(MainActivity.java:254)
    at com.musicianfocus.ben.wordedfm.MainActivity$JSONTask.onPostExecute(MainActivity.java:208)
    at android.os.AsyncTask.finish(AsyncTask.java:631)
    at android.os.AsyncTask.access$600(AsyncTask.java:177)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)
    06


问:
Adding transformations in Sybase replication server
We have primary source database as Oracle 11gR2 and target as SAP HANA. We are trying to test SAP - Sybase Replication server for replication from Primary ORACLE to Target HANA.

We need to add extra columns such as RECORD_DATE and LAST_MODIFIED_DATE to HANA tables. Is it possible to add Transformations or extra columns to target tables which are not present in Primary Database.

Best Regards

答:
I'm assuming you want to capture auditing data for records inserted/updated by the Repserver maintenance user (in the HANA database).

While the column default (for inserts; as discussed with Shivam) will work, for updates you've got a few options:

an update trigger on the HANA table [I don't work with HANA so I don't know if this is doable]

defining the update column as a (materialized) computed column, with the associated function being responsible for obtaining the current date/time when  other columns in the table are modified [while this is doable in Sybase ASE, I don't know if this is doable in HANA]

(in repserver) create a custom function string for the rs_update function on this table which emulates a standard rs_update function string with the addition  of an update of LAST_MODIFIED_DATE = getdate() (replace getdate() with HANA's equivalent of the current date/time) [there are a couple different ways to do this depending on SRS version, what's doable with HANA-specific function strings, and personal preference - a bit much to go into at this point if a custom function string is going to be out of the question or you've already got an acceptable solution]


问:
Hadoop - java.net.ConnectException: Connection refused
I want connect to hdfs (in localhost) and i have a error:

Call From despubuntu-ThinkPad-E420/127.0.1.1 to localhost:54310 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused

I follow all the steps in other posts, but i dont solve my problem. I use hadoop 2.7 and this is configurations:

core-site.xml

```<code><configuration>
  <property>
    <name>hadoop.tmp.dir</name>
    <value>/home/despubuntu/hadoop/name/data</value>
  </property>

  <property>
    <name>fs.default.name</name>
    <value>hdfs://localhost:54310</value>
  </property>
</configuration>
</code>```

hdfs-site.xml

```<code><configuration>
  <property>
    <name>dfs.replication</name>
    <value>1</value>
  </property>
</configuration>
</code>```

I type /usr/local/hadoop/bin/hdfs namenode -format and
/usr/local/hadoop/sbin/start-all.sh

But when i type "jps" the result is:

```<code>10650 Jps
4162 Main
5255 NailgunRunner
20831 Launcher
</code>```

I need help...

答: I got the same issue. You can see Name node, DataNode, Resource manager and Task manager daemons are running when you type. So just do start-all.sh then all daemons start running and now you can access HDFS.</p>

Body:
I want connect to hdfs (in localhost) and i have a error:

Call From despubuntu-ThinkPad-E420/127.0.1.1 to localhost:54310 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused

I follow all the steps in other posts, but i dont solve my problem. I use hadoop 2.7 and this is configurations:

core-site.xml

<configuration>
  <property>
    <name>hadoop.tmp.dir</name>
    <value>/home/despubuntu/hadoop/name/data</value>
  </property>

  <property>
    <name>fs.default.name</name>
    <value>hdfs://localhost:54310</value>
  </property>
</configuration>

hdfs-site.xml

<configuration>
  <property>
    <name>dfs.replication</name>
    <value>1</value>
  </property>
</configuration>

I type /usr/local/hadoop/bin/hdfs namenode -format and
/usr/local/hadoop/sbin/start-all.sh

But when i type "jps" the result is:

10650 Jps
4162 Main
5255 NailgunRunner
20831 Launcher

I need help...


问:
SQL Server: Group By based on one column and get columns based on other column
My data:

```<code>ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
C                          ABCD                Yes
</code>```

My SQL should be able to do following:

Group by Column A

Select only those groups of A that contain Yes and Null both in the result of a

Expected Result is:

```<code>ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
</code>```

How do I select all values that satisfy above rule?

答:
```<code>create table #t(ColumnA varchar(10),ColumnB varchar(10),ColumnC varchar(10))
insert into #t
    select 'A','Hi','Yes' union all
    select 'A','Hello',NULL union all
    select 'B','Hola','Yes' union all
    select 'B','Hola','Yes' union all
    select 'B','Hi',NULL union all
    select 'C','ABCD','Yes'
 select * from (
     select *,sum(case when ColumnC='YES' THEN 1 else 0 end)over(partition by ColumnA) as YesCount
             ,sum(case when ColumnC is null then 1 else 0 end)over(partition by ColumnA) as NULLCount
     from #t
) as t where t.YesCount>0 and t.NULLCount>0
</code>```

```
    ColumnA ColumnB ColumnC YesCount    NULLCount
1   A   Hi  Yes 1   1
2   A   Hello   NULL    1   1
3   B   Hola    Yes 2   1
4   B   Hola    Yes 2   1
5   B   Hi  NULL    2   1
```

Body:
My data:

ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
C                          ABCD                Yes

My SQL should be able to do following:

Group by Column A

Select only those groups of A that contain Yes and Null both in the result of a

Expected Result is:

ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL

How do I select all values that satisfy above rule?

Body:
create table #t(ColumnA varchar(10),ColumnB varchar(10),ColumnC varchar(10))
insert into #t
    select 'A','Hi','Yes' union all
    select 'A','Hello',NULL union all
    select 'B','Hola','Yes' union all
    select 'B','Hola','Yes' union all
    select 'B','Hi',NULL union all
    select 'C','ABCD','Yes'
 select * from (
     select *,sum(case when ColumnC='YES' THEN 1 else 0 end)over(partition by ColumnA) as YesCount
             ,sum(case when ColumnC is null then 1 else 0 end)over(partition by ColumnA) as NULLCount
     from #t
) as t where t.YesCount>0 and t.NULLCount>0

    ColumnA ColumnB ColumnC YesCount    NULLCount
1   A   Hi  Yes 1   1
2   A   Hello   NULL    1   1
3   B   Hola    Yes 2   1
4   B   Hola    Yes 2   1
5   B   Hi  NULL    2   1


问:
The C# Project is targeting ".NetFramework, Version=v4.5,Profile=Unity Full v3.5", which is not instaled on this machine
I tried to open a script in VS2015 from Unity 5.6.
For some reasons, this popup shows up and I click the first option and change the target to .Net Framework 4.5.2 and everything builds and works as expected.
However, every time I made changes in the Unity editor and switched back to Visual Studio, this dialog pops up again.

When I looked into the csproj files, I can see that, after I made changes in the Unity editor, I see this:

```<code><TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkProfile>Unity Full v3.5</TargetFrameworkProfile>
</code>```

Then after I selected "Change the target to .NET Framework 4.5.2"
I see this:

```<code><TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
</code>```

It seems that the Unity editor is configured to change the .Net Framework to 4.5.
I tried to install .Net Framework 4.5 but it is already installed.

Is there any way I can either use .Net 4.5 in Visual Studio or change the target framework in Unity such that this dialog won't pop up again?

答:
In the Unity roadmap is stated that support for .net 4.6 will be added arround july 2017. The beta is out allready.

Scripting Runtime Upgrade (Preview)

Upgrade Mono and IL2CPP .NET runtimes to support the latest .NET functionality and APIs. This includes access to C# 6 and the .NET 4.6.x class library profile.

Currently Unity is only compatible with .net 3.5 but here is an workaround which may help.

If you have any of the .NET Framework v4.6 series allready installed you only need to install the Visual Studio 2015 Tools for Unity to be able to use the project without conversions.

Body:
I tried to open a script in VS2015 from Unity 5.6.
For some reasons, this popup shows up and I click the first option and change the target to .Net Framework 4.5.2 and everything builds and works as expected.
However, every time I made changes in the Unity editor and switched back to Visual Studio, this dialog pops up again.

When I looked into the csproj files, I can see that, after I made changes in the Unity editor, I see this:

<TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkProfile>Unity Full v3.5</TargetFrameworkProfile>

Then after I selected "Change the target to .NET Framework 4.5.2"
I see this:

<TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>

It seems that the Unity editor is configured to change the .Net Framework to 4.5.
I tried to install .Net Framework 4.5 but it is already installed.

Is there any way I can either use .Net 4.5 in Visual Studio or change the target framework in Unity such that this dialog won't pop up again?


问:
Solving a logic riddle in Prolog
I'm in the "early phase" of learning prolog and came across a logic riddle that seams easy to implement:

Link to the riddle | Link to solution

We are looking for the 10-digit number which satisfies the following conditions:

All digits from 0-9 occur exactly once.

The first 2 digits are divisible by 2.

The first 3 digits are divisible by 3.

...

The first 10 digits are divisible by 10.

I think I would first need to implement the rules to the .pl file right?
The rules from the solution are:

An integer can be divided by 1 without remainder.

An integer is divisible by 2 without remainder, if the last digit is straight.

An integer can be divided by 3 without a remainder if its transverse sum is divisible by 3.

An integer can be divided by 4 without a remainder if the last two digits are divisible by 4.

An integer is divisible by 5 if the last digit is divisible by 5.

An integer is divisible by 6 without a remainder if its transverse sum is divisible by 3 and the last digit by 2.

An integer is divisible by 8 without a remainder if the last three digits are divisible by 8.

An integer is divisible by 9 without a remainder if its transverse sum is divisible by 9.

An integer is divisible by 10 without a remainder if the last digit is a 0.

I read multiple introductions to rules in prolog but still dont get how do it. Can anyone help? Would be great :)

答:
Here's a slightly different approach with CLP(FD). First let's consider a predicate, that describes a relation between a list, its first n elements and the number those n elements yield. This version is somewhat similar but less general than @mat's digits_integer/2.

```<code>:- use_module(library(clpfd)).

digits_firstn_number_(_D,0,Num,Num).
digits_firstn_number_([D|Ds],X1,Num,Acc0) :-
   X1 #> 0,
   X0 #= X1-1,
   Acc1 #= Acc0*10+D,
   digits_firstn_number_(Ds,X0,Num,Acc1).
</code>```

The calling predicate num/1 consists of a goal num_/2, that describes the actual relation and a second goal label/1 that is labeling the list of digits which is the second argument of num_/2. As a minor difference to @mat's version num/1 has the actual number rather than the list of digits as an argument:

```<code>num(Num) :-
   num_(Num,Digits),     % <- actual relation
   label(Digits).        % <- labeling the digits
</code>```

The actual relation, num_/2 differs insofar, as the divisibility rules are, wherever possible, expressed as constraints on the respective digits (as suggested in the solution you linked) rather than on the corresponding numbers:

```<code>num_(Num,Digits) :-
   Digits=[A,B,C,D,E,F,G,H,I,J],
   Digits ins 0..9,
   all_distinct(Digits),                     % divisibility for:
   0 #= B mod 2,                             % <- first 2 digits
   0 #= (A+B+C) mod 3,                       % <- first 3 digits
   digits_firstn_number_([C,D],2,Num4,0),    % <- first 4 digits
   0 #= Num4 mod 4,                          % <- first 4 digits
   0 #= (E) mod 5,                           % <- first 5 digits
   0 #= (A+B+C+D+E+F) mod 3,                 % <- first 6 digits
   0 #= F mod 2,                             % <- first 6 digits
   digits_firstn_number_(Digits,7,Num7,0),   % <- first 7 digits
   0 #= Num7 mod 7,                          % <- first 7 digits
   digits_firstn_number_([F,G,H],3,Num8,0),  % <- first 8 digits
   0 #= Num8 mod 8,                          % <- first 8 digits
   0 #= (A+B+C+D+E+F+G+H+I) mod 9,           % <- first 9 digits
   J #= 0,                                   % <- all 10 digits
   digits_firstn_number_(Digits,10,Num,0).   % <- the actual number
</code>```

The downside of this approach (besides more code) is, that it is exceedingly tailored towards this specific puzzle while @mat's version can be more easily extended to search for numbers with a different amount of digits with similar constraints (first n digits divisible by n). On the upside this approach is faster (compared with SWI-Prolog (Multi-threaded, 64 bits, Version 6.6.4)):

```<code>?- time((num(Num),false)).
% 2,544,064 inferences, 0.486 CPU in 0.486 seconds (100% CPU, 5235403 Lips)
false.

?- time((solution(Ds),label(Ds),false)).
% 19,289,281 inferences, 3.323 CPU in 3.324 seconds (100% CPU, 5805472 Lips)
false.
</code>```

And of course, num/1 yields the same solution:

```<code>?- num(Num).
Num = 3816547290 ;
false.
</code>```

Title: Solving a logic riddle in Prolog

Body:
Here's a slightly different approach with CLP(FD). First let's consider a predicate, that describes a relation between a list, its first n elements and the number those n elements yield. This version is somewhat similar but less general than @mat's digits_integer/2.

:- use_module(library(clpfd)).

digits_firstn_number_(_D,0,Num,Num).
digits_firstn_number_([D|Ds],X1,Num,Acc0) :-
   X1 #> 0,
   X0 #= X1-1,
   Acc1 #= Acc0*10+D,
   digits_firstn_number_(Ds,X0,Num,Acc1).

The calling predicate num/1 consists of a goal num_/2, that describes the actual relation and a second goal label/1 that is labeling the list of digits which is the second argument of num_/2. As a minor difference to @mat's version num/1 has the actual number rather than the list of digits as an argument:

num(Num) :-
   num_(Num,Digits),     % <- actual relation
   label(Digits).        % <- labeling the digits

The actual relation, num_/2 differs insofar, as the divisibility rules are, wherever possible, expressed as constraints on the respective digits (as suggested in the solution you linked) rather than on the corresponding numbers:

num_(Num,Digits) :-
   Digits=[A,B,C,D,E,F,G,H,I,J],
   Digits ins 0..9,
   all_distinct(Digits),                     % divisibility for:
   0 #= B mod 2,                             % <- first 2 digits
   0 #= (A+B+C) mod 3,                       % <- first 3 digits
   digits_firstn_number_([C,D],2,Num4,0),    % <- first 4 digits
   0 #= Num4 mod 4,                          % <- first 4 digits
   0 #= (E) mod 5,                           % <- first 5 digits
   0 #= (A+B+C+D+E+F) mod 3,                 % <- first 6 digits
   0 #= F mod 2,                             % <- first 6 digits
   digits_firstn_number_(Digits,7,Num7,0),   % <- first 7 digits
   0 #= Num7 mod 7,                          % <- first 7 digits
   digits_firstn_number_([F,G,H],3,Num8,0),  % <- first 8 digits
   0 #= Num8 mod 8,                          % <- first 8 digits
   0 #= (A+B+C+D+E+F+G+H+I) mod 9,           % <- first 9 digits
   J #= 0,                                   % <- all 10 digits
   digits_firstn_number_(Digits,10,Num,0).   % <- the actual number

The downside of this approach (besides more code) is, that it is exceedingly tailored towards this specific puzzle while @mat's version can be more easily extended to search for numbers with a different amount of digits with similar constraints (first n digits divisible by n). On the upside this approach is faster (compared with SWI-Prolog (Multi-threaded, 64 bits, Version 6.6.4)):

?- time((num(Num),false)).
% 2,544,064 inferences, 0.486 CPU in 0.486 seconds (100% CPU, 5235403 Lips)
false.

?- time((solution(Ds),label(Ds),false)).
% 19,289,281 inferences, 3.323 CPU in 3.324 seconds (100% CPU, 5805472 Lips)
false.

And of course, num/1 yields the same solution:

?- num(Num).
Num = 3816547290 ;
false.


问:
How to get Average Rating using SQL
I have a table:

How can I calculate average rating for a tutor using T-SQL in SQL Server 2008?

答:
If I understand your question, this should do it.</p>

```<code>SELECT tutorid,
       CAST((SUM(CASE WHEN rated1 = 1 THEN 1.00 ELSE 0.00 END)+
       SUM(CASE WHEN rated2 = 1 THEN 2.00 ELSE 0.00 END)+
       SUM(CASE WHEN rated3 = 1 THEN 3.00 ELSE 0.00 END)+
       SUM(CASE WHEN rated4 = 1 THEN 4.00 ELSE 0.00 END)+
       SUM(CASE WHEN rated5 = 1 THEN 5.00 ELSE 0.00 END))/(COUNT (*))AS DECIMAL(3,2)) 'Average'
FROM YourTable
GROUP BY tutorid
</code>```

Title: How to get Average Rating using SQL

Body:
If I understand your question, this should do it.

SELECT tutorid,
       CAST((SUM(CASE WHEN rated1 = 1 THEN 1.00 ELSE 0.00 END)+
       SUM(CASE WHEN rated2 = 1 THEN 2.00 ELSE 0.00 END)+
       SUM(CASE WHEN rated3 = 1 THEN 3.00 ELSE 0.00 END)+
       SUM(CASE WHEN rated4 = 1 THEN 4.00 ELSE 0.00 END)+
       SUM(CASE WHEN rated5 = 1 THEN 5.00 ELSE 0.00 END))/(COUNT (*))AS DECIMAL(3,2)) 'Average'
FROM YourTable
GROUP BY tutorid


问:
Deployment files not updating (BitBucket, OneDrive)
I'm developing a bot using the online editor, to add and remove files I was first using the OneDrive continuous integration then tried using BitBucket.

Using OneDrive adding files seemed to work but recently I wanted to also remove some files. I removed them from my local drive, waited for it to sync up to onedrive (I checked and they had gone from the web view) and then did a sync from the bot console.

The new files were created but the files I had deleted are still in the bot and screwing up the compilation.

More recently I have setup a BitBucket account and created everything there, connected it up etc and deployed to the bot account and it also doesn't change any of the code.

答: I don't know what the root cause is for why it was not behaving correctly but I have deleted & recreated my bot service account and the new one works fine. </p>


问:
What is wrong with my Grails deploy to Tomcat container?
I am seeing an issue where my Grails 3 web application does not start up correctly on an EC2 instance that we have successfully deployed a Grails 2 web application to. This same Grails 2 application has been upgraded to Grails 3, and is now causing the issue.

The version of Grails I am using is 3.2.4. The version of Tomcat that is being used on the EC2 instance is 8.0.20. Also, the JVM version is 1.8.0_31.

The war file is built using the Grails command grails package (I'm not sure if there's a difference between this and grails war as other Grails 3.2.4 applications package and deploy just fine using this command), and the file is subsequently placed into the Tomcat webapps directory.

This is the issue I see when starting up Tomcat:

```<code>Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'grailsCacheFilter': Cannot create inner bean '(inner bean)#2fb114b8' of type [grails.plugin.cache.web.filter.simple.MemoryPageFragmentCachingFilter] while setting bean property 'filter'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#2fb114b8': Unsatisfied dependency expressed through method 'setUrlMappingsHandlerMapping' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'urlMappingsHandlerMapping': Unsatisfied dependency expressed through method 'setWebRequestInterceptors' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'openSessionInViewInterceptor': Cannot resolve reference to bean 'hibernateDatastore' while setting bean property 'hibernateDatastore'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastore': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor threw exception; nested exception is java.lang.NullPointerException
</code>```

This happens when I package, deploy, and start up the application using production mode only. I have tried setting the project up in a Tomcat 8 container locally, in qa mode on a different EC2 instance, and also in qa mode on an EC2 instance that was launched from an image that I made of the production instance I am trying to deploy to. I could not reproduce the issue on any of these.

I thought that it was possible that the dataSource in application.groovy production environment block was causing the issue. Since this particular project doesn't rely on a database, I have tried removing that and deploying the web app again in production mode on the production instance, but I still faced the same issue.

I have also tried to replicate the production dataSource configuration in qa mode. The project still started up correctly using qa mode with the same dataSource properties. I didn't see the issue appear in the Tomcat logs.

I have also read the docs a few times (particularly the deployment section), and have made sure to change the line for spring-boot-starter-tomcat dependency to provided "org.springframework.boot:spring-boot-starter-tomcat" in build.gradle since I am not using an embedded Tomcat.

After doing some more research, I am still unsure of what could be causing this issue. Maybe there is some incompatibility with Tomcat that I am overlooking. Does anyone have any ideas? Any help would be greatly appreciated. Thank you.

答:
It is a bug in grails v.3.2.4.
https://github.com/grails/grails-core/issues/10377</p>

Body:
I am seeing an issue where my Grails 3 web application does not start up correctly on an EC2 instance that we have successfully deployed a Grails 2 web application to. This same Grails 2 application has been upgraded to Grails 3, and is now causing the issue.

The version of Grails I am using is 3.2.4. The version of Tomcat that is being used on the EC2 instance is 8.0.20. Also, the JVM version is 1.8.0_31.

The war file is built using the Grails command grails package (I'm not sure if there's a difference between this and grails war as other Grails 3.2.4 applications package and deploy just fine using this command), and the file is subsequently placed into the Tomcat webapps directory.

This is the issue I see when starting up Tomcat:

Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'grailsCacheFilter': Cannot create inner bean '(inner bean)#2fb114b8' of type [grails.plugin.cache.web.filter.simple.MemoryPageFragmentCachingFilter] while setting bean property 'filter'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#2fb114b8': Unsatisfied dependency expressed through method 'setUrlMappingsHandlerMapping' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'urlMappingsHandlerMapping': Unsatisfied dependency expressed through method 'setWebRequestInterceptors' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'openSessionInViewInterceptor': Cannot resolve reference to bean 'hibernateDatastore' while setting bean property 'hibernateDatastore'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastore': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor threw exception; nested exception is java.lang.NullPointerException

This happens when I package, deploy, and start up the application using production mode only. I have tried setting the project up in a Tomcat 8 container locally, in qa mode on a different EC2 instance, and also in qa mode on an EC2 instance that was launched from an image that I made of the production instance I am trying to deploy to. I could not reproduce the issue on any of these.

I thought that it was possible that the dataSource in application.groovy production environment block was causing the issue. Since this particular project doesn't rely on a database, I have tried removing that and deploying the web app again in production mode on the production instance, but I still faced the same issue.

I have also tried to replicate the production dataSource configuration in qa mode. The project still started up correctly using qa mode with the same dataSource properties. I didn't see the issue appear in the Tomcat logs.

I have also read the docs a few times (particularly the deployment section), and have made sure to change the line for spring-boot-starter-tomcat dependency to provided "org.springframework.boot:spring-boot-starter-tomcat" in build.gradle since I am not using an embedded Tomcat.

After doing some more research, I am still unsure of what could be causing this issue. Maybe there is some incompatibility with Tomcat that I am overlooking. Does anyone have any ideas? Any help would be greatly appreciated. Thank you.


问:
JavaFX: Call method on specific time
Is there a way to simply get a method to run on a specific frame or time?
I've read up on the Timeline and Keyframe + KeyValue documentation and it seems overkill for what I am trying to achieve.
I'm trying to get something as simple as this, (refer to my pesudocode):

```<code>atTime(Duration.millis(2000)){
     myMethod();
   } //do this at the time 00:00:02
atTime(Duration.millis(3000)){
     myMethod();
   } //do this at the time 00:00:03
atTime(Duration.millis(5000)){
     myMethod();
   } //do this at the time 00:00:05
</code>```

And I keep timing when my method is called until I want it to stop.
Is there a way to achieve this without using complicated methods revolving around keyframes and keyvalues?

答:
You can do this in a pretty simple way using a Timeline:

```<code>Timeline timeline = new Timeline(
    new KeyFrame(Duration.seconds(2), e -> myMethod()),
    new KeyFrame(Duration.seconds(3), e -> myMethod()),
    new KeyFrame(Duration.seconds(5), e -> myMethod())
);

// If you want to repeat indefinitely:
timeline.setCycleCount(Animation.INDEFINITE);

timeline.play();
</code>```

Title: JavaFX: Call method on specific time

Body:
Is there a way to simply get a method to run on a specific frame or time?
I've read up on the Timeline and Keyframe + KeyValue documentation and it seems overkill for what I am trying to achieve.
I'm trying to get something as simple as this, (refer to my pesudocode):

atTime(Duration.millis(2000)){
     myMethod();
   } //do this at the time 00:00:02
atTime(Duration.millis(3000)){
     myMethod();
   } //do this at the time 00:00:03
atTime(Duration.millis(5000)){
     myMethod();
   } //do this at the time 00:00:05

And I keep timing when my method is called until I want it to stop.
Is there a way to achieve this without using complicated methods revolving around keyframes and keyvalues?

Body:
You can do this in a pretty simple way using a Timeline:

Timeline timeline = new Timeline(
    new KeyFrame(Duration.seconds(2), e -> myMethod()),
    new KeyFrame(Duration.seconds(3), e -> myMethod()),
    new KeyFrame(Duration.seconds(5), e -> myMethod())
);

// If you want to repeat indefinitely:
timeline.setCycleCount(Animation.INDEFINITE);

timeline.play();


问:
How to make an audio play/pause button?
I recently learned about embedding audio in html like below.

```<code> <audio controls>
  <source src="sample.ogg" type="audio/ogg">
  <source src="sample.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</code>```

Which displays something like a rectangle with various options on it like pause/play, download, set volume etc.

But how can I instead of this "audio playing rectangle" have a button that when clicked plays the audio once and on clicking on it while the audio is playing pauses it and on clicking again continuous playing.

答:
You can use Javascript to perform such actions.

Try the following

```<code>var myAudio = document.getElementById("myAudio");
var isPlaying = false;

function togglePlay() {
  if (isPlaying) {
    myAudio.pause()
  } else {
    myAudio.play();
  }
};
myAudio.onplaying = function() {
  isPlaying = true;
};
myAudio.onpause = function() {
  isPlaying = false;
};
</code>```

Just replace the parameters to yours.

Title: How to make an audio play/pause button?

Body:
I recently learned about embedding audio in html like below.

 <audio controls>
  <source src="sample.ogg" type="audio/ogg">
  <source src="sample.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

Which displays something like a rectangle with various options on it like pause/play, download, set volume etc.

But how can I instead of this "audio playing rectangle" have a button that when clicked plays the audio once and on clicking on it while the audio is playing pauses it and on clicking again continuous playing.

Body:
You can use Javascript to perform such actions.

Try the following

var myAudio = document.getElementById("myAudio");
var isPlaying = false;

function togglePlay() {
  if (isPlaying) {
    myAudio.pause()
  } else {
    myAudio.play();
  }
};
myAudio.onplaying = function() {
  isPlaying = true;
};
myAudio.onpause = function() {
  isPlaying = false;
};

Just replace the parameters to yours.


问:
mix ecto.create connection refused
I received this error when trying to run mix ecto.create:

13:27:47.442 [error] GenServer #PID<0.3189.0> terminating
      ** (DBConnection.ConnectionError) tcp connect (localhost:5432):connection refused - :econnrefused
      (db_connection) lib/db_connection/connection.ex:148:DBConnection.Connection.connect/2
      (connection) lib/connection.ex:622: Connection.enter_connect/5
      (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
      Last message: nil
      State: Postgrex.Protocol
      ** (Mix) The database for Hello.Repo couldn't be created: an exception was raised:
      ** (DBConnection.ConnectionError) tcp connect (localhost:5432): connection refused - :econnrefused
          (db_connection) lib/db_connection/connection.ex:148: DBConnection.Connection.connect/2
          (connection) lib/connection.ex:622: Connection.enter_connect/5
          (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3

答:
You must make sure that the postgresql server is running. The easiest way to this on mac OS X is through brew.

Run the command brew services start postgresql and you should see the result:

==> Successfully started postgresql (label: homebrew.mxcl.postgresql)

Title: mix ecto.create connection refused


问:
Using Promises to iteratively delete items in IndexedDb
I'm a bit new to promises here so the solution may be trivial / syntactical.

My goal when storing media is to see if a quota is set and - if needed - delete items from the store until we have space.

My attempt is here, but my biggest pain point is that while loop - figuring out how to wait until an item is deleted to re-evaluate whether or not to continue deleting:

```<code>   const store = database.transaction(storeName, "readwrite").objectStore(storeName);
   while (storageUsedInGb > storageQuotaInGb) {
       // problem: pause loop here
       const latestMediaRequest = store.get(latestMediaGuid);
       latestMediaRequest.onsuccess = function(event) {
              var deleteRequest = store.delete(latestMediaGuid);
              deleteRequest.onsuccess = function () {
                    storageUsedInGb -= event.target.media.size / 1024 / 1000 / 1000;
                       // problem: continue loop here
              }
              deleteRequest.onerror = reject;
        }
        latestMediaRequest.onerror = reject;
    }
</code>```

How can I tell that while loop to wait to iterate until I have a resolution from the latestMediaRequest and then the deleteRequest (updating storageUsedInGb)?

答:
You can loop asynchronously with a function you call recursively. The function can be an immediately invoked function expression:</p>

```<code>const store = database.transaction(storeName, "readwrite").objectStore(storeName);
(function loop(storageUsedInGb) {
    if (storageUsedInGb <= storageQuotaInGb) {
        // if you are in a promise constructor callback, you will call resolve() here
        return; // exit chain of loop calls
    }
    const latestMediaRequest = store.get(latestMediaGuid);
    latestMediaRequest.onsuccess = function(event) {
        var deleteRequest = store.delete(latestMediaGuid);
        deleteRequest.onsuccess =
            loop.bind(null, storageUsedInGb-event.target.media.size / 1024 / 1000 / 1000);
        deleteRequest.onerror = reject;
    }
    latestMediaRequest.onerror = reject;
})(storageUsedInGb); // call immediately
</code>```

Body:
I'm a bit new to promises here so the solution may be trivial / syntactical.

My goal when storing media is to see if a quota is set and - if needed - delete items from the store until we have space.

My attempt is here, but my biggest pain point is that while loop - figuring out how to wait until an item is deleted to re-evaluate whether or not to continue deleting:

   const store = database.transaction(storeName, "readwrite").objectStore(storeName);
   while (storageUsedInGb > storageQuotaInGb) {
       // problem: pause loop here
       const latestMediaRequest = store.get(latestMediaGuid);
       latestMediaRequest.onsuccess = function(event) {
              var deleteRequest = store.delete(latestMediaGuid);
              deleteRequest.onsuccess = function () {
                    storageUsedInGb -= event.target.media.size / 1024 / 1000 / 1000;
                       // problem: continue loop here
              }
              deleteRequest.onerror = reject;
        }
        latestMediaRequest.onerror = reject;
    }

How can I tell that while loop to wait to iterate until I have a resolution from the latestMediaRequest and then the deleteRequest (updating storageUsedInGb)?

Body:
You can loop asynchronously with a function you call recursively. The function can be an immediately invoked function expression:

const store = database.transaction(storeName, "readwrite").objectStore(storeName);
(function loop(storageUsedInGb) {
    if (storageUsedInGb <= storageQuotaInGb) {
        // if you are in a promise constructor callback, you will call resolve() here
        return; // exit chain of loop calls
    }
    const latestMediaRequest = store.get(latestMediaGuid);
    latestMediaRequest.onsuccess = function(event) {
        var deleteRequest = store.delete(latestMediaGuid);
        deleteRequest.onsuccess =
            loop.bind(null, storageUsedInGb-event.target.media.size / 1024 / 1000 / 1000);
        deleteRequest.onerror = reject;
    }
    latestMediaRequest.onerror = reject;
})(storageUsedInGb); // call immediately


问:
change date format in vaadin-grid
I'm pulling a Date from a database into the vaadin-grid(vaadin-table) with angular2. All I need is MM/DD/YYYY format. The date filters is not working in the vaadin-grid like {{dateOfBirth | date:'dd/mm/yyyy'}}.

Thank you! Examples make the most sense to me as I'm very new to vaadin.

答:
Formatting to DD/MM/YYYY of vaadin-date input when selecting a date(vaadin-date-picker).     </p>

```<code>toDDMMYYYY = function(dateFromInput){ //DD/MM/YYYY
           dateFromInput.set('i18n.formatDate', function(d) {
             var yearStr = d.getFullYear().toString();
             var dateFormatted =  d.getDate() + '/' + (d.getMonth() + 1) + '/' + yearStr;
             return dateFormatted
           });
           dateFromInput.set('i18n.parseDate', function(t) {
             var parts = t.split('/');
             var today = new Date();
             var date, month = today.getMonth(), year = today.getFullYear();

             if (parts.length === 3) {
               year = parseInt(parts[2]);
               if (parts[2].length < 3 && year >= 0) {
                 year += year < 50 ? 2000 : 1900;
               }
               month = parseInt(parts[1]) - 1;
               date = parseInt(parts[0]);
             } else if (parts.length === 2) {
               month = parseInt(parts[1]) - 1;
               date = parseInt(parts[0]);
             } else if (parts.length === 1) {
               date = parseInt(parts[1]);
             }
             if (date !== undefined) {
               var result = new Date(0, 0); // Wrong date (1900-01-01), but with midnight in local time
               result.setFullYear(year);
               result.setMonth(month);
               result.setDate(date);
               return result;
             }
           });
         };
</code>```

Title: change date format in vaadin-grid

Body:
Formatting to DD/MM/YYYY of vaadin-date input when selecting a date(vaadin-date-picker).

toDDMMYYYY = function(dateFromInput){ //DD/MM/YYYY
           dateFromInput.set('i18n.formatDate', function(d) {
             var yearStr = d.getFullYear().toString();
             var dateFormatted =  d.getDate() + '/' + (d.getMonth() + 1) + '/' + yearStr;
             return dateFormatted
           });
           dateFromInput.set('i18n.parseDate', function(t) {
             var parts = t.split('/');
             var today = new Date();
             var date, month = today.getMonth(), year = today.getFullYear();

             if (parts.length === 3) {
               year = parseInt(parts[2]);
               if (parts[2].length < 3 && year >= 0) {
                 year += year < 50 ? 2000 : 1900;
               }
               month = parseInt(parts[1]) - 1;
               date = parseInt(parts[0]);
             } else if (parts.length === 2) {
               month = parseInt(parts[1]) - 1;
               date = parseInt(parts[0]);
             } else if (parts.length === 1) {
               date = parseInt(parts[1]);
             }
             if (date !== undefined) {
               var result = new Date(0, 0); // Wrong date (1900-01-01), but with midnight in local time
               result.setFullYear(year);
               result.setMonth(month);
               result.setDate(date);
               return result;
             }
           });
         };


问:
How to upload a file using Ajax in Scalajs
I'm learning Scalajs by building an image sharing webapp.
In a form, I have a classic file input tag and would like to upload it using Ajax and jQuery to a remote server through a HTTP Post request.

This is the html:

```<code><input id="postTitle" class="form-control" placeholder="Title" type="text" aria-describedby="basic-addon1">

<input id="file" class="form-control" placeholder="Browse" type="file" aria-describedby="basic-addon1">

<input id="tags" class="form-control" placeholder="Tags in format ['tag 1', 'tag 2',...]" type="text">

<button id="postButton" class="btn btn-success">Submit</button>
</code>```

And here is the underlying Scala code:

```<code>lazy val submitElement = jQuery("#postButton")
jQuery(() => {
  submitElement.click {
    (_: JQueryEvent) => {
            dom.ext.Ajax.post(
          url = [server_url],
          data = ???, // <-- How do I get the file?
          headers = Map("Content-Type" -> "application/json")
        ).foreach { xhr =>
          if (xhr.status == 200) {
            val x = JSON.parse(xhr.responseText)
            println(x)
          }
        }
    }
  }
})
</code>```

Any help would be greatly appreciated

答:
I used FormData Api. It is doing with libs for scalajs https://github.com/scalajs-io/form-data</p>

```<code>lazy val submitElement = jQuery("#postButton")

jQuery(() => {
  submitElement.click {
    (_: JQueryEvent) => {
       val file_data = jQuery('#file').prop("files")(0);
       val form_data = FormData();
           form_data.append('file', file_data);

          dom.ext.Ajax.post(
          url = [server_url],
          data = form_data,
          headers = Map("Content-Type" -> "application/json")
        ).foreach { xhr =>
          if (xhr.status == 200) {
            val x = JSON.parse(xhr.responseText)
            println(x)
          }
        }
    }
  }
})
</code>```

Body:
I'm learning Scalajs by building an image sharing webapp.
In a form, I have a classic file input tag and would like to upload it using Ajax and jQuery to a remote server through a HTTP Post request.

This is the html:

<input id="postTitle" class="form-control" placeholder="Title" type="text" aria-describedby="basic-addon1">

<input id="file" class="form-control" placeholder="Browse" type="file" aria-describedby="basic-addon1">

<input id="tags" class="form-control" placeholder="Tags in format ['tag 1', 'tag 2',...]" type="text">

<button id="postButton" class="btn btn-success">Submit</button>

And here is the underlying Scala code:

lazy val submitElement = jQuery("#postButton")
jQuery(() => {
  submitElement.click {
    (_: JQueryEvent) => {
            dom.ext.Ajax.post(
          url = [server_url],
          data = ???, // <-- How do I get the file?
          headers = Map("Content-Type" -> "application/json")
        ).foreach { xhr =>
          if (xhr.status == 200) {
            val x = JSON.parse(xhr.responseText)
            println(x)
          }
        }
    }
  }
})

Any help would be greatly appreciated

Body:
I used FormData Api. It is doing with libs for scalajs https://github.com/scalajs-io/form-data

lazy val submitElement = jQuery("#postButton")

jQuery(() => {
  submitElement.click {
    (_: JQueryEvent) => {
       val file_data = jQuery('#file').prop("files")(0);
       val form_data = FormData();
           form_data.append('file', file_data);

          dom.ext.Ajax.post(
          url = [server_url],
          data = form_data,
          headers = Map("Content-Type" -> "application/json")
        ).foreach { xhr =>
          if (xhr.status == 200) {
            val x = JSON.parse(xhr.responseText)
            println(x)
          }
        }
    }
  }
})


问:
The constructor Random() is not visible
I am creating a gwt application.I get the error "The constructor Random() is not visible" in the method below.I have tried putting it in the main onModuleLoad() as well.

```<code>public void jump(){
 Random generator = new Random();
}
</code>```

I have imported random via the following

```<code>import com.google.gwt.user.client.Random;
</code>```

No matter where I put this I still keep getting that error.

Thanks

答:
Don't instantiate it. Instead, call the static methods on the class:</p>

```<code>Random.nextInt(...)
</code>```

Title: The constructor Random() is not visible

Body:
I am creating a gwt application.I get the error "The constructor Random() is not visible" in the method below.I have tried putting it in the main onModuleLoad() as well.

public void jump(){
 Random generator = new Random();
}

I have imported random via the following

import com.google.gwt.user.client.Random;

No matter where I put this I still keep getting that error.

Thanks

Body:
Don't instantiate it. Instead, call the static methods on the class:

Random.nextInt(...)


问:
What would we do without NULL?
I once read that having nullable types is an absolute evil. I believe it was in an article written by the very person who created them(in Ada?) I believe this is the article

Anyway, so what if by default a language like C# used non-nullable types? How would you replace some of the common idioms in C# or Ruby or any other common language where null is an acceptable value?

答: Realistically speaking, in any powerful programming language that allows pointers or object references in the first place, there are going to be situations where code will be able to access pointers which have not had any initialization code run upon them.  It may be possible to guarantee that such pointers will be initialized to some static value, but that doesn't seem terribly useful.  If a machine has a general means of trapping accesses to uninitialized variables (be they pointers or something else), that's better than special-casing null pointers, but otherwise the biggest null-related mistakes I see occur in implementations that allow arithmetic with null pointers.  Adding 5 to a (char*)0 shouldn't yield a character pointer to address 5; it should trigger an error (if it's appropriate to create pointers to absolute addresses, there should be some other means of doing it).</p>

Title: What would we do without NULL?


问:
Seemingly semantic difference in global versus local variable assignment regarding return values
Given the following bash script:

```<code>#!/usr/bin/env bash

echo $BASH_VERSION

# local [option] [name[=value] ... | - ]
#   For each argument, a local variable named name is created, and assigned value.  The option can  be  any
#   of  the options accepted by declare.  When local is used within a function, it causes the variable name
#   to have a visible scope restricted to that function and its children.  If name is -, the set  of  shell
#   options  is  made  local to the function in which local is invoked: shell options changed using the set
#   builtin inside the function are restored to their original values when the function returns.   With  no
#   operands,  local  writes a list of local variables to the standard output.  It is an error to use local
#   when not within a function.  The return status is 0 unless local is used outside a function, an invalid
#   name is supplied, or name is a readonly variable.

function __count_words {
    local feedback=$(echo "app1 app2")
    echo $feedback
    return $(IFS=' ' set -- ${feedback} && echo $#)
}

function invoke_func {
    declare -f $1_${DF_SYSTEM} >/dev/null
    [ $? -eq 0 ] && { $1_${DF_SYSTEM}; return $?; } || { $1; return $?; }
}

function check_words {
    local list=$(invoke_func __count_words)
    local count=$?
    echo "V1: XXXX [c=$count] > $list"
    list2=$(invoke_func __count_words)
    local count2=$?
    echo "V2: XXXX [c=$count2] > $list2"
}

check_words
</code>```

The output is:

```<code>4.4.12(1)-release
V1: XXXX [c=0] > app1 app2
V2: XXXX [c=2] > app1 app2
</code>```

What is the rationale behind the decision to make a seemingly similar assignment syntax different with regard to return values? I reckon I found the relevant section of the bash(1) man page, however it is unclear as to why this was done that way.

In the case of the local variable assignment, the return status is always 0, however with the global assignment, the return status varies depending on the return status of the called function inside the assignment.

答:
This is an issue that Shellcheck detects as SC2155; consider reading the linked wiki page (and, perhaps, running your code through Shellcheck before asking about it here in the future).

A best-practices implementation of your check_words function would look like this, and does not exhibit your issue:

```<code>check_words() {
    local list count count2               # intentionally leaving list2 global
    list=$(invoke_func __count_words)
    count=$?
    echo "V1: XXXX [c=$count] > $list"
    list2=$(invoke_func __count_words)
    count2=$?
    echo "V2: XXXX [c=$count2] > $list2"
}
</code>```

The local keyword is a built-in command. Like other commands, it has an exit status. Thus, that exit status overrides any exit status from a command substitution used to derive a value.

(Also, the function keyword makes your code gratuitously incompatible with POSIX sh, while not adding any compensating advantages; it's best avoided in favor of POSIX-compliant function declaration syntax).

Body:
Given the following bash script:

#!/usr/bin/env bash

echo $BASH_VERSION

# local [option] [name[=value] ... | - ]
#   For each argument, a local variable named name is created, and assigned value.  The option can  be  any
#   of  the options accepted by declare.  When local is used within a function, it causes the variable name
#   to have a visible scope restricted to that function and its children.  If name is -, the set  of  shell
#   options  is  made  local to the function in which local is invoked: shell options changed using the set
#   builtin inside the function are restored to their original values when the function returns.   With  no
#   operands,  local  writes a list of local variables to the standard output.  It is an error to use local
#   when not within a function.  The return status is 0 unless local is used outside a function, an invalid
#   name is supplied, or name is a readonly variable.

function __count_words {
    local feedback=$(echo "app1 app2")
    echo $feedback
    return $(IFS=' ' set -- ${feedback} && echo $#)
}

function invoke_func {
    declare -f $1_${DF_SYSTEM} >/dev/null
    [ $? -eq 0 ] && { $1_${DF_SYSTEM}; return $?; } || { $1; return $?; }
}

function check_words {
    local list=$(invoke_func __count_words)
    local count=$?
    echo "V1: XXXX [c=$count] > $list"
    list2=$(invoke_func __count_words)
    local count2=$?
    echo "V2: XXXX [c=$count2] > $list2"
}

check_words

The output is:

4.4.12(1)-release
V1: XXXX [c=0] > app1 app2
V2: XXXX [c=2] > app1 app2

What is the rationale behind the decision to make a seemingly similar assignment syntax different with regard to return values? I reckon I found the relevant section of the bash(1) man page, however it is unclear as to why this was done that way.

In the case of the local variable assignment, the return status is always 0, however with the global assignment, the return status varies depending on the return status of the called function inside the assignment.

Body:
This is an issue that Shellcheck detects as SC2155; consider reading the linked wiki page (and, perhaps, running your code through Shellcheck before asking about it here in the future).

A best-practices implementation of your check_words function would look like this, and does not exhibit your issue:

check_words() {
    local list count count2               # intentionally leaving list2 global
    list=$(invoke_func __count_words)
    count=$?
    echo "V1: XXXX [c=$count] > $list"
    list2=$(invoke_func __count_words)
    count2=$?
    echo "V2: XXXX [c=$count2] > $list2"
}

The local keyword is a built-in command. Like other commands, it has an exit status. Thus, that exit status overrides any exit status from a command substitution used to derive a value.

(Also, the function keyword makes your code gratuitously incompatible with POSIX sh, while not adding any compensating advantages; it's best avoided in favor of POSIX-compliant function declaration syntax).


问:
Management VLAN Networking
Question regarding a management VLAN. Should there be an IP address for every device you need to manage, or just enough addresses on the subnet for a few people to manage devices?</p>

答: Often, admin workstations with access to the management VLAN do not have a direct connection but they are routed by a firewall.</p>

Title: Management VLAN Networking


问:
Is it a palindrome in more than 1 base?
I quickly put together some Python code to test my knowledge. I'm trying to detect "multiple palindromes" without using strings. Here's my code:

```<code>from math import log
from math import ceil
from math import floor

palindrome = 0

def palindromify(half, base):
    assert base != 0
    reversedhalf = 0
    palindrome = 0
    iterator = 0
    size = floor(log(half, base)) + 1
    """
        for base = 10 and half = 100,
        log10(100) = 2, floored + 1 = 2 + 1 = 3.

        for base = 10 and half = 999,
        log10(999) = 2.9... (or something).
        floored + 1 = 2 + 1 = 3.

        size = digits.
    """
    palindrome = half * (base ** size)
    while iterator < size:
        digit = floor(half / (base ** iterator)) % base
        reversedhalf = (base ** (size - iterator - 1)) * digit + reversedhalf
        iterator = iterator + 1
    palindrome = reversedhalf + palindrome
    return palindrome

def depalindromify(whole, base):
    halfsize = (ceil(log(whole,base)) / 2)
    """
        if the half is 100 and base = 10, whole = 100001.
        log10(100001) = just over 5
        ceil(just above 5) = 6
        6 / 2 = 3. And 100 is 3 digits!

        if the half is 999 and base = 10, whole = 999999.
        log10(999999) = just under 6.
        ceil(just under 6) = 6
        6 / 2 = 3. 999 is 3 digits.
    """
    halfbottom = whole % (base ** halfsize)
    halftop = (whole - halfbottom) / (base ** halfsize)
    """
        (whole - (whole % (base ** halfsize))) / (base ** halfsize)
        if base = 10, whole = 526625,
        (526625 - (526625 mod 1000)) / (1000)
        = (526625 - 625) / 1000
        = (526000) / 1000
        = 526
    """
    return halftop

"""
    Does not work
"""
def multipalindrome():
    current = 2
    currentbase = 2
    palindromed = 0
    dun = False
    highest = 2
    while True:
        dun = False
        current = (highest ** 4) if current < (highest ** 4) else current + 1
        currentbase = 2
        while not dun:
            palindromed = palindromify(current, currentbase)
            currentbase = currentbase + 1
            depalindromed = depalindromify(palindromed, currentbase)
            print '(D) depalindromed = ', depalindromed
            if (current != depalindromed): ## here
                if currentbase > highest:
                    print 'New highest! In bases from 2 to ', currentbase, ', top half ', current, '!\n'
                highest = currentbase
                dun = True

multipalindrome()

# x = input("Enter first half: ")
# y = input("Enter base:       ")
#
# print palindromify(x, y)
</code>```

I've added the """ comments """ to help myself understand the ceil and floor functions. Basically, multipalindrome() should run an infinite loop that chooses a number, palindromifies it, and sees if that palindrome is a palindrome in more than 1 base. It attempts to do this enough to get a palindrome in all bases (this probably won't happen). I'm not sure where to go as far as detecting multiple palindromes and what bases to use in the function, etc..

When I run this with the python interpreter (2.7), I get:

```<code>...
(D) depalindromed =  30657.0
(D) depalindromed =  30657.0
(D) depalindromed =  30658.0
(D) depalindromed =  30659.0
(D) depalindromed =  30661.0
(D) depalindromed =  30661.0
(D) depalindromed =  30662.0
(D) depalindromed =  30663.0
(D) depalindromed =  30664.0
(D) depalindromed =  30665.0
(D) depalindromed =  30666.0
(D) depalindromed =  30667.0
(D) depalindromed =  30668.0
(D) depalindromed =  30668.0
(D) depalindromed =  30670.0
(D) depalindromed =  30671.0
(D) depalindromed =  30672.0
(D) depalindromed =  30672.0
(D) depalindromed =  30674.0
(D) depalindromed =  30674.0
(D) depalindromed =  30676.0
(D) depalindromed =  30676.0
(D) depalindromed =  30678.0
(D) depalindromed =  30678.0
(D) depalindromed =  30680.0
(D) depalindromed =  30680.0
(D) depalindromed =  30681.0
(D) depalindromed =  30682.0
(D) depalindromed =  30684.0
(D) depalindromed =  30684.0
(D) depalindromed =  30685.0
(D) depalindromed =  30686.0
(D) depalindromed =  30688.0
(D) depalindromed =  30688.0
(D) depalindromed =  30689.0
(D) depalindromed =  30690.0
(D) depalindromed =  30691.0
(D) depalindromed =  30692.0
(D) depalindromed =  30693.0
(D) depalindromed =  30694.0
(D) depalindromed =  30695.0
(D) depalindromed =  30695.0
(D) depalindromed =  30697.0
(D) depalindromed =  30697.0
(D) depalindromed =  30699.0
(D) depalindromed =  30699.0
(D) depalindromed =  30701.0
(D) depalindromed =  30701.0
(D) depalindromed =  30703.0
(D) depalindromed =  30703.0
(D) depalindromed =  30704.0
(D) depalindromed =  30705.0
(D) depalindromed =  30707.0
(D) depalindromed =  30707.0
(D) depalindromed =  30708.0
(D) depalindromed =  30709.0
(D) depalindromed =  30711.0
(D) depalindromed =  30711.0
(D) depalindromed =  30712.0
(D) depalindromed =  30713.0
(D) depalindromed =  30714.0
(D) depalindromed =  30715.0
(D) depalindromed =  30716.0
(D) depalindromed =  30717.0
(D) depalindromed =  30718.0
(D) depalindromed =  30718.0
(D) depalindromed =  30720.0
(D) depalindromed =  30721.0
(D) depalindromed =  30722.0
(D) depalindromed =  30722.0
(D) depalindromed =  30724.0
(D) depalindromed =  30725.0
(D) depalindromed =  30726.0
(D) depalindromed =  30726.0
(D) depalindromed =  30727.0
(D) depalindromed =  30728.0
(D) depalindromed =  30730.0
^CTraceback (most recent call last):
  File "palindrome.py", line 77, in <module>
    multipalindrome()
  File "palindrome.py", line 67, in multipalindrome
    palindromed = palindromify(current, currentbase)
  File "palindrome.py", line 26, in palindromify
    reversedhalf = (base ** (size - iterator - 1)) * digit + reversedhalf
KeyboardInterrupt
henry@FusionReactor:~/code4fun/palindrome$
</code>```

Edit:
Question: I'm not sure what check to run to detect a multiple palindrome.
If you don't understand what I'm trying to do, feel free to ask. Thanks!

答:
First up, since you are using python, you really should take advantage of it. Please take a look at this link on how to efficiently convert any base to any base.

Second, you can check if a number is a palindrome by doing str(num) == str(num)[::-1], which returns True or False depending on whether said number in whatever base is palindromic or not. The [::-1] part reverses the string.

Title: Is it a palindrome in more than 1 base?

Body:
I quickly put together some Python code to test my knowledge. I'm trying to detect "multiple palindromes" without using strings. Here's my code:

from math import log
from math import ceil
from math import floor

palindrome = 0

def palindromify(half, base):
    assert base != 0
    reversedhalf = 0
    palindrome = 0
    iterator = 0
    size = floor(log(half, base)) + 1
    """
        for base = 10 and half = 100,
        log10(100) = 2, floored + 1 = 2 + 1 = 3.

        for base = 10 and half = 999,
        log10(999) = 2.9... (or something).
        floored + 1 = 2 + 1 = 3.

        size = digits.
    """
    palindrome = half * (base ** size)
    while iterator < size:
        digit = floor(half / (base ** iterator)) % base
        reversedhalf = (base ** (size - iterator - 1)) * digit + reversedhalf
        iterator = iterator + 1
    palindrome = reversedhalf + palindrome
    return palindrome

def depalindromify(whole, base):
    halfsize = (ceil(log(whole,base)) / 2)
    """
        if the half is 100 and base = 10, whole = 100001.
        log10(100001) = just over 5
        ceil(just above 5) = 6
        6 / 2 = 3. And 100 is 3 digits!

        if the half is 999 and base = 10, whole = 999999.
        log10(999999) = just under 6.
        ceil(just under 6) = 6
        6 / 2 = 3. 999 is 3 digits.
    """
    halfbottom = whole % (base ** halfsize)
    halftop = (whole - halfbottom) / (base ** halfsize)
    """
        (whole - (whole % (base ** halfsize))) / (base ** halfsize)
        if base = 10, whole = 526625,
        (526625 - (526625 mod 1000)) / (1000)
        = (526625 - 625) / 1000
        = (526000) / 1000
        = 526
    """
    return halftop

"""
    Does not work
"""
def multipalindrome():
    current = 2
    currentbase = 2
    palindromed = 0
    dun = False
    highest = 2
    while True:
        dun = False
        current = (highest ** 4) if current < (highest ** 4) else current + 1
        currentbase = 2
        while not dun:
            palindromed = palindromify(current, currentbase)
            currentbase = currentbase + 1
            depalindromed = depalindromify(palindromed, currentbase)
            print '(D) depalindromed = ', depalindromed
            if (current != depalindromed): ## here
                if currentbase > highest:
                    print 'New highest! In bases from 2 to ', currentbase, ', top half ', current, '!\n'
                highest = currentbase
                dun = True

multipalindrome()

# x = input("Enter first half: ")
# y = input("Enter base:       ")
#
# print palindromify(x, y)

I've added the """ comments """ to help myself understand the ceil and floor functions. Basically, multipalindrome() should run an infinite loop that chooses a number, palindromifies it, and sees if that palindrome is a palindrome in more than 1 base. It attempts to do this enough to get a palindrome in all bases (this probably won't happen). I'm not sure where to go as far as detecting multiple palindromes and what bases to use in the function, etc..

When I run this with the python interpreter (2.7), I get:

...
(D) depalindromed =  30657.0
(D) depalindromed =  30657.0
(D) depalindromed =  30658.0
(D) depalindromed =  30659.0
(D) depalindromed =  30661.0
(D) depalindromed =  30661.0
(D) depalindromed =  30662.0
(D) depalindromed =  30663.0
(D) depalindromed =  30664.0
(D) depalindromed =  30665.0
(D) depalindromed =  30666.0
(D) depalindromed =  30667.0
(D) depalindromed =  30668.0
(D) depalindromed =  30668.0
(D) depalindromed =  30670.0
(D) depalindromed =  30671.0
(D) depalindromed =  30672.0
(D) depalindromed =  30672.0
(D) depalindromed =  30674.0
(D) depalindromed =  30674.0
(D) depalindromed =  30676.0
(D) depalindromed =  30676.0
(D) depalindromed =  30678.0
(D) depalindromed =  30678.0
(D) depalindromed =  30680.0
(D) depalindromed =  30680.0
(D) depalindromed =  30681.0
(D) depalindromed =  30682.0
(D) depalindromed =  30684.0
(D) depalindromed =  30684.0
(D) depalindromed =  30685.0
(D) depalindromed =  30686.0
(D) depalindromed =  30688.0
(D) depalindromed =  30688.0
(D) depalindromed =  30689.0
(D) depalindromed =  30690.0
(D) depalindromed =  30691.0
(D) depalindromed =  30692.0
(D) depalindromed =  30693.0
(D) depalindromed =  30694.0
(D) depalindromed =  30695.0
(D) depalindromed =  30695.0
(D) depalindromed =  30697.0
(D) depalindromed =  30697.0
(D) depalindromed =  30699.0
(D) depalindromed =  30699.0
(D) depalindromed =  30701.0
(D) depalindromed =  30701.0
(D) depalindromed =  30703.0
(D) depalindromed =  30703.0
(D) depalindromed =  30704.0
(D) depalindromed =  30705.0
(D) depalindromed =  30707.0
(D) depalindromed =  30707.0
(D) depalindromed =  30708.0
(D) depalindromed =  30709.0
(D) depalindromed =  30711.0
(D) depalindromed =  30711.0
(D) depalindromed =  30712.0
(D) depalindromed =  30713.0
(D) depalindromed =  30714.0
(D) depalindromed =  30715.0
(D) depalindromed =  30716.0
(D) depalindromed =  30717.0
(D) depalindromed =  30718.0
(D) depalindromed =  30718.0
(D) depalindromed =  30720.0
(D) depalindromed =  30721.0
(D) depalindromed =  30722.0
(D) depalindromed =  30722.0
(D) depalindromed =  30724.0
(D) depalindromed =  30725.0
(D) depalindromed =  30726.0
(D) depalindromed =  30726.0
(D) depalindromed =  30727.0
(D) depalindromed =  30728.0
(D) depalindromed =  30730.0
^CTraceback (most recent call last):
  File "palindrome.py", line 77, in <module>
    multipalindrome()
  File "palindrome.py", line 67, in multipalindrome
    palindromed = palindromify(current, currentbase)
  File "palindrome.py", line 26, in palindromify
    reversedhalf = (base ** (size - iterator - 1)) * digit + reversedhalf
KeyboardInterrupt
henry@FusionReactor:~/code4fun/palindrome$

Edit:
Question: I'm not sure what check to run to detect a multiple palindrome.
If you don't understand what I'm trying to do, feel free to ask. Thanks!