问:
implicitly convert higher order type
I'm a scala newbie...so assume ignorance.

so if I look at the definition of <:<

sealed abstract class <:<[-From, +To] extends (From => To)
implicit def conforms[A]: A <:< A = new (A <:< A) {def apply(x: A) = x}

and this is used to define evidence that a type A is a subtype of B.

A <: B

...but what if I want to have evidence that;

forall T. A[T] <: B[T]

?

ok....so I try to follow the same recipe

```<code>abstract class Foo[-A[_],+B[_]] { def apply[C](x : A[C]) : B[C] }

implicit def conforms[A[_]] : Foo[A,A] = new Foo[A,A] { def apply[C](x : A[C]) : A[C] = x }
</code>```

I can use this constraint an manually apply the conversion, but I can't get the compiler to implicitly "apply" it. (because it doesn't extend A=>B?)

so for example if I define;

```<code>  abstract class FooInt[-A[_],+B[_]] extends (A[Int] => B[Int])

implicit def conformsInt[A[Int]] : FooInt[A,A] = new FooInt[A,A] { def apply(x : A[Int]) : A[Int] = x }
</code>```

then the compiler will automatically apply the conversion to values of type A[Int]

I just want to generalise this to A[T]

thoughts?

答:
sealed abstract class <:< - this tells you that you cannot construct "new evidence". You have to rely on the compiler confirming that two existing types do meet the existing evidence. This should work for all types already, if not, you try to proof something that is wrong.

You state you want proof that A[T] <: B[T] forAll { type T }. This will depend on the variance of A's and B's type parameter. If you want to ignore that parameter, you can only ask for evidence A[_] <:< B[_]. E.g.

```<code>trait Animal; trait Cat extends Animal

trait Foo[A]
trait Bar[A] extends Foo[A]

implicitly[Bar[Cat]    <:< Foo[Cat]]     // ok, A is fixed
implicitly[Bar[Cat]    <:< Foo[Animal]]  // not possible
implicitly[Bar[Animal] <:< Foo[Cat]]     // not possible
implicitly[Bar[_]      <:< Foo[_]]       // ok, we forget about A
</code>```

If you had variances, you could preserve A:

```<code>trait Breeds[+A]  // covariant, can "produce" A
trait Feeds [-A]  // contravariant, can "consume" A
class Baz[A] extends Breeds[A] with Feeds[A]

implicitly[Baz[Cat]    <:< Feeds[Animal]]  // nope
implicitly[Baz[Animal] <:< Feeds[Cat]]     // ok
implicitly[Baz[Cat]    <:< Breeds[Animal]] // ok
implicitly[Baz[Animal] <:< Breeds[Cat]]    // nope
</code>```

Title: implicitly convert higher order type

Body:
I'm a scala newbie...so assume ignorance.

so if I look at the definition of <:<

sealed abstract class <:<[-From, +To] extends (From => To)
implicit def conforms[A]: A <:< A = new (A <:< A) {def apply(x: A) = x}

and this is used to define evidence that a type A is a subtype of B.

A <: B

...but what if I want to have evidence that;

forall T. A[T] <: B[T]

?

ok....so I try to follow the same recipe

abstract class Foo[-A[_],+B[_]] { def apply[C](x : A[C]) : B[C] }

implicit def conforms[A[_]] : Foo[A,A] = new Foo[A,A] { def apply[C](x : A[C]) : A[C] = x }

I can use this constraint an manually apply the conversion, but I can't get the compiler to implicitly "apply" it. (because it doesn't extend A=>B?)

so for example if I define;

  abstract class FooInt[-A[_],+B[_]] extends (A[Int] => B[Int])

implicit def conformsInt[A[Int]] : FooInt[A,A] = new FooInt[A,A] { def apply(x : A[Int]) : A[Int] = x }

then the compiler will automatically apply the conversion to values of type A[Int]

I just want to generalise this to A[T]

thoughts?

Body:
sealed abstract class <:< - this tells you that you cannot construct "new evidence". You have to rely on the compiler confirming that two existing types do meet the existing evidence. This should work for all types already, if not, you try to proof something that is wrong.

You state you want proof that A[T] <: B[T] forAll { type T }. This will depend on the variance of A's and B's type parameter. If you want to ignore that parameter, you can only ask for evidence A[_] <:< B[_]. E.g.

trait Animal; trait Cat extends Animal

trait Foo[A]
trait Bar[A] extends Foo[A]

implicitly[Bar[Cat]    <:< Foo[Cat]]     // ok, A is fixed
implicitly[Bar[Cat]    <:< Foo[Animal]]  // not possible
implicitly[Bar[Animal] <:< Foo[Cat]]     // not possible
implicitly[Bar[_]      <:< Foo[_]]       // ok, we forget about A

If you had variances, you could preserve A:

trait Breeds[+A]  // covariant, can "produce" A
trait Feeds [-A]  // contravariant, can "consume" A
class Baz[A] extends Breeds[A] with Feeds[A]

implicitly[Baz[Cat]    <:< Feeds[Animal]]  // nope
implicitly[Baz[Animal] <:< Feeds[Cat]]     // ok
implicitly[Baz[Cat]    <:< Breeds[Animal]] // ok
implicitly[Baz[Animal] <:< Breeds[Cat]]    // nope


来源: stackexchange

问:
How to play mp3 audio file from Resources?(using Media player not SoundPlayer)
```<code>var p2 = new System.Windows.Media.MediaPlayer();
p2.Open(Properties.Resources.myfile);
</code>```

Error: can not convert from System.IO.Stream to System.Uri

答:
I think you want something like this:

https://learn.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/how-to-play-media-using-a-videodrawing

Windows.Mediaplayer needs a reference position(time) and the path of your file to start with. Plus you should convert these into Uri.

ContentLicense: CC BY-SA 3.0

Body:
var p2 = new System.Windows.Media.MediaPlayer();
p2.Open(Properties.Resources.myfile);

Error: can not convert from System.IO.Stream to System.Uri


问:
MySQL: How to allow remote connection to mysql
I have installed MySQL Community Edition 5.5 on my local machine and I want to allow remote connections so that I can connect from external source.

How can I do that?

答:
Just a note from my experience, you can find configuration file under this path /etc/mysql/mysql.conf.d/mysqld.cnf.

(I struggled for some time to find this path)

ContentLicense: CC BY-SA 4.0


问:
ES6 Map key to be either string or number
I have a ES6 Map , where keys are number. Some time the key is number and some time the key is string which represents a number. The map will never have duplicate key at runtime for me. Example I will never have key "1" and 1 .

While retrieving from map I need a simple one liner code which will negate whether if the key is a string or a number.

```<code>var map = new Map();
undefined
map.set('1', 'string one');
map.set(2, 'number tow')
Map(2) {"1" => "string one", 2 => "number tow"}
map.get(1)
undefined
map.get('1')
"string one"
</code>```

答:
You could use just an object with no prototypes. For the access the key is converted to string.

var map = Object.create(null);

map['1'] = 'string one';
map[2] = 'number two';

console.log(map[1]);   // 'string one'
console.log(map['1']); // 'string one'
console.log(map);```

Body:
I have a ES6 Map , where keys are number. Some time the key is number and some time the key is string which represents a number. The map will never have duplicate key at runtime for me. Example I will never have key "1" and 1 .

While retrieving from map I need a simple one liner code which will negate whether if the key is a string or a number.

var map = new Map();
undefined
map.set('1', 'string one');
map.set(2, 'number tow')
Map(2) {"1" => "string one", 2 => "number tow"}
map.get(1)
undefined
map.get('1')
"string one"


问:
AngularJS + bootstrap carousel help to display all the images
I have an array of objects, where I have the url of the image. I need to display these images in carousel:

```<code><div class="item active">
    <div class="row cst-carouselImg">
        <div class="col-sm-3 col-xs-6" ng-repeat="image in pack.hotels.current.hotelImages | limitTo:'4'">
            <a href="#"><img
                         ng-src="<?php
                         echo 'http://photos.hotelbeds.com/giata/';
                         ?>{{image.path}}"
                         alt="Image" class="img-responsive"></a>
        </div>
    </div>
</div>
</code>```

At this point I have only the first 4 pictures from the array. Next I display the next 4 images from the array:

```<code><div class="item">
     <div class="row cst-carouselImg">
         <div class="col-sm-3 col-xs-6" ng-repeat="image in pack.hotels.current.hotelImages" ng-if="$index > 3 && $index <8">
             <a href="#"><img
                         ng-src="<?php echo
                         'http://photos.hotelbeds.com/giata/';
                         ?>{{image.path}}"
                         alt="Image" class="img-responsive"></a>
         </div>
    </div>
</div>
</code>```

How can I display all the images using ng-repeat instead of manually adding
 and setting manually $index?

答:
Here i take some sample array you can modify it accordingly

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.hotelImages=[{id:1},{id:2},{id:3},{id:4},{id:5},{id:6},{id:7}];
$scope.loopCount=Math.ceil($scope.hotelImages.length/4);
$scope.getNumber = function(num) {
    var arr=[];
    for(i=0;i<num;i++){
    arr.push(i);
    }
    return arr;
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div  ng-app="myApp" ng-controller="MyCtrl">

<div class="item" ng-repeat="i in getNumber(loopCount) track by $index">
Carousel :-{{i}}
     <div class="row cst-carouselImg">

         <div class="col-sm-3 col-xs-6" ng-repeat="image in hotelImages" ng-if="$index >=(i*4) && $index <(i*4)+4"  >
            image:- {{image.id}}
         </div>
    </div>
</div>
</div></code>```

Body:
I have an array of objects, where I have the url of the image. I need to display these images in carousel:

            <img
                         ng-src="<?php
                         echo 'http://photos.hotelbeds.com/giata/';
                         ?>{{image.path}}"
                         alt="Image" class="img-responsive">

At this point I have only the first 4 pictures from the array. Next I display the next 4 images from the array:

 3 && $index <8">
             <img
                         ng-src="<?php echo
                         'http://photos.hotelbeds.com/giata/';
                         ?>{{image.path}}"
                         alt="Image" class="img-responsive">

How can I display all the images using ng-repeat instead of manually adding
 and setting manually $index?

