问:
arising from a use of `Control.Exception.catch'
When i load a haskell file, it has error</p>

```<code>module REPL(REPL(..), repl) where
import qualified Control.Exception as E
import System.Console.Readline(readline, addHistory)

data REPL s = REPL {
    repl_init :: IO (String, s),        -- prompt and initial state
    repl_eval :: s -> String -> IO (Bool, s),       -- quit flag and new state
    repl_exit :: s -> IO ()
    }

repl :: REPL s -> IO ()
repl p = do
    (prompt, state) <- repl_init p
    let loop s = (do
        mline <- readline prompt
        case mline of
        Nothing -> loop s
        Just line -> do
            (quit, s') <- repl_eval p s line
            if quit then
            repl_exit p s'
             else do
            addHistory line
            loop s'
        ) E.catch undefined (\(e :: E.SomeException) -> putStrLn "Handled exception!"
        )
    loop state

REPL.hs:21:5:
    Couldn't match expected type `IO (Maybe String)'
           against inferred type `t -> Maybe String'
    In a stmt of a 'do' expression: mline <- readline prompt
    In the expression:
        (do { mline <- readline prompt;
              case mline of {
                Nothing -> loop s
                Just line
                  -> do { (quit, s') <- repl_eval p s line;
                          .... } } })
          E.catch
          undefined
          (\ (e :: E.SomeException) -> putStrLn "Handled exception!")
    In the definition of `loop':
        loop s = (do { mline <- readline prompt;
                       case mline of {
                         Nothing -> loop s
                         Just line -> do { ... } } })
                   E.catch
                   undefined
                   (\ (e :: E.SomeException) -> putStrLn "Handled exception!")
</code>```

答:
Use scoped type variables by including this line at the top of your file:

```<code>{-# LANGUAGE ScopedTypeVariables #-}
</code>```

Or in a GHCi session just do:

```<code>> :set -XScopedTypeVariables
</code>```

And in your catch function provide a signature.  In GHCi:

```<code>> import Control.Exception as E
> E.catch undefined (\(e :: E.SomeException) -> putStrLn "Handled exception!")
Handled exception!
</code>```

Celebrate good times, come on!

Body:
When i load a haskell file, it has error

module REPL(REPL(..), repl) where
import qualified Control.Exception as E
import System.Console.Readline(readline, addHistory)

data REPL s = REPL {
    repl_init :: IO (String, s),        -- prompt and initial state
    repl_eval :: s -> String -> IO (Bool, s),       -- quit flag and new state
    repl_exit :: s -> IO ()
    }

repl :: REPL s -> IO ()
repl p = do
    (prompt, state) <- repl_init p
    let loop s = (do
        mline <- readline prompt
        case mline of
        Nothing -> loop s
        Just line -> do
            (quit, s') <- repl_eval p s line
            if quit then
            repl_exit p s'
             else do
            addHistory line
            loop s'
        ) E.catch undefined (\(e :: E.SomeException) -> putStrLn "Handled exception!"
        )
    loop state

REPL.hs:21:5:
    Couldn't match expected type `IO (Maybe String)'
           against inferred type `t -> Maybe String'
    In a stmt of a 'do' expression: mline <- readline prompt
    In the expression:
        (do { mline <- readline prompt;
              case mline of {
                Nothing -> loop s
                Just line
                  -> do { (quit, s') <- repl_eval p s line;
                          .... } } })
          E.catch
          undefined
          (\ (e :: E.SomeException) -> putStrLn "Handled exception!")
    In the definition of `loop':
        loop s = (do { mline <- readline prompt;
                       case mline of {
                         Nothing -> loop s
                         Just line -> do { ... } } })
                   E.catch
                   undefined
                   (\ (e :: E.SomeException) -> putStrLn "Handled exception!")

Body:
Use scoped type variables by including this line at the top of your file:

{-# LANGUAGE ScopedTypeVariables #-}

Or in a GHCi session just do:

> :set -XScopedTypeVariables

And in your catch function provide a signature.  In GHCi:

> import Control.Exception as E
> E.catch undefined (\(e :: E.SomeException) -> putStrLn "Handled exception!")
Handled exception!

Celebrate good times, come on!


来源: stackexchange

问:
How to dynamic load Jquery inside a JavaScript Class constructor and proceed the execution only after jquery has been fully loaded
This is actually a merge of three differents questions already all well answered here on stack overflow !

1 - How to Dynamic Load a JavaScript file from  inside a Js Script :

2 - How to Dynamic Load Jquery

3 - SetTimeout inside a JS Class using this

Basically, I am building a class that will inject some pages inside my clients's website.

To do so, the client just need to add my script src on the page.

```<code><script src="<my_pub_http_address>/MyClass.js">
</code>```

Once the script is invoked, I will need jquery to continue the execution !
But, I cannot know if the website that invoked the scripts has jquery already loaded.

So, I need to check if jquery is loaded, if not, I will have to load it, append to head and only then when jquery is loaded and working, I will proceed with the script's execution .

PS: this is a kind of legacy answer ! I already had the solution beforehand !
So, any improvement will be appreciated !

答:
That's the solution I've found:

// MyClass.js

```<code>var counterLoopLoad = 0;

class MyClass {

    constructor(){
        // do the code that does not need jQuery
        return this.Init()
    }

    JqueryLoader() {
        // Loop Breaker
        counterLoopLoad ++;

        if (counterLoopLoad == 100) {
            throw 'I need jQuery in order to do what I am suppose to do!';
        }

        var __jquery = document.createElement('script');
        __jquery.src = "http://code.jquery.com/jquery-latest.min.js";
        __jquery.type = 'text/javascript';

        // if needed ....
        // __jquery.onload = function() {
        //     some code here
        //
        // };

        // must be prepend !!! append won't work !!!!
        document.head.prepend(__jquery);

        // here is the point that makes all work !!!!
        // without setTimeOut, the script will get in a loop !

        var that = this;
        setTimeout(function () {
            that.Init();
        }, 500);
    }

    Init() {
        if (typeof jQuery == 'undefined') {
            return this.JqueryLoader();
         }

         jQuery.ajax(...);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
That's the solution I've found:

// MyClass.js

var counterLoopLoad = 0;

class MyClass {

    constructor(){
        // do the code that does not need jQuery
        return this.Init()
    }

    JqueryLoader() {
        // Loop Breaker
        counterLoopLoad ++;

        if (counterLoopLoad == 100) {
            throw 'I need jQuery in order to do what I am suppose to do!';
        }

        var __jquery = document.createElement('script');
        __jquery.src = "http://code.jquery.com/jquery-latest.min.js";
        __jquery.type = 'text/javascript';

        // if needed ....
        // __jquery.onload = function() {
        //     some code here
        //
        // };

        // must be prepend !!! append won't work !!!!
        document.head.prepend(__jquery);

        // here is the point that makes all work !!!!
        // without setTimeOut, the script will get in a loop !

        var that = this;
        setTimeout(function () {
            that.Init();
        }, 500);
    }

    Init() {
        if (typeof jQuery == 'undefined') {
            return this.JqueryLoader();
         }

         jQuery.ajax(...);
    }
}


问:
Temporarily Override Scrolling Javascript

Quick version:

Using Javascript, how do I temporarily disable scrolling, but still get the values from wheel, so I can trigger an if statement?

Context:

I'm adding an easter egg into a website that should work as follows:

First, there is a fixed element that is partially overlayed by a scrollable element. When you scroll down the page normally, everything behaves as you'd expect--the scrollable element rolls over the fixed element.

Initial state

Here's the easter egg: If you are at the top of the page, when you scroll up, I have JS adding a class to the scrollable element which gives it a larger top margin, so the scrollable element slides down, revealing the little easter egg on the fixed element that had been previously hidden.

effect

What I've got so far:

window.onwheel = function() {reveal()};

function reveal() {

 var y = event.deltaY;

 var scrollPosition = document.body.scrollTop;

 if ( scrollPosition <= 0 && y < 0 ) {

  document.getElementById("scrolling-area").className = "reveal";

 };

 if ( y > 0 ) {

  document.getElementById("scrolling-area").classList.remove("reveal");
 };

};```
</div>
</div>
</p>

<p>This code achieves the basics: If you are at the top of the page and scroll up, it triggers the CSS animation, and if you scroll down, it animates back into its initial state.</p>

<p>There is one nagging issue that I'd like to polish up though.</p>

<h2>Where I'm stuck</h2>

<p>The problem with this behavior is that when the easter egg is revealed when you scroll up, it both hides the easter egg <em>and</em> scrolls down the page. This is a problem, because it makes it so the user has to scroll back to the top to trigger the easter egg again, which feels buggy.</p>

<p>Here's what I want: When the 'reveal' class is engaged, I want to totally disable the page from scrolling, and have the wheel input only trigger the css animation hidding the easter egg, so that the scroll position remains at the very top of the page. Once the 'reveal' class is removed, I want to reengage scrolling as normal.</p>

<p>I've spent time using this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>window.onwheel = preventDefault;

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
  e.returnValue = false;
};</code>```

But when I do that, it seems to stop deltaY from getting any values, so I can't trigger the condition to hide the easter egg again.

Any ideas?

答:
You might want to check How to disable scrolling temporarily?.
....

I can't comment hence the link in answers sections

Body:
Quick version:

Using Javascript, how do I temporarily disable scrolling, but still get the values from wheel, so I can trigger an if statement?

Context:

I'm adding an easter egg into a website that should work as follows:

First, there is a fixed element that is partially overlayed by a scrollable element. When you scroll down the page normally, everything behaves as you'd expect--the scrollable element rolls over the fixed element.

Initial state

Here's the easter egg: If you are at the top of the page, when you scroll up, I have JS adding a class to the scrollable element which gives it a larger top margin, so the scrollable element slides down, revealing the little easter egg on the fixed element that had been previously hidden.

effect

What I've got so far:

window.onwheel = function() {reveal()};

function reveal() {

 var y = event.deltaY;

 var scrollPosition = document.body.scrollTop;

 if ( scrollPosition <= 0 && y < 0 ) {

  document.getElementById("scrolling-area").className = "reveal";

 };

 if ( y > 0 ) {

  document.getElementById("scrolling-area").classList.remove("reveal");
 };

};

This code achieves the basics: If you are at the top of the page and scroll up, it triggers the CSS animation, and if you scroll down, it animates back into its initial state.

There is one nagging issue that I'd like to polish up though.

Where I'm stuck

The problem with this behavior is that when the easter egg is revealed when you scroll up, it both hides the easter egg and scrolls down the page. This is a problem, because it makes it so the user has to scroll back to the top to trigger the easter egg again, which feels buggy.

Here's what I want: When the 'reveal' class is engaged, I want to totally disable the page from scrolling, and have the wheel input only trigger the css animation hidding the easter egg, so that the scroll position remains at the very top of the page. Once the 'reveal' class is removed, I want to reengage scrolling as normal.

I've spent time using this:

window.onwheel = preventDefault;

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
  e.returnValue = false;
};

But when I do that, it seems to stop deltaY from getting any values, so I can't trigger the condition to hide the easter egg again.

Any ideas?


问:
got positional argument error when using decorator in python
I have defined a decorator function in python, but I get positional argument error when using it. This is my code:

```<code>def my_upper_case(func):

    def wrapper():
        return func().upper()

    return wrapper

@my_upper_case
def print_name(name):
    return name

if __name__ == "__main__":
    print(print_name("zeinab"))
</code>```

Returned error is:

```<code>Traceback (most recent call last):
  File "test.py", line 31, in <module>
    print(print_name("zeinab"))
TypeError: wrapper() takes no arguments (1 given)
</code>```

I tried running the code with both python 2.7 and python 3.6. Both returned exact error.

答:
wrapper wraps the function, meaning it will 'act in its place'.

Therefore, if you call print_name("zeinab"), the wrapper will be called instead with wrapper("zeinab").

wrapper doesn't accept the "zeinab" argument, because you didn't give it any parameters.

def my_upper_case(func):

    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()

    return wrapper

@my_upper_case
def print_name(name):
    return name

if __name__ == "__main__":
    print(print_name("zeinab"))
```

Body:
I have defined a decorator function in python, but I get positional argument error when using it. This is my code:

def my_upper_case(func):

    def wrapper():
        return func().upper()

    return wrapper

@my_upper_case
def print_name(name):
    return name

if __name__ == "__main__":
    print(print_name("zeinab"))

Returned error is:

Traceback (most recent call last):
  File "test.py", line 31, in <module>
    print(print_name("zeinab"))
TypeError: wrapper() takes no arguments (1 given)

I tried running the code with both python 2.7 and python 3.6. Both returned exact error.


问:
Conditional (Dynamic) Struct Tags
I'm trying to parse some xml documents in Go. I need to define a few structs for this purpose, and my struct tags depend on a certain condition.

Imagine the following code (even though I know it won't work)

```<code>if someCondition {
    type MyType struct {
        // some common fields
        Date    []string `xml:"value"`
    }
} else {
    type MyType struct {
        // some common fields
        Date    []string `xml:"anotherValue"`
    }
}

var t MyType
// do the unmarshalling ...
</code>```

The problem is that these two structs have lots of fields in common. The only difference is in one of the fields and I want to prevent duplication. How can I solve this problem?

答: You use different types to unmarshal. Basically, you write the unmarshaling code twice and either run the first version or the second. There is no dynamic solution to this.

Title: Conditional (Dynamic) Struct Tags

Body:
I'm trying to parse some xml documents in Go. I need to define a few structs for this purpose, and my struct tags depend on a certain condition.

Imagine the following code (even though I know it won't work)

if someCondition {
    type MyType struct {
        // some common fields
        Date    []string `xml:"value"`
    }
} else {
    type MyType struct {
        // some common fields
        Date    []string `xml:"anotherValue"`
    }
}

var t MyType
// do the unmarshalling ...

The problem is that these two structs have lots of fields in common. The only difference is in one of the fields and I want to prevent duplication. How can I solve this problem?


问:
How can I prevent my System.Timers.Timer from raising the Elapsed event after it got stopped?
I have the followig code:

```<code>using (FileStream sourceStream = sourceFile.Open())
{
    using (FileStream targetStream = File.Create(targetFilePath))
    {
        using (Timer timer = new Timer(250))
        {
            timer.Elapsed += (sender, e) =>
            {
                if (this.FileCopyProgressChanged != null)
                {
                    //Here the ObjectDisposedException appears
                    this.FileCopyProgressChanged(this,
                        new CopyProgressEventArgs(
                            sourceStream.Length,
                            targetStream.Length));
                }
            };

            timer.Start();

            sourceStream.CopyTo(targetStream);

            timer.Stop();
        }
    }
}
</code>```

My timer elapses every 250 milliseconds and raises an event with information about the stream copy progress.
The problem is, that sometimes in the timer event, a ObjectDisposedException gets thrown, because the streams are not opened anymore.

How can I prevent my timer from raising the elapsed event after my streams are disposed?

答:
Why not just do this, no timers required:</p>

```<code>using (FileStream sourceStream = sourceFile.Open())
{
    using (FileStream targetStream = File.Create(targetFilePath))
    {
        int bytesTotal = sourceStream.Length;
        int bytesCurrent = 0;
        var buffer = new byte[32*1024];
        int bytes;
        while ((bytes = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            targetStream.Write(buffer, 0, bytes);
            bytesCurrent += bytes;
            FileCopyProgressChanged(this,
                new CopyProgressEventArgs(bytesTotal, bytesCurrent));
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the followig code:

using (FileStream sourceStream = sourceFile.Open())
{
    using (FileStream targetStream = File.Create(targetFilePath))
    {
        using (Timer timer = new Timer(250))
        {
            timer.Elapsed += (sender, e) =>
            {
                if (this.FileCopyProgressChanged != null)
                {
                    //Here the ObjectDisposedException appears
                    this.FileCopyProgressChanged(this,
                        new CopyProgressEventArgs(
                            sourceStream.Length,
                            targetStream.Length));
                }
            };

            timer.Start();

            sourceStream.CopyTo(targetStream);

            timer.Stop();
        }
    }
}

My timer elapses every 250 milliseconds and raises an event with information about the stream copy progress.
The problem is, that sometimes in the timer event, a ObjectDisposedException gets thrown, because the streams are not opened anymore.

How can I prevent my timer from raising the elapsed event after my streams are disposed?

Body:
Why not just do this, no timers required:

using (FileStream sourceStream = sourceFile.Open())
{
    using (FileStream targetStream = File.Create(targetFilePath))
    {
        int bytesTotal = sourceStream.Length;
        int bytesCurrent = 0;
        var buffer = new byte[32*1024];
        int bytes;
        while ((bytes = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            targetStream.Write(buffer, 0, bytes);
            bytesCurrent += bytes;
            FileCopyProgressChanged(this,
                new CopyProgressEventArgs(bytesTotal, bytesCurrent));
        }
    }
}


问:
Maven local repo in a common global directory for multiple parallel execution
I have a machine in which multiple parallel maven execution happen. Each execution executes the below command in a separate workspace directory

mvn -f main/pom.xml clean package -DskipTests -T 6

Can someone let me know should I use a separate maven local repo path (-Dmaven.repo.local=$MAVEN_REPO) for each execution or I can use a common .m2 directory for all parallel runs? What is the common practice followed?

Maven Version 3.5

Java 8

答:
I will start by saying that it is possible to set multiple local repositories or a local repository for each project.
Indeed, the way to do it is by setting each project with its own settings.xml.
Each settings.xml will have a localRepository tag pointing to a different path.
The Dmaven.repo.local=/path/to/repo flag to run the project points the execution to the settings.xml with the specific local repository.

Usually, it is not needed at all. Maven can handle parallel executions and having a central local repository for all your projects (where all artifacts are installed and download) can facilitate their handling and will not short the building time.
The only way it can effect you is if one of your projects require artifact created by another - but this should not be handled by multiple local repositories either.


问:
Flex positionning in CSS
I'm creating a React Native application and I would like to use flex to structure the positionning of my elements on the screen. Considering that we have the following screen: the red zone got a flex-grow value of 1, the yellow zone 2 and the green zone 3. They all have a parent with a display: flex and flex-grow: 1. (This is React Native so default flex-direction is column).

My question is the following: What if there is no green zone? How could I tell flex to take 1/6 of the parent for the red zone, 2/6 for the yellow zone and leave the rest empty ?

答:
Théo, do you want to do it only with flex or can you hear another suggestion?

This is a perfect example to use grid.

Fiddle: https://jsfiddle.net/h17tezLd/

```<code><div class="container">
    <div class="zone1"></div>
    <div class="zone2"></div>
    <div class="zone3"></div>
</div>

<style>
    .container {
        width: 150px;
        height: 300px;
        background: grey;
        display: grid;
        grid-template: 1fr 2fr 3fr / 100%;
        }
    .zone1 { background: red; }
    .zone2 { background: blue; }
    .zone3 { background: green; }
</style>
</code>```

Title: Flex positionning in CSS

Body:
Théo, do you want to do it only with flex or can you hear another suggestion?

This is a perfect example to use grid.

Fiddle: https://jsfiddle.net/h17tezLd/

<div class="container">
    <div class="zone1"></div>
    <div class="zone2"></div>
    <div class="zone3"></div>
</div>

<style>
    .container {
        width: 150px;
        height: 300px;
        background: grey;
        display: grid;
        grid-template: 1fr 2fr 3fr / 100%;
        }
    .zone1 { background: red; }
    .zone2 { background: blue; }
    .zone3 { background: green; }
</style>


问:
In what scenario would Slate and Swagger be used together?
From this question I have seen that

Swagger and Slate serve two different purposes. Swagger is an attempt at a standardized way of describing a RESTful API.

Slate, on the other hand is a pretty theme for writing nice API docs.

It further states that

The two are not mutually exclusive
Ideally, one should generate your slate documentation from your Swagger API description

I am a bit confused. Why would I need slate when I already have Swagger UI like so.

What more do I need to ‘document’ ? I am genuinely asking because as I said I am a bit confused by their uses.

答:
There are a few things that are worth mentioning when creating documentation for a new API.

Swagger provides a really nice graphical interface for exploring the endpoints of an API, but there are still other things that should be included in your documentation, including (but not limited to):

Authentication methods (OAuth/JWT, Basic Auth, Cookie/Session, Apikey/token)

Date formats for date output + timezone

Filtering/pagination/selecting/sorting settings for the API

Which environments exists (usually test, pre-production and production) including their differences.

Error handling including error codes, exception types and logging

Potential rate limits for your API

Terms and conditions for using your API


问:
Django Rest Framework object is not iterable?
I have serialised one of my models that has a foreign key in. I get 'Parent' object is not iterable

models.py

```<code>class Parent(models.Model):
    # Parent data

class Child(models.Model):
    parent = ForeignKey(Parent)
</code>```

serializer.py

```<code>class ChildSerializers(serializers.ModelSerializer):
    parent = serializers.RelatedField(many=True)
    class Meta:
        model = ReportField
        fields = (
            'id',
            'parent'
        )
</code>```

api.py

```<code>class ChildList(APIView):
    def get(self, request, format=None):
        child = Child.objects.all()
        serialized_child = ChildSerializers(child, many=True)
        return Response(serialized_child.data)
</code>```

Im guessing i have to pass the parent list to the child list but not sure of the best way to do it

attempt api.py

```<code>class ChildList(APIView):
    def get(self, request, format=None):
        child = Child.objects.all()
        parent = Parent.objects.all()
        serialized_child = ChildSerializers(child, many=True)
        serialized_parent = ChildSerializers(parent, many=True)
        return Response(serialized_child.data, serialized_parent.data)
</code>```

答:
```<code>You can do something like this using python collections as an intermediate

#serializers.py
class TimelineSerializer(serializers.Serializer):
    childs= childSerializer(many=True)
    parents = parentSerializer(many=True)

#apiviews.py
from collections import namedtuple
Timeline = namedtuple('Timeline', ('childs', 'parents'))

def list(self, request):
        timeline = Timeline(
            childs=Child.objects.all(),
            parents=Parent.objects.all(),
        )
        serializer = TimelineSerializer(timeline)
        return Response(serializer.data)
</code>```

Body:
I have serialised one of my models that has a foreign key in. I get 'Parent' object is not iterable

models.py

class Parent(models.Model):
    # Parent data

class Child(models.Model):
    parent = ForeignKey(Parent)

serializer.py

class ChildSerializers(serializers.ModelSerializer):
    parent = serializers.RelatedField(many=True)
    class Meta:
        model = ReportField
        fields = (
            'id',
            'parent'
        )

api.py

class ChildList(APIView):
    def get(self, request, format=None):
        child = Child.objects.all()
        serialized_child = ChildSerializers(child, many=True)
        return Response(serialized_child.data)

Im guessing i have to pass the parent list to the child list but not sure of the best way to do it

attempt api.py

class ChildList(APIView):
    def get(self, request, format=None):
        child = Child.objects.all()
        parent = Parent.objects.all()
        serialized_child = ChildSerializers(child, many=True)
        serialized_parent = ChildSerializers(parent, many=True)
        return Response(serialized_child.data, serialized_parent.data)


问:
How to get detailed error messages from rails console?
Say I wish to create a user from console with an email which already exists. If I do User.create(...)

Because of model validations (uniqueness in this case). create fails and the output in rails console will say: rollback transaction (user is not saved)

For the purpose of testing. Is their a way I can get the explicit error which triggered the rollback? In this case it would say something like: "ROLLBACK: email is not unique".

答:
If you mean by using "rails console", I hope and this small example is useful for you:

Model Student (student.rb):

```<code>class Student < ApplicationRecord
  validates :name, presence: true, length: {minimum: 5, maximum: 50}
end
</code>```

And at Rails console ($ rails console) do something like this:

```<code>> student = Student.create(name:"alba")
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
 => #<Student id: nil, name: "alba">

> student.errors.any?
 => true

> student.errors.full_messages
 => ["Name is too short (minimum is 5 characters)"]
</code>```

Hope this helps.

Body:
If you mean by using "rails console", I hope and this small example is useful for you:

Model Student (student.rb):

class Student < ApplicationRecord
  validates :name, presence: true, length: {minimum: 5, maximum: 50}
end

And at Rails console ($ rails console) do something like this:

> student = Student.create(name:"alba")
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
 => #<Student id: nil, name: "alba">

> student.errors.any?
 => true

> student.errors.full_messages
 => ["Name is too short (minimum is 5 characters)"]

Hope this helps.


问:
Extracting .node files
I found the .node files in the modules folder of Discord. I tried searching the internet but nobody has really asked a question about extracting .node files. I even tried to open up WinRAR but it failed to extract the .node file.

I tried to search or extract it but failed.

When I went to "C:\Users\USER_NAME\AppData\Roaming\Discord\0.0.305\modules\discord_zstd"
it contains a discord_zstd.node file

On WinRAR, I tried extracting it but it says this: "ERROR: This file is unsupported."

.node file image

答: .node files are compiled C++ addons, not archive files. You can't extract them (though you might be able to decompile them).

Title: Extracting .node files


问:
Count Bold Cells with ability to copy/drag in Google Sheets Scripts
I have many rows that I want to count how many cells are bolded in a Google Sheets. I've looked through plugins and searched for pre-made code snippets (I have no programming skills).

I found a script that does exactly what I want it to do, but the cells it checks and where it outputs the answer is hard coded in located here (answer from user random-parts): Count Bold Cells in Google Sheets Script

I have several hundred rows that I want to know how many, if any, bolded cells, so I would have to make hundreds of separate scripts to use that. I've tried to turn it into a command I can drag/copy on the sheet but that skill is way beyond me.

This is the code that counts all the cells with bold, but the range input and output is hard coded in

```<code>  var book = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = book.getActiveSheet();
  var range_input = sheet.getRange("E2:S7");
  var range_output = sheet.getRange("G14");

  // Get the fontWeights of the range and flatten the array
  var cell_styles = range_input.getFontWeights().join().split(",");

  // Filter out any value that is not "bold"
  var filter_bold = cell_styles.filter(function (e) { return e == "bold" });

  // Set the count
  range_output.setValue(filter_bold.length);

}
</code>```

Can someone please provide a script and formula that would allow me to define a range in the sheet and then drag it and have it update?

答:
Here is the link to a working example, and below is the code behind.
The important thing to note is that you need to refresh your browser window for formulas to re-calculate. The formula result cannot be refreshed by just changing the cells style.</p>

```<code>function onOpen(){
  refresh()
}

function refresh(){
  var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet2")
  var formulaCol = sheet.getRange("E:E").getColumn()
  var formulaRange = sheet.getRange(2, formulaCol, sheet.getDataRange().getLastRow()-1, 1)
  var rowCount = formulaRange.getLastRow()-formulaRange.getRow()+1
  var dummyFormulas = []
  var formulas = formulaRange.getFormulas()
  for(var i=0; i<rowCount; i++){
    dummyFormulas.push(['=""'])
  }
  Logger.log(dummyFormulas)
  Logger.log(formulas)
  formulaRange.setFormulas(dummyFormulas)
  SpreadsheetApp.flush()
  formulaRange.setFormulas(formulas)
}

function countBoldCells(startRow, startColumn, endRow, endColumn, random){
  var book = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = book.getActiveSheet();
  var range_input = SpreadsheetApp.getActiveSheet().getRange(startRow, startColumn, endRow-startRow+1, endColumn-startColumn+1)

  // Get the fontWeights of the range and flatten the array
  var cell_styles = range_input.getFontWeights().join().split(",");

  // Filter out any value that is not "bold"
  var filter_bold = cell_styles.filter(function (e) { return e == "bold" });

  return filter_bold.length;
}
</code>```

Body:
I have many rows that I want to count how many cells are bolded in a Google Sheets. I've looked through plugins and searched for pre-made code snippets (I have no programming skills).

I found a script that does exactly what I want it to do, but the cells it checks and where it outputs the answer is hard coded in located here (answer from user random-parts): Count Bold Cells in Google Sheets Script

I have several hundred rows that I want to know how many, if any, bolded cells, so I would have to make hundreds of separate scripts to use that. I've tried to turn it into a command I can drag/copy on the sheet but that skill is way beyond me.

This is the code that counts all the cells with bold, but the range input and output is hard coded in

  var book = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = book.getActiveSheet();
  var range_input = sheet.getRange("E2:S7");
  var range_output = sheet.getRange("G14");

  // Get the fontWeights of the range and flatten the array
  var cell_styles = range_input.getFontWeights().join().split(",");

  // Filter out any value that is not "bold"
  var filter_bold = cell_styles.filter(function (e) { return e == "bold" });

  // Set the count
  range_output.setValue(filter_bold.length);

}

Can someone please provide a script and formula that would allow me to define a range in the sheet and then drag it and have it update?

Body:
Here is the link to a working example, and below is the code behind.
The important thing to note is that you need to refresh your browser window for formulas to re-calculate. The formula result cannot be refreshed by just changing the cells style.

function onOpen(){
  refresh()
}

function refresh(){
  var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet2")
  var formulaCol = sheet.getRange("E:E").getColumn()
  var formulaRange = sheet.getRange(2, formulaCol, sheet.getDataRange().getLastRow()-1, 1)
  var rowCount = formulaRange.getLastRow()-formulaRange.getRow()+1
  var dummyFormulas = []
  var formulas = formulaRange.getFormulas()
  for(var i=0; i<rowCount; i++){
    dummyFormulas.push(['=""'])
  }
  Logger.log(dummyFormulas)
  Logger.log(formulas)
  formulaRange.setFormulas(dummyFormulas)
  SpreadsheetApp.flush()
  formulaRange.setFormulas(formulas)
}

function countBoldCells(startRow, startColumn, endRow, endColumn, random){
  var book = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = book.getActiveSheet();
  var range_input = SpreadsheetApp.getActiveSheet().getRange(startRow, startColumn, endRow-startRow+1, endColumn-startColumn+1)

  // Get the fontWeights of the range and flatten the array
  var cell_styles = range_input.getFontWeights().join().split(",");

  // Filter out any value that is not "bold"
  var filter_bold = cell_styles.filter(function (e) { return e == "bold" });

  return filter_bold.length;
}


问:
Flood fill NumPy Array `numpy.ndarray`, i. e. assign new value to element and change neighboring elements of the same value, too
Another, similar post called Flood Fill in Python is a very general question on flood fill and the answer only contains a broad pseudo code example. I'm look for an explicit solution with numpy or scipy.

Let's take this array for example:

```<code>a = np.array([
    [0, 1, 1, 1, 1, 0],
    [0, 0, 1, 2, 1, 1],
    [0, 1, 1, 1, 1, 0]
])
</code>```

For selecting element 0, 0 and flood fill with value 3, I'd expect:

```<code>[
    [3, 1, 1, 1, 1, 0],
    [3, 3, 1, 2, 1, 1],
    [3, 1, 1, 1, 1, 0]
]
</code>```

For selecting element 0, 1 and flood fill with value 3, I'd expect:

```<code>[
    [0, 3, 3, 3, 3, 0],
    [0, 0, 3, 2, 3, 3],
    [0, 3, 3, 3, 3, 0]
]
</code>```

For selecting element 0, 5 and flood fill with value 3, I'd expect:

```<code>[
    [0, 1, 1, 1, 1, 3],
    [0, 0, 1, 2, 1, 1],
    [0, 1, 1, 1, 1, 0]
]
</code>```

This should be a fairly basic operation, no? Which numpy or scipy method am I overlooking?

答:
Approach #1

Module scikit-image offers the built-in to do the same with skimage.segmentation.flood_fill -

```<code>from skimage.morphology import flood_fill

flood_fill(image, (x, y), newval)
</code>```

Sample runs -

```<code>In [17]: a
Out[17]:
array([[0, 1, 1, 1, 1, 0],
       [0, 0, 1, 2, 1, 1],
       [0, 1, 1, 1, 1, 0]])

In [18]: flood_fill(a, (0, 0), 3)
Out[18]:
array([[3, 1, 1, 1, 1, 0],
       [3, 3, 1, 2, 1, 1],
       [3, 1, 1, 1, 1, 0]])

In [19]: flood_fill(a, (0, 1), 3)
Out[19]:
array([[0, 3, 3, 3, 3, 0],
       [0, 0, 3, 2, 3, 3],
       [0, 3, 3, 3, 3, 0]])

In [20]: flood_fill(a, (0, 5), 3)
Out[20]:
array([[0, 1, 1, 1, 1, 3],
       [0, 0, 1, 2, 1, 1],
       [0, 1, 1, 1, 1, 0]])
</code>```

Approach #2

We can use skimage.measure.label with some array-masking -

```<code>from skimage.measure import label

def floodfill_by_xy(a,xy,newval):
    x,y = xy
    l = label(a==a[x,y])
    a[l==l[x,y]] = newval
    return a
</code>```

To make use of SciPy based label function - scipy.ndimage.measurements.label, it would mostly be the same -

```<code>from scipy.ndimage.measurements import label

def floodfill_by_xy_scipy(a,xy,newval):
    x,y = xy
    l = label(a==a[x,y])[0]
    a[l==l[x,y]] = newval
    return a
</code>```

Note : These would work as in-situ edits.

Body:
Another, similar post called Flood Fill in Python is a very general question on flood fill and the answer only contains a broad pseudo code example. I'm look for an explicit solution with numpy or scipy.

Let's take this array for example:

a = np.array([
    [0, 1, 1, 1, 1, 0],
    [0, 0, 1, 2, 1, 1],
    [0, 1, 1, 1, 1, 0]
])

For selecting element 0, 0 and flood fill with value 3, I'd expect:

[
    [3, 1, 1, 1, 1, 0],
    [3, 3, 1, 2, 1, 1],
    [3, 1, 1, 1, 1, 0]
]

For selecting element 0, 1 and flood fill with value 3, I'd expect:

[
    [0, 3, 3, 3, 3, 0],
    [0, 0, 3, 2, 3, 3],
    [0, 3, 3, 3, 3, 0]
]

For selecting element 0, 5 and flood fill with value 3, I'd expect:

[
    [0, 1, 1, 1, 1, 3],
    [0, 0, 1, 2, 1, 1],
    [0, 1, 1, 1, 1, 0]
]

This should be a fairly basic operation, no? Which numpy or scipy method am I overlooking?

Body:
Approach #1

Module scikit-image offers the built-in to do the same with skimage.segmentation.flood_fill -

from skimage.morphology import flood_fill

flood_fill(image, (x, y), newval)

Sample runs -

In [17]: a
Out[17]:
array([[0, 1, 1, 1, 1, 0],
       [0, 0, 1, 2, 1, 1],
       [0, 1, 1, 1, 1, 0]])

In [18]: flood_fill(a, (0, 0), 3)
Out[18]:
array([[3, 1, 1, 1, 1, 0],
       [3, 3, 1, 2, 1, 1],
       [3, 1, 1, 1, 1, 0]])

In [19]: flood_fill(a, (0, 1), 3)
Out[19]:
array([[0, 3, 3, 3, 3, 0],
       [0, 0, 3, 2, 3, 3],
       [0, 3, 3, 3, 3, 0]])

In [20]: flood_fill(a, (0, 5), 3)
Out[20]:
array([[0, 1, 1, 1, 1, 3],
       [0, 0, 1, 2, 1, 1],
       [0, 1, 1, 1, 1, 0]])

Approach #2

We can use skimage.measure.label with some array-masking -

from skimage.measure import label

def floodfill_by_xy(a,xy,newval):
    x,y = xy
    l = label(a==a[x,y])
    a[l==l[x,y]] = newval
    return a

To make use of SciPy based label function - scipy.ndimage.measurements.label, it would mostly be the same -

from scipy.ndimage.measurements import label

def floodfill_by_xy_scipy(a,xy,newval):
    x,y = xy
    l = label(a==a[x,y])[0]
    a[l==l[x,y]] = newval
    return a

Note : These would work as in-situ edits.


问:
Work Manager with periodic request called multiple times
I'm using work manager for periodic task. I've to
execute single instance of worker

my code is below

```<code>  val workManager = WorkManager.getInstance()
  val callDataRequest = PeriodicWorkRequest.Builder(MyLoggerWork::class.java,
                15, TimeUnit.MINUTES)
                .addTag(worker)
                .build()
   workManager.enqueueUniquePeriodicWork(worker, ExistingPeriodicWorkPolicy.KEEP, callDataRequest)
</code>```

and my worker logs as follows

```<code>18/09/2018 03:18:19
18/09/2018 03:18:19
18/09/2018 03:18:19
18/09/2018 03:18:19

18/09/2018 03:37:18
18/09/2018 03:37:18
18/09/2018 03:37:18
18/09/2018 03:37:18
</code>```

here is my MyLoggerWork class

```<code>public class MyLoggerWork: Worker(){

override fun doWork(): Result {
    addlog()
    return Worker.Result.SUCCESS
}

private fun addlog() {

    try {

        val directory = File(Environment.getExternalStorageDirectory().path + "/", "Jobs")
        if (!directory.exists()) {
            directory.mkdir()
        }
        val file = File(directory.path, "jobs_.txt")
        if (!file.exists() && directory.exists()) {
            file.createNewFile()
        }
        try {
            val text = SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(Date())
            val stream = FileOutputStream(file, true)
            stream.write("\r\n".toByteArray())
            stream.write(text.toByteArray())
            stream.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }

    } catch (e: IOException) {
        e.printStackTrace()
    }
}
}
</code>```

i am using following dependency

```<code> implementation 'android.arch.work:work-runtime:1.0.0-alpha08'
</code>```

why my work gets called 4 times???

答: You are using a very old version of WorkManager. You should switch to the latest stable version. You can try using 1.0.1 or better yet, switch to 2.0.1 which includes androidx dependencies.

Body:
I'm using work manager for periodic task. I've to
execute single instance of worker

my code is below

  val workManager = WorkManager.getInstance()
  val callDataRequest = PeriodicWorkRequest.Builder(MyLoggerWork::class.java,
                15, TimeUnit.MINUTES)
                .addTag(worker)
                .build()
   workManager.enqueueUniquePeriodicWork(worker, ExistingPeriodicWorkPolicy.KEEP, callDataRequest)

and my worker logs as follows

18/09/2018 03:18:19
18/09/2018 03:18:19
18/09/2018 03:18:19
18/09/2018 03:18:19

18/09/2018 03:37:18
18/09/2018 03:37:18
18/09/2018 03:37:18
18/09/2018 03:37:18

here is my MyLoggerWork class

public class MyLoggerWork: Worker(){

override fun doWork(): Result {
    addlog()
    return Worker.Result.SUCCESS
}

private fun addlog() {

    try {

        val directory = File(Environment.getExternalStorageDirectory().path + "/", "Jobs")
        if (!directory.exists()) {
            directory.mkdir()
        }
        val file = File(directory.path, "jobs_.txt")
        if (!file.exists() && directory.exists()) {
            file.createNewFile()
        }
        try {
            val text = SimpleDateFormat("dd/MM/yyyy hh:mm:ss").format(Date())
            val stream = FileOutputStream(file, true)
            stream.write("\r\n".toByteArray())
            stream.write(text.toByteArray())
            stream.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }

    } catch (e: IOException) {
        e.printStackTrace()
    }
}
}

i am using following dependency

 implementation 'android.arch.work:work-runtime:1.0.0-alpha08'

why my work gets called 4 times???


问:
Python 3.6 Module cannot be found: Folium
I am trying to import folium into a Jupyter notebook I'm working on and I cannot seem to solve the import issues with the Folium library.  Has anyone else solved this problem?

```<code>!pip install folium
import pandas as pd
import folium
</code>```

Output from the above yields:

```<code>`ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-7-a9938c267a0c> in <module>()
      1 get_ipython().system('pip install folium')
      2 import pandas as pd
----> 3 import folium

ModuleNotFoundError: No module named 'folium'`
</code>```

答:
I am using windows 10. I was getting same issue. This is how I fixed it.

Open Command prompt, run as administrator.

type "python" to check if python is installed, if not install python globally.

if python is installed, you will see python prompt, Ctrl+Z to exit and Run :

```<code>python -m pip install folium
</code>```

Body:
I am trying to import folium into a Jupyter notebook I'm working on and I cannot seem to solve the import issues with the Folium library.  Has anyone else solved this problem?

!pip install folium
import pandas as pd
import folium

Output from the above yields:

`ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-7-a9938c267a0c> in <module>()
      1 get_ipython().system('pip install folium')
      2 import pandas as pd
----> 3 import folium

ModuleNotFoundError: No module named 'folium'`

Body:
I am using windows 10. I was getting same issue. This is how I fixed it.

Open Command prompt, run as administrator.

type "python" to check if python is installed, if not install python globally.

if python is installed, you will see python prompt, Ctrl+Z to exit and Run :

python -m pip install folium


问:
Scroll Position GUI with Silverlight
I have a text chat application developed in Silverlight. The app is polling the server every 2 seconds for incoming data and thats when I set my scroll bar's position to the last message.

There is something fishy with the scroll bar's position which I cannot understand. I have hosted the app here, http://bit.ly/h2yopt

Can you please help me work out the scroll position.

PS: Please try entering the message and then move the scroll bar.

Thank you.

答: It looks as if the scrollbar is moved down every 2 seconds. Show us the code.</p>

Title: Scroll Position GUI with Silverlight


问:
Foreign Key issue with migrations
Im using the package https://github.com/musonza/groups to added group system on my laravel app, but when I want to migrate I get the error:

```<code>Migration table created successfully.
Migrating: 2019_05_26_125854_create_groups_tables

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table `groupsystem`.`#sql-2678_26` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `groups` add constraint `groups_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
</code>```

This is my 2 migrations table code:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
</code>```

And also this is the migration table I get from installing the package:
That I mentioned in the link in the top of this post
This is the first time I try to use this package
And im trying tocreate a group system on my laravel application
Any other suggetions will be welcomed

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGroupsTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description')->nullable();
            $table->string('short_description')->nullable();
            $table->string('image')->nullable();
            $table->string('url')->nullable();
            $table->integer('user_id')->unsigned();
            $table->boolean('private')->unsigned()->default(false);
            $table->integer('conversation_id')->unsigned()->nullable();
            $table->text('extra_info')->nullable();
            $table->text('settings')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });

        Schema::create('group_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('group_id')->unsigned();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');
        });

        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->string('type');
            $table->integer('user_id')->unsigned();
            $table->text('extra_info')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });

        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->string('body');
            $table->integer('user_id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->string('type')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users');

            $table->foreign('post_id')
                ->references('id')
                ->on('posts');
        });

        Schema::create('group_post', function (Blueprint $table) {
            $table->integer('group_id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->timestamps();

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');

            $table->foreign('post_id')
                ->references('id')
                ->on('posts')
                ->onDelete('cascade');
        });

        Schema::create('likes', function (Blueprint $table) {
            $table->integer('user_id')->index();
            $table->integer('likeable_id')->unsigned();
            $table->string('likeable_type');
            $table->primary(['user_id', 'likeable_id', 'likeable_type']);
            $table->timestamps();
        });

        Schema::create('reports', function (Blueprint $table) {
            $table->integer('user_id')->index();
            $table->integer('reportable_id')->unsigned();
            $table->string('reportable_type');
            $table->primary(['user_id', 'reportable_id', 'reportable_type']);
            $table->timestamps();
        });

        Schema::create('group_request', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->integer('group_id')->unsigned()->index();
            $table->timestamps();

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('groups');
        Schema::drop('group_user');
        Schema::drop('posts');
        Schema::drop('comments');
        Schema::drop('group_post');
        Schema::drop('likes');
        Schema::drop('reports');
        Schema::drop('group_request');
    }
}
</code>```

答:
If you have used laravel 5.8 then </p>

```<code>$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
</code>```

<p>If you have used laravel  < 5.8 then </p>

```<code>$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
</code>```

Title: Foreign Key issue with migrations

Body:
Im using the package https://github.com/musonza/groups to added group system on my laravel app, but when I want to migrate I get the error:

Migration table created successfully.
Migrating: 2019_05_26_125854_create_groups_tables

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table `groupsystem`.`#sql-2678_26` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `groups` add constraint `groups_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

This is my 2 migrations table code:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

And also this is the migration table I get from installing the package:
That I mentioned in the link in the top of this post
This is the first time I try to use this package
And im trying tocreate a group system on my laravel application
Any other suggetions will be welcomed

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGroupsTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description')->nullable();
            $table->string('short_description')->nullable();
            $table->string('image')->nullable();
            $table->string('url')->nullable();
            $table->integer('user_id')->unsigned();
            $table->boolean('private')->unsigned()->default(false);
            $table->integer('conversation_id')->unsigned()->nullable();
            $table->text('extra_info')->nullable();
            $table->text('settings')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });

        Schema::create('group_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('group_id')->unsigned();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');
        });

        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->string('type');
            $table->integer('user_id')->unsigned();
            $table->text('extra_info')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });

        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->string('body');
            $table->integer('user_id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->string('type')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users');

            $table->foreign('post_id')
                ->references('id')
                ->on('posts');
        });

        Schema::create('group_post', function (Blueprint $table) {
            $table->integer('group_id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->timestamps();

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');

            $table->foreign('post_id')
                ->references('id')
                ->on('posts')
                ->onDelete('cascade');
        });

        Schema::create('likes', function (Blueprint $table) {
            $table->integer('user_id')->index();
            $table->integer('likeable_id')->unsigned();
            $table->string('likeable_type');
            $table->primary(['user_id', 'likeable_id', 'likeable_type']);
            $table->timestamps();
        });

        Schema::create('reports', function (Blueprint $table) {
            $table->integer('user_id')->index();
            $table->integer('reportable_id')->unsigned();
            $table->string('reportable_type');
            $table->primary(['user_id', 'reportable_id', 'reportable_type']);
            $table->timestamps();
        });

        Schema::create('group_request', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->integer('group_id')->unsigned()->index();
            $table->timestamps();

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('groups');
        Schema::drop('group_user');
        Schema::drop('posts');
        Schema::drop('comments');
        Schema::drop('group_post');
        Schema::drop('likes');
        Schema::drop('reports');
        Schema::drop('group_request');
    }
}

Body:
If you have used laravel 5.8 then

$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');

If you have used laravel  < 5.8 then

$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');


问:
Instagram API: The access_token provided is invalid
I have registred a sandbox user. Now I am trying to use it, but I recieve "The access_token provided is invalid".
Sample request:

https://api.instagram.com/v1/users/searchq=abc&count=2&client_id=7b67cff1a7ab462881298434c08b5ab8

It was working in live mode, but I can't find why it isn't working in sandbox.

答:
I found it when solving the same problem with access by access_token

Here is official faq how to get access_token

You just should go through following steps (link to Instagram API documentation https://www.instagram.com/developer/authentication/):

1.Request the CODE

```<code>https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
</code>```

change CLIENT_ID to you client id (you could get it here https://www.instagram.com/developer/clients/manage/ )

change REDIRECT-URI to your redirect_uri from tab security in client settings(open link above and tap to 'manage' button). I Used this one https://meyerweb.com/eric/tools/dencoder/ Encode url here and paste te result instead REDIRECT-URI

After you prepared it cope ready link to adress bar in your browser and run

2. Get the CODE

Browser ask you a premissons and redirect you to callback url with the code in the end. It will be look like this in adress bar:

```<code>http://yoursite.some/?code=d8af5619af6853d4ad11b4dd5f1ef17e
</code>```

In this example your code is d8af5619af6853d4ad11b4dd5f1ef17e
Save it. You should use it in access_token request below

3. Make an access_token request

Open terminal and use curl:

```<code>curl -F 'client_id=CLIENT_ID' \
-F 'client_secret=CLIENT_SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=AUTHORIZATION_REDIRECT_URI' \
-F 'code=CODE' \
https://api.instagram.com/oauth/access_token
</code>```

Change CLIENT_ID, CLIENT_SECRET, AUTHORIZATION_REDIRECT_URI and CODE to your own data and run it.

Curl return you JSON with access_token like this:

```<code>{
    "access_token": "fb2e77d.47a0473320504cb3ab4a1f626d174d2d",
    "user": {
        "id": "1576583",
        "username": "some",
        "full_name": "Some",
        "profile_picture": "..."
    }
}
</code>```

Well done! In this example fb2e77d.47a0473320504cb3ab4a1f626d174d2d is your access_token. Copy access_token value, use it in your app and enjoy you coding! :)

Body:
I found it when solving the same problem with access by access_token

Here is official faq how to get access_token

You just should go through following steps (link to Instagram API documentation https://www.instagram.com/developer/authentication/):

1.Request the CODE

https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code

change CLIENT_ID to you client id (you could get it here https://www.instagram.com/developer/clients/manage/ )

change REDIRECT-URI to your redirect_uri from tab security in client settings(open link above and tap to 'manage' button). I Used this one https://meyerweb.com/eric/tools/dencoder/ Encode url here and paste te result instead REDIRECT-URI

After you prepared it cope ready link to adress bar in your browser and run

2. Get the CODE

Browser ask you a premissons and redirect you to callback url with the code in the end. It will be look like this in adress bar:

http://yoursite.some/?code=d8af5619af6853d4ad11b4dd5f1ef17e

In this example your code is d8af5619af6853d4ad11b4dd5f1ef17e
Save it. You should use it in access_token request below

3. Make an access_token request

Open terminal and use curl:

curl -F 'client_id=CLIENT_ID' \
-F 'client_secret=CLIENT_SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=AUTHORIZATION_REDIRECT_URI' \
-F 'code=CODE' \
https://api.instagram.com/oauth/access_token

Change CLIENT_ID, CLIENT_SECRET, AUTHORIZATION_REDIRECT_URI and CODE to your own data and run it.

Curl return you JSON with access_token like this:

{
    "access_token": "fb2e77d.47a0473320504cb3ab4a1f626d174d2d",
    "user": {
        "id": "1576583",
        "username": "some",
        "full_name": "Some",
        "profile_picture": "..."
    }
}

Well done! In this example fb2e77d.47a0473320504cb3ab4a1f626d174d2d is your access_token. Copy access_token value, use it in your app and enjoy you coding! :)


问:
Typescript type guard with optional wrapped type
I couldn't find another question that asked this. I am trying to create a type guard that will determine the type of a specific variable. With a singular type it's simple.

```<code>type A = { id: number, title: string, type: string };
type B = { id: number, title: string, type: string };
type ABUnion = A | B;

const isA = (value: ABUnion): value is A => value.type === 'A';
</code>```

However I have a few scenarios where I have these types wrapped in another type and I want to maintain the wrapped type, but assert that the contained type is what I want it to be.

```<code>type A = { id: number, title: string, type: string };
type B = { id: number, title: string, type: string };
type ABUnion = A | B | Readonly<A> | Readonly<B>;

const isA = (value: ABUnion): value is A => value.type === 'A';
</code>```

In this scenario I will always get back a typeof A even when I pass a Readonly into the guard. I fully expect this to happen.

How can I refactor isA to return either A or Readonly (or another wrapped type)?

答:
I'm fairly certain I found my own answer pretty quickly after posting this.</p>

```<code>const isA = <T>(value: T): value is T => value.type === 'A';
</code>```

Body:
I couldn't find another question that asked this. I am trying to create a type guard that will determine the type of a specific variable. With a singular type it's simple.

type A = { id: number, title: string, type: string };
type B = { id: number, title: string, type: string };
type ABUnion = A | B;

const isA = (value: ABUnion): value is A => value.type === 'A';

However I have a few scenarios where I have these types wrapped in another type and I want to maintain the wrapped type, but assert that the contained type is what I want it to be.

type A = { id: number, title: string, type: string };
type B = { id: number, title: string, type: string };
type ABUnion = A | B | Readonly | Readonly;

const isA = (value: ABUnion): value is A => value.type === 'A';

In this scenario I will always get back a typeof A even when I pass a Readonly into the guard. I fully expect this to happen.

How can I refactor isA to return either A or Readonly (or another wrapped type)?

Body:
I'm fairly certain I found my own answer pretty quickly after posting this.

const isA = <T>(value: T): value is T => value.type === 'A';


问:
How to access views defined with a specific [plone.]browserlayer in test cases
I'm new to testing and I'm trying to create a test for my Plone product for the first time.
I'm on Plone 3.3.

The basic test suite works, I can execute it without errors.
I followed this documentation : http://plone.org/documentation/kb/testing
...except that I'm writing my tests in Python classes instead of doctests.

My problem is that I cannot seem to access the views defined in my app (I get ComponentLookupError).

The problem seems to be with the "browserlayer" defined by my applications.
When I remove the layer="..." attribute from my configure.zcml, the test can access the views without problem. However, if I add it back, it doesn't work.
I guess that's because de browserlayer interface doesn't get applied to the request.

The only reference to this problem I found is in the tests for googlesitemap : http://dev.plone.org/collective/browser/googlesitemap/googlesitemap.common/trunk/googlesitemap/common/tests?rev=

The author seems to have made a custom ZCML file for the test, in which the layer="..." attribute has been removed. (which would work but it seems very bad having to maintain a separate zcml file for the tests)

In my test, I have included the following (taken from the googlesitemap tests), which passes :

```<code>from jambette.site.interfaces import IJambetteLayer # this is my browserlayer
from plone.browserlayer.utils import registered_layers
self.assertTrue(IJambetteLayer in registered_layers())
</code>```

So I think my skin and browserlayer are registered correctly.

Is there anything I need to do so that the browserlayer will be applied to the request?

答:
Browser layer interfaces are simply 'painted' onto the request with directlyProvides. Simply do so in your test setup before you look up the view:

```<code>from zope import interface
from jambette.site.interfaces import IJambetteLayer

...

    directlyProvides(request, IJambetteLayer)
</code>```

Body:
I'm new to testing and I'm trying to create a test for my Plone product for the first time.
I'm on Plone 3.3.

The basic test suite works, I can execute it without errors.
I followed this documentation : http://plone.org/documentation/kb/testing
...except that I'm writing my tests in Python classes instead of doctests.

My problem is that I cannot seem to access the views defined in my app (I get ComponentLookupError).

The problem seems to be with the "browserlayer" defined by my applications.
When I remove the layer="..." attribute from my configure.zcml, the test can access the views without problem. However, if I add it back, it doesn't work.
I guess that's because de browserlayer interface doesn't get applied to the request.

The only reference to this problem I found is in the tests for googlesitemap : http://dev.plone.org/collective/browser/googlesitemap/googlesitemap.common/trunk/googlesitemap/common/tests?rev=

The author seems to have made a custom ZCML file for the test, in which the layer="..." attribute has been removed. (which would work but it seems very bad having to maintain a separate zcml file for the tests)

In my test, I have included the following (taken from the googlesitemap tests), which passes :

from jambette.site.interfaces import IJambetteLayer # this is my browserlayer
from plone.browserlayer.utils import registered_layers
self.assertTrue(IJambetteLayer in registered_layers())

So I think my skin and browserlayer are registered correctly.

Is there anything I need to do so that the browserlayer will be applied to the request?

Body:
Browser layer interfaces are simply 'painted' onto the request with directlyProvides. Simply do so in your test setup before you look up the view:

from zope import interface
from jambette.site.interfaces import IJambetteLayer

...

    directlyProvides(request, IJambetteLayer)


问:
Confusing CSS - can anyone explain
I understand the dot in css is class but what is h2 dot h1 supposed to be selecting in the following I have found in a page?

```<code>h1 {
  font-size: 30px;
  line-height: 32px;
}
h2.h1 {
  font-size: 36px;
  line-height: 40px;
}
.title.title_size_medium h1 {
  font-size: 38px;
  line-height: 38px;
}
</code>```

The h1 tag itself is never used in the page.

Many Thanks

答:
h2.h1 is selecting an h2 element with the class h1:

h1 {
  font-size: 30px;
  line-height: 32px;
  color: red;
}

h2.h1 {
  font-size: 36px;
  line-height: 40px;
  color: blue;
}

.title.title_size_medium h1 {
  font-size: 38px;
  line-height: 38px;
  color: grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Just an h1 element</h1>
<h2 class="h1">h2 element with the class "h1"</h2>

<div class="title title_size_medium">
  <h1>An h1 element inside a div with the class "title" and "title_size_medium"</h1>
</div></code>```

Title: Confusing CSS - can anyone explain

Body:
I understand the dot in css is class but what is h2 dot h1 supposed to be selecting in the following I have found in a page?

h1 {
  font-size: 30px;
  line-height: 32px;
}
h2.h1 {
  font-size: 36px;
  line-height: 40px;
}
.title.title_size_medium h1 {
  font-size: 38px;
  line-height: 38px;
}

The h1 tag itself is never used in the page.

Many Thanks

Body:
h2.h1 is selecting an h2 element with the class h1:

h1 {
  font-size: 30px;
  line-height: 32px;
  color: red;
}

h2.h1 {
  font-size: 36px;
  line-height: 40px;
  color: blue;
}

.title.title_size_medium h1 {
  font-size: 38px;
  line-height: 38px;
  color: grey;
}

<h1>Just an h1 element</h1>
<h2 class="h1">h2 element with the class "h1"</h2>

<div class="title title_size_medium">
  <h1>An h1 element inside a div with the class "title" and "title_size_medium"</h1>
</div>


问:
jQuery multiple filters by class
I am building an filter option with multiple filters option. I want to filter on classes but I can’t get it working. I manage to create multiple filters. These filters can also be combined. But if you then adjust/change one of these filters the results do not want to update.

First change filter 1

Than change filter 2 (location)

If you now change filter 1 again (with filter 2 not changed) it don’t update the results.

$('select').change(function() {
  var current = this.value;
  $.each($('#FilterContainer').find('div.all').not('.hidden').not('.' + current), function() {
    $(this).addClass('hidden');
  });
  $.each($('#FilterContainer').find('div.all').is('.' + current), function() {
    $(this).removeClass('hidden');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden { display: none; }</code>```

Filter:

<select class="filterby">
  <option value="all">
Show All
</option>
  <option value="1">
One
</option>
  <option value="2">
Two
</option>
  <option value="3">
Three
</option>
</select>

Location:

<select class="filterby">
  <option value="all">
All Locations
</option>
  <option value="nj">
NJ
</option>
  <option value="ny">
NY
</option>
  <option value="pa">
PA
</option>
</select>

Test One NJ

Test One NY

Test One PA

Test Two NJ

Test Two NY

Test Two PA

Test Three NJ

Test Three NY

Test Three PA

```

(or on jsfiddle)

答:
You might want to reset all the elements on each user interaction by removing .hidden class. At the top of your .change() function, try this:

```<code>.removeClass('hidden');
</code>```

Once you remove .hidden from all the elements, you can add the class to the elements that need it.

In the JSFiddle example, you can write this this way:

```<code>$('select').change(function () {
    var current = this.value;
    $.each($('#FilterContainer').find('div.all'), function () {
        $(this).removeClass('hidden');
    });

    $.each($('#FilterContainer').find('div.all').not('.' + current), function () {
        $(this).addClass('hidden');
    });
});
</code>```

Title: jQuery multiple filters by class

Body:
I am building an filter option with multiple filters option. I want to filter on classes but I can’t get it working. I manage to create multiple filters. These filters can also be combined. But if you then adjust/change one of these filters the results do not want to update.

First change filter 1

Than change filter 2 (location)

If you now change filter 1 again (with filter 2 not changed) it don’t update the results.

$('select').change(function() {
  var current = this.value;
  $.each($('#FilterContainer').find('div.all').not('.hidden').not('.' + current), function() {
    $(this).addClass('hidden');
  });
  $.each($('#FilterContainer').find('div.all').is('.' + current), function() {
    $(this).removeClass('hidden');
  });
});

.hidden { display: none; }

Filter:

<select class="filterby">
  <option value="all">
Show All
</option>
  <option value="1">
One
</option>
  <option value="2">
Two
</option>
  <option value="3">
Three
</option>
</select>

Location:

<select class="filterby">
  <option value="all">
All Locations
</option>
  <option value="nj">
NJ
</option>
  <option value="ny">
NY
</option>
  <option value="pa">
PA
</option>
</select>

Test One NJ

Test One NY

Test One PA

Test Two NJ

Test Two NY

Test Two PA

Test Three NJ

Test Three NY

Test Three PA

(or on jsfiddle)

Body:
You might want to reset all the elements on each user interaction by removing .hidden class. At the top of your .change() function, try this:

.removeClass('hidden');

Once you remove .hidden from all the elements, you can add the class to the elements that need it.

In the JSFiddle example, you can write this this way:

$('select').change(function () {
    var current = this.value;
    $.each($('#FilterContainer').find('div.all'), function () {
        $(this).removeClass('hidden');
    });

    $.each($('#FilterContainer').find('div.all').not('.' + current), function () {
        $(this).addClass('hidden');
    });
});


问:
Pattern matching problem with Prolog
EDIT: See my answer below for why I am a fool. There is still a riddle in this that I would love to have answered though.

I've been stuck on this for far too long. I'm trying to print out a sudoku solution in a nice looking grid.

I think I'm running into problems because I don't understand some key part of how pattern matching works in Prolog.

Without further ado, my code:

```<code>prettier_print([]).
prettier_print([Puzzle]) :- prettier_print(0, [Puzzle]).

prettier_print(0, Puzzle) :-
    writeln('┌───────┬───────┬───────┐'),
    prettier_print(1, Puzzle).
prettier_print(4, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(5, Puzzle).
prettier_print(8, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(9, Puzzle).
prettier_print(12, []) :-
    writeln('└───────┴───────┴───────┘').

prettier_print(N, [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | Puzzle]) :-
    member(N, [1,2,3,5,6,7,9,10,11]),  % tried this when the line below did not work
    % N =\= 0, N =\= 4, N =\= 8, N =\= 13,

    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]),
    succ(N, N1),
    prettier_print(N1, Puzzle).
</code>```

Here is the call:

```<code>prettier_print(0, [1,2,3,4,5,6,7,8,9,
                   2,2,3,4,5,6,7,8,9,
                   3,2,3,4,5,6,7,8,9,
                   4,2,3,4,5,6,7,8,9,
                   5,2,3,4,5,6,7,8,9,
                   6,2,3,4,5,6,7,8,9,
                   7,2,3,4,5,6,7,8,9,
                   8,2,3,4,5,6,7,8,9,
                   9,2,3,4,5,6,7,8,9]).
</code>```

And here is the output:

```<code>┌───────┬───────┬───────┐
│ 1 2 3 │ 4 5 6 │ 7 8 9 │
│ 2 2 3 │ 4 5 6 │ 7 8 9 │
│ 3 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 4 2 3 │ 4 5 6 │ 7 8 9 │
│ 5 2 3 │ 4 5 6 │ 7 8 9 │
│ 6 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 7 2 3 │ 4 5 6 │ 7 8 9 │
│ 8 2 3 │ 4 5 6 │ 7 8 9 │
│ 9 2 3 │ 4 5 6 │ 7 8 9 │
└───────┴───────┴───────┘
true ;
false.
</code>```

The problem is it doesn't JUST return with true, I have to press ;, and then it returns false. This in turn means that my prettier_print/1 rule doesn't work properly.

I think I know enough to figure out that this means:

Prolog is backtracking and trying another interpretation of my rules (seeing if there is anything else it can unify with, if I'm understanding my terms correctly). This finds one other thing to unify with that, but that fails immediately. Is that right?

I want there to be only one possible interpretation. How can I fix my function to mean that?

Thank you for any help, this has me feeling like such a fool!

答:
Augh, nevermind, I'm an idiot!

I had pinpointed something that wasn't a  problem in the first place. Changing prettier_print/1 to this:

```<code>prettier_print([]).
prettier_print(Puzzle) :- prettier_print(0, Puzzle).
</code>```

Makes it work fine.

I would still like to understand why it was returning true and then false though. If someone can answer that I'll mark their answer accepted.

Title: Pattern matching problem with Prolog

Body:
EDIT: See my answer below for why I am a fool. There is still a riddle in this that I would love to have answered though.

I've been stuck on this for far too long. I'm trying to print out a sudoku solution in a nice looking grid.

I think I'm running into problems because I don't understand some key part of how pattern matching works in Prolog.

Without further ado, my code:

prettier_print([]).
prettier_print([Puzzle]) :- prettier_print(0, [Puzzle]).

prettier_print(0, Puzzle) :-
    writeln('┌───────┬───────┬───────┐'),
    prettier_print(1, Puzzle).
prettier_print(4, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(5, Puzzle).
prettier_print(8, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(9, Puzzle).
prettier_print(12, []) :-
    writeln('└───────┴───────┴───────┘').

prettier_print(N, [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | Puzzle]) :-
    member(N, [1,2,3,5,6,7,9,10,11]),  % tried this when the line below did not work
    % N =\= 0, N =\= 4, N =\= 8, N =\= 13,

    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]),
    succ(N, N1),
    prettier_print(N1, Puzzle).

Here is the call:

prettier_print(0, [1,2,3,4,5,6,7,8,9,
                   2,2,3,4,5,6,7,8,9,
                   3,2,3,4,5,6,7,8,9,
                   4,2,3,4,5,6,7,8,9,
                   5,2,3,4,5,6,7,8,9,
                   6,2,3,4,5,6,7,8,9,
                   7,2,3,4,5,6,7,8,9,
                   8,2,3,4,5,6,7,8,9,
                   9,2,3,4,5,6,7,8,9]).

And here is the output:

┌───────┬───────┬───────┐
│ 1 2 3 │ 4 5 6 │ 7 8 9 │
│ 2 2 3 │ 4 5 6 │ 7 8 9 │
│ 3 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 4 2 3 │ 4 5 6 │ 7 8 9 │
│ 5 2 3 │ 4 5 6 │ 7 8 9 │
│ 6 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 7 2 3 │ 4 5 6 │ 7 8 9 │
│ 8 2 3 │ 4 5 6 │ 7 8 9 │
│ 9 2 3 │ 4 5 6 │ 7 8 9 │
└───────┴───────┴───────┘
true ;
false.

The problem is it doesn't JUST return with true, I have to press ;, and then it returns false. This in turn means that my prettier_print/1 rule doesn't work properly.

I think I know enough to figure out that this means:

Prolog is backtracking and trying another interpretation of my rules (seeing if there is anything else it can unify with, if I'm understanding my terms correctly). This finds one other thing to unify with that, but that fails immediately. Is that right?

I want there to be only one possible interpretation. How can I fix my function to mean that?

Thank you for any help, this has me feeling like such a fool!

Body:
Augh, nevermind, I'm an idiot!

I had pinpointed something that wasn't a  problem in the first place. Changing prettier_print/1 to this:

prettier_print([]).
prettier_print(Puzzle) :- prettier_print(0, Puzzle).

Makes it work fine.

I would still like to understand why it was returning true and then false though. If someone can answer that I'll mark their answer accepted.


问:
How to implement PeriodicWorkRequest chain?
I study Android WorkManager, and fond one problem.

I have 2 Works, first of them fetch some data from server and second preload resources (depends on result of first work). I need doing this chains one time per hour.

I need something like:

```<code>workManager.beginWith(work1).then(work2)
</code>```

But in WorkManger API I found chain only for OneTimeWorkRequest.

答:
You cannot chain PeriodicWorkRequests. For your use-case you might consider using a OneTimeWorkRequest with a Worker that enqueues a copy of itself at the end of doWork() with an initial delay (to simulate periodicity).

That way you can still do chaining. I would tag all work requests consistently so you can getWorkInfosByTagLiveData() correctly.

Body:
I study Android WorkManager, and fond one problem.

I have 2 Works, first of them fetch some data from server and second preload resources (depends on result of first work). I need doing this chains one time per hour.

I need something like:

workManager.beginWith(work1).then(work2)

But in WorkManger API I found chain only for OneTimeWorkRequest.


答:
h2.h1 selects the
 tags in your html, and the .h1 css class styles the h2 tag with the styles from the h2 css class.

Title: Confusing CSS - can anyone explain

Body: h2.h1 selects the <h2> tags in your html, and the .h1 css class styles the h2 tag with the styles from the h2 css class.


问:
Create a flag URL column based on country name
I have a pandas column with country names as the column.

I need the PNG url for the flags of the country as a separate column. A URL for the US will be like the following,

```<code>https://upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/1280px-Flag_of_the_United_States.svg.png
</code>```

How can I achieve the same.

here is my dataframe with the country names.

```<code>0                           Afghanistan
1                               Albania
2                               Algeria
3                               Andorra
4                                Angola
5                   Antigua and Barbuda
6                             Argentina
7                               Armenia
8                             Australia
9                               Austria
10                      Austria-Hungary
11                           Azerbaijan
12                              Bahamas
13                              Bahrain
14                           Bangladesh
15                             Barbados
16                              Belarus
17                              Belgium
18                               Belize
19                                Benin
20                               Bhutan

.......
.......
Name: Entity, dtype: object

</code>```

答:
So looking at Wikipedia for flag links, it doesn't look like there is a unified format for their urls, so you won't be able to just iterate over your Country list to create the column.

Your best bet would be to simply scrape Wikipedia and iterate your country list into the base File:Flag page.  Something like this:

```<code>import requests
from bs4 import BeautifulSoup

for item in df['Country']:
    url = 'https://en.wikipedia.org/wiki/File:Flag_of_'+str(item)+'.svg'
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'lxml')
    df['Flag_Link'] = soup.find('span', {'class':'mw-filepage-other-resolutions'}).findAll('a')[3]['href']
</code>```

I assumed you wanted the 1280X853 links, which is the [3] span. Let me know if you have any questions.

Body:
I have a pandas column with country names as the column.

I need the PNG url for the flags of the country as a separate column. A URL for the US will be like the following,

https://upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/1280px-Flag_of_the_United_States.svg.png

How can I achieve the same.

here is my dataframe with the country names.

0                           Afghanistan
1                               Albania
2                               Algeria
3                               Andorra
4                                Angola
5                   Antigua and Barbuda
6                             Argentina
7                               Armenia
8                             Australia
9                               Austria
10                      Austria-Hungary
11                           Azerbaijan
12                              Bahamas
13                              Bahrain
14                           Bangladesh
15                             Barbados
16                              Belarus
17                              Belgium
18                               Belize
19                                Benin
20                               Bhutan

.......
.......
Name: Entity, dtype: object

Body:
So looking at Wikipedia for flag links, it doesn't look like there is a unified format for their urls, so you won't be able to just iterate over your Country list to create the column.

Your best bet would be to simply scrape Wikipedia and iterate your country list into the base File:Flag page.  Something like this:

import requests
from bs4 import BeautifulSoup

for item in df['Country']:
    url = 'https://en.wikipedia.org/wiki/File:Flag_of_'+str(item)+'.svg'
    r = requests.get(url)
    soup = BeautifulSoup(r.text, 'lxml')
    df['Flag_Link'] = soup.find('span', {'class':'mw-filepage-other-resolutions'}).findAll('a')[3]['href']

I assumed you wanted the 1280X853 links, which is the [3] span. Let me know if you have any questions.


问:
Go to the next page
I have a problem regarding displaying the next page on a Website.
I use jQuery and want to Display the next Page if the Enter key is pressed?
How can I accomplish that.
The code below shows already what I have written.
Is there any method that will do fine?</p>

```<code><script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<script>

    $(document).on("keypress", "input", function(e){

        if(e.which == 13){

        }

    });

</script>
</code>```

答:
you can use window.location for redirect to another page: </p>

```<code>window.location = "http://www.google.com" // set your next page url instead of www.google.com
</code>```

Title: Go to the next page

Body:
you can use window.location for redirect to another page:

window.location = "http://www.google.com" // set your next page url instead of www.google.com


问:
Optimal block size in java streams
I have a theoretical question. Let's imagine you have an InputStream and an OutputStream. You nead to copy content from one to the other and you don't know exactly the size of the content you need to transfer. What is the best choice in general of the block size in the write method?

答:
The default buffer size for BufferedInputStream and BufferedOutputStream is 8 KB and this is typically a good size.

Note: if you are reading a Socket fast enough, you will rarely get more one packet, ~1.5 KB. If you are reading from disk, you typically get whatever size you ask for, however the performance doesn't improve much from 32 KB to 256 KB and is likely to be dependant on the hardware you use.

However I have also found, unless you are benchmarking you rarely see a noticeable difference if you use only 512 bytes as a buffer size (which Inflator/Deflator streams do) i.e. the difference might be 15% or less.

In summary, you are unlikely to notice a difference with buffer sizes between 512 bytes and 32 KB. The latter is likely to be more than enough for most situations.  I tend to use 256 KB as I have a lot of memory and few pre-allocated buffers.

Title: Optimal block size in java streams


问:
Deny creation of new resources via Service Control Policy
Is it possible to create such a SCP (Service Control Policy) and attach it to account which denies any new resources (infrastructure) launching within this account? Assuming that the account is part of AWS Organizations.

The question arises from the following confusions:

can SCP restrict specific actions like launching infrastructure?

can SCP be applied on the account level (not to the organizational one!)?

答:
Yes, it is possible to do.

SCP can contain explicit deny rules, for example deny creation of any EC2-related instances and resources:

```<code>    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Deny",
            "Action": [
                "ec2:Create*"
            ],
            "Resource": "*"
        }
    ]
}
</code>```

Any SCP can be attached to:

Accounts

Organizational units

Root account

Body:
Yes, it is possible to do.

SCP can contain explicit deny rules, for example deny creation of any EC2-related instances and resources:

    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Deny",
            "Action": [
                "ec2:Create*"
            ],
            "Resource": "*"
        }
    ]
}

Any SCP can be attached to:

Accounts

Organizational units

Root account


问:
How to fix this error while using statsmodels" ImportError: cannot import name 'factorial'"?
I have already gone through this answer
While importing auto_arima from pmdarima: ERROR : cannot import name 'factorial' from 'scipy.misc'
but couldn't fix the error,I do not understand how to use developer version.
Is there any other method for applying Seasonal ARIMA model?

import statsmodels.api as sm
mod = sm.tsa.statespace.SARIMAX(train_weekly.Price,
                                order=(1, 0, 0),
                                seasonal_order=(1, 1, 0, 12),
                                enforce_stationarity=False,
                                enforce_invertibility=False)

results = mod.fit()
print(results.summary().tables[0])
print(results.summary().tables[1])
```

<p>Following is the output</p>

<pre class="lang-py prettyprint-override"><code>ImportError                               Traceback (most recent call last)
<ipython-input-30-a5d9120bdc57> in <module>()
----> 1 import statsmodels.api as sm
      2 mod = sm.tsa.statespace.SARIMAX(train_weekly.Price,
      3                                 order=(1, 0, 0),
      4                                 seasonal_order=(1, 1, 0, 12),
      5                                 enforce_stationarity=False,

3 frames
/usr/local/lib/python3.6/dist-packages/statsmodels/api.py in <module>()
     14 from . import robust
     15 from .robust.robust_linear_model import RLM
---> 16 from .discrete.discrete_model import (Poisson, Logit, Probit,
     17                                       MNLogit, NegativeBinomial,
     18                                       GeneralizedPoisson,

/usr/local/lib/python3.6/dist-packages/statsmodels/discrete/discrete_model.py in <module>()
     43
     44 from statsmodels.base.l1_slsqp import fit_l1_slsqp
---> 45 from statsmodels.distributions import genpoisson_p
     46
     47 try:

/usr/local/lib/python3.6/dist-packages/statsmodels/distributions/__init__.py in <module>()
      1 from .empirical_distribution import ECDF, monotone_fn_inverter, StepFunction
----> 2 from .edgeworth import ExpandedNormal
      3 from .discrete import genpoisson_p, zipoisson, zigenpoisson, zinegbin

/usr/local/lib/python3.6/dist-packages/statsmodels/distributions/edgeworth.py in <module>()
      5 import numpy as np
      6 from numpy.polynomial.hermite_e import HermiteE
----> 7 from scipy.misc import factorial
      8 from scipy.stats import rv_continuous
      9 import scipy.special as special

ImportError: cannot import name 'factorial'
</code>```

I just want to use seasonal ARIMA,if there is any other way please help me.
Thanks.

答:
Seems like there is a version mismatch of scipy module. Try downgrading scipy module.

In windows execute the following command in Administrative mode,

```<code>pip3 install --user scipy==1.2.0
</code>```

If you're using Linux,

```<code>python3.6 -m pip install scipy==1.2 --upgrade
</code>```

Body:
I have already gone through this answer
While importing auto_arima from pmdarima: ERROR : cannot import name 'factorial' from 'scipy.misc'
but couldn't fix the error,I do not understand how to use developer version.
Is there any other method for applying Seasonal ARIMA model?

import statsmodels.api as sm
mod = sm.tsa.statespace.SARIMAX(train_weekly.Price,
                                order=(1, 0, 0),
                                seasonal_order=(1, 1, 0, 12),
                                enforce_stationarity=False,
                                enforce_invertibility=False)

results = mod.fit()
print(results.summary().tables[0])
print(results.summary().tables[1])

Following is the output

ImportError                               Traceback (most recent call last)
<ipython-input-30-a5d9120bdc57> in <module>()
----> 1 import statsmodels.api as sm
      2 mod = sm.tsa.statespace.SARIMAX(train_weekly.Price,
      3                                 order=(1, 0, 0),
      4                                 seasonal_order=(1, 1, 0, 12),
      5                                 enforce_stationarity=False,

3 frames
/usr/local/lib/python3.6/dist-packages/statsmodels/api.py in <module>()
     14 from . import robust
     15 from .robust.robust_linear_model import RLM
---> 16 from .discrete.discrete_model import (Poisson, Logit, Probit,
     17                                       MNLogit, NegativeBinomial,
     18                                       GeneralizedPoisson,

/usr/local/lib/python3.6/dist-packages/statsmodels/discrete/discrete_model.py in <module>()
     43
     44 from statsmodels.base.l1_slsqp import fit_l1_slsqp
---> 45 from statsmodels.distributions import genpoisson_p
     46
     47 try:

/usr/local/lib/python3.6/dist-packages/statsmodels/distributions/__init__.py in <module>()
      1 from .empirical_distribution import ECDF, monotone_fn_inverter, StepFunction
----> 2 from .edgeworth import ExpandedNormal
      3 from .discrete import genpoisson_p, zipoisson, zigenpoisson, zinegbin

/usr/local/lib/python3.6/dist-packages/statsmodels/distributions/edgeworth.py in <module>()
      5 import numpy as np
      6 from numpy.polynomial.hermite_e import HermiteE
----> 7 from scipy.misc import factorial
      8 from scipy.stats import rv_continuous
      9 import scipy.special as special

ImportError: cannot import name 'factorial'

I just want to use seasonal ARIMA,if there is any other way please help me.
Thanks.

Body:
Seems like there is a version mismatch of scipy module. Try downgrading scipy module.

In windows execute the following command in Administrative mode,

pip3 install --user scipy==1.2.0

If you're using Linux,

python3.6 -m pip install scipy==1.2 --upgrade