问:
Google Agera vs rxAndroid
When I first step into reactive programming in Android I found rxJava and rxAndroid which prefer by many developers in the world. But today I found another library called Agera of Google which still in maintain process (last commit is 2 months ago).

It looks like rxJava at first glance, but has more meaningful api names which help me easy to understand reactive programming. More important, awesome developers at Google is using it in their project (Google Play Movies) and I believe there is reason for that.

I want to know whether Google Agera supposed to be more light-weight? And how about the performance compare to rxJava and rxAndroid? Is there any big company use it in production? Did I need to learn it to understand reactive programming in Android?

答:
A nice comparison from David Karnok (RxJava maintainer) can be found in the issues on Github.

I've glanced over the documentation and my impression is that Agera is almost a 1st generation reactive library with strong 0th generation ties. To put it in perspective:

0th generation is when you have addListener/removeListener and update() with or without an actual value. java.util.Observable and most GUI frameworks can be considered 0th gen. It is possible, although generally cumbersome to make a composable, native library out of them.

1st generation is what the Microsoft folks invented back in ~2009. It's a step upwards with straightforward architecture and great composability. However, their concept has some shortcomings discovered in late ~2013. Example: Rx.NET, Reactive4Java

2nd generation is what RxJava 1.x currently is. It fixes the synchronous cancellation problem, introduced some optional backpressure and the notion of lifting into a chain.

3rd generation is the Reactive-Streams initiative with fleshed out, standardized APIs, designed ~2015. The architecture is reactive-push with backpressure. Examples are Reactor 1, 2 and Akka-Streams.

4th generation is the cutting edge of the field. It builds on Reactive-Streams and adds an adaptive push-pull option, in the form of operator-fusion, that allows both efficient synchronous and asynchronous use. Example is Reactor 2.5. (RxJava 2.x is in between 3 and 4 right now).

I know this is an optional library, don't use it if you don't like it. Don't get me wrong, it's not about how many operators you have, how strong do you inline your reactive library with the underlying platform or that you don't care about backpressure in GUI. It's about the architectural experiences, pitfalls and possibilities of the Rx family that maybe could have helped/inspired this library. If Agera were based on Reactive-Streams or designed in spirit of it, I'd say okay, why not.

As for the original questions:

Isn't it RxJava reinvented?

No.

Is it supposed to be more light-weight?

Seems so API-vise, not sure about performance-vise

Complementary?

As complementary as addListener-based APIs are in general. The name conflict of Observable and Supplier may be of some inconvenience.

Or just inspired?

Apparently not inspired by Rx.

Google Play Movies and we like to open source code whenever possible

In Netflix' footsteps I see. You see, they got significant help along the way...

Title: Google Agera vs rxAndroid


来源: stackexchange

问:
Setting up GUI with Tkinter for Image and Text inputs
Im using python 2.7 to build a satellite tracker for a cubesat project at my university. Now I've got the whole thing running as I want it to. I produce 4 images and a load of text based on the ISS's orbit parameters as our cubesat is not yet flying.

The 4 pictures are:

1) Satellite's current position on a globe based on its TLE straight from celestrak.

2) Satellite's current position on a mercator(flat) map.

3) Its current lat/lon position translated to a google earth view to physically interpret where it is.

4) Its current lat/lon position based on current weather maps, for whether or not there are clouds in the region, obscuring the satellites remote sensing imaging capabilities. (Reason why the picture looks ugly and purple, is because this region had no current weather data at the time of retrieving data)

Then I need to implement a text box with information on altitude, velocity, spatial resolution etc.

It's all nice and dandy. But I cant for the love of god figure out how to get this Tkinter GUI to play nice! I'm a geoscientist, not a computer scientist and python programming is very new to me :D

Anyway I did a quick layout in photoshop as of how I want the finished data to be produced in a Tkinter GUI. See the primitive image below:

Now here is my shameful code below:

```<code>import Tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Satellite Control Center")
window.geometry("1000x800")
window.configure(background='grey')

#Imports the pictures.
pic1 = "Globeview.png"
pic2 = "MercatorView.png"
pic3 = "currentweathercroppedsmall.png"
pic4 = "GECurrentcroppedsmall.png"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img1 = ImageTk.PhotoImage(Image.open(pic1))
img2 = ImageTk.PhotoImage(Image.open(pic2))
img3 = ImageTk.PhotoImage(Image.open(pic3))
img4 = ImageTk.PhotoImage(Image.open(pic4))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
globeview = tk.Label(window, image = img1)
mercatorview = tk.Label(window, image = img2)
currentweather= tk.Label(window, image = img3)
gearth = tk.Label(window, image = img4)

#The Pack geometry manager packs widgets in rows or columns.
globeview.pack(side = "top", fill = "both", expand = "yes")
mercatorview.pack(side = "top", fill = "both", expand = "yes")
currentweather.pack(side = "bottom", fill = "both", expand = "yes")
gearth.pack(side = "bottom", fill = "both", expand = "yes")

#Start the GUI
window.mainloop()
</code>```

Which produces this horror show!

My issues are clearly:

1) Images are not aligned in any way I want. Normally in HTML I'd set up table rows, align and fit it with spacers as I want. But I don't know how to define that here and I've spend hours being frustrated of this by now.

2) I need to add a text box. Every time I've tried to add various versions of text boxes. I get weird pyimage'xx' errors and no text box seems to materialize.

3) For the future: A button under the images that will show the full size uncropped picture. But that's not imperative right now!

So I'm hoping one of you have a nice way to do this, or can point me in a direction.. or perhaps even have done something like it where I can see your code and just tweak the numbers of a bit for aligning the pixels.

Thank you in advance.

答:
You are trying to lay everything out in a single frame. That can be done, but it's much easier to make subframes for things that fall in neat rows, columns or grids, and then put the subframes into the final arrangement. </p>

<p>Totally untested guess: </p>