Body:
Here i take some sample array you can modify it accordingly

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.hotelImages=[{id:1},{id:2},{id:3},{id:4},{id:5},{id:6},{id:7}];
$scope.loopCount=Math.ceil($scope.hotelImages.length/4);
$scope.getNumber = function(num) {
    var arr=[];
    for(i=0;i<num;i++){
    arr.push(i);
    }
    return arr;
}
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div  ng-app="myApp" ng-controller="MyCtrl">

<div class="item" ng-repeat="i in getNumber(loopCount) track by $index">
Carousel :-{{i}}
     <div class="row cst-carouselImg">

         <div class="col-sm-3 col-xs-6" ng-repeat="image in hotelImages" ng-if="$index >=(i*4) && $index <(i*4)+4"  >
            image:- {{image.id}}
         </div>
    </div>
</div>
</div>


问:
Why do we say functional API in Keras is used for non-sequential models?
AFAIK, we still need to create a model and add layers to the model using the functional API. Why people say that the functional AI is used to create non-sequential neural network?</p>

答:
Well, "sequential" is not really the most correct term, but it's the name chosen by Keras developers. All models work in sequence, of course.

The difference is:

The Sequential model is a straight line. You keep adding layers, every new layer takes the output of the previous layer. You cannot make creative graphs with branches.

The functoinal API Model is completely free to have as many ramifications, inputs and outputs as you need.

Example with the Sequential model:

```<code>from keras.models import Sequential
from keras.layers import *

#you create a model
model = Sequential()

#and you add layers
model.add(SomeKerasLayer(...))
model.add(AnotherKerasLayer(...))

#as you can see, this model is a straight line, you only add layers "sequentially"
</code>```

Example with the functional API Model:

Now here we start creating really fancy models.

```<code>from keras.models import Model
from keras.layers import *
</code>```

We start by defining input tensors. And we can have any number of inputs! (The sequential model is limited to one input, that you define in the first layer with input_shape).

```<code>input1 = Input(inputShape1)

#We can have more inputs if we want!
input2 = Input(inputShape2)
input3 = Input(inputShape3)
</code>```

We work by creating layers and "calling layers with input tensors".

When we call a layer with an input tensor, we get an output tensor.

And we can create whatever path we want.

```<code>#Example: two separate layers taking two separate inputs:
output1 = SomeLayer(...)(input1)
output2 = AnotherLayer(...)(input2)
</code>```

We can join two branches with different options, such as add, multiply, concatenate, etc.:

```<code>#joining the previous tensors output1 and output2
joined1_2 = Concatenate()([output1,output2])
</code>```

We can reuse the same layers with different inputs, getting different outputs:

```<code>aLayer = AKerasLayer(...) #notice I'm creating this layer but not calling it yet

#calling the same layer with two different inputs
output1 = aLayer(joined1_2)
output2 = aLayer(input3)
</code>```

And finally, we can define the model with as many inputs and outputs we want:

```<code>model = Model([input1,input2,input3],[output1, output2])
</code>```

Reusing and associating models

Both models, Sequential and functional API, can be used as if they were layers.

You can call a model with and input tensor and get an output tensor, just like you would do when creating a functional API model:

```<code>input1 = Input(shape)
output1 = anExistingSequentialModel(input1)
output2 = anExistingFunctionalModel(input1)

newModel = Model(input1,[output1,output2])
</code>```

And you can add models in sequential models as well (beware of the branches, it's best to have one input and one output for the added model, since this is a Sequential one)

```<code>seqModel = Sequential()
seqModel.add(anotherModel)
</code>```

Body:
Well, "sequential" is not really the most correct term, but it's the name chosen by Keras developers. All models work in sequence, of course.

The difference is:

The Sequential model is a straight line. You keep adding layers, every new layer takes the output of the previous layer. You cannot make creative graphs with branches.

The functoinal API Model is completely free to have as many ramifications, inputs and outputs as you need.

Example with the Sequential model:

from keras.models import Sequential
from keras.layers import *

#you create a model
model = Sequential()

#and you add layers
model.add(SomeKerasLayer(...))
model.add(AnotherKerasLayer(...))

#as you can see, this model is a straight line, you only add layers "sequentially"

Example with the functional API Model:

Now here we start creating really fancy models.

from keras.models import Model
from keras.layers import *

We start by defining input tensors. And we can have any number of inputs! (The sequential model is limited to one input, that you define in the first layer with input_shape).

input1 = Input(inputShape1)

#We can have more inputs if we want!
input2 = Input(inputShape2)
input3 = Input(inputShape3)

We work by creating layers and "calling layers with input tensors".

When we call a layer with an input tensor, we get an output tensor.

And we can create whatever path we want.

#Example: two separate layers taking two separate inputs:
output1 = SomeLayer(...)(input1)
output2 = AnotherLayer(...)(input2)

We can join two branches with different options, such as add, multiply, concatenate, etc.:

#joining the previous tensors output1 and output2
joined1_2 = Concatenate()([output1,output2])

We can reuse the same layers with different inputs, getting different outputs:

aLayer = AKerasLayer(...) #notice I'm creating this layer but not calling it yet

#calling the same layer with two different inputs
output1 = aLayer(joined1_2)
output2 = aLayer(input3)

And finally, we can define the model with as many inputs and outputs we want:

model = Model([input1,input2,input3],[output1, output2])

Reusing and associating models

Both models, Sequential and functional API, can be used as if they were layers.

You can call a model with and input tensor and get an output tensor, just like you would do when creating a functional API model:

input1 = Input(shape)
output1 = anExistingSequentialModel(input1)
output2 = anExistingFunctionalModel(input1)

newModel = Model(input1,[output1,output2])

And you can add models in sequential models as well (beware of the branches, it's best to have one input and one output for the added model, since this is a Sequential one)

seqModel = Sequential()
seqModel.add(anotherModel)


问:
Add an X to the end of a div with pure CSS?
I'm trying to figure out how to add a small X on the right side of my . I went through some existing solutions but couldn't find a clean (and fairly simple) solution.

Here's a mock-up of what I'm trying to achieve:

Here's what I have so far:

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="categoryTag">category 1</span>
<span class="categoryTag">category 2</span>
<span class="categoryTag">category 3</span></code>```

Note that content: 'X' would match the same font as the span, while I need a different color and font size.

Any suggestions would be welcome.

答:
You can use a pseudo element:

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   position: relative;
   padding:6px;
   padding-right: 25px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}

.categoryTag.medium {
  padding-right: 35px;
  font-size: 20px;
}

.categoryTag.large {
  padding-right: 45px;
  font-size: 25px;
}

.categoryTag::after {
   content: 'X';
   position: absolute;
   top: 50%;
   right: 10px;
   transform: translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="categoryTag">category 1</span>
<span class="categoryTag medium">category 2</span>
<span class="categoryTag large">category 3</span></code>```

Body:
I'm trying to figure out how to add a small X on the right side of my . I went through some existing solutions but couldn't find a clean (and fairly simple) solution.

Here's a mock-up of what I'm trying to achieve:

Here's what I have so far:

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}

category 1
category 2
category 3

Note that content: 'X' would match the same font as the span, while I need a different color and font size.

Any suggestions would be welcome.

Body:
You can use a pseudo element:

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   position: relative;
   padding:6px;
   padding-right: 25px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}

.categoryTag.medium {
  padding-right: 35px;
  font-size: 20px;
}

.categoryTag.large {
  padding-right: 45px;
  font-size: 25px;
}

.categoryTag::after {
   content: 'X';
   position: absolute;
   top: 50%;
   right: 10px;
   transform: translateY(-50%);
}

<span class="categoryTag">category 1</span>
<span class="categoryTag medium">category 2</span>
<span class="categoryTag large">category 3</span>


问:
Applying filter for column using multi select dropdown with checkbox in datatable
My question is based on this original fiddle: https://jsfiddle.net/x92c3qu2/

This is a kind of example I am looking for.
But my problem is when any value is having special characters (say, round brackets), then the example doesn't work.

This is my code - almost similar to original link

```<code>    $('#dropdown').multiselect({
    onChange: function(element, checked) {

      var cities = $('#dropdown option:selected');

      var selected = [];
      $(cities).each(function(index, city) {
        selected.push([$(this).val()]);
      });

      var regex = selected.join("|");

      $('#table').DataTable().column(1).search(
        regex, true, false, true
      ).draw();
    }
  });
});
</code>```

https://jsfiddle.net/x92c3qu2/110/  - edited fiddle by me

Now in this, if you select "(Paris) France", it does not show any result despite having record in a table.