```<code>import Tkinter as tk
from tkFont import Font
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Aarhus University Satellite Control Center")
window.geometry("1000x800")
window.configure(background='grey')

#Imports the pictures.
pic1 = "Globeview.png"
pic2 = "MercatorView.png"
pic3 = "currentweathercroppedsmall.png"
pic4 = "GECurrentcroppedsmall.png"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img1 = ImageTk.PhotoImage(Image.open(pic1))
img2 = ImageTk.PhotoImage(Image.open(pic2))
img3 = ImageTk.PhotoImage(Image.open(pic3))
img4 = ImageTk.PhotoImage(Image.open(pic4))

header = tk.Label(window, text="Header", font=Font(size=40))
header.pack()

toprow = tk.Frame(window)
globeview = tk.Label(toprow, image = img1)
globeview.pack(side = "left") # the side argument sets this to pack in a row rather than a column
infobox = tk.Text(toprow)
infobox.pack(side = "left")
toprow.pack() # pack the toprow frame into the window

bottomrow = tk.Frame(window)
mercatorview = tk.Label(bottomrow, image = img2)
currentweather= tk.Label(bottomrow, image = img3)
gearth = tk.Label(bottomrow, image = img4)
mercatorview.pack(side = "left")
currentweather.pack(side = "left")
gearth.pack(side = "left")
bottomrow.pack()

#Start the GUI
window.mainloop()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im using python 2.7 to build a satellite tracker for a cubesat project at my university. Now I've got the whole thing running as I want it to. I produce 4 images and a load of text based on the ISS's orbit parameters as our cubesat is not yet flying.

The 4 pictures are:

1) Satellite's current position on a globe based on its TLE straight from celestrak.

2) Satellite's current position on a mercator(flat) map.

3) Its current lat/lon position translated to a google earth view to physically interpret where it is.

4) Its current lat/lon position based on current weather maps, for whether or not there are clouds in the region, obscuring the satellites remote sensing imaging capabilities. (Reason why the picture looks ugly and purple, is because this region had no current weather data at the time of retrieving data)

Then I need to implement a text box with information on altitude, velocity, spatial resolution etc.

It's all nice and dandy. But I cant for the love of god figure out how to get this Tkinter GUI to play nice! I'm a geoscientist, not a computer scientist and python programming is very new to me :D

Anyway I did a quick layout in photoshop as of how I want the finished data to be produced in a Tkinter GUI. See the primitive image below:

Now here is my shameful code below:

import Tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Satellite Control Center")
window.geometry("1000x800")
window.configure(background='grey')

#Imports the pictures.
pic1 = "Globeview.png"
pic2 = "MercatorView.png"
pic3 = "currentweathercroppedsmall.png"
pic4 = "GECurrentcroppedsmall.png"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img1 = ImageTk.PhotoImage(Image.open(pic1))
img2 = ImageTk.PhotoImage(Image.open(pic2))
img3 = ImageTk.PhotoImage(Image.open(pic3))
img4 = ImageTk.PhotoImage(Image.open(pic4))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
globeview = tk.Label(window, image = img1)
mercatorview = tk.Label(window, image = img2)
currentweather= tk.Label(window, image = img3)
gearth = tk.Label(window, image = img4)

#The Pack geometry manager packs widgets in rows or columns.
globeview.pack(side = "top", fill = "both", expand = "yes")
mercatorview.pack(side = "top", fill = "both", expand = "yes")
currentweather.pack(side = "bottom", fill = "both", expand = "yes")
gearth.pack(side = "bottom", fill = "both", expand = "yes")

#Start the GUI
window.mainloop()

Which produces this horror show!

My issues are clearly:

1) Images are not aligned in any way I want. Normally in HTML I'd set up table rows, align and fit it with spacers as I want. But I don't know how to define that here and I've spend hours being frustrated of this by now.

2) I need to add a text box. Every time I've tried to add various versions of text boxes. I get weird pyimage'xx' errors and no text box seems to materialize.

3) For the future: A button under the images that will show the full size uncropped picture. But that's not imperative right now!

So I'm hoping one of you have a nice way to do this, or can point me in a direction.. or perhaps even have done something like it where I can see your code and just tweak the numbers of a bit for aligning the pixels.

Thank you in advance.

Body:
You are trying to lay everything out in a single frame. That can be done, but it's much easier to make subframes for things that fall in neat rows, columns or grids, and then put the subframes into the final arrangement.

Totally untested guess:

import Tkinter as tk
from tkFont import Font
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Aarhus University Satellite Control Center")
window.geometry("1000x800")
window.configure(background='grey')

#Imports the pictures.
pic1 = "Globeview.png"
pic2 = "MercatorView.png"
pic3 = "currentweathercroppedsmall.png"
pic4 = "GECurrentcroppedsmall.png"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img1 = ImageTk.PhotoImage(Image.open(pic1))
img2 = ImageTk.PhotoImage(Image.open(pic2))
img3 = ImageTk.PhotoImage(Image.open(pic3))
img4 = ImageTk.PhotoImage(Image.open(pic4))

header = tk.Label(window, text="Header", font=Font(size=40))
header.pack()

toprow = tk.Frame(window)
globeview = tk.Label(toprow, image = img1)
globeview.pack(side = "left") # the side argument sets this to pack in a row rather than a column
infobox = tk.Text(toprow)
infobox.pack(side = "left")
toprow.pack() # pack the toprow frame into the window

bottomrow = tk.Frame(window)
mercatorview = tk.Label(bottomrow, image = img2)
currentweather= tk.Label(bottomrow, image = img3)
gearth = tk.Label(bottomrow, image = img4)
mercatorview.pack(side = "left")
currentweather.pack(side = "left")
gearth.pack(side = "left")
bottomrow.pack()

#Start the GUI
window.mainloop()


问:
Using Observable and Subscribe in Angular with Firebase
I am trying to subscribe to an function returning observable object in angular 2 .
So when there is any new worker added the main calling function should have the value

// functiion based on firebase DB

```<code>getWorkers():Observable<any> {
    firebase.database().ref('/workers').on('child_added', (snapshot) => {
        return snapshot.val();

    });

}
</code>```

subscriber function

```<code>workers: any[];
public ngOnInit() {
    this.db.getWorkers().subscribe(workers => this.workers = workers);
}
</code>```

It is saying the function return type is not Observable and hence throwing error .

答:
your first method must return observable.</p>

```<code>getWorkers():Observable<any> {
    firebase.database().ref('/workers').on('child_added', (snapshot) => {
        return Observable.of(snapshot.val());

    });
}
</code>```

Body:
I am trying to subscribe to an function returning observable object in angular 2 .
So when there is any new worker added the main calling function should have the value

// functiion based on firebase DB

getWorkers():Observable<any> {
    firebase.database().ref('/workers').on('child_added', (snapshot) => {
        return snapshot.val();

    });

}

subscriber function

workers: any[];
public ngOnInit() {
    this.db.getWorkers().subscribe(workers => this.workers = workers);
}

It is saying the function return type is not Observable and hence throwing error .

Body:
your first method must return observable.

getWorkers():Observable<any> {
    firebase.database().ref('/workers').on('child_added', (snapshot) => {
        return Observable.of(snapshot.val());

    });
}


问:
Redirect to Url after domain
I want to get redirect by click on button, I use:

```<code><inputtype="submit" onclick="location.href='first';" value="goSomewhere1"/>
<inputtype="submit" onclick="location.href='second';" value="goSomewhere2"/>
</code>```

and it workf if is clicked on page http://ADDRESS but if is clicked when url is like http://ADDRESS/something it redirects to http://ADDRESS/something/first

How is it possible to get redirect just before ADDRESS but not put this value (ADDRESS) because it could change? (for this example it should get http://ADRESS/first insted of http://ADDRESS/something/first)

答:
You want /first not first.

Without a slash, it's a relative link. With the slash, it's absolute to the base URL.

```<code><input type="submit" onclick="location.href='/first'" value="goSomewhere1"/>
<input type="submit" onclick="location.href='/second'" value="goSomewhere2"/>
</code>```

Title: Redirect to Url after domain

Body:
I want to get redirect by click on button, I use:

<inputtype="submit" onclick="location.href='first';" value="goSomewhere1"/>
<inputtype="submit" onclick="location.href='second';" value="goSomewhere2"/>

and it workf if is clicked on page http://ADDRESS but if is clicked when url is like http://ADDRESS/something it redirects to http://ADDRESS/something/first

How is it possible to get redirect just before ADDRESS but not put this value (ADDRESS) because it could change? (for this example it should get http://ADRESS/first insted of http://ADDRESS/something/first)

Body:
You want /first not first.

Without a slash, it's a relative link. With the slash, it's absolute to the base URL.

<input type="submit" onclick="location.href='/first'" value="goSomewhere1"/>
<input type="submit" onclick="location.href='/second'" value="goSomewhere2"/>


问:
How do i get the root, not the document root
I want to upload images outside the document root:

```<code>// on server:
/home1/myname/artist_gallery