(tried by changing search(regax,true,false,true) - but doesn't work.

If you select "Paris", it shows both records related to "Paris"- according to me which is wrong. It should show exact result when value selected from drop down.

Try selecting multiple values of with and without special characters - the result is weird.

Please let me know if any further clarifications required.

答:
If you want the regex to match the exact string you have to encapsulate the search string with the ^ and the $ characters. If the string has to match the exact string anyway you can disable the smart option in the search method.

There are two problems with the entry (Paris) France. In your sample you are pushing the value of the option element which is set to Paris_France but in your table the entry to look for is still (Paris) France, so you should change that.
The second issue is that the ( is a special character in Regex which you should escape in this case consider something like this when adding the value:

selected.push(['^(' + $(this).val().replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') +')$']);

I've edited your JS fiddle with my proposed changes.

Body:
My question is based on this original fiddle: https://jsfiddle.net/x92c3qu2/

This is a kind of example I am looking for.
But my problem is when any value is having special characters (say, round brackets), then the example doesn't work.

This is my code - almost similar to original link

    $('#dropdown').multiselect({
    onChange: function(element, checked) {

      var cities = $('#dropdown option:selected');

      var selected = [];
      $(cities).each(function(index, city) {
        selected.push([$(this).val()]);
      });

      var regex = selected.join("|");

      $('#table').DataTable().column(1).search(
        regex, true, false, true
      ).draw();
    }
  });
});

https://jsfiddle.net/x92c3qu2/110/  - edited fiddle by me

Now in this, if you select "(Paris) France", it does not show any result despite having record in a table.

(tried by changing search(regax,true,false,true) - but doesn't work.

If you select "Paris", it shows both records related to "Paris"- according to me which is wrong. It should show exact result when value selected from drop down.

Try selecting multiple values of with and without special characters - the result is weird.

Please let me know if any further clarifications required.


问:
Accessing an iframe with nightwatch without a fixed id
I have

```<code><div class="ap-content" id="office-addon">
  <div class="ap-iframe-container iframe-init" id="office-addon__5e83ed1">
    <iframe id="office-addon__5e83ed1">
      <!-- As it appears in the dev console: -->
      #document
      <!DOCTYPE html>
        <html>
          <head></head>
          <body>
            <div id="addon"></div>
          </body>
        </html>
    </iframe>
  <div>
<div>
</code>```

I want to access it with nightwatch like so:

```<code>browser
  .waitForElementPresent('#office-addon', 20000);
  .frame('#office-addon iframe')
  .waitForElementPresent('#addon', 1000)
  .end();
</code>```

But it times out waiting for #addon, though #addon is in the browser. How do I have to write the frame() parameters? The iframe id changes with every page build.

答: Iframes are elements to display another page, and it will not render any html written inside of it unless your browser doesn't support iframes. So that div with the id #addon is never being rendered in the first place.</p>

Body:
I have

      #document
      <!DOCTYPE html>

I want to access it with nightwatch like so:

browser
  .waitForElementPresent('#office-addon', 20000);
  .frame('#office-addon iframe')
  .waitForElementPresent('#addon', 1000)
  .end();

But it times out waiting for #addon, though #addon is in the browser. How do I have to write the frame() parameters? The iframe id changes with every page build.


答:
You can use pseudo element after:

Here is the sample code

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}

.categoryTag::after {
  content: ' x';
  font-size: 20px;
  color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="categoryTag">category 1</span>
<span class="categoryTag">category 2</span>
<span class="categoryTag">category 3</span></code>```

codepen

More on after

Title: Add an X to the end of a div with pure CSS?

Body:
You can use pseudo element after:

Here is the sample code

.categoryTag {
   display:inline-block;
   background-color:#eaeaea;
   border-radius:4px;
   padding:6px;
   font-size:12px;
   cursor:pointer;
   margin:4px;
}

.categoryTag::after {
  content: ' x';
  font-size: 20px;
  color: blue;
}

<span class="categoryTag">category 1</span>
<span class="categoryTag">category 2</span>
<span class="categoryTag">category 3</span>

codepen

More on after


问:
How to change dateTimePicker calendar size in WinForm?
How do I change the size of the calendar? If I change the font size of the dateTime picker, it incresses in size. But when I do it with the calendar font, it does not change the size of the calendar or the font.

What is the proper way to do this?

答:
```<code>DateTimePicker dtp = new DateTimePicker();
dtp.Font = new Font("Arial", 20, FontStyle.Regular);
</code>```

That way You will change the size of field where the date is shown, but not the size of rectangle of the popup Calendar. So... it is not possible!

Body:
DateTimePicker dtp = new DateTimePicker();
dtp.Font = new Font("Arial", 20, FontStyle.Regular);

That way You will change the size of field where the date is shown, but not the size of rectangle of the popup Calendar. So... it is not possible!


问:
How Using UTF ( Persian Language ) in Bracket?
When i Using The Persian (UTF) in Bracket Show Me Like This .

This My Text in Bracket :

```<code><h1>سلام این ایت منه</h1>
</code>```

This Show Me in google Chrome

```<code>Ø³Ù„Ø§Ù… Ø§ÛŒÙ† Ø§ÛŒØª Ù…Ù†Ù‡
</code>```

答:
add this line inside your html  tag.

```<code><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</code>```

Body:
When i Using The Persian (UTF) in Bracket Show Me Like This .

This My Text in Bracket :

سلام این ایت منه

This Show Me in google Chrome

Ø³Ù„Ø§Ù… Ø§ÛŒÙ† Ø§ÛŒØª Ù…Ù†Ù‡

Body:
add this line inside your html <head></head> tag.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


问:
Java functional generics
ComputeIfAbsent method of Map has following declaration:

computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction).

Why wasn't parameter declared as Function<K,V> when K and V types are not used anywhere else?

Now I understand that K and V are very important and they are part of the Map class declaration.

答:
K and V are part of the type of the mapping function. So they are actually used. Specifically, they determine the acceptable and most general bounds for the argument type and the return type of the mapping function.

For

```<code>Function<? super K,? extends V> mappingFunction
</code>```

this means that you can pass any function that is able to at least map everything that can serve as a key in your map (thus ? super K) and maps those keys to values that can be put into the map (thus extends V). In effect this gives you more flexibility in the choice of the mapping function.

In more theoretical terms: under sub-typing functions are contravariant in its argument type and covariant in its return type. This determines the type of mappingFunction to Function<? super K,? extends V> when regarding Map<K, V> as a function from K to V.

Title: Java functional generics

Body:
K and V are part of the type of the mapping function. So they are actually used. Specifically, they determine the acceptable and most general bounds for the argument type and the return type of the mapping function.

For

Function<? super K,? extends V> mappingFunction

this means that you can pass any function that is able to at least map everything that can serve as a key in your map (thus ? super K) and maps those keys to values that can be put into the map (thus extends V). In effect this gives you more flexibility in the choice of the mapping function.

In more theoretical terms: under sub-typing functions are contravariant in its argument type and covariant in its return type. This determines the type of mappingFunction to Function<? super K,? extends V> when regarding Map<K, V> as a function from K to V.


问:
Combining different fees columns to create PivotTable income statement?
I have a table which records revenue for each product, split into type of revenue: price, fees, tax etc.

To analyze the data I'd like to build a PivotTable to show the revenue breakdown, e.g.:

So to build this PivotTable I need to somehow create an intermediate table of the following format so the PivotTable can be used:

My question is, how do I create a PivotTable from the original table automatically without manually constructing the second table?

答:
Here are the steps you have to do:

(1) Enter the data.

(2) Go to the Data tab and select From Table/Range.

(3) A new window will open up with the Query Editor. Here you need to go to the Transform tab, select the three columns you wish to unpivot and then click Unpivot Columns.

(4) The result will be the following (shown in the Query Editor)

(5) Now you can Load this data to the sheet using Close & Load To... on the Home tab

(6) Select the option to show the data in a pivot table and indicate where the pivot table should be placed before clicking OK

(7) The final result should look something like this once you have dragged the various field into the respective boxes: product and attribute into rows while values goes into the values box


问:
java.io.IOException: No FileSystem for scheme : hdfs
I am using Cloudera Quickstart VM CDH5.3.0 (in terms of parcels bundle) and Spark 1.2.0 with $SPARK_HOME=/opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/spark and submitting Spark application using the command

./bin/spark-submit --class <Spark_App_Main_Class_Name> --master spark://localhost.localdomain:7077 --deploy-mode client --executor-memory 4G ../apps/<Spark_App_Target_Jar_Name>.jar

Spark_App_Main_Class_Name.scala

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.mllib.util.MLUtils

object Spark_App_Main_Class_Name {

    def main(args: Array[String]) {
        val hConf = new SparkConf()
            .set("fs.hdfs.impl", classOf[org.apache.hadoop.hdfs.DistributedFileSystem].getName)
            .set("fs.file.impl", classOf[org.apache.hadoop.fs.LocalFileSystem].getName)
        val sc = new SparkContext(hConf)
        val data = MLUtils.loadLibSVMFile(sc, "hdfs://localhost.localdomain:8020/analytics/data/mllib/sample_libsvm_data.txt")
        ...
    }

}
</code>```

But I am getting the ClassNotFoundException for org.apache.hadoop.hdfs.DistributedFileSystem while spark-submitting the application in client mode

```<code>[cloudera@localhost bin]$ ./spark-submit --class Spark_App_Main_Class_Name --master spark://localhost.localdomain:7077 --deploy-mode client --executor-memory 4G ../apps/Spark_App_Target_Jar_Name.jar
15/11/30 09:46:34 INFO SparkContext: Spark configuration:
spark.app.name=Spark_App_Main_Class_Name
spark.driver.extraLibraryPath=/opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/hadoop/lib/native
spark.eventLog.dir=hdfs://localhost.localdomain:8020/user/spark/applicationHistory
spark.eventLog.enabled=true
spark.executor.extraLibraryPath=/opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/hadoop/lib/native
spark.executor.memory=4G
spark.jars=file:/opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/spark/bin/../apps/Spark_App_Target_Jar_Name.jar
spark.logConf=true
spark.master=spark://localhost.localdomain:7077
spark.yarn.historyServer.address=http://localhost.localdomain:18088
15/11/30 09:46:34 WARN Utils: Your hostname, localhost.localdomain resolves to a loopback address: 127.0.0.1; using 10.113.234.150 instead (on interface eth12)
15/11/30 09:46:34 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
15/11/30 09:46:34 INFO SecurityManager: Changing view acls to: cloudera
15/11/30 09:46:34 INFO SecurityManager: Changing modify acls to: cloudera
15/11/30 09:46:34 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(cloudera); users with modify permissions: Set(cloudera)
15/11/30 09:46:35 INFO Slf4jLogger: Slf4jLogger started
15/11/30 09:46:35 INFO Remoting: Starting remoting
15/11/30 09:46:35 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriver@10.113.234.150:59473]
15/11/30 09:46:35 INFO Remoting: Remoting now listens on addresses: [akka.tcp://sparkDriver@10.113.234.150:59473]
15/11/30 09:46:35 INFO Utils: Successfully started service 'sparkDriver' on port 59473.
15/11/30 09:46:36 INFO SparkEnv: Registering MapOutputTracker
15/11/30 09:46:36 INFO SparkEnv: Registering BlockManagerMaster
15/11/30 09:46:36 INFO DiskBlockManager: Created local directory at /tmp/spark-local-20151130094636-8c3d
15/11/30 09:46:36 INFO MemoryStore: MemoryStore started with capacity 267.3 MB
15/11/30 09:46:38 INFO HttpFileServer: HTTP File server directory is /tmp/spark-7d1f2861-a568-4919-8f7e-9a9fe6aab2b4
15/11/30 09:46:38 INFO HttpServer: Starting HTTP Server
15/11/30 09:46:38 INFO Utils: Successfully started service 'HTTP file server' on port 50003.
15/11/30 09:46:38 INFO Utils: Successfully started service 'SparkUI' on port 4040.
15/11/30 09:46:38 INFO SparkUI: Started SparkUI at http://10.113.234.150:4040
15/11/30 09:46:39 INFO SparkContext: Added JAR file:/opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/spark/bin/../apps/Spark_App_Target_Jar_Name.jar at http://10.113.234.150:50003/jars/Spark_App_Target_Jar_Name.jar with timestamp 1448894799228
15/11/30 09:46:39 INFO AppClient$ClientActor: Connecting to master spark://localhost.localdomain:7077...
15/11/30 09:46:40 INFO SparkDeploySchedulerBackend: Connected to Spark cluster with app ID app-20151130094640-0000
15/11/30 09:46:41 INFO NettyBlockTransferService: Server created on 56458
15/11/30 09:46:41 INFO BlockManagerMaster: Trying to register BlockManager
15/11/30 09:46:41 INFO BlockManagerMasterActor: Registering block manager 10.113.234.150:56458 with 267.3 MB RAM, BlockManagerId(<driver>, 10.113.234.150, 56458)
15/11/30 09:46:41 INFO BlockManagerMaster: Registered BlockManager
Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.hdfs.DistributedFileSystem not found
    at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2047)
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2578)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2591)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:367)
    at org.apache.spark.util.FileLogger.<init>(FileLogger.scala:90)
    at org.apache.spark.scheduler.EventLoggingListener.<init>(EventLoggingListener.scala:63)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:352)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:92)
    at Spark_App_Main_Class_Name$.main(Spark_App_Main_Class_Name.scala:22)
    at Spark_App_Main_Class_Name.main(Spark_App_Main_Class_Name.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:358)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: Class org.apache.hadoop.hdfs.DistributedFileSystem not found
    at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:1953)
    at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2045)
    ... 16 more
</code>```

It appears that Spark application is not being able to map the HDFS because initially I was getting the error:

```<code>Exception in thread "main" java.io.IOException: No FileSystem for scheme: hdfs
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2584)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2591)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:367)
    at org.apache.spark.util.FileLogger.<init>(FileLogger.scala:90)
    at org.apache.spark.scheduler.EventLoggingListener.<init>(EventLoggingListener.scala:63)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:352)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:92)
    at LogisticRegressionwithBFGS$.main(LogisticRegressionwithBFGS.scala:21)
    at LogisticRegressionwithBFGS.main(LogisticRegressionwithBFGS.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:358)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
</code>```

and I followed hadoop No FileSystem for scheme: file to add "fs.hdfs.impl" and "fs.file.impl" to the Spark configuration settings

答:
I was facing the same issue while running Spark code from my IDE and accessing remote HDFS.<br>
So I set the following configuration, and it got resolved. </p>

```<code>JavaSparkContext jsc=new JavaSparkContext(conf);
Configuration hadoopConfig = jsc.hadoopConfiguration();
hadoopConfig.set("fs.hdfs.impl",org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
hadoopConfig.set("fs.file.impl",org.apache.hadoop.fs.LocalFileSystem.class.getName());
</code>```

Body:
I am using Cloudera Quickstart VM CDH5.3.0 (in terms of parcels bundle) and Spark 1.2.0 with $SPARK_HOME=/opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/spark and submitting Spark application using the command

./bin/spark-submit --class <Spark_App_Main_Class_Name> --master spark://localhost.localdomain:7077 --deploy-mode client --executor-memory 4G ../apps/<Spark_App_Target_Jar_Name>.jar

Spark_App_Main_Class_Name.scala

import org.apache.spark.SparkContext
import org.apache.spark.SparkConf
import org.apache.spark.mllib.util.MLUtils

object Spark_App_Main_Class_Name {

    def main(args: Array[String]) {
        val hConf = new SparkConf()
            .set("fs.hdfs.impl", classOf[org.apache.hadoop.hdfs.DistributedFileSystem].getName)
            .set("fs.file.impl", classOf[org.apache.hadoop.fs.LocalFileSystem].getName)
        val sc = new SparkContext(hConf)
        val data = MLUtils.loadLibSVMFile(sc, "hdfs://localhost.localdomain:8020/analytics/data/mllib/sample_libsvm_data.txt")
        ...
    }

}

But I am getting the ClassNotFoundException for org.apache.hadoop.hdfs.DistributedFileSystem while spark-submitting the application in client mode

[cloudera@localhost bin]$ ./spark-submit --class Spark_App_Main_Class_Name --master spark://localhost.localdomain:7077 --deploy-mode client --executor-memory 4G ../apps/Spark_App_Target_Jar_Name.jar
15/11/30 09:46:34 INFO SparkContext: Spark configuration:
spark.app.name=Spark_App_Main_Class_Name
spark.driver.extraLibraryPath=/opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/hadoop/lib/native
spark.eventLog.dir=hdfs://localhost.localdomain:8020/user/spark/applicationHistory
spark.eventLog.enabled=true
spark.executor.extraLibraryPath=/opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/hadoop/lib/native
spark.executor.memory=4G
spark.jars=file:/opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/spark/bin/../apps/Spark_App_Target_Jar_Name.jar
spark.logConf=true
spark.master=spark://localhost.localdomain:7077
spark.yarn.historyServer.address=http://localhost.localdomain:18088
15/11/30 09:46:34 WARN Utils: Your hostname, localhost.localdomain resolves to a loopback address: 127.0.0.1; using 10.113.234.150 instead (on interface eth12)
15/11/30 09:46:34 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
15/11/30 09:46:34 INFO SecurityManager: Changing view acls to: cloudera
15/11/30 09:46:34 INFO SecurityManager: Changing modify acls to: cloudera
15/11/30 09:46:34 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(cloudera); users with modify permissions: Set(cloudera)
15/11/30 09:46:35 INFO Slf4jLogger: Slf4jLogger started
15/11/30 09:46:35 INFO Remoting: Starting remoting
15/11/30 09:46:35 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriver@10.113.234.150:59473]
15/11/30 09:46:35 INFO Remoting: Remoting now listens on addresses: [akka.tcp://sparkDriver@10.113.234.150:59473]
15/11/30 09:46:35 INFO Utils: Successfully started service 'sparkDriver' on port 59473.
15/11/30 09:46:36 INFO SparkEnv: Registering MapOutputTracker
15/11/30 09:46:36 INFO SparkEnv: Registering BlockManagerMaster
15/11/30 09:46:36 INFO DiskBlockManager: Created local directory at /tmp/spark-local-20151130094636-8c3d
15/11/30 09:46:36 INFO MemoryStore: MemoryStore started with capacity 267.3 MB
15/11/30 09:46:38 INFO HttpFileServer: HTTP File server directory is /tmp/spark-7d1f2861-a568-4919-8f7e-9a9fe6aab2b4
15/11/30 09:46:38 INFO HttpServer: Starting HTTP Server
15/11/30 09:46:38 INFO Utils: Successfully started service 'HTTP file server' on port 50003.
15/11/30 09:46:38 INFO Utils: Successfully started service 'SparkUI' on port 4040.
15/11/30 09:46:38 INFO SparkUI: Started SparkUI at http://10.113.234.150:4040
15/11/30 09:46:39 INFO SparkContext: Added JAR file:/opt/cloudera/parcels/CDH-5.3.0-1.cdh5.3.0.p0.30/lib/spark/bin/../apps/Spark_App_Target_Jar_Name.jar at http://10.113.234.150:50003/jars/Spark_App_Target_Jar_Name.jar with timestamp 1448894799228
15/11/30 09:46:39 INFO AppClient$ClientActor: Connecting to master spark://localhost.localdomain:7077...
15/11/30 09:46:40 INFO SparkDeploySchedulerBackend: Connected to Spark cluster with app ID app-20151130094640-0000
15/11/30 09:46:41 INFO NettyBlockTransferService: Server created on 56458
15/11/30 09:46:41 INFO BlockManagerMaster: Trying to register BlockManager
15/11/30 09:46:41 INFO BlockManagerMasterActor: Registering block manager 10.113.234.150:56458 with 267.3 MB RAM, BlockManagerId(<driver>, 10.113.234.150, 56458)
15/11/30 09:46:41 INFO BlockManagerMaster: Registered BlockManager
Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.hdfs.DistributedFileSystem not found
    at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2047)
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2578)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2591)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:367)
    at org.apache.spark.util.FileLogger.<init>(FileLogger.scala:90)
    at org.apache.spark.scheduler.EventLoggingListener.<init>(EventLoggingListener.scala:63)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:352)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:92)
    at Spark_App_Main_Class_Name$.main(Spark_App_Main_Class_Name.scala:22)
    at Spark_App_Main_Class_Name.main(Spark_App_Main_Class_Name.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:358)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: Class org.apache.hadoop.hdfs.DistributedFileSystem not found
    at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:1953)
    at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2045)
    ... 16 more

It appears that Spark application is not being able to map the HDFS because initially I was getting the error:

Exception in thread "main" java.io.IOException: No FileSystem for scheme: hdfs
    at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2584)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2591)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:367)
    at org.apache.spark.util.FileLogger.<init>(FileLogger.scala:90)
    at org.apache.spark.scheduler.EventLoggingListener.<init>(EventLoggingListener.scala:63)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:352)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:92)
    at LogisticRegressionwithBFGS$.main(LogisticRegressionwithBFGS.scala:21)
    at LogisticRegressionwithBFGS.main(LogisticRegressionwithBFGS.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:358)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

and I followed hadoop No FileSystem for scheme: file to add "fs.hdfs.impl" and "fs.file.impl" to the Spark configuration settings

Body:
I was facing the same issue while running Spark code from my IDE and accessing remote HDFS.

So I set the following configuration, and it got resolved.

JavaSparkContext jsc=new JavaSparkContext(conf);
Configuration hadoopConfig = jsc.hadoopConfiguration();
hadoopConfig.set("fs.hdfs.impl",org.apache.hadoop.hdfs.DistributedFileSystem.class.getName());
hadoopConfig.set("fs.file.impl",org.apache.hadoop.fs.LocalFileSystem.class.getName());


问:
Load all relationships for a model
Usually to eager load a relationship I would do something like this:

Model::with('foo', 'bar', 'baz')...

A solution might be to set $with = ['foo','bar','baz'] however that will always load these three relations whenever I call Model

Is it possible to do something like this: Model::with('*')?

答:
Since i've met with a similar problem, and found a good solution that isn't described here and doesn't require filling some custom arrays or whatever, i'll post it for the future.

What i do, is first create a trait, called RelationsManager:

```<code>trait RelationsManager
{
    protected static $relationsList = [];

    protected static $relationsInitialized = false;

    protected static $relationClasses = [
        HasOne::class,
        HasMany::class,
        BelongsTo::class,
        BelongsToMany::class
    ];

    public static function getAllRelations($type = null) : array
    {
        if (!self::$relationsInitialized) {
            self::initAllRelations();
        }

        return $type ? (self::$relationsList[$type] ?? []) : self::$relationsList;
    }

    protected static function initAllRelations()
    {
        self::$relationsInitialized = true;

        $reflect = new ReflectionClass(static::class);

        foreach($reflect->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
            /** @var ReflectionMethod $method */
            if ($method->hasReturnType() && in_array((string)$method->getReturnType(), self::$relationClasses)) {
                self::$relationsList[(string)$method->getReturnType()][] = $method->getName();
            }
        }
    }

    public static function withAll() : Builder
    {
        $relations = array_flatten(static::getAllRelations());

        return $relations ? self::with($relations) : self::query();
    }
}
</code>```

Now you can use it with any class, like -

```<code>class Project extends Model
{
    use RelationsManager;

    //... some relations

}
</code>```

and then when you need to fetch them from the database:

```<code>$projects = Project::withAll()->get();
</code>```

Some notes - my example relation classes list doesn't include morph relations, so if you want to get them as well - you need to add them to $relationClasses variable. Also, this solution only works with PHP 7.

Title: Load all relationships for a model

Body:
Since i've met with a similar problem, and found a good solution that isn't described here and doesn't require filling some custom arrays or whatever, i'll post it for the future.

What i do, is first create a trait, called RelationsManager:

trait RelationsManager
{
    protected static $relationsList = [];

    protected static $relationsInitialized = false;

    protected static $relationClasses = [
        HasOne::class,
        HasMany::class,
        BelongsTo::class,
        BelongsToMany::class
    ];

    public static function getAllRelations($type = null) : array
    {
        if (!self::$relationsInitialized) {
            self::initAllRelations();
        }

        return $type ? (self::$relationsList[$type] ?? []) : self::$relationsList;
    }

    protected static function initAllRelations()
    {
        self::$relationsInitialized = true;

        $reflect = new ReflectionClass(static::class);

        foreach($reflect->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
            /** @var ReflectionMethod $method */
            if ($method->hasReturnType() && in_array((string)$method->getReturnType(), self::$relationClasses)) {
                self::$relationsList[(string)$method->getReturnType()][] = $method->getName();
            }
        }
    }

    public static function withAll() : Builder
    {
        $relations = array_flatten(static::getAllRelations());

        return $relations ? self::with($relations) : self::query();
    }
}

Now you can use it with any class, like -

class Project extends Model
{
    use RelationsManager;

    //... some relations

}

and then when you need to fetch them from the database:

$projects = Project::withAll()->get();

Some notes - my example relation classes list doesn't include morph relations, so if you want to get them as well - you need to add them to $relationClasses variable. Also, this solution only works with PHP 7.


问:
Python 2.7 File Handling saving username
Ok im doing some coding work making a username saver, I need to save multiple users to different text files, But I get an error when trying to set the file directory,

```<code>fileloc = "N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\"
filename = fileloc+newname+".txt"
print filename
adduserfile = open(filename, "rw+")
</code>```

I get the error "EOL while scanning string literal", It then highlights the last quotation mark at the end of line 1, Im not sure how to fix this, Please help

Sorry for asking such a simple question, I understand that it was my use of the address because of the special characters () causing it to break, thanks for the time and help

答:
Using forward slashes will work under Windows.

```<code>fileloc = "N:/Documents/1) Subjects, Word and Powerpoint/GCSE Computing/NEA/GCSE 2017/users/"
</code>```

Alternatively you can use a raw string literal by prefixing an r.

```<code>fileloc = r"N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\"
</code>```

Body:
Ok im doing some coding work making a username saver, I need to save multiple users to different text files, But I get an error when trying to set the file directory,

fileloc = "N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\"
filename = fileloc+newname+".txt"
print filename
adduserfile = open(filename, "rw+")

I get the error "EOL while scanning string literal", It then highlights the last quotation mark at the end of line 1, Im not sure how to fix this, Please help

Sorry for asking such a simple question, I understand that it was my use of the address because of the special characters () causing it to break, thanks for the time and help

Body:
Using forward slashes will work under Windows.

fileloc = "N:/Documents/1) Subjects, Word and Powerpoint/GCSE Computing/NEA/GCSE 2017/users/"

Alternatively you can use a raw string literal by prefixing an r.

fileloc = r"N:\Documents\1) Subjects, Word and Powerpoint\GCSE Computing\NEA\GCSE 2017\users\"


问:
Facebook Messenger Bot wait to respond after many request and resume
When I write the alphabet on my facebook bot, my bot wait to respond.

I write for example : I write "a"... bot respond "a", I write "b"... bot respond "b", etc...

But, for example on the letter "l", the bot waits to respond, and resume after about some minutes :

after about some minutes, the bot responds :

I use the official code, from https://developers.facebook.com/docs/messenger-platform/guides/quick-start/

app.js

```<code>app.get('/webhook', function(req, res) {
    if (req.query['hub.mode'] === 'subscribe' &&
        req.query['hub.verify_token'] === CONFIGURATION.webhook_token) {
        console.log("Validating webhook");
        res.status(200).send(req.query['hub.challenge']);
    } else {
        console.error("Failed validation. Make sure the validation tokens match.");
        res.sendStatus(403);
    }
});

app.post('/webhook', function (req, res) {
    let data = req.body;

    // Make sure this is a page subscription
    if (data.object === 'page') {

        // Iterate over each entry - there may be multiple if batched
        data.entry.forEach(function(entry) {
            let pageID = entry.id;
            let timeOfEvent = entry.time;

            // Iterate over each messaging event
            entry.messaging.forEach(function(event) {
                if (event.message) {
                    receivedMessage(event);
                } else {
                    console.log("Webhook received unknown event: ", event);
                }
            });
        });

        // Assume all went well.
        //
        // You must send back a 200, within 20 seconds, to let us know
        // you've successfully received the callback. Otherwise, the request
        // will time out and we will keep trying to resend.
        res.sendStatus(200);
    }
});

function receivedMessage(event) {
    let senderID = event.sender.id;
    let recipientID = event.recipient.id;
    let timeOfMessage = event.timestamp;
    let message = event.message;

    console.log("Received message for user %d and page %d at %d with message:",
        senderID, recipientID, timeOfMessage);
    console.log(JSON.stringify(message));

    let messageId = message.mid;

    let messageText = message.text;
    let messageAttachments = message.attachments;

    if (messageText) {

        // If we receive a text message, check to see if it matches a keyword
        // and send back the example. Otherwise, just echo the text we received.
        switch (messageText) {
            case 'generic':
                sendGenericMessage(senderID);
                break;

            default:
                sendTextMessage(senderID, messageText);
        }
    } else if (messageAttachments) {
        sendTextMessage(senderID, "Message with attachment received");
    }
}

function sendGenericMessage(recipientId) {
    let messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            attachment: {
                type: "template",
                payload: {
                    template_type: "generic",
                    elements: [{
                        title: "rift",
                        subtitle: "Next-generation virtual reality",
                        item_url: "https://www.oculus.com/en-us/rift/",
                        image_url: "http://messengerdemo.parseapp.com/img/rift.png",
                        buttons: [{
                            type: "web_url",
                            url: "https://www.oculus.com/en-us/rift/",
                            title: "Open Web URL"
                        }, {
                            type: "postback",
                            title: "Call Postback",
                            payload: "Payload for first bubble",
                        }],
                    }, {
                        title: "touch",
                        subtitle: "Your Hands, Now in VR",
                        item_url: "https://www.oculus.com/en-us/touch/",
                        image_url: "http://messengerdemo.parseapp.com/img/touch.png",
                        buttons: [{
                            type: "web_url",
                            url: "https://www.oculus.com/en-us/touch/",
                            title: "Open Web URL"
                        }, {
                            type: "postback",
                            title: "Call Postback",
                            payload: "Payload for second bubble",
                        }]
                    }]
                }
            }
        }
    };

    callSendAPI(messageData);
}

function sendTextMessage(recipientId, messageText) {
    let messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            text: messageText
        }
    };

    callSendAPI(messageData);
}

function callSendAPI(messageData) {
    request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: { access_token: CONFIGURATION.access_token },
        method: 'POST',
        json: messageData

    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            let recipientId = body.recipient_id;
            let messageId = body.message_id;

            console.log("Successfully sent generic message with id %s to recipient %s",
                messageId, recipientId);
        } else {
            console.error("Unable to send message.");
            console.error(response);
            console.error(error);
        }
    });
}

let server = app.listen(port, function () {
    InterfaceLogin.process();

    console.log('App listening on port 8080!');
});

server.timeout = 1000;
</code>```

In my console, During the last respond I see :

```<code>Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xxxx,"text":"k"}
Successfully sent generic message with id mid.$xxx to recipient xxxxx
</code>```

the bot don't respond, and after some minutes I see :

```<code>Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xxxx,"text":"l"}
Successfully sent generic message with id mid.$xxx to recipient xxxx
Webhook received unknown event:  { sender: { id: 'xxx' },
  recipient: { id: 'xxx' },
  timestamp: xxx,
  delivery:
   { mids: [ 'mid.$xxx' ],
     watermark: xxx,
     seq: 0 } }
</code>```

the bots responds

My last respond is :