// on localhost
c:/artist_gallery
</code>```

I use the following to create the DEFINE for both local and server:

```<code>define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('GALLERY_FILE', DOCUMENT_ROOT . '/artist_gallery/');
</code>```

but, i get

```<code>/home1/myname/public_html/artist_gallery
C:/public_html/artist_gallery
</code>```

Notice the folder public_html... i dont want that folder...

So, how do I get the root (not the document root) in one DEFINE rule for both the localhost and server?

答:
in localhost change valuse of DocumentRoot in your file php.ini -> DocumentRoot "C:/public_html/"
to DocumentRoot "C:/"

And if you are not the server's host, you will not be able to

Body:
I want to upload images outside the document root:

// on server:
/home1/myname/artist_gallery

// on localhost
c:/artist_gallery

I use the following to create the DEFINE for both local and server:

define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('GALLERY_FILE', DOCUMENT_ROOT . '/artist_gallery/');

but, i get

/home1/myname/public_html/artist_gallery
C:/public_html/artist_gallery

Notice the folder public_html... i dont want that folder...

So, how do I get the root (not the document root) in one DEFINE rule for both the localhost and server?


问:
Yii2 GridView cannot set column width
this is the first time I am using the Yii2 GridView Widget. I have tried setting a column's width after reading some answers here on stackoverflow, but it just won't work for me and I would love it if the columns had different widths (especially the first one).

I have tried setting the width using 'contentOptions' directly for the first column and also with an external CSS file for the product name column.

Can someone please tell me if there is an alternative or if there is something I am doing wrong?

```<code> <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        [
            'class' => 'yii\grid\SerialColumn',
            'contentOptions' => ['style' => 'max-width:20px;'],
        ],

        [
            'format' => 'raw',
            'label' => 'Image',
            'value' => function ($data) {
                $url = $data->imgSrc;
                return Html::img($url, ['width' => '40px']);
            },
        ],

        [
            'attribute' => 'name',
            'format' => 'raw',
            'label' => 'Product name',
            'contentOptions' => function ($model, $key, $index, $column) {
                return ['class' => 'tbl_name'];
            },
        ],
    ],
]); ?>
</code>```

答:
First add Option like

```<code>GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'options' => [ 'style' => 'table-layout:fixed;' ],
</code>```

after that add below lines

```<code>[
    'attribute' => 'news_description',
    'contentOptions' => [ 'style' => 'width: 25%;' ],
],
</code>```

Title: Yii2 GridView cannot set column width

Body:
this is the first time I am using the Yii2 GridView Widget. I have tried setting a column's width after reading some answers here on stackoverflow, but it just won't work for me and I would love it if the columns had different widths (especially the first one).

I have tried setting the width using 'contentOptions' directly for the first column and also with an external CSS file for the product name column.

Can someone please tell me if there is an alternative or if there is something I am doing wrong?

 <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        [
            'class' => 'yii\grid\SerialColumn',
            'contentOptions' => ['style' => 'max-width:20px;'],
        ],

        [
            'format' => 'raw',
            'label' => 'Image',
            'value' => function ($data) {
                $url = $data->imgSrc;
                return Html::img($url, ['width' => '40px']);
            },
        ],

        [
            'attribute' => 'name',
            'format' => 'raw',
            'label' => 'Product name',
            'contentOptions' => function ($model, $key, $index, $column) {
                return ['class' => 'tbl_name'];
            },
        ],
    ],
]); ?>

Body:
First add Option like

GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'options' => [ 'style' => 'table-layout:fixed;' ],

after that add below lines

[
    'attribute' => 'news_description',
    'contentOptions' => [ 'style' => 'width: 25%;' ],
],


问:
How Do I Use The CSS Background Property?
```<code>body {
  background: #fff url("milkshakeonthewindowsill.jpg") cover no-repeat fixed;
}
</code>```

That's my CSS for my body, yet, it won't load the image, but somehow,

```<code>body {
  background-color: #fff;
  background-image: url("milkshakeonthewindowsill.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}
</code>```

this code does. What am I missing or doing wrong?

答:
Background size cover must be added separately:</p>

```<code>body {
  background: #fff url("milkshakeonthewindowsill.jpg") no-repeat fixed;
  background-size: cover;
}
</code>```

Body:
body {
  background: #fff url("milkshakeonthewindowsill.jpg") cover no-repeat fixed;
}

That's my CSS for my body, yet, it won't load the image, but somehow,

body {
  background-color: #fff;
  background-image: url("milkshakeonthewindowsill.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

this code does. What am I missing or doing wrong?

Body:
Background size cover must be added separately:

body {
  background: #fff url("milkshakeonthewindowsill.jpg") no-repeat fixed;
  background-size: cover;
}


问:
Symfony Exception, DB query with controller and twig Template
I have a controller file and a twig template but the communication is disturbed.
The Exception is:

An exception has been thrown during the rendering of a template ("Error producing an iterator").

Either I still miss something in the controller file or something is wrong with the settings.

My Object is "ArticleCategory"
Controller:

```<code>namespace AppBundle\Controller;
use Pimcore\Controller\Configuration\ResponseHeader;
use Pimcore\Model\Asset;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Pimcore\Model\DataObject\ArticleCategory;
use Zend\Paginator\Paginator;

class ContentController extends FrontendController
{
    public function testroot1Action(Request $request)
    {
        $articleCategory = new ArticleCategory\Listing();
        $articleCategory->setOrderKey('date');
        $articleCategory->setOrder('DESC');

        $paginator = new Paginator($articleCategory);
        $paginator->setCurrentPageNumber($request->get('page'));
        $paginator->setItemCountPerPage(5);
        var_dump($paginator);

        $this->view->content = $paginator;

    }
}
</code>```

The Twig Template. The Exception comes from my for in loop. The iterate of "content" dosent work:

```<code>{% extends 'layout.html.twig' %}
{% block content %}

    {{ dump(content)}}

   {% for contents in content %}

        {{ dump(contents)}}

    {% endfor %}

{% block content %}
</code>```

Is there somthing more to do or is somthing wrong?

答:
it should be :</p>

```<code>{% extends 'layout.html.twig' %}
{% block content %}

   {% for content in contents %}

       // here you have access to a singular content object

    {% endfor %}

{% block content %}
</code>```

Body:
I have a controller file and a twig template but the communication is disturbed.
The Exception is:

An exception has been thrown during the rendering of a template ("Error producing an iterator").

Either I still miss something in the controller file or something is wrong with the settings.

My Object is "ArticleCategory"
Controller:

namespace AppBundle\Controller;
use Pimcore\Controller\Configuration\ResponseHeader;
use Pimcore\Model\Asset;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Pimcore\Model\DataObject\ArticleCategory;
use Zend\Paginator\Paginator;

class ContentController extends FrontendController
{
    public function testroot1Action(Request $request)
    {
        $articleCategory = new ArticleCategory\Listing();
        $articleCategory->setOrderKey('date');
        $articleCategory->setOrder('DESC');

        $paginator = new Paginator($articleCategory);
        $paginator->setCurrentPageNumber($request->get('page'));
        $paginator->setItemCountPerPage(5);
        var_dump($paginator);

        $this->view->content = $paginator;

    }
}

The Twig Template. The Exception comes from my for in loop. The iterate of "content" dosent work:

{% extends 'layout.html.twig' %}
{% block content %}

    {{ dump(content)}}

   {% for contents in content %}

        {{ dump(contents)}}

    {% endfor %}

{% block content %}

Is there somthing more to do or is somthing wrong?

Body:
it should be :

{% extends 'layout.html.twig' %}
{% block content %}

   {% for content in contents %}

       // here you have access to a singular content object

    {% endfor %}

{% block content %}


问:
Design Pattern to handle actions based on multiple inputs in C#
Let's say that there are two properties in a business model for eg., country and type, and we need to handle different logic for each country and for each type.

```<code>if(country=="us"){
    if(type=="type1){
        usType1Handler.Execute();
    }
    else if(type=="type2"){
        usType2Handler.Execute();
    }
    .
    .
    .
    else{
        usDefaultHandler.Execute();
    }
}
else if(country=="uk"){
    if(type=="type1){
        ukType1Handler.Execute();
    }
    else if(type=="type2"){
        ukType2Handler.Execute();
    }
    .
    .
    .
    else{
        ukDefaultHandler.Execute();
    }
}
else{
    throw exception("unknown country");
}
</code>```

There will be lot of if's to mix and match the each implementation specific to each country type combination. Is there any design pattern we can use to handle this scenario?

答:
Your use case is well suited for a Strategy+Factory pattern implementation. You should have factories to move out the instantiation part for your handler. As you can see, we have not done away with if-else blocks but simply moved them to more manageable classes of their own. No doubt, it increases number of classes but this helps you make your code scaleable as well as less bug prone in the long run. You can add as many countries as you want without touching your existing code. This ensures you won't be introducing bugs in already existing functionality. Also, if you want you can have factory to return CountryFactory as well which would be even better. This way your "YourExecutingClass" would always remain untouched no matter how many countries and types you onboard in the future.

    public abstract class CountryFactory {
      protected abstract CountryTypeHandler getCountryTypeHandler(String type);
    }

    public class USHandlerFactory{
      @Override
      protected USHandlerFactory getCountryTypeHandler(String type){
        if(type=="type1"){
          return new USType1Handler();
        }
        else if(type=="type2"){
          return new USType2Handler();
        }
      }
    }

    public class UKHandlerFactory{
      @Override
      protected UKHandlerFactory getCountryTypeHandler(String type){
        if(type=="type1"){
          return new UKType1Handler();
        }
        else if(type=="type2"){
          return new UKType2Handler();
        }
      }
    }

    public void YourExecutingClass {
      USHandlerFactory handler; // Since this is your handler interface, it can hold any type of handler. You don't need to instantiate all your handlers.

      String country = "us"; // Both country and type are input and can vary anyway you handle
      String type = "type1";
      CountryFactory factory;
      if(country=="us"){
        factory = new USHandlerFactory();
      } else if(country=="uk") {
        factory = new UKHandlerFactory();
      }else{
        throw exception("unknown country");
      }

      handler = factory.getCountryTypeHandler(type);
      handler.Execute();
    }
```

Body:
Let's say that there are two properties in a business model for eg., country and type, and we need to handle different logic for each country and for each type.

if(country=="us"){
    if(type=="type1){
        usType1Handler.Execute();
    }
    else if(type=="type2"){
        usType2Handler.Execute();
    }
    .
    .
    .
    else{
        usDefaultHandler.Execute();
    }
}
else if(country=="uk"){
    if(type=="type1){
        ukType1Handler.Execute();
    }
    else if(type=="type2"){
        ukType2Handler.Execute();
    }
    .
    .
    .
    else{
        ukDefaultHandler.Execute();
    }
}
else{
    throw exception("unknown country");
}

There will be lot of if's to mix and match the each implementation specific to each country type combination. Is there any design pattern we can use to handle this scenario?

ContentLicense: CC BY-SA 4.0


问:
How to get values from JObject
I want to integrate Pipedrive with Dynamics CRM. I am calling webhook whenever deal is updated in Pipedrive. I am getting data in JObject form. I want to extract two fields from that. One is status and other is title.How can I do that?

Code to call Webhook:

```<code> [RoutePrefix("api/webhook")]
public class WebhookController : ApiController
{
    [HttpPost]
    [Route("")]
    public void Post(JObject message)
    {
        Console.WriteLine($"Received webhook: {message}");
    }
}
</code>```

Json which I am getting :

```<code>{
  "v":1,
  "matches_filters":{
    "current":[

    ]
  },
  "meta":{
    "v":1,
    "action":"updated",
    "object":"deal",
    "id":1,
    "company_id":2278508,
    "user_id":3371496,
    "host":"agniket.pipedrive.com",
    "timestamp":1512620040,
    "timestamp_micro":1512620040475200,
    "permitted_user_ids":[
      3371496
    ],
    "trans_pending":false,
    "is_bulk_update":false,
    "pipedrive_service_name":false,
    "matches_filters":{
      "current":[

      ]
    },
    "webhook_id":"31814"
  },
  "current":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-07 04:14:00",
    "stage_change_time":null,
    "active":false,
    "deleted":false,
    "status":"won",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":"2017-12-07 04:14:00",
    "pipeline_id":1,
    "won_time":"2017-12-07 04:14:00",
    "first_won_time":"2017-12-07 04:14:00",
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "previous":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-04 06:33:56",
    "stage_change_time":null,
    "active":true,
    "deleted":false,
    "status":"open",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":null,
    "pipeline_id":1,
    "won_time":null,
    "first_won_time":null,
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "event":"updated.deal",
  "retry":0
}
</code>```

答:
I would use SelectToken.  You can specify a JSONPath to the target value.  Assuming you want the current status and title you would do:

```<code>string status = (string)message.SelectToken("current.status");
string title = (string)message.SelectToken("current.title");
</code>```

If you want the previous status and title, use previous.status and previous.title instead.

Title: How to get values from JObject

Body:
I want to integrate Pipedrive with Dynamics CRM. I am calling webhook whenever deal is updated in Pipedrive. I am getting data in JObject form. I want to extract two fields from that. One is status and other is title.How can I do that?

Code to call Webhook:

 [RoutePrefix("api/webhook")]
public class WebhookController : ApiController
{
    [HttpPost]
    [Route("")]
    public void Post(JObject message)
    {
        Console.WriteLine($"Received webhook: {message}");
    }
}

Json which I am getting :

{
  "v":1,
  "matches_filters":{
    "current":[

    ]
  },
  "meta":{
    "v":1,
    "action":"updated",
    "object":"deal",
    "id":1,
    "company_id":2278508,
    "user_id":3371496,
    "host":"agniket.pipedrive.com",
    "timestamp":1512620040,
    "timestamp_micro":1512620040475200,
    "permitted_user_ids":[
      3371496
    ],
    "trans_pending":false,
    "is_bulk_update":false,
    "pipedrive_service_name":false,
    "matches_filters":{
      "current":[

      ]
    },
    "webhook_id":"31814"
  },
  "current":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-07 04:14:00",
    "stage_change_time":null,
    "active":false,
    "deleted":false,
    "status":"won",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":"2017-12-07 04:14:00",
    "pipeline_id":1,
    "won_time":"2017-12-07 04:14:00",
    "first_won_time":"2017-12-07 04:14:00",
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "previous":{
    "id":1,
    "public_id":null,
    "creator_user_id":3371496,
    "user_id":3371496,
    "person_id":1,
    "org_id":null,
    "stage_id":1,
    "title":"vaishali deal",
    "value":0,
    "currency":"INR",
    "add_time":"2017-12-04 04:44:15",
    "update_time":"2017-12-04 06:33:56",
    "stage_change_time":null,
    "active":true,
    "deleted":false,
    "status":"open",
    "probability":null,
    "next_activity_date":null,
    "next_activity_time":null,
    "next_activity_id":null,
    "last_activity_id":null,
    "last_activity_date":null,
    "lost_reason":null,
    "visible_to":"3",
    "close_time":null,
    "pipeline_id":1,
    "won_time":null,
    "first_won_time":null,
    "lost_time":null,
    "products_count":0,
    "files_count":0,
    "notes_count":0,
    "followers_count":1,
    "email_messages_count":0,
    "activities_count":0,
    "done_activities_count":0,
    "undone_activities_count":0,
    "reference_activities_count":0,
    "participants_count":1,
    "expected_close_date":null,
    "last_incoming_mail_time":null,
    "last_outgoing_mail_time":null,
    "stage_order_nr":1,
    "person_name":"vaishali",
    "org_name":null,
    "next_activity_subject":null,
    "next_activity_type":null,
    "next_activity_duration":null,
    "next_activity_note":null,
    "formatted_value":"₹0",
    "rotten_time":null,
    "weighted_value":0,
    "formatted_weighted_value":"₹0",
    "owner_name":"riya dalvi",
    "cc_email":"agniket+deal1@pipedrivemail.com",
    "org_hidden":false,
    "person_hidden":false
  },
  "event":"updated.deal",
  "retry":0
}

Body:
I would use SelectToken.  You can specify a JSONPath to the target value.  Assuming you want the current status and title you would do:

string status = (string)message.SelectToken("current.status");
string title = (string)message.SelectToken("current.title");

If you want the previous status and title, use previous.status and previous.title instead.


问:
How do I use node debug cli with Jest?
How can I just use the simple node cli/repl debugger with Jest?

The Jest documentation uses node-inspector, but it is outdated/deprecated as of Node 6.3. I tried the recommended command anyway on Node 7.7.4:

```<code>node --debug-brk ./node_modules/.bin/jest --runInBand --no-cache [your_test_file]
</code>```

But this simply hangs on the following (assumedly waiting on node-inspector):

(node:13452) DeprecationWarning: node --debug is deprecated. Please use node --inspect instead. Debugger listening on 127.0.0.1:5858

I added --inspect as specified by the warning, but even then execution doesn't stop on my debugger statement in Chrome DevTools.

This seems overly complicated for a very simple use case.

答:
From node v8.4 the debugger keyword within the code is fixed for VM context. Refer this git comment.

1.Type debugger keyword in your Jest code:

```<code>describe('Testcase definition', () => {
   it('should be defined with subobjects', () => {
     debugger; // <-- This keyword breaks on Chrome inspect
     expect(true).toBe(true);
   });
});
</code>```

Command to Run:

node --inspect-brk --inspect ./node_modules/.bin/jest -i tests/mytest.test.js

Now open chrome://inspect/#devices on Chrome. Voila!

Title: How do I use node debug cli with Jest?

Body:
How can I just use the simple node cli/repl debugger with Jest?

The Jest documentation uses node-inspector, but it is outdated/deprecated as of Node 6.3. I tried the recommended command anyway on Node 7.7.4:

node --debug-brk ./node_modules/.bin/jest --runInBand --no-cache [your_test_file]

But this simply hangs on the following (assumedly waiting on node-inspector):

(node:13452) DeprecationWarning: node --debug is deprecated. Please use node --inspect instead. Debugger listening on 127.0.0.1:5858

I added --inspect as specified by the warning, but even then execution doesn't stop on my debugger statement in Chrome DevTools.

This seems overly complicated for a very simple use case.

Body:
From node v8.4 the debugger keyword within the code is fixed for VM context. Refer this git comment.

1.Type debugger keyword in your Jest code:

describe('Testcase definition', () => {
   it('should be defined with subobjects', () => {
     debugger; // <-- This keyword breaks on Chrome inspect
     expect(true).toBe(true);
   });
});

Command to Run:

node --inspect-brk --inspect ./node_modules/.bin/jest -i tests/mytest.test.js

Now open chrome://inspect/#devices on Chrome. Voila!


答:
```<code>import Tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Aarhus University Satellite Control Center")
window.geometry("1000x800")
window.configure(background='grey')

#Imports the pictures.
pic1 = "Globeview.png"
pic2 = "MercatorView.png"
pic3 = "currentweathercroppedsmall.png"
pic4 = "GECurrentcroppedsmall.png"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img1 = ImageTk.PhotoImage(Image.open(pic1))
img2 = ImageTk.PhotoImage(Image.open(pic2))
img3 = ImageTk.PhotoImage(Image.open(pic3))
img4 = ImageTk.PhotoImage(Image.open(pic4))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
globeview = tk.Label(window, image = img1).grid(row=0,column=0)
mercatorview = tk.Label(window, image = img2).grid(row=1,column=0)
currentweather= tk.Label(window, image = img3).grid(row=1,column=1)
gearth = tk.Label(window, image = img4).grid(row=1,column=2)

#Start the GUI
window.mainloop()
</code>```

You need to add row and column in the label grid option. After you are creating the Label , put the grid and mention row and column . I have updated the code, just check it . If you face any problem write us back,  and remove pack, which I deleted in the code :) Cheers

Title: Setting up GUI with Tkinter for Image and Text inputs

Body:
Im using python 2.7 to build a satellite tracker for a cubesat project at my university. Now I've got the whole thing running as I want it to. I produce 4 images and a load of text based on the ISS's orbit parameters as our cubesat is not yet flying.

The 4 pictures are:

1) Satellite's current position on a globe based on its TLE straight from celestrak.