```<code>Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xx,"text":"k"}
Successfully sent generic message with id mid.$xxx to recipient xxx
Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xx,"text":"l"}
Successfully sent generic message with id mid.$xxx to recipient xxxx
Webhook received unknown event:  { sender: { id: 'xxx' },
  recipient: { id: 'xxx' },
  timestamp: xxx,
  delivery:
   { mids: [ 'mid.$xxx' ],
     watermark: xxx,
     seq: 0 } }
</code>```

答:
The messenger bot platform has rate limit, if you exceed it the requests will queue up and execute later.

https://developers.facebook.com/docs/messenger-platform/reference/send-api/

Body:
When I write the alphabet on my facebook bot, my bot wait to respond.

I write for example : I write "a"... bot respond "a", I write "b"... bot respond "b", etc...

But, for example on the letter "l", the bot waits to respond, and resume after about some minutes :

after about some minutes, the bot responds :

I use the official code, from https://developers.facebook.com/docs/messenger-platform/guides/quick-start/

app.js

app.get('/webhook', function(req, res) {
    if (req.query['hub.mode'] === 'subscribe' &&
        req.query['hub.verify_token'] === CONFIGURATION.webhook_token) {
        console.log("Validating webhook");
        res.status(200).send(req.query['hub.challenge']);
    } else {
        console.error("Failed validation. Make sure the validation tokens match.");
        res.sendStatus(403);
    }
});

app.post('/webhook', function (req, res) {
    let data = req.body;

    // Make sure this is a page subscription
    if (data.object === 'page') {

        // Iterate over each entry - there may be multiple if batched
        data.entry.forEach(function(entry) {
            let pageID = entry.id;
            let timeOfEvent = entry.time;

            // Iterate over each messaging event
            entry.messaging.forEach(function(event) {
                if (event.message) {
                    receivedMessage(event);
                } else {
                    console.log("Webhook received unknown event: ", event);
                }
            });
        });

        // Assume all went well.
        //
        // You must send back a 200, within 20 seconds, to let us know
        // you've successfully received the callback. Otherwise, the request
        // will time out and we will keep trying to resend.
        res.sendStatus(200);
    }
});

function receivedMessage(event) {
    let senderID = event.sender.id;
    let recipientID = event.recipient.id;
    let timeOfMessage = event.timestamp;
    let message = event.message;

    console.log("Received message for user %d and page %d at %d with message:",
        senderID, recipientID, timeOfMessage);
    console.log(JSON.stringify(message));

    let messageId = message.mid;

    let messageText = message.text;
    let messageAttachments = message.attachments;

    if (messageText) {

        // If we receive a text message, check to see if it matches a keyword
        // and send back the example. Otherwise, just echo the text we received.
        switch (messageText) {
            case 'generic':
                sendGenericMessage(senderID);
                break;

            default:
                sendTextMessage(senderID, messageText);
        }
    } else if (messageAttachments) {
        sendTextMessage(senderID, "Message with attachment received");
    }
}

function sendGenericMessage(recipientId) {
    let messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            attachment: {
                type: "template",
                payload: {
                    template_type: "generic",
                    elements: [{
                        title: "rift",
                        subtitle: "Next-generation virtual reality",
                        item_url: "https://www.oculus.com/en-us/rift/",
                        image_url: "http://messengerdemo.parseapp.com/img/rift.png",
                        buttons: [{
                            type: "web_url",
                            url: "https://www.oculus.com/en-us/rift/",
                            title: "Open Web URL"
                        }, {
                            type: "postback",
                            title: "Call Postback",
                            payload: "Payload for first bubble",
                        }],
                    }, {
                        title: "touch",
                        subtitle: "Your Hands, Now in VR",
                        item_url: "https://www.oculus.com/en-us/touch/",
                        image_url: "http://messengerdemo.parseapp.com/img/touch.png",
                        buttons: [{
                            type: "web_url",
                            url: "https://www.oculus.com/en-us/touch/",
                            title: "Open Web URL"
                        }, {
                            type: "postback",
                            title: "Call Postback",
                            payload: "Payload for second bubble",
                        }]
                    }]
                }
            }
        }
    };

    callSendAPI(messageData);
}

function sendTextMessage(recipientId, messageText) {
    let messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            text: messageText
        }
    };

    callSendAPI(messageData);
}

function callSendAPI(messageData) {
    request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: { access_token: CONFIGURATION.access_token },
        method: 'POST',
        json: messageData

    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            let recipientId = body.recipient_id;
            let messageId = body.message_id;

            console.log("Successfully sent generic message with id %s to recipient %s",
                messageId, recipientId);
        } else {
            console.error("Unable to send message.");
            console.error(response);
            console.error(error);
        }
    });
}

let server = app.listen(port, function () {
    InterfaceLogin.process();

    console.log('App listening on port 8080!');
});

server.timeout = 1000;

In my console, During the last respond I see :

Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xxxx,"text":"k"}
Successfully sent generic message with id mid.$xxx to recipient xxxxx

the bot don't respond, and after some minutes I see :

Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xxxx,"text":"l"}
Successfully sent generic message with id mid.$xxx to recipient xxxx
Webhook received unknown event:  { sender: { id: 'xxx' },
  recipient: { id: 'xxx' },
  timestamp: xxx,
  delivery:
   { mids: [ 'mid.$xxx' ],
     watermark: xxx,
     seq: 0 } }

the bots responds

My last respond is :

Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xx,"text":"k"}
Successfully sent generic message with id mid.$xxx to recipient xxx
Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xx,"text":"l"}
Successfully sent generic message with id mid.$xxx to recipient xxxx
Webhook received unknown event:  { sender: { id: 'xxx' },
  recipient: { id: 'xxx' },
  timestamp: xxx,
  delivery:
   { mids: [ 'mid.$xxx' ],
     watermark: xxx,
     seq: 0 } }


问:
Gridview scroll width
I have this Gridview

```<code><GridView
    android:id="@+id/gridview_example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="45dp"
    android:layout_marginRight="45dp"
    android:layout_marginTop="35dp"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"
    android:numColumns="3"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp"
    android:fadeScrollbars="false"
    android:scrollbarStyle="outsideInset"
    android:scrollbarSize="30dp"
    android:smoothScrollbar="true">
</GridView>
</code>```

for which I'm trying to increase the scroll width. I've tried using scrollbarSize but nothing changes. Is there a way to increase the width of the scrollbar without customizing it?

I'm new in Android development so please be gentle :)

Update: Tested this possible solution and added my gridview inside the scrollview

```<code><ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="45dp"
    android:layout_marginRight="45dp"
    android:layout_marginTop="35dp"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"
    android:layout_above="@+id/bottomMenu"
    android:scrollbarSize="50dip">
    <GridView
        android:id="@+id/gridview_holes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:horizontalSpacing="10dp"
        android:verticalSpacing="10dp">
    </GridView>
</ScrollView>
</code>```

But the gridview is much more smaller and I'm seeing just the gridview thin scroll.

答:
use Scrollview for scrolling  sub view

https://developer.android.com/reference/android/widget/ScrollView.html

Title: Gridview scroll width

Body:
I have this Gridview

<GridView
    android:id="@+id/gridview_example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="45dp"
    android:layout_marginRight="45dp"
    android:layout_marginTop="35dp"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"
    android:numColumns="3"
    android:horizontalSpacing="10dp"
    android:verticalSpacing="10dp"
    android:fadeScrollbars="false"
    android:scrollbarStyle="outsideInset"
    android:scrollbarSize="30dp"
    android:smoothScrollbar="true">
</GridView>

for which I'm trying to increase the scroll width. I've tried using scrollbarSize but nothing changes. Is there a way to increase the width of the scrollbar without customizing it?

I'm new in Android development so please be gentle :)

Update: Tested this possible solution and added my gridview inside the scrollview

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="45dp"
    android:layout_marginRight="45dp"
    android:layout_marginTop="35dp"
    android:layout_centerHorizontal="true"
    android:layout_centerInParent="true"
    android:layout_above="@+id/bottomMenu"
    android:scrollbarSize="50dip">
    <GridView
        android:id="@+id/gridview_holes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:horizontalSpacing="10dp"
        android:verticalSpacing="10dp">
    </GridView>
</ScrollView>

But the gridview is much more smaller and I'm seeing just the gridview thin scroll.


问:
how to disable auto resizing in all view controllers
I have to remove the auto-resizing applied on all view controllers in my project. Is there a way to disable auto-resizing applied on all view controllers.</p>

答:
```<code>You are able to Disable **Autolayout** in view controller But there is no direct way to disable **Auto-Resizing** in iOS.

You need to manage PIN in **Auto-Resizing**. Set appropriate PIN of relevant object. Please review attached screenshot for **Auto-Resizing**.

Happy Coding! :)
</code>```


问:
How can I know my iOS app crashed?
I am developing an iOS app with swift 3-4 and I have to know the time when my app crashed. How do I achieve that? I don't use firebase.</p>

答: Integrate crashlytics to know about the crash, line of code that caused the crash, number of times it got crashed for the same issue etc.</p>

Title: How can I know my iOS app crashed?


问:
Finding letters that are near, exact or not in a user input string
I am currently developing a small modified version of Hangman in Rails for children. The game starts by randomly generating a word from a text file and the user has to guess the word by entering a four letter word. Each word is the split by each character for example "r", "e", "a", "l" and returns a message on how they are to the word.

Random Generated word is "real"

Input
   rlax

Output
    Correct, Close, Correct, Incorrect

I have tried other things which I have found online but haven't worked and I am fairly new to Ruby and Rails. Hopefully someone can guide me in the right direction.

Here is some code

```<code>def letterCheck(lookAtLetter)
  lookAHead = lookAtLetter =~ /[[:alpha:]]/
end

def displayWord
  $ranWordBool.each_index do |i|
      if($ranWordBool[i])
          print $ranWordArray[i]
          $isWin += 1
      else
          print "_"
      end
  end
end

def gameLoop
  turns = 10
  turnsLeft = 0
  lettersUsed = []
  while(turnsLeft < turns)
     $isWin = 0
     displayWord

     if($isWin == $ranWordBool.length)
       system "cls"
       puts "1: Quit"
       puts "The word is #{$ranWord} and You Win"
       puts "Press any key to continue"
       return
     end

     print "\n" + "Words Used: "
     lettersUsed.each_index do |looper|
     print " #{lettersUsed[looper]} "
     end
     puts "\n" + "Turns left: #{turns - turnsLeft}"

     puts "Enter a word"
     input = gets.chomp
     system "cls"

     if(input.length != 4)
       puts "Please enter 4 lettered word"
     elsif(letterCheck(input))
       if(lettersUsed.include?(input))
         puts "#{input} already choosen"
         elsif($ranWordArray.include?(input))
           puts "Close"
           $ranWordArray.each_index do |i|
             if(input == $ranWordArray[i])
               $ranWordBool[i] = true
             end
             if($ranWordBool[i] = true)
               puts "Correct"
             else
               puts "Incorrect"
             end
           end
          else
            lettersUsed << input
            turnsLeft += 1
          end
          else
            puts "Not a letter"
          end
        end
        puts "You lose"
        puts "The word was #{$ranWord}"
        puts "Press any key to continue"
      end

      words = []
      File.foreach('words.txt') do |line|
      words << line.chomp
      end

      while(true)
        $ranWord = words[rand(words.length) + 1]
        $ranWordArray = $ranWord.chars
        $ranWordBool = []
        $ranWordArray.each_index do |i|
        $ranWordBool[i] = false
      end

      system "cls"
      gameLoop
      input = gets.chomp
      shouldQuit(input)
    end
</code>```

答:
Something like that:</p>

```<code># Picking random word to guess
word = ['open', 'real', 'hang', 'mice'].sample

loop do
  puts "So, guess the word:"

  input_word = gets.strip
  if word == input_word
    puts("You are right, the word is: #{input_word}")
    break
  end

  puts "You typed: #{input_word}"

  # Split both the word to guess and the suggested word into array of letters
  word_in_letters  = word.split('')
  input_in_letters = input_word.split('')

  result = []
  # Iterate over each letter in the word to guess
  word_in_letters.each_with_index do |letter, index|
    # Pick the corresponding letter in the entered word
    letter_from_input = input_in_letters[index]

    if letter == letter_from_input
      result << "#{letter_from_input} - Correct"
      next
    end

    # Take nearby letters by nearby indexes
    # `reject` is here to skip negative indexes
    # ie: letter 'i' in a word "mice"
    #   this will return 'm' and 'c'
    # ie: letter 'm' in a word "mice"
    #   this will return 'i'
    letters_around =
      [index - 1, index + 1]
      .reject { |i| i < 0 }
      .map { |i| word_in_letters[i] }
    if letters_around.include?(letter_from_input)
      result << "#{letter_from_input} - Close"
      next
    end

    result << "#{letter_from_input} - Incorrect"
  end

  puts result.join("\n")
end
</code>```

Body:
I am currently developing a small modified version of Hangman in Rails for children. The game starts by randomly generating a word from a text file and the user has to guess the word by entering a four letter word. Each word is the split by each character for example "r", "e", "a", "l" and returns a message on how they are to the word.

Random Generated word is "real"

Input
   rlax

Output
    Correct, Close, Correct, Incorrect

I have tried other things which I have found online but haven't worked and I am fairly new to Ruby and Rails. Hopefully someone can guide me in the right direction.

Here is some code

def letterCheck(lookAtLetter)
  lookAHead = lookAtLetter =~ /[[:alpha:]]/
end

def displayWord
  $ranWordBool.each_index do |i|
      if($ranWordBool[i])
          print $ranWordArray[i]
          $isWin += 1
      else
          print "_"
      end
  end
end

def gameLoop
  turns = 10
  turnsLeft = 0
  lettersUsed = []
  while(turnsLeft < turns)
     $isWin = 0
     displayWord

     if($isWin == $ranWordBool.length)
       system "cls"
       puts "1: Quit"
       puts "The word is #{$ranWord} and You Win"
       puts "Press any key to continue"
       return
     end

     print "\n" + "Words Used: "
     lettersUsed.each_index do |looper|
     print " #{lettersUsed[looper]} "
     end
     puts "\n" + "Turns left: #{turns - turnsLeft}"

     puts "Enter a word"
     input = gets.chomp
     system "cls"

     if(input.length != 4)
       puts "Please enter 4 lettered word"
     elsif(letterCheck(input))
       if(lettersUsed.include?(input))
         puts "#{input} already choosen"
         elsif($ranWordArray.include?(input))
           puts "Close"
           $ranWordArray.each_index do |i|
             if(input == $ranWordArray[i])
               $ranWordBool[i] = true
             end
             if($ranWordBool[i] = true)
               puts "Correct"
             else
               puts "Incorrect"
             end
           end
          else
            lettersUsed << input
            turnsLeft += 1
          end
          else
            puts "Not a letter"
          end
        end
        puts "You lose"
        puts "The word was #{$ranWord}"
        puts "Press any key to continue"
      end

      words = []
      File.foreach('words.txt') do |line|
      words << line.chomp
      end

      while(true)
        $ranWord = words[rand(words.length) + 1]
        $ranWordArray = $ranWord.chars
        $ranWordBool = []
        $ranWordArray.each_index do |i|
        $ranWordBool[i] = false
      end

      system "cls"
      gameLoop
      input = gets.chomp
      shouldQuit(input)
    end

Body:
Something like that:

# Picking random word to guess
word = ['open', 'real', 'hang', 'mice'].sample

loop do
  puts "So, guess the word:"

  input_word = gets.strip
  if word == input_word
    puts("You are right, the word is: #{input_word}")
    break
  end

  puts "You typed: #{input_word}"

  # Split both the word to guess and the suggested word into array of letters
  word_in_letters  = word.split('')
  input_in_letters = input_word.split('')

  result = []
  # Iterate over each letter in the word to guess
  word_in_letters.each_with_index do |letter, index|
    # Pick the corresponding letter in the entered word
    letter_from_input = input_in_letters[index]

    if letter == letter_from_input
      result << "#{letter_from_input} - Correct"
      next
    end

    # Take nearby letters by nearby indexes
    # `reject` is here to skip negative indexes
    # ie: letter 'i' in a word "mice"
    #   this will return 'm' and 'c'
    # ie: letter 'm' in a word "mice"
    #   this will return 'i'
    letters_around =
      [index - 1, index + 1]
      .reject { |i| i < 0 }
      .map { |i| word_in_letters[i] }
    if letters_around.include?(letter_from_input)
      result << "#{letter_from_input} - Close"
      next
    end

    result << "#{letter_from_input} - Incorrect"
  end

  puts result.join("\n")
end


问:
Combining two functions in LISP to atomize list and then find max?
So, id like to take in a list of numbers, atomize it (to remove nested integers), then find the max value.  I have two functions written that accomplish this individually, but can't figure out how to combine them in LISP so I can make one call and have them both run. Any help would be appreciated.  </p>

```<code>:Atomize function to remove nests
:(atomify ‘( a (b c) (e (f (g h) i)) j)->(a b c e f g h i j)

(defun atomify (numbers)
  (cond ((null numbers) nil)
        ((atom (car numbers))
         (cons (car numbers)
               (atomify (cdr numbers))))
        (t
         (append (atomify (car numbers))
                 (atomify (cdr numbers))))))

:Max value of a list of integers function

(defun large_atom (numbers)
  (if (null numbers)
      0
      (max (first numbers)
           (large_atom (rest numbers)))))
</code>```

答:
Jamie. Your way has two steps:
1. Flatten list
2. Find max value from result of 1'st step
In this case it's true way. But you need do it with one function call. It's easy. Just use labels, apply and of course max

```<code>(defun foo (lst)
  (labels ((flatten (lst acc)
             (cond
               ((null lst)
                acc)
               ((consp (car lst))
                (flatten (cdr lst) (flatten (car lst) acc)))
               (t
                (flatten (cdr lst) (cons (car lst) acc))))))
    (apply #'max (flatten lst nil))))
</code>```

Another way, is do not flatten source list. But in this case you need find first value to compare with other values. Try it yourself.

Body:
So, id like to take in a list of numbers, atomize it (to remove nested integers), then find the max value.  I have two functions written that accomplish this individually, but can't figure out how to combine them in LISP so I can make one call and have them both run. Any help would be appreciated.