2) Satellite's current position on a mercator(flat) map.

3) Its current lat/lon position translated to a google earth view to physically interpret where it is.

4) Its current lat/lon position based on current weather maps, for whether or not there are clouds in the region, obscuring the satellites remote sensing imaging capabilities. (Reason why the picture looks ugly and purple, is because this region had no current weather data at the time of retrieving data)

Then I need to implement a text box with information on altitude, velocity, spatial resolution etc.

It's all nice and dandy. But I cant for the love of god figure out how to get this Tkinter GUI to play nice! I'm a geoscientist, not a computer scientist and python programming is very new to me :D

Anyway I did a quick layout in photoshop as of how I want the finished data to be produced in a Tkinter GUI. See the primitive image below:

Now here is my shameful code below:

import Tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Satellite Control Center")
window.geometry("1000x800")
window.configure(background='grey')

#Imports the pictures.
pic1 = "Globeview.png"
pic2 = "MercatorView.png"
pic3 = "currentweathercroppedsmall.png"
pic4 = "GECurrentcroppedsmall.png"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img1 = ImageTk.PhotoImage(Image.open(pic1))
img2 = ImageTk.PhotoImage(Image.open(pic2))
img3 = ImageTk.PhotoImage(Image.open(pic3))
img4 = ImageTk.PhotoImage(Image.open(pic4))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
globeview = tk.Label(window, image = img1)
mercatorview = tk.Label(window, image = img2)
currentweather= tk.Label(window, image = img3)
gearth = tk.Label(window, image = img4)

#The Pack geometry manager packs widgets in rows or columns.
globeview.pack(side = "top", fill = "both", expand = "yes")
mercatorview.pack(side = "top", fill = "both", expand = "yes")
currentweather.pack(side = "bottom", fill = "both", expand = "yes")
gearth.pack(side = "bottom", fill = "both", expand = "yes")

#Start the GUI
window.mainloop()

Which produces this horror show!

My issues are clearly:

1) Images are not aligned in any way I want. Normally in HTML I'd set up table rows, align and fit it with spacers as I want. But I don't know how to define that here and I've spend hours being frustrated of this by now.

2) I need to add a text box. Every time I've tried to add various versions of text boxes. I get weird pyimage'xx' errors and no text box seems to materialize.

3) For the future: A button under the images that will show the full size uncropped picture. But that's not imperative right now!

So I'm hoping one of you have a nice way to do this, or can point me in a direction.. or perhaps even have done something like it where I can see your code and just tweak the numbers of a bit for aligning the pixels.

Thank you in advance.

Body:
import Tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Aarhus University Satellite Control Center")
window.geometry("1000x800")
window.configure(background='grey')

#Imports the pictures.
pic1 = "Globeview.png"
pic2 = "MercatorView.png"
pic3 = "currentweathercroppedsmall.png"
pic4 = "GECurrentcroppedsmall.png"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img1 = ImageTk.PhotoImage(Image.open(pic1))
img2 = ImageTk.PhotoImage(Image.open(pic2))
img3 = ImageTk.PhotoImage(Image.open(pic3))
img4 = ImageTk.PhotoImage(Image.open(pic4))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
globeview = tk.Label(window, image = img1).grid(row=0,column=0)
mercatorview = tk.Label(window, image = img2).grid(row=1,column=0)
currentweather= tk.Label(window, image = img3).grid(row=1,column=1)
gearth = tk.Label(window, image = img4).grid(row=1,column=2)

#Start the GUI
window.mainloop()

You need to add row and column in the label grid option. After you are creating the Label , put the grid and mention row and column . I have updated the code, just check it . If you face any problem write us back,  and remove pack, which I deleted in the code :) Cheers


问:
Functional programming in Python: find smallest odd number in list

How can I find the smallest odd number in a list of integers, if the problem statement says that I can't use for and if?

答:
Why should anyone consider using for or if?

```<code>min(numbers, key=lambda n: (n&1==0, n))
</code>```

Body:
Why should anyone consider using for or if?

min(numbers, key=lambda n: (n&1==0, n))