:Atomize function to remove nests
:(atomify ‘( a (b c) (e (f (g h) i)) j)->(a b c e f g h i j)

(defun atomify (numbers)
  (cond ((null numbers) nil)
        ((atom (car numbers))
         (cons (car numbers)
               (atomify (cdr numbers))))
        (t
         (append (atomify (car numbers))
                 (atomify (cdr numbers))))))

:Max value of a list of integers function

(defun large_atom (numbers)
  (if (null numbers)
      0
      (max (first numbers)
           (large_atom (rest numbers)))))

Body:
Jamie. Your way has two steps:
1. Flatten list
2. Find max value from result of 1'st step
In this case it's true way. But you need do it with one function call. It's easy. Just use labels, apply and of course max

(defun foo (lst)
  (labels ((flatten (lst acc)
             (cond
               ((null lst)
                acc)
               ((consp (car lst))
                (flatten (cdr lst) (flatten (car lst) acc)))
               (t
                (flatten (cdr lst) (cons (car lst) acc))))))
    (apply #'max (flatten lst nil))))

Another way, is do not flatten source list. But in this case you need find first value to compare with other values. Try it yourself.


问:
Trying to route Heroku to index.html
I am using Heroku to deploy my website, and am using node.js. In my index.js file, the tutorial uses "Hello World" in the response.end; however I want it to display my index.html file instead. How would I do this?

var http = require('http')

http.createServer(function (request, response){
    response.writeHead(200, {"Content-Type": "text/plain"})
    response.end("Hello World/n")
}).listen(process.env.PORT)```

答:
You can do it like this:

fs.readFile reads your html file and converts it to buffer.
response.writeHead defines the response header and specifies the content type as html.
response.end sends the file and completes the response.

```<code>var http = require('http')
var fs = require('fs')

http.createServer(function (request, response) {
  fs.readFile('index.html', function (err, file) {
    response.writeHead(200, { "Content-Type": "text/html" })
    response.end(file)
  })
})
  .listen(process.env.PORT)
</code>```

Title: Trying to route Heroku to index.html

Body:
You can do it like this:

fs.readFile reads your html file and converts it to buffer.
response.writeHead defines the response header and specifies the content type as html.
response.end sends the file and completes the response.

var http = require('http')
var fs = require('fs')

http.createServer(function (request, response) {
  fs.readFile('index.html', function (err, file) {
    response.writeHead(200, { "Content-Type": "text/html" })
    response.end(file)
  })
})
  .listen(process.env.PORT)


问:
moment.calendar() without the time
I would like to use the moment.calendar() option without the time... so instead of
"Last Tuesday at 5pm" I want "Last Tuesday".
Does anybody know whether moment has a solution for that by now?
I found this fiddle http://jsfiddle.net/nawxZ/, which apparently shows a solution for that, but I can't see how this is supposed to work?
thanks
carl</p>

```<code>function log(str) {
    $('body').append('<p>' + str + '</p>');
}

log(moment().calendar());
log(moment().calendar(true));
</code>```

答:
If you don't have custom times set and are only working on a day base, you can use this simple and multilang (tested for EN/DE/FR/IT) solution. (full days are always saved with a 00:00 timetag)</p>

```<code>let dateParts = moment(DATE).calendar().split(' '),
    index = dateParts.indexOf('00:00');

// ['Yesterday', 'at', '00:00', 'PM'] -> ['Yesterday']
dateParts.length = (index !== -1 ? (index - 1) : dateParts.length);
</code>```

Title: moment.calendar() without the time

Body:
I would like to use the moment.calendar() option without the time... so instead of
"Last Tuesday at 5pm" I want "Last Tuesday".
Does anybody know whether moment has a solution for that by now?
I found this fiddle http://jsfiddle.net/nawxZ/, which apparently shows a solution for that, but I can't see how this is supposed to work?
thanks
carl

function log(str) {
    $('body').append('
' + str + '
');
}

log(moment().calendar());
log(moment().calendar(true));

Body:
If you don't have custom times set and are only working on a day base, you can use this simple and multilang (tested for EN/DE/FR/IT) solution. (full days are always saved with a 00:00 timetag)

let dateParts = moment(DATE).calendar().split(' '),
    index = dateParts.indexOf('00:00');

// ['Yesterday', 'at', '00:00', 'PM'] -> ['Yesterday']
dateParts.length = (index !== -1 ? (index - 1) : dateParts.length);


问:
how to add extra information in every row of autocomplete
I am doing autocomplete of venues from all over the world and it is working fine but now I want the address of that particular venue to be in the next line of venue name.

if my autocomplete is reading venue name as ABCD, then below the ABCD it should be the address of this venue. I can return the address of venue but have no idea how to place it here.

my javaScript

```<code>$("#venueName").autocomplete({
    minLength: 3,
    source: function(request, response) {

    var city_lat = $('#city_lat').val();
    var city_lon = $('#city_lon').val();

    request.call = "auto_poi_ugc";
    request.cityid = $('#eventCityId').val();
    request.lat = city_lat;
    request.lon = city_lon;

    setTimeout(function() {
      ajax_req = $.ajax({
        url: "/ajaxcalls",
        dataType: "json",
        data: request,
        success: function( data ) {
            data.splice(venue_limit,data.length);
            response( data );
        }
      });
      }, 700);
    },
    select: function(event, ui) {

        if(ui.item.value == "Loading..."){
          return false;
        }
        if(ajax_req != undefined)
        {
            ajax_req.abort();
        }
        if(ui.item.value != '')
        {
            $('#venue_latitude').val(ui.item.latitude);
            $('#venue_longitude').val(ui.item.longitude);
            $('#primus_id').val(ui.item.id);
            $('#event_venue_add').val(ui.item.add);
        }
     },
    search: function(event, ui) {
        if($(this).hasClass('error-border')){
            $(this).removeClass('error-border');
        }
    },
});
</code>```

答:
You can achieve it by adding autocomplete into it.

```<code>.autocomplete( "instance" )._renderItem = function( ul, item ) {
    if(item.add == undefined){
        item.add = "";
    }
    return $( "<li>" ).append( "<div>" + item.label + "</div><div class='v_address_auto'>" + item.add + "</div>" ).appendTo( ul );
};
</code>```

http://jqueryui.com/autocomplete/#custom-data

your code will become like this

```<code>$("#venueName").autocomplete({
minLength: 3,
source: function(request, response) {

var city_lat = $('#city_lat').val();
var city_lon = $('#city_lon').val();

request.call = "auto_poi_ugc";
request.cityid = $('#eventCityId').val();
request.lat = city_lat;
request.lon = city_lon;

setTimeout(function() {
  ajax_req = $.ajax({
    url: "/ajaxcalls",
    dataType: "json",
    data: request,
    success: function( data ) {
        data.splice(venue_limit,data.length);
        response( data );
    }
  });
  }, 700);
},
select: function(event, ui) {

    if(ui.item.value == "Loading..."){
      return false;
    }
    if(ajax_req != undefined)
    {
        ajax_req.abort();
    }
    if(ui.item.value != '')
    {
        $('#venue_latitude').val(ui.item.latitude);
        $('#venue_longitude').val(ui.item.longitude);
        $('#primus_id').val(ui.item.id);
        $('#event_venue_add').val(ui.item.add);
    }
 },
search: function(event, ui) {
    if($(this).hasClass('error-border')){
        $(this).removeClass('error-border');
    }
},
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
    if(item.add == undefined){
        item.add = "";
    }
    return $( "<li>" ).append( "<div>" + item.label + "</div><div class='v_address_auto'>" + item.add + "</div>" ).appendTo( ul );
};
</code>```

Body:
I am doing autocomplete of venues from all over the world and it is working fine but now I want the address of that particular venue to be in the next line of venue name.

if my autocomplete is reading venue name as ABCD, then below the ABCD it should be the address of this venue. I can return the address of venue but have no idea how to place it here.

my javaScript

$("#venueName").autocomplete({
    minLength: 3,
    source: function(request, response) {

    var city_lat = $('#city_lat').val();
    var city_lon = $('#city_lon').val();

    request.call = "auto_poi_ugc";
    request.cityid = $('#eventCityId').val();
    request.lat = city_lat;
    request.lon = city_lon;

    setTimeout(function() {
      ajax_req = $.ajax({
        url: "/ajaxcalls",
        dataType: "json",
        data: request,
        success: function( data ) {
            data.splice(venue_limit,data.length);
            response( data );
        }
      });
      }, 700);
    },
    select: function(event, ui) {

        if(ui.item.value == "Loading..."){
          return false;
        }
        if(ajax_req != undefined)
        {
            ajax_req.abort();
        }
        if(ui.item.value != '')
        {
            $('#venue_latitude').val(ui.item.latitude);
            $('#venue_longitude').val(ui.item.longitude);
            $('#primus_id').val(ui.item.id);
            $('#event_venue_add').val(ui.item.add);
        }
     },
    search: function(event, ui) {
        if($(this).hasClass('error-border')){
            $(this).removeClass('error-border');
        }
    },
});

Body:
You can achieve it by adding autocomplete into it.

.autocomplete( "instance" )._renderItem = function( ul, item ) {
    if(item.add == undefined){
        item.add = "";
    }
    return $( "<li>" ).append( "<div>" + item.label + "</div><div class='v_address_auto'>" + item.add + "</div>" ).appendTo( ul );
};

http://jqueryui.com/autocomplete/#custom-data

your code will become like this

$("#venueName").autocomplete({
minLength: 3,
source: function(request, response) {

var city_lat = $('#city_lat').val();
var city_lon = $('#city_lon').val();

request.call = "auto_poi_ugc";
request.cityid = $('#eventCityId').val();
request.lat = city_lat;
request.lon = city_lon;

setTimeout(function() {
  ajax_req = $.ajax({
    url: "/ajaxcalls",
    dataType: "json",
    data: request,
    success: function( data ) {
        data.splice(venue_limit,data.length);
        response( data );
    }
  });
  }, 700);
},
select: function(event, ui) {

    if(ui.item.value == "Loading..."){
      return false;
    }
    if(ajax_req != undefined)
    {
        ajax_req.abort();
    }
    if(ui.item.value != '')
    {
        $('#venue_latitude').val(ui.item.latitude);
        $('#venue_longitude').val(ui.item.longitude);
        $('#primus_id').val(ui.item.id);
        $('#event_venue_add').val(ui.item.add);
    }
 },
search: function(event, ui) {
    if($(this).hasClass('error-border')){
        $(this).removeClass('error-border');
    }
},
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
    if(item.add == undefined){
        item.add = "";
    }
    return $( "<li>" ).append( "<div>" + item.label + "</div><div class='v_address_auto'>" + item.add + "</div>" ).appendTo( ul );
};


问:
Tile not getting center in Collapsed toolbar
I tried setting collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER);

```<code>collapsingToolbarLayout.setExpandedTitleGravity(Gravity.CENTER);
</code>```

and almost all available links on INTERNET but i am not able to put the title in center of toolbar.

plz help !

答:
To center the text in the toolbar you need to use a custom toolbar with a textview inside it rather than using android:title=""

```<code><android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:id="@+id/toolbar"
    android:layout_height="?actionBarSize">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textColor="#000000"
        android:id="@+id/tvToolbarTitle"
        android:layout_gravity="center"
        android:textSize="16sp"/>

</android.support.v7.widget.Toolbar>
</code>```

You can apply the same logic in a collapsible toolbar.

Body:
I tried setting collapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER);

collapsingToolbarLayout.setExpandedTitleGravity(Gravity.CENTER);

and almost all available links on INTERNET but i am not able to put the title in center of toolbar.

plz help !

Body:
To center the text in the toolbar you need to use a custom toolbar with a textview inside it rather than using android:title=""

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:id="@+id/toolbar"
    android:layout_height="?actionBarSize">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textColor="#000000"
        android:id="@+id/tvToolbarTitle"
        android:layout_gravity="center"
        android:textSize="16sp"/>

</android.support.v7.widget.Toolbar>

You can apply the same logic in a collapsible toolbar.