问:
How to change item in recycler view dynamically based on user's favorite item
I have a recycler view with drink categories (7 items), and I wanted all 7 items to change position dynamically based on customer's favorite drink saved in Favorites table.

How could this be possible in such a way?

Drink categories table

Favorites table

My current code:

```<code>    private void loadMenu() {

    Query query = category.orderByChild("views");

    adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>(
            Category.class,
            R.layout.menu_item,
            MenuViewHolder.class,
            query
    ) {
        @Override
        protected void populateViewHolder(final MenuViewHolder viewHolder, final Category model, int position) {
            viewHolder.txtMenuName.setText(model.getName());
            Picasso.with(getBaseContext()).load(model.getImage())
                    .into(viewHolder.imageView);
            viewHolder.txtViews.setText(model.getViews());

            viewHolder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onClick(View view, int position, boolean isLongClick) {
                    //No of click
                    count++;
                    category.child(adapter.getRef(position).getKey()).child("views").setValue(count);

                    //Get CategoryId and send to new Activity
                    Intent drinkList = new Intent(Home.this, DrinkList.class);
                    //Because CategoryId is key, so we just get key of this item
                    drinkList.putExtra("CategoryId",adapter.getRef(position).getKey());
                    startActivity(drinkList);
                }
            });
        }
    };
    adapter.notifyDataSetChanged();
    recycler_menu.setAdapter(adapter);
}
</code>```

答:
If I got you right you want to order the categories based on field like the is favorite or how much the user like the category, if so
To get a sorted and filtered result, you have to pass a query into the FirebaseRecyclerAdapter constructor, where you are now passing in a DatabaseReference. So add a constructor to your adapter that takes a Query:

```<code>public MyFireAdapterDiasFiestaRecyclerView(
    Class<DiaFiestaMeta> modelClass,
    int modelLayout,
    Class<MyFireViewHolder> viewHolderClass,
    Query query) {
    ...
</code>```

And then invoke it with a query that orders and filters:

```<code>adapter = new MyFireAdapterDiasFiestaRecyclerView(
   DiaFiestaMeta.class,
   layout_that_you_use,
   MyFireViewHolder.class,
   ref.orderByChild("property_to_sort_and_filter_on").equalTo("value_to_filter_on")
);
</code>```

And  orderByChild() will sort your query in ascending order, to have Descending query when using orderByChild() use this trick  good solution if you're using the DatabaseReference to populate a FirebaseRecyclerAdapter, here it goes:

Inside the FirebaseRecyclerAdapter declaration, override the getItem() function just like we this :

```<code>@Override
public User getItem(int position) {
        return super.getItem(getItemCount() - 1 - position);
}
</code>```

ref : Sort a FirebaseRecyclerAdapter

Body:
I have a recycler view with drink categories (7 items), and I wanted all 7 items to change position dynamically based on customer's favorite drink saved in Favorites table.

How could this be possible in such a way?

Drink categories table

Favorites table

My current code:

    private void loadMenu() {

    Query query = category.orderByChild("views");

    adapter = new FirebaseRecyclerAdapter<Category, MenuViewHolder>(
            Category.class,
            R.layout.menu_item,
            MenuViewHolder.class,
            query
    ) {
        @Override
        protected void populateViewHolder(final MenuViewHolder viewHolder, final Category model, int position) {
            viewHolder.txtMenuName.setText(model.getName());
            Picasso.with(getBaseContext()).load(model.getImage())
                    .into(viewHolder.imageView);
            viewHolder.txtViews.setText(model.getViews());

            viewHolder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onClick(View view, int position, boolean isLongClick) {
                    //No of click
                    count++;
                    category.child(adapter.getRef(position).getKey()).child("views").setValue(count);

                    //Get CategoryId and send to new Activity
                    Intent drinkList = new Intent(Home.this, DrinkList.class);
                    //Because CategoryId is key, so we just get key of this item
                    drinkList.putExtra("CategoryId",adapter.getRef(position).getKey());
                    startActivity(drinkList);
                }
            });
        }
    };
    adapter.notifyDataSetChanged();
    recycler_menu.setAdapter(adapter);
}

Body:
If I got you right you want to order the categories based on field like the is favorite or how much the user like the category, if so
To get a sorted and filtered result, you have to pass a query into the FirebaseRecyclerAdapter constructor, where you are now passing in a DatabaseReference. So add a constructor to your adapter that takes a Query:

public MyFireAdapterDiasFiestaRecyclerView(
    Class<DiaFiestaMeta> modelClass,
    int modelLayout,
    Class<MyFireViewHolder> viewHolderClass,
    Query query) {
    ...

And then invoke it with a query that orders and filters:

adapter = new MyFireAdapterDiasFiestaRecyclerView(
   DiaFiestaMeta.class,
   layout_that_you_use,
   MyFireViewHolder.class,
   ref.orderByChild("property_to_sort_and_filter_on").equalTo("value_to_filter_on")
);

And  orderByChild() will sort your query in ascending order, to have Descending query when using orderByChild() use this trick  good solution if you're using the DatabaseReference to populate a FirebaseRecyclerAdapter, here it goes:

Inside the FirebaseRecyclerAdapter declaration, override the getItem() function just like we this :

@Override
public User getItem(int position) {
        return super.getItem(getItemCount() - 1 - position);
}

ref : Sort a FirebaseRecyclerAdapter


问:
How to ORDER MySQL results while excluding a string from the order title
Im trying use MySQL to order by excluding "excl" if it's found at the start of a string, and using what ever comes after "excl" to order the results.

So it will order like this:

title a name

excl title b name2

title c name

title d name

But not:

title a name

title c name

title d name

excl title b name2

答:
Edit: misread the question, I thought rows starting with excl should go to the end, so the CASE needs to use substring() like in enobrev's answer.</p>

```
...
ORDER BY
   CASE
      WHEN title_column LIKE 'excl%' THEN substring(title, 6)
      ELSE title_column
   END
```

ContentLicense: CC BY-SA 2.5

Body:
Edit: misread the question, I thought rows starting with excl should go to the end, so the CASE needs to use substring() like in enobrev's answer.

...
ORDER BY
   CASE
      WHEN title_column LIKE 'excl%' THEN substring(title, 6)
      ELSE title_column
   END


问:
Regex that match 3 consecutive words that start and end with the same letter
I have to match 3 consecutive words that start and end with same letters

I have a code like this:

```<code>import re

def regex(file):

    with open(file) as f:

         s=f.read()

    rx=re.compile(r"([a-z])+\s+\1",re.I)

    r=re.findall(rx,s)

    print(r)

    return len(r)
</code>```

The text from the file is something like this

dcvs xa Allo ozo zn bnro ce erdda anfgato e csdfa

and i'm expecting this result:

dcvs xa Allo ozo zn bnro ce erdda anfgato e csdfa

```<code>[('a','o'),('e','a')]
2
</code>```

but i'm getting this:

```<code>['a', 'o', 'e', 'a']
4
</code>```

Any clue?

答:
You may use

```<code>re.compile(r"[^a-z][a-z]*([a-z])[^a-z]+\1[a-z]*([a-z])[^a-z]+\2[a-z]*[^a-z]",re.I)
</code>```

See the regex demo.

Note that re.findall will return a list of tuples (of the captured values) in this case, since there are 2 capturing groups, and re.findall only returns captures if capturing groups are defined in a regex pattern.

Details

[^a-z] - any char but an ASCII letter

[a-z]*  - 0+ ASCII letters

([a-z]) - Group 1: any ASCII letter

[^a-z]+ - any 1+ chars other than ASCII letters

\1 - backreference to the Group 1 contents, same text as captured in Group 1

[a-z]* - 0+ ASCII letters

([a-z]) - Group 2: an ASCII letter

[^a-z]+ - any 1+ chars other than ASCII letters

\2 - backreference to the Group 1 contents, same text as captured in Group 2

[a-z]* - 0+ ASCII letters

[^a-z] - any 1 char other than an ASCII letter

Python demo:

```<code>import re
def regex(s):
    rx=re.compile(r"[^a-z][a-z]*([a-z])[^a-z]+\1[a-z]*([a-z])[^a-z]+\2[a-z]*[^a-z]",re.I)
    d=rx.findall(s)
    print(d)
    return len(d)
print(regex('dcvs xa Allo ozo zn bnro ce erdda anfgato e csdfa'))
</code>```

Output:

```<code>[('a', 'o'), ('e', 'a')]
2
</code>```

Body:
I have to match 3 consecutive words that start and end with same letters

I have a code like this:

import re

def regex(file):

    with open(file) as f:

         s=f.read()

    rx=re.compile(r"([a-z])+\s+\1",re.I)

    r=re.findall(rx,s)

    print(r)

    return len(r)

The text from the file is something like this

dcvs xa Allo ozo zn bnro ce erdda anfgato e csdfa

and i'm expecting this result:

dcvs xa Allo ozo zn bnro ce erdda anfgato e csdfa

[('a','o'),('e','a')]
2

but i'm getting this:

['a', 'o', 'e', 'a']
4

Any clue?

Body:
You may use

re.compile(r"[^a-z][a-z]*([a-z])[^a-z]+\1[a-z]*([a-z])[^a-z]+\2[a-z]*[^a-z]",re.I)

See the regex demo.

Note that re.findall will return a list of tuples (of the captured values) in this case, since there are 2 capturing groups, and re.findall only returns captures if capturing groups are defined in a regex pattern.

Details

[^a-z] - any char but an ASCII letter

[a-z]*  - 0+ ASCII letters

([a-z]) - Group 1: any ASCII letter

[^a-z]+ - any 1+ chars other than ASCII letters

\1 - backreference to the Group 1 contents, same text as captured in Group 1

[a-z]* - 0+ ASCII letters

([a-z]) - Group 2: an ASCII letter

[^a-z]+ - any 1+ chars other than ASCII letters

\2 - backreference to the Group 1 contents, same text as captured in Group 2

[a-z]* - 0+ ASCII letters

[^a-z] - any 1 char other than an ASCII letter

Python demo:

import re
def regex(s):
    rx=re.compile(r"[^a-z][a-z]*([a-z])[^a-z]+\1[a-z]*([a-z])[^a-z]+\2[a-z]*[^a-z]",re.I)
    d=rx.findall(s)
    print(d)
    return len(d)
print(regex('dcvs xa Allo ozo zn bnro ce erdda anfgato e csdfa'))

Output:

[('a', 'o'), ('e', 'a')]
2


问:
Laravel get last inserted data
Please find the code below, Here I am trying to create master record and based on the id I am adding related data.

```<code>    $country = new Country;

    $country->name = $request->post('country-name');
    $country->xyz  = $request->post('xyz');

    if($country->save()) {
        $n = count($request->post('bname'));

        for ($i = 0; $i < $n; $i++) {
            $dimention = new BoxDimentions;

            $dimention->name = $request->post('bname')[$i];
            $dimention->xyz  = $request->post('xyz')[$i];
            $dimention->cid  = $country->id;

            $dimention->save();
        }
    }
</code>```

Is there any inbuilt laravel function I can use to get all the information about country & BoxDimentions(including id, date time stamp etc) after the operation?

I have created a relation in the Country Model class "boxes" which will return all the box information. I know I can fetch the data using another query with the last created country id. I dont want to go for another query because I believe we have all the data is in our hand.

答:
Well unfortunately save() returns bool.

Your way around this would be using create() static wrapper that way you can get the recently created model instance.

You proppably want to refactor that code, so in your Country model you would prolly create a function like this (assuming u have defined relationships Country and BoxDimensions):

Your Country Model:

```<code>public function addBoxDimensions(array $data){

    return $this->boxes()->create($data);
}
</code>```

Then your controller would look something like this:

```<code>$country = new Country;

$country->name = $request->post('country-name');

$country->xyz  = $request->post('xyz');

if($country->save()) {

    $n = count($request->post('bname'));

for ($i = 0; $i < $n; $i++) {

            // Here I will use relationships to create box dimensions for given country that's why I do not need to initialize BoxDimentions
           // $dimention = new BoxDimentions;

           $dimention = $country->addBoxDimensions([
             'name' = $request->post('bname')[$i],
             'xyz'  = $request->post('xyz')[$i],
             'cid'  = $country->id
            ]);
       }
        //here you can return the country with all the box dimentions
        // also used eager loading to load boxdimensions so we can aviod N+1

       return $dimention->load('boxes');

        }
</code>```

Title: Laravel get last inserted data

Body:
Please find the code below, Here I am trying to create master record and based on the id I am adding related data.

    $country = new Country;

    $country->name = $request->post('country-name');
    $country->xyz  = $request->post('xyz');

    if($country->save()) {
        $n = count($request->post('bname'));

        for ($i = 0; $i < $n; $i++) {
            $dimention = new BoxDimentions;

            $dimention->name = $request->post('bname')[$i];
            $dimention->xyz  = $request->post('xyz')[$i];
            $dimention->cid  = $country->id;

            $dimention->save();
        }
    }

Is there any inbuilt laravel function I can use to get all the information about country & BoxDimentions(including id, date time stamp etc) after the operation?

I have created a relation in the Country Model class "boxes" which will return all the box information. I know I can fetch the data using another query with the last created country id. I dont want to go for another query because I believe we have all the data is in our hand.

Body:
Well unfortunately save() returns bool.

Your way around this would be using create() static wrapper that way you can get the recently created model instance.

You proppably want to refactor that code, so in your Country model you would prolly create a function like this (assuming u have defined relationships Country and BoxDimensions):

Your Country Model:

public function addBoxDimensions(array $data){

    return $this->boxes()->create($data);
}

Then your controller would look something like this:

$country = new Country;

$country->name = $request->post('country-name');

$country->xyz  = $request->post('xyz');

if($country->save()) {

    $n = count($request->post('bname'));

for ($i = 0; $i < $n; $i++) {

            // Here I will use relationships to create box dimensions for given country that's why I do not need to initialize BoxDimentions
           // $dimention = new BoxDimentions;

           $dimention = $country->addBoxDimensions([
             'name' = $request->post('bname')[$i],
             'xyz'  = $request->post('xyz')[$i],
             'cid'  = $country->id
            ]);
       }
        //here you can return the country with all the box dimentions
        // also used eager loading to load boxdimensions so we can aviod N+1

       return $dimention->load('boxes');

        }


问:
rows sql is null, how to fix it?
```<code><?php
    $sql = "(SELECT dari FROM mapping WHERE author = '$_SESSION[user]')
    UNION
    (SELECT ke FROM mapping WHERE author = '$_SESSION[user]')";

    $run = mysqli_query($conn, $sql);

    while ($rows = mysqli_fetch_assoc($run)) {
    if(!empty($rows['dari'])) {?>
        <option value="<?php echo $rows['dari']; ?>"><?php echo $rows['dari']; ?></option> <?php
        } else {?>
            <option value="A1">A1</option><?php
        }
    }
 ?>
</code>```

menu option with value A1 can not appear in the form

答:
You need enter to the block at least once</p>

```<code>do
{
    $rows = mysqli_fetch_assoc($run);
    if (null !== $rows && !empty($rows['dari']))
    { ?>
        <option value="<?php echo $rows['dari']; ?>"><?php echo $rows['dari']; ?></option> <?php
    }
    else
    { ?>
        <option value="A1">A1</option><?php
    }
} while ($rows);
</code>```

Title: rows sql is null, how to fix it?

Body:
<?php
    $sql = "(SELECT dari FROM mapping WHERE author = '$_SESSION[user]')
    UNION
    (SELECT ke FROM mapping WHERE author = '$_SESSION[user]')";

    $run = mysqli_query($conn, $sql);

    while ($rows = mysqli_fetch_assoc($run)) {
    if(!empty($rows['dari'])) {?>
        <option value="<?php echo $rows['dari']; ?>"><?php echo $rows['dari']; ?></option> <?php
        } else {?>
            <option value="A1">A1</option><?php
        }
    }
 ?>

menu option with value A1 can not appear in the form

Body:
You need enter to the block at least once

do
{
    $rows = mysqli_fetch_assoc($run);
    if (null !== $rows && !empty($rows['dari']))
    { ?>
        <option value="<?php echo $rows['dari']; ?>"><?php echo $rows['dari']; ?></option> <?php
    }
    else
    { ?>
        <option value="A1">A1</option><?php
    }
} while ($rows);


问:
Defining model in migration not working for Rails 5
Currently working on a data migration and having issues.
I have this in my migration file.

```<code>class DropTutorProfileTable < ActiveRecord::Migration[5.1]
  class Subject < ActiveRecord::Base
    has_and_belongs_to_many :tutor_accounts
  end

  class TutorAccount < ActiveRecord::Base
    has_and_belongs_to_many :subjects
  end

  def change
    send_data_to_subject_tutor_account
    drop_table :tutor_profiles
  end

  private

  def send_data_to_subject_tutor_account
    TutorProfile.all.find_each do |tutor_profile|
      # data migration code here
      tutor_account.subjects << subject
    end
  end
end
</code>```

When I run this migration, I get the following error.

```<code>StandardError: An error has occurred, this and all later migrations canceled:

Subject(#70181814234340) expected, got #<DropTutorProfileTable::Subject id: 3, name: "Writing", academic_type: "academic"> which is an instance of DropTutorProfileTable::Subject(#70181808133400)
</code>```

This is the first time I'm dealing with this issue. I've had other migrations where I define models in the migration and had no issues. Interestingly enough, when I output the class of the TutorAccount instance and the class of Subject instance, I get...

```<code>TutorAccount
DropTutorProfileTable::Subject
</code>```

I have no idea what's going on here. Your help is greatly appreciated!

答:
So I found the solution to this issue. The issue was how the instance of the class was being called within the migration. When making a direct call to the model defined in the migration in the migration code, it is namespaced for the migration. for instance.

```<code>class DropTutorProfileTable < ActiveRecord::Migration[5.1]
  class Subject < ActiveRecord::Base; end

  def change
    Subject.new.class # Returns DropTutorProfileTable::Subject
    TutorProfile.subject.class # Returns Subject
  end
end
</code>```

This makes sense since the Subject class is defined in the migration and is being called as its own entity. However, the class for associated subjects is defined by the Subject class that is defined in the codebase and not the migration. This is behavior that should be obvious if one understands plain ruby. I actually ran this code as an example and it validated my thesis. Thanks @inveterateliterate and @Shiko for pointing me in the right direction.

Body:
Currently working on a data migration and having issues.
I have this in my migration file.

class DropTutorProfileTable < ActiveRecord::Migration[5.1]
  class Subject < ActiveRecord::Base
    has_and_belongs_to_many :tutor_accounts
  end

  class TutorAccount < ActiveRecord::Base
    has_and_belongs_to_many :subjects
  end

  def change
    send_data_to_subject_tutor_account
    drop_table :tutor_profiles
  end

  private

  def send_data_to_subject_tutor_account
    TutorProfile.all.find_each do |tutor_profile|
      # data migration code here
      tutor_account.subjects << subject
    end
  end
end

When I run this migration, I get the following error.

StandardError: An error has occurred, this and all later migrations canceled:

Subject(#70181814234340) expected, got #<DropTutorProfileTable::Subject id: 3, name: "Writing", academic_type: "academic"> which is an instance of DropTutorProfileTable::Subject(#70181808133400)

This is the first time I'm dealing with this issue. I've had other migrations where I define models in the migration and had no issues. Interestingly enough, when I output the class of the TutorAccount instance and the class of Subject instance, I get...

TutorAccount
DropTutorProfileTable::Subject

I have no idea what's going on here. Your help is greatly appreciated!

Body:
So I found the solution to this issue. The issue was how the instance of the class was being called within the migration. When making a direct call to the model defined in the migration in the migration code, it is namespaced for the migration. for instance.

class DropTutorProfileTable < ActiveRecord::Migration[5.1]
  class Subject < ActiveRecord::Base; end

  def change
    Subject.new.class # Returns DropTutorProfileTable::Subject
    TutorProfile.subject.class # Returns Subject
  end
end

This makes sense since the Subject class is defined in the migration and is being called as its own entity. However, the class for associated subjects is defined by the Subject class that is defined in the codebase and not the migration. This is behavior that should be obvious if one understands plain ruby. I actually ran this code as an example and it validated my thesis. Thanks @inveterateliterate and @Shiko for pointing me in the right direction.


问:
language link to pick correct language file
I have a two language setup, structured like this:

```<code>includes/languages/lang-it [has the defines]
includes/languages/lang-en [has the defines]
includes/languages/languages [has the languages array]
en/files
en/subs/files
it/files
it/subs/files
</code>```

I have en/sub-1/index.php and en/sub-1/file-1.php and need to be able to change language when in file-1.php page

This is the code I have, and of course it does'nt work

```<code>require("../../includes/languages/lang-en.php");
<a href="<?php echo '../../' . LANG_ENG . '/sub-1/' . LINK_1 ?>">link to file-1 English</a>
<a href="<?php echo '../../' . LANG_ITA . '/sub-1/' . LINK_1 ?>">link to file-1 Italian</a>
</code>```

Where LANG_ENG and LANG_IT are the directories (en and it)
So I need it to pick the includes/languages/lang-en.php for the the English, and includes/languages/lang-it.php for the Italian.

I guess I need to "require" the correct language file before "LINK-1", but don't know how.

答:
I solved it like this:

Added $thispage, added variables for the file-name, and put that in the link.
Perhaps there are better ways, but that's what I could think of, and is working.

```<code><?php require("../../includes/languages/lang-en.php");?>
<?php // variables for pages to use for language links
$file_1_en="file-1-en.php";
$file_1_it="file-1-it.php";
?>
<?php if ($thisPage=="page name")
echo'
<a href="../../' . LANG_ENG . '/sub-1/' . $file_1_en . '"></a>
<a href="../../' . LANG_ITA . '/sub-1/' . $file_1_it . '"></a>
'?>
</code>```

Body:
I have a two language setup, structured like this:

includes/languages/lang-it [has the defines]
includes/languages/lang-en [has the defines]
includes/languages/languages [has the languages array]
en/files
en/subs/files
it/files
it/subs/files

I have en/sub-1/index.php and en/sub-1/file-1.php and need to be able to change language when in file-1.php page

This is the code I have, and of course it does'nt work

require("../../includes/languages/lang-en.php");
<a href="<?php echo '../../' . LANG_ENG . '/sub-1/' . LINK_1 ?>">link to file-1 English
<a href="<?php echo '../../' . LANG_ITA . '/sub-1/' . LINK_1 ?>">link to file-1 Italian

Where LANG_ENG and LANG_IT are the directories (en and it)
So I need it to pick the includes/languages/lang-en.php for the the English, and includes/languages/lang-it.php for the Italian.

I guess I need to "require" the correct language file before "LINK-1", but don't know how.

Body:
I solved it like this:

Added $thispage, added variables for the file-name, and put that in the link.
Perhaps there are better ways, but that's what I could think of, and is working.

<?php require("../../includes/languages/lang-en.php");?>
<?php // variables for pages to use for language links
$file_1_en="file-1-en.php";
$file_1_it="file-1-it.php";
?>
<?php if ($thisPage=="page name")
echo'
<a href="../../' . LANG_ENG . '/sub-1/' . $file_1_en . '"></a>
<a href="../../' . LANG_ITA . '/sub-1/' . $file_1_it . '"></a>
'?>