问:
Git push error: "origin does not appear to be a git repository"
I am following the instructions given here to create a Git repository. All went well until the last line:

```<code>$ git push -u origin master
</code>```

fatal: 'origin' does not appear to be a git repository

  fatal: The remote end hung up unexpectedly

I'm using git version 1.7.11.3 on OS X 10.6.8

```<code>$ git remote -v
</code>```

returns nothing

Config file for the repository:

```<code>[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
</code>```

I've had to open sudoers file using sudo visudo command and add the following to it (under # User privilege specification):

```<code>git ALL=(ALL) ALL.
</code>```

Now if I do:

```<code>$ git remote add origin /Volumes/500GB/git-repository/myproject.git
</code>```

it comes back with no error, but I don't see any code in the repository
(it has the aforementioned directories like branches, hooks, ...)

If I do:

```<code>$ git push -u origin master
fatal: 'origin' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

$ git remote -v
origin /Volumes/500GB/git-repository/myproject.git (fetch)
origin /Volumes/500GB/git-repository/myproject.git (push)
</code>```

答:
I'll still share my short answer humbly, knowing that I'm super late to answer this question.

Here's, a simple and clean explanation that solved my issue

Also, since I was using the SSH key I used the following command:

$ git remote add origin
git@github.com:{your-username}/{your-remote-repo-branch}

for instance it would look like:

$ git remote add origin git@github.com:aniketrb-github/microservices.git

If you are using the HTTPS URL, refer to the answer provided by @sunny-jim above.

Do correct me if I'm wrong. Thanks.

Body:
I am following the instructions given here to create a Git repository. All went well until the last line:

$ git push -u origin master

fatal: 'origin' does not appear to be a git repository

  fatal: The remote end hung up unexpectedly

I'm using git version 1.7.11.3 on OS X 10.6.8

$ git remote -v

returns nothing

Config file for the repository:

[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true

I've had to open sudoers file using sudo visudo command and add the following to it (under # User privilege specification):

git ALL=(ALL) ALL.

Now if I do:

$ git remote add origin /Volumes/500GB/git-repository/myproject.git

it comes back with no error, but I don't see any code in the repository
(it has the aforementioned directories like branches, hooks, ...)

If I do:

$ git push -u origin master
fatal: 'origin' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

$ git remote -v
origin /Volumes/500GB/git-repository/myproject.git (fetch)
origin /Volumes/500GB/git-repository/myproject.git (push)


来源: stackexchange

问:
Unity3D - Mesh.colors is extremely slow?
Update (solved): The horrible performance was because I didn't realize that Mesh.vertices.Length does an Array copy on every call.

I need to procedurally generate a mesh of quads.   Ideally I would like to be able to change the color of individual quads.  However it's okay if color variance only occurs on the x-axis (see photo below).

However setting Mesh.Colors is very slow.  For example, setting colors for 100,000 vertices takes ~10000 milliseconds.   How can I do this more performantly? Am I doing something wrong?

```<code>void CreateMesh()
{
    Mesh.Clear();
    Mesh.vertices = Vertices.ToArray();
    Mesh.triangles = Triangles.ToArray();

    // Set Colors to Mesh
    Color32[] colors = new Color32[] { new Color32(0, 255, 0, 255), new Color32(255, 0, 255, 255), new Color32(0, 0, 255, 255) };
    Color32[] colorsArray = new Color32[Mesh.vertices.Length];

    System.Random rnd = new System.Random();
    for (int i = 0; i < Mesh.vertices.Length; i++)
        colorsArray[i] = colors[rnd.Next(0, 2)];

    Mesh.colors32 = colorsArray;
}
</code>```

答:
So I didn't realize that Mesh.vertices.length does an array copy on every call. WHAT!?

Calculating the length before fixes this problem:

```<code>void CreateMesh()
{
    Mesh.Clear();
    Mesh.vertices = Vertices.ToArray();
    Mesh.triangles = Triangles.ToArray();
    Mesh.MarkDynamic();

    int len = Mesh.vertices.Length;

    // Set Colors to Mesh
    Color32[] colors = new Color32[] { new Color32(0, 255, 0, 255), new Color32(255, 0, 255, 255), new Color32(0, 0, 255, 255) };
    Color32[] colorsArray = new Color32[len];

    System.Random rnd = new System.Random();
    for (int i = 0; i < len; i++)
        colorsArray[i] = colors[rnd.Next(0, 2)];

    Mesh.colors32 = colorsArray;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Update (solved): The horrible performance was because I didn't realize that Mesh.vertices.Length does an Array copy on every call.

I need to procedurally generate a mesh of quads.   Ideally I would like to be able to change the color of individual quads.  However it's okay if color variance only occurs on the x-axis (see photo below).

However setting Mesh.Colors is very slow.  For example, setting colors for 100,000 vertices takes ~10000 milliseconds.   How can I do this more performantly? Am I doing something wrong?

void CreateMesh()
{
    Mesh.Clear();
    Mesh.vertices = Vertices.ToArray();
    Mesh.triangles = Triangles.ToArray();

    // Set Colors to Mesh
    Color32[] colors = new Color32[] { new Color32(0, 255, 0, 255), new Color32(255, 0, 255, 255), new Color32(0, 0, 255, 255) };
    Color32[] colorsArray = new Color32[Mesh.vertices.Length];

    System.Random rnd = new System.Random();
    for (int i = 0; i < Mesh.vertices.Length; i++)
        colorsArray[i] = colors[rnd.Next(0, 2)];

    Mesh.colors32 = colorsArray;
}

Body:
So I didn't realize that Mesh.vertices.length does an array copy on every call. WHAT!?

Calculating the length before fixes this problem:

void CreateMesh()
{
    Mesh.Clear();
    Mesh.vertices = Vertices.ToArray();
    Mesh.triangles = Triangles.ToArray();
    Mesh.MarkDynamic();

    int len = Mesh.vertices.Length;

    // Set Colors to Mesh
    Color32[] colors = new Color32[] { new Color32(0, 255, 0, 255), new Color32(255, 0, 255, 255), new Color32(0, 0, 255, 255) };
    Color32[] colorsArray = new Color32[len];

    System.Random rnd = new System.Random();
    for (int i = 0; i < len; i++)
        colorsArray[i] = colors[rnd.Next(0, 2)];

    Mesh.colors32 = colorsArray;
}


问:
How to show exactly 4 numbers after decimal point without rounding in Python?
I want to calculate square root of numbers and print them with exactly 4 numbers after decimal point without rounding.
This code rounds the numbers

```<code>num="%.4f" % num
</code>```

and this one doesn't show 1.0000 or numbers like this.

```<code>num=math.floor(num * 10000)/10000
</code>```

答:
Move the significant digits to the left of the decimal point, truncate it with ‘int’ and them move them back.</p>

```<code>num = float (int (num * 10000) / 10000)
print (num)
</code>```

Body:
I want to calculate square root of numbers and print them with exactly 4 numbers after decimal point without rounding.
This code rounds the numbers

num="%.4f" % num

and this one doesn't show 1.0000 or numbers like this.

num=math.floor(num * 10000)/10000

Body:
Move the significant digits to the left of the decimal point, truncate it with ‘int’ and them move them back.

num = float (int (num * 10000) / 10000)
print (num)


问:
Change Hyperlink behaviour in silverlight

```<code>    <StackPanel Orientation="Horizontal">
        <HyperlinkButton Content="Menue Item 1" FontSize="24" />
        <HyperlinkButton Content="Menue Item 2" FontSize="24" />
    </StackPanel>
</code>```

In Silverlight, How can I change its border color on selected item.

答:
Drop the following into your control resources:

```<code><Style TargetType="HyperlinkButton" x:name="NewHyperlinkControl">
    <Setter Property="Foreground" Value="#FF73A9D8" />
    <Setter Property="Padding" Value="2,0,2,0"/>
    <Setter Property="Cursor" Value="Hand"/>
    <Setter Property="HorizontalContentAlignment" Value="Left"/>
    <Setter Property="VerticalContentAlignment" Value="Top"/>
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="FontSize" Value="24"  /> <!-- Embedded your font size here -->
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="HyperlinkButton">
                <Grid Cursor="{TemplateBinding Cursor}" Background="{TemplateBinding Background}">
                    <vsm:VisualStateManager.VisualStateGroups>
                        <vsm:VisualStateGroup x:Name="CommonStates">
                            <vsm:VisualState x:Name="Normal"/>
                            <vsm:VisualState x:Name="MouseOver">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="UnderlineTextBlock" Storyboard.TargetProperty="Visibility" Duration="0">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="UnderlineTextBlock" Storyboard.TargetProperty="Visibility" Duration="0">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="DisabledOverlay" Storyboard.TargetProperty="Visibility" Duration="0">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </vsm:VisualState>
                        </vsm:VisualStateGroup>
                        <vsm:VisualStateGroup x:Name="FocusStates">
                            <vsm:VisualState x:Name="Focused">
                                <Storyboard>
                                    <DoubleAnimation   Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity" Duration="0" To="1"/>
                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="Unfocused"/>
                        </vsm:VisualStateGroup>
                    </vsm:VisualStateManager.VisualStateGroups>
                    <TextBlock
                        x:Name="UnderlineTextBlock"
                        Text="{TemplateBinding Content}"
                        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                        Margin="{TemplateBinding Padding}"
                        TextDecorations="Underline"
                        Visibility="Collapsed"/>
                    <TextBlock Canvas.ZIndex="1"
                        x:Name="DisabledOverlay"
                        Text="{TemplateBinding Content}"
                        Foreground="#FFAAAAAA"
                        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                        Margin="{TemplateBinding Padding}"
                        Visibility="Collapsed"/>
                    <ContentPresenter
                        x:Name="contentPresenter"
                        Content="{TemplateBinding Content}"
                        ContentTemplate="{TemplateBinding ContentTemplate}"
                        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                        Margin="{TemplateBinding Padding}"/>
                    <Rectangle x:Name="FocusVisualElement" Stroke="#FF6DBDD1" StrokeThickness="1" Opacity="0" IsHitTestVisible="false" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

and change the following line:

```<code><Rectangle x:Name="FocusVisualElement" Stroke="#FF6DBDD1" StrokeThickness="1" Opacity="0" IsHitTestVisible="false" />
</code>```

to be something like

```<code><Rectangle x:Name="FocusVisualElement" Stroke="#FF00FF00" StrokeThickness="1" Opacity="0" IsHitTestVisible="false" />
</code>```

and then set your control like so:

```<code>    <HyperlinkButton Content="Menue Item 2" Style="{StaticResource NewHyperlinkControl}" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
    <StackPanel Orientation="Horizontal">
        <HyperlinkButton Content="Menue Item 1" FontSize="24" />
        <HyperlinkButton Content="Menue Item 2" FontSize="24" />
    </StackPanel>

In Silverlight, How can I change its border color on selected item.

Body:
Drop the following into your control resources:

<Style TargetType="HyperlinkButton" x:name="NewHyperlinkControl">
    <Setter Property="Foreground" Value="#FF73A9D8" />
    <Setter Property="Padding" Value="2,0,2,0"/>
    <Setter Property="Cursor" Value="Hand"/>
    <Setter Property="HorizontalContentAlignment" Value="Left"/>
    <Setter Property="VerticalContentAlignment" Value="Top"/>
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="FontSize" Value="24"  /> <!-- Embedded your font size here -->
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="HyperlinkButton">
                <Grid Cursor="{TemplateBinding Cursor}" Background="{TemplateBinding Background}">
                    <vsm:VisualStateManager.VisualStateGroups>
                        <vsm:VisualStateGroup x:Name="CommonStates">
                            <vsm:VisualState x:Name="Normal"/>
                            <vsm:VisualState x:Name="MouseOver">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="UnderlineTextBlock" Storyboard.TargetProperty="Visibility" Duration="0">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="UnderlineTextBlock" Storyboard.TargetProperty="Visibility" Duration="0">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="DisabledOverlay" Storyboard.TargetProperty="Visibility" Duration="0">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </vsm:VisualState>
                        </vsm:VisualStateGroup>
                        <vsm:VisualStateGroup x:Name="FocusStates">
                            <vsm:VisualState x:Name="Focused">
                                <Storyboard>
                                    <DoubleAnimation   Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity" Duration="0" To="1"/>
                                </Storyboard>
                            </vsm:VisualState>
                            <vsm:VisualState x:Name="Unfocused"/>
                        </vsm:VisualStateGroup>
                    </vsm:VisualStateManager.VisualStateGroups>
                    <TextBlock
                        x:Name="UnderlineTextBlock"
                        Text="{TemplateBinding Content}"
                        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                        Margin="{TemplateBinding Padding}"
                        TextDecorations="Underline"
                        Visibility="Collapsed"/>
                    <TextBlock Canvas.ZIndex="1"
                        x:Name="DisabledOverlay"
                        Text="{TemplateBinding Content}"
                        Foreground="#FFAAAAAA"
                        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                        Margin="{TemplateBinding Padding}"
                        Visibility="Collapsed"/>
                    <ContentPresenter
                        x:Name="contentPresenter"
                        Content="{TemplateBinding Content}"
                        ContentTemplate="{TemplateBinding ContentTemplate}"
                        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                        Margin="{TemplateBinding Padding}"/>
                    <Rectangle x:Name="FocusVisualElement" Stroke="#FF6DBDD1" StrokeThickness="1" Opacity="0" IsHitTestVisible="false" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

and change the following line:

<Rectangle x:Name="FocusVisualElement" Stroke="#FF6DBDD1" StrokeThickness="1" Opacity="0" IsHitTestVisible="false" />

to be something like

<Rectangle x:Name="FocusVisualElement" Stroke="#FF00FF00" StrokeThickness="1" Opacity="0" IsHitTestVisible="false" />

and then set your control like so:

    <HyperlinkButton Content="Menue Item 2" Style="{StaticResource NewHyperlinkControl}" />


问:
Is there a way to turn a list of lists into a list with no other lists in it in Python?
Let's say I have a list of lists.

>>> my_list = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 0]]]
```

<p>Is there a way to take all the items from that list and make it a single, un-nested list?
Something like this:</p>

<pre class="lang-py prettyprint-override"><code>>>> break_up(my_list)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

</code>```

答:
This uses recursion</p>

```<code>def appnd(new_list = [], list_to_append=[]):
    for i in list_to_append:
        if type(i) == list:
            appnd(new_list=new_list, list_to_append=i)
        else:
            new_list.append(i)

def main():
    my_list = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 0]]]
    new_list = []
    appnd(new_list=new_list, list_to_append=my_list)
    print(new_list)

if __name__ == '__main__':
    main()
</code>```

Body:
Let's say I have a list of lists.

>>> my_list = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 0]]]

Is there a way to take all the items from that list and make it a single, un-nested list?
Something like this:

>>> break_up(my_list)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Body:
This uses recursion

def appnd(new_list = [], list_to_append=[]):
    for i in list_to_append:
        if type(i) == list:
            appnd(new_list=new_list, list_to_append=i)
        else:
            new_list.append(i)

def main():
    my_list = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 0]]]
    new_list = []
    appnd(new_list=new_list, list_to_append=my_list)
    print(new_list)

if __name__ == '__main__':
    main()


问:
How to change angular's default module
While learning about angular modules, I started wondering if we can change the angular's default module or not.
I tried it but failed.
Changes I made to the files:

I created a new dir under src directory named: core which contains the following class: core.module.ts

```<code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CoreComponent }  from './core.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ CoreComponent ],
  bootstrap:    [ CoreComponent ]
})
export class CoreModule { }
</code>```

core dir also contains the core.component.ts

```<code>import { Component } from "@angular/core";

@Component({
    selector: 'core',
    template: `<h2> Core Component Welcome you</h2>`
})
export class CoreComponent { }
</code>```

Following changes were made to the main.ts

```<code>import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { environment } from './environments/environment';
import { CoreModule } from './core/core.module';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(CoreModule)
  .catch(err => console.error(err));
</code>```

and index.html

```<code><core>loading core component</core>
</code>```

I know in real world scenario no one would bother changing the app module, but i just want to understand how things work, so if you can kindly help me understand how things are working, what am i missing, or if its not even possible to change the default module.

Update:
Console doesn't report any errors, but the content doesn't load. Instead of displaying (comes from core.component.ts template portion):

Core Component Welcome you.

It's only displaying (comes from index.html portion):

loading core component

答:
app.module is consider a root module and root module has just few difference from other angular module

1⃣ import BrowserModule

2⃣ one of the declared component at latest must add to bootstrap array

3⃣ add a element in the index.html match the bootstrap components selector

4⃣ set the new module as root module by pass a module refrence to bootstrapModule method of  platformBrowserDynamic object at main.ts.

core.module.ts

@NgModule({
  imports: [BrowserModule], //  1⃣
  declarations: [CoreComponent],
  bootstrap: [CoreComponent] //  2⃣
})
export class CoreModule {}
```

<p><em>index.html</em></p>

<pre class="lang-html prettyprint-override"><code><core>loading</core> <!-- //  3⃣-->
</code>```

main.ts

platformBrowserDynamic().bootstrapModule(CoreModule) //  4⃣
 .then(ref => {

 })
 .catch(err => console.error(err));
```

demo

check this bootstrapping  for more details.

Title: How to change angular's default module

Body:
While learning about angular modules, I started wondering if we can change the angular's default module or not.
I tried it but failed.
Changes I made to the files:

I created a new dir under src directory named: core which contains the following class: core.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CoreComponent }  from './core.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ CoreComponent ],
  bootstrap:    [ CoreComponent ]
})
export class CoreModule { }

core dir also contains the core.component.ts

import { Component } from "@angular/core";

@Component({
    selector: 'core',
    template: `<h2> Core Component Welcome you</h2>`
})
export class CoreComponent { }

Following changes were made to the main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { environment } from './environments/environment';
import { CoreModule } from './core/core.module';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(CoreModule)
  .catch(err => console.error(err));

and index.html

<core>loading core component</core>

I know in real world scenario no one would bother changing the app module, but i just want to understand how things work, so if you can kindly help me understand how things are working, what am i missing, or if its not even possible to change the default module.

Update:
Console doesn't report any errors, but the content doesn't load. Instead of displaying (comes from core.component.ts template portion):

Core Component Welcome you.

It's only displaying (comes from index.html portion):

loading core component

Body:
app.module is consider a root module and root module has just few difference from other angular module

1⃣ import BrowserModule

2⃣ one of the declared component at latest must add to bootstrap array

3⃣ add a element in the index.html match the bootstrap components selector

4⃣ set the new module as root module by pass a module refrence to bootstrapModule method of  platformBrowserDynamic object at main.ts.

core.module.ts

@NgModule({
  imports: [BrowserModule], //  1⃣
  declarations: [CoreComponent],
  bootstrap: [CoreComponent] //  2⃣
})
export class CoreModule {}

index.html

<core>loading</core> <!-- //  3⃣-->

main.ts

platformBrowserDynamic().bootstrapModule(CoreModule) //  4⃣
 .then(ref => {

 })
 .catch(err => console.error(err));

demo

check this bootstrapping  for more details.


问:
Implementing instanceof checks for custom typescript Error instances?
Typescript has this instanceof checks on custom errors issue, but it's not clear what we need to do to get instanceof working.  For example for this exception how would we get instanceof working:

```<code>    /**
     * @param message The error message
     * @param value The value that violates the constraint
     * @param field The name of the field
     * @param type The expected type for the field
     * @param constraint The name of the constraint violated
     * @param code The application or module code for the error
     */
    export class IsError extends Error {
      constructor(
        public message:string,
        public value: any,
        public field?:string,
        public type?: string,
        public constraint?: string,
        public code?:string) {
          super(message);
          this.name = 'IsError';
          Object.setPrototypeOf(this, IsError.prototype);
      }
    }
</code>```

This link says we can manually adjust the prototype, which is what I'm doing, but this test is not passing:

```<code>it("should be an instance of IsError", () => {
   let error = new IsError("This is an IsError", 'value');
   expect(error instanceof IsError)).toBeTruthy();
});
</code>```

Correction

I had an additional parenthesis in the test ...IsError)) that I mistook for the test not passing.  I updated the test and now it work.  So the example IsError implementation in this question is correct.

IIUC this implementation will not not work in ES5, but AFAIK clients that include CoreJS will be ok.

答:
Read https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work

Now, a complete implementation of @Mathyn and @TmTron answers:

```<code>/**
 * Base Error.
 */
class BaseError extends Error {
  constructor(message?: string) {
    const trueProto = new.target.prototype;
    super(message);
    Object.setPrototypeOf(this, trueProto);
  }
}

class Err1 extends BaseError {}
const e1 = new Err1();
console.log(e1 instanceof Err1); // true
console.log(e1 instanceof Error); // true

class Err2 extends Err1 {}
const e2 = new Err2();
console.log(e2 instanceof Err1); // true
console.log(e2 instanceof Err2); // true
console.log(e2 instanceof Error); // true

class NoBaseErr extends Error {}
const x = new NoBaseErr();
console.log(x instanceof Error); // true
console.log(x instanceof NoBaseErr); // false !!!
</code>```

Package

```<code>import BaseError from 'ts-base-error';
</code>```

See: https://www.npmjs.com/package/ts-base-error

Body:
Typescript has this instanceof checks on custom errors issue, but it's not clear what we need to do to get instanceof working.  For example for this exception how would we get instanceof working:

    /**
     * @param message The error message
     * @param value The value that violates the constraint
     * @param field The name of the field
     * @param type The expected type for the field
     * @param constraint The name of the constraint violated
     * @param code The application or module code for the error
     */
    export class IsError extends Error {
      constructor(
        public message:string,
        public value: any,
        public field?:string,
        public type?: string,
        public constraint?: string,
        public code?:string) {
          super(message);
          this.name = 'IsError';
          Object.setPrototypeOf(this, IsError.prototype);
      }
    }

This link says we can manually adjust the prototype, which is what I'm doing, but this test is not passing:

it("should be an instance of IsError", () => {
   let error = new IsError("This is an IsError", 'value');
   expect(error instanceof IsError)).toBeTruthy();
});

Correction

I had an additional parenthesis in the test ...IsError)) that I mistook for the test not passing.  I updated the test and now it work.  So the example IsError implementation in this question is correct.

IIUC this implementation will not not work in ES5, but AFAIK clients that include CoreJS will be ok.

Body:
Read https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work

Now, a complete implementation of @Mathyn and @TmTron answers:

/**
 * Base Error.
 */
class BaseError extends Error {
  constructor(message?: string) {
    const trueProto = new.target.prototype;
    super(message);
    Object.setPrototypeOf(this, trueProto);
  }
}

class Err1 extends BaseError {}
const e1 = new Err1();
console.log(e1 instanceof Err1); // true
console.log(e1 instanceof Error); // true

class Err2 extends Err1 {}
const e2 = new Err2();
console.log(e2 instanceof Err1); // true
console.log(e2 instanceof Err2); // true
console.log(e2 instanceof Error); // true

class NoBaseErr extends Error {}
const x = new NoBaseErr();
console.log(x instanceof Error); // true
console.log(x instanceof NoBaseErr); // false !!!

Package

import BaseError from 'ts-base-error';

See: https://www.npmjs.com/package/ts-base-error


问:
Can't resolve redux
I'm trying to use react-redux but keep getting this error whenever I import anything from redux or react-redux:

```<code>./node_modules/react-redux/es/index.js
Module not found: Can't resolve '/Users/danielcraig/Documents/ill/ill/node_modules/react-scripts/node_modules/babel-loader/lib/index.js' in '/Users/danielcraig/Documents/ill/ill'

</code>```

where the directory of my project is 'ill'.

Any idea on how to resolve?

答:
You need to install redux in order to be able to load react-redux</p>

```<code>npm install --save redux react-redux
</code>```

Title: Can't resolve redux

Body:
I'm trying to use react-redux but keep getting this error whenever I import anything from redux or react-redux:

./node_modules/react-redux/es/index.js
Module not found: Can't resolve '/Users/danielcraig/Documents/ill/ill/node_modules/react-scripts/node_modules/babel-loader/lib/index.js' in '/Users/danielcraig/Documents/ill/ill'

where the directory of my project is 'ill'.

Any idea on how to resolve?

Body:
You need to install redux in order to be able to load react-redux

npm install --save redux react-redux


问:
what is the use of route 53 in aws when ISPs can also route traffic into our instances
I know route 53 can route dns traffic into our instances . but  why specially need to use route 53 when ISPs  can also provide same routing.</p>

答:
If your instances are inside AWS, Route 53 has better options in terms of ways of routing. For instance, you can put an ELB in front of your instance(s) then tell Route 53 to use an ALIAS record type to route traffic to that ELB. This allows you to move your instances into a private subnet.

The benefits of this approach is that your instances are no longer "out in the open" on the internet with a public IP. And depending on how you configured your public IP if it is not an Elastic IP, you will lose it if you ever stop/start your instance.

The "best practice" is to put all your instances in a private subnet, setup a NAT gateway so they can access the internet, then put ELBs in front of the instances (with an SSL certificate so it can terminate SSL), and finally, setup Route 53 to forward requests over the ALIAS record type. If you start/stop the instance, or if it dies and you replace it, there is no reconfiguration.


问:
Facebook logout C# SDK
Hi

I am having trouble trying to logout of facebook using the FB C# SDK.

Here's a sample of my test

```<code>var oauth = new FacebookOAuthClient();
                    oauth.AppId = fbSection.AppId;
                    string bbc = @"http://www.bbc.co.uk";
                    var logoutParameters = new Dictionary<string, object>  {{ "next", bbc }} ;
                    this.NavigateUrl = oauth.GetLogoutUrl(logoutParameters).AbsoluteUri;
</code>```

The problem is that it´s always redirecting to:

```<code>http://m.facebook.com/
</code>```

I'm trying to redirect to an external site in this case bbc.co.uk, as in first case I tried redirecting to localhost and had the same problem.

I really wouldnt like to implement a javascript solution as I have already implemented my login functionality server side.

Any suggestions much appreciated.

答:
After some time searching I came across this post: http://forum.developers.facebook.net/viewtopic.php?id=87109

which suggests to call:

```<code>this.NavigateUrl =  https://www.facebook.com/logout.php?next=[redirect_uri]&access_token=[access_token]
</code>```

Which worked for me.

Title: Facebook logout C# SDK

Body:
Hi

I am having trouble trying to logout of facebook using the FB C# SDK.

Here's a sample of my test

var oauth = new FacebookOAuthClient();
                    oauth.AppId = fbSection.AppId;
                    string bbc = @"http://www.bbc.co.uk";
                    var logoutParameters = new Dictionary<string, object>  {{ "next", bbc }} ;
                    this.NavigateUrl = oauth.GetLogoutUrl(logoutParameters).AbsoluteUri;

The problem is that it´s always redirecting to:

http://m.facebook.com/

I'm trying to redirect to an external site in this case bbc.co.uk, as in first case I tried redirecting to localhost and had the same problem.

I really wouldnt like to implement a javascript solution as I have already implemented my login functionality server side.

Any suggestions much appreciated.

Body:
After some time searching I came across this post: http://forum.developers.facebook.net/viewtopic.php?id=87109

which suggests to call:

this.NavigateUrl =  https://www.facebook.com/logout.php?next=[redirect_uri]&access_token=[access_token]

Which worked for me.


问:
Get all "username" and "id" in MySQL database and split using php
I have MySQL database like this.

```<code>id........username
 1 .......rap
 2 .......dafy
 3 .......kay
</code>```

I want to make them like thies

```<code>username-id,username-id,use...
</code>```

for ex.

```<code>rap-1,dafy-2,kay-3
</code>```

the code should use the param to prevent the sql injection, but i have no idea how to write code.

答:
Use this query for a result:

```<code>SELECT GROUP_CONCAT(CONCAT(`username` , '-',`id`) SEPARATOR ',')
FROM table1;
</code>```

Result

```<code>GROUP_CONCAT(CONCAT(`username` , '-',`id`) SEPARATOR ',')
rap-1,dafy-2,kay-3 .
</code>```

Example PHP code with PDO:

```<code><?php
  $pdo = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $sql = "SELECT GROUP_CONCAT(CONCAT(`username` , '-',`id`) SEPARATOR ',') user FROM Table1";
  foreach ($pdo->query($sql) as $row) {
   echo $row['user']."<br />";
  }
  $pdo ->close();
</code>```

Body:
I have MySQL database like this.

id........username
 1 .......rap
 2 .......dafy
 3 .......kay

I want to make them like thies

username-id,username-id,use...

for ex.

rap-1,dafy-2,kay-3

the code should use the param to prevent the sql injection, but i have no idea how to write code.

Body:
Use this query for a result:

SELECT GROUP_CONCAT(CONCAT(`username` , '-',`id`) SEPARATOR ',')
FROM table1;

Result

GROUP_CONCAT(CONCAT(`username` , '-',`id`) SEPARATOR ',')
rap-1,dafy-2,kay-3 .

Example PHP code with PDO:

<?php
  $pdo = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $sql = "SELECT GROUP_CONCAT(CONCAT(`username` , '-',`id`) SEPARATOR ',') user FROM Table1";
  foreach ($pdo->query($sql) as $row) {
   echo $row['user']."<br />";
  }
  $pdo ->close();


问:
android-gts Setup android-gts on ubuntu16.04
I try to setup andorid-gts on ubuntu16.04. python version is 2.7.16. I have installed below packages:

```<code>pip install future
pip install protobuf
pip install auth
pip install compiler
pip install virtualenv
pip install PyPi
pip install google-cloud-storage
pip install oauth2client
</code>```

But when I try to run gts command from console, I always get below error:

```<code>android Google Mobile Services (GMS) Test Suite 7.0_r3 (6045416)
Use "help" or "help all" to get more information on running commands.
02-06 15:25:34 I/DeviceManager: Detected new device xxxxxxxx
gts-tf > run gts
02-06 15:25:39 I/TestInvocation: Starting invocation for 'gts' with '[ DeviceBuildInfo{bid=6045416, serial=xxxxxxxx} on device 'xxxxxxxx']
02-06 15:25:53 W/BusinessLogicPreparer: Option config-filename isn't set. Using empty string instead.
02-06 15:25:53 W/BusinessLogicPreparer: Option version isn't set. Using 'null' instead.
02-06 15:27:54 W/NativeDevice: TimeoutException () when attempting adb content on device xxxxxxxx
02-06 15:30:04 W/NativeDevice: TimeoutException () when attempting adb content on device xxxxxxxx
02-06 15:32:13 W/NativeDevice: TimeoutException () when attempting adb content on device xxxxxxxx
02-06 15:32:21 W/TestInvocation: Invocation did not complete due to device xxxxxxxx becoming not available. Reason: Attempted adb content multiple times on device xxxxxxxx without communication success. Aborting.
02-06 15:33:02 E/RunCommandTargetPreparer: Skipping command teardown since exception was DeviceNotAvailable
02-06 15:33:02 E/RunCommandTargetPreparer: Skipping command teardown since exception was DeviceNotAvailable
02-06 15:33:02 I/SuiteResultReporter:
============================================
================= Results ==================
=============== Consumed Time ==============
Total aggregated tests run time: 0 ms
=============== Summary ===============
Total Run time: 7m 22s
0/0 modules completed
Total Tests       : 0
PASSED            : 0
FAILED            : 0
============== End of Results ==============
============================================

gts-tf >
</code>```

I guess it maybe caused by the timeout logs:

```<code>02-06 15:27:54 W/NativeDevice: TimeoutException () when attempting adb content on device xxxxxxxx
</code>```

答: This error is caused by old adb version. just use adb version from android sdk should work. if you use sudo apt-get install adb, this timeout error will happen.

Body:
I try to setup andorid-gts on ubuntu16.04. python version is 2.7.16. I have installed below packages:

pip install future
pip install protobuf
pip install auth
pip install compiler
pip install virtualenv
pip install PyPi
pip install google-cloud-storage
pip install oauth2client

But when I try to run gts command from console, I always get below error:

android Google Mobile Services (GMS) Test Suite 7.0_r3 (6045416)
Use "help" or "help all" to get more information on running commands.
02-06 15:25:34 I/DeviceManager: Detected new device xxxxxxxx
gts-tf > run gts
02-06 15:25:39 I/TestInvocation: Starting invocation for 'gts' with '[ DeviceBuildInfo{bid=6045416, serial=xxxxxxxx} on device 'xxxxxxxx']
02-06 15:25:53 W/BusinessLogicPreparer: Option config-filename isn't set. Using empty string instead.
02-06 15:25:53 W/BusinessLogicPreparer: Option version isn't set. Using 'null' instead.
02-06 15:27:54 W/NativeDevice: TimeoutException () when attempting adb content on device xxxxxxxx
02-06 15:30:04 W/NativeDevice: TimeoutException () when attempting adb content on device xxxxxxxx
02-06 15:32:13 W/NativeDevice: TimeoutException () when attempting adb content on device xxxxxxxx
02-06 15:32:21 W/TestInvocation: Invocation did not complete due to device xxxxxxxx becoming not available. Reason: Attempted adb content multiple times on device xxxxxxxx without communication success. Aborting.
02-06 15:33:02 E/RunCommandTargetPreparer: Skipping command teardown since exception was DeviceNotAvailable
02-06 15:33:02 E/RunCommandTargetPreparer: Skipping command teardown since exception was DeviceNotAvailable
02-06 15:33:02 I/SuiteResultReporter:
============================================
================= Results ==================
=============== Consumed Time ==============
Total aggregated tests run time: 0 ms
=============== Summary ===============
Total Run time: 7m 22s
0/0 modules completed
Total Tests       : 0
PASSED            : 0
FAILED            : 0
============== End of Results ==============
============================================

gts-tf >

I guess it maybe caused by the timeout logs:

02-06 15:27:54 W/NativeDevice: TimeoutException () when attempting adb content on device xxxxxxxx


问:
show/hide buttons on resizable navbar
I have a nivagation bar with button links in row on resize the window to smaller width each button wrap underneath which changing the navigation height, gets removed from the nav and appended into a dropdown menu.

I managed to append wrapped buttons when the navigation height is higher than 80, but it will only work if the initial size of the screen is big which will have all buttons in one row. but if the screen started at a smaller width it won't append all wrapped buttons in the menu.

80">

Here is my attempt

$(window).resize(function() {
  var navbar = $("#navbar");
  var list = $("#list");
  var btns = $("#btns");
  var last_element;
  for (var i = 0; i < list.children().length; i++) {
    setTimeout(function() {
      if (list.height() > 80) {
        last_element = list.children().last();
        setTimeout(function() {
          $("#btns .dropdown-menu").prepend(last_element);
        }, 300);
        last_element.remove();
      }
    }, 500);

  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#navbar {
  width: fit-content;
  background-color: #dbdbdb;
  box-shadow: 2px 2px 2px #999;
  border-radius: 10px;
  padding: 10px;
}

#list {
  margin: 0;
  padding: 0;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
}

.item {
  color: #333;
  font-size: 30px;
  font-weight: bold;
  background-color: #f5f5f5;
  /*    display: inline-block; */
  padding: 10px 30px;
  border-radius: 5px;
  box-shadow: 2px 2px 2px #888;
  margin: 4px 2px;
  list-style-type: none;
}

.dropdown-menu {
  width: 200px;
  padding: 0 20px;
}</code>```

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

item 1

item 2

item 3

item 4

item 5

item 6

item 7

      <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Dropdown button
         </button>

```

I would love to have similar action to this image,

Can someone offer a snippet suggestion or what should I use to implement such action?

答:
Updated - move hidden items to dropdown menu

First, make changes on css:

apply display: flex to #navbar.

calculate the maximum height of #list manually and set max-height & overflow: hidden property to it. In this case, the maximum height of #list would be 73px but not 80px. (the height of .item 65px + top margin of .item 4px + bottom margin of .item 4px = 73px) If the max-height is not correct, #list may not hide the .items properly.

set display: inline-block for .items.

`

```<code>#navbar{
   width: fit-content;
   background-color: #dbdbdb;
   box-shadow: 2px 2px 2px #999;
   border-radius: 10px;
   padding: 10px;

   /*Flex layout*/
   display:flex;
   flex-direction:row;
   align-items:center;
}

#list{
   margin: 0;
   padding: 0;

   /*Calculate the max-height and set overflow hidden*/
   overflow:hidden;
   max-height:73px;
}

.item{
   color: #333;
   font-size: 30px;
   font-weight: bold;
   background-color: #f5f5f5;
   display: inline-block;
   padding: 10px 30px;
   border-radius: 5px;
   box-shadow: 2px 2px 2px #888;
   margin: 4px 2px;
   list-style-type: none;

   /*Move text-align center to here*/
   text-align: center;

   /*Remove flex layout & add display inline-block*/
   display: inline-block;

}

.dropdown-menu{
   width: 200px;
   padding: 0 20px;
}
</code>```

`

Then, update the $(window).resize() function.
The below code will check if the item is being moved to a hidden area. Moreover, use .html() to refresh the dropdown menu.

```<code>let list = $("#list");
let listItems = $("#list .item");
let dropdownMenu = $("#btns .dropdown-menu");

$(window).resize(function() {
    let listPosition = list.position().top;
    let hiddenItems = listItems.filter(function(){
    return $(this).position().top - listPosition > 0;
  }).clone();
    dropdownMenu.html(hiddenItems);
});
</code>```

Title: show/hide buttons on resizable navbar

Body:
I have a nivagation bar with button links in row on resize the window to smaller width each button wrap underneath which changing the navigation height, gets removed from the nav and appended into a dropdown menu.

I managed to append wrapped buttons when the navigation height is higher than 80, but it will only work if the initial size of the screen is big which will have all buttons in one row. but if the screen started at a smaller width it won't append all wrapped buttons in the menu.

80">

Here is my attempt

$(window).resize(function() {
  var navbar = $("#navbar");
  var list = $("#list");
  var btns = $("#btns");
  var last_element;
  for (var i = 0; i < list.children().length; i++) {
    setTimeout(function() {
      if (list.height() > 80) {
        last_element = list.children().last();
        setTimeout(function() {
          $("#btns .dropdown-menu").prepend(last_element);
        }, 300);
        last_element.remove();
      }
    }, 500);

  }
});

#navbar {
  width: fit-content;
  background-color: #dbdbdb;
  box-shadow: 2px 2px 2px #999;
  border-radius: 10px;
  padding: 10px;
}

#list {
  margin: 0;
  padding: 0;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
}

.item {
  color: #333;
  font-size: 30px;
  font-weight: bold;
  background-color: #f5f5f5;
  /*    display: inline-block; */
  padding: 10px 30px;
  border-radius: 5px;
  box-shadow: 2px 2px 2px #888;
  margin: 4px 2px;
  list-style-type: none;
}

.dropdown-menu {
  width: 200px;
  padding: 0 20px;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

item 1

item 2

item 3

item 4

item 5

item 6

item 7

      <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Dropdown button
         </button>

I would love to have similar action to this image,

Can someone offer a snippet suggestion or what should I use to implement such action?

Body:
Updated - move hidden items to dropdown menu

First, make changes on css:

apply display: flex to #navbar.

calculate the maximum height of #list manually and set max-height & overflow: hidden property to it. In this case, the maximum height of #list would be 73px but not 80px. (the height of .item 65px + top margin of .item 4px + bottom margin of .item 4px = 73px) If the max-height is not correct, #list may not hide the .items properly.

set display: inline-block for .items.

`

#navbar{
   width: fit-content;
   background-color: #dbdbdb;
   box-shadow: 2px 2px 2px #999;
   border-radius: 10px;
   padding: 10px;

   /*Flex layout*/
   display:flex;
   flex-direction:row;
   align-items:center;
}

#list{
   margin: 0;
   padding: 0;

   /*Calculate the max-height and set overflow hidden*/
   overflow:hidden;
   max-height:73px;
}

.item{
   color: #333;
   font-size: 30px;
   font-weight: bold;
   background-color: #f5f5f5;
   display: inline-block;
   padding: 10px 30px;
   border-radius: 5px;
   box-shadow: 2px 2px 2px #888;
   margin: 4px 2px;
   list-style-type: none;

   /*Move text-align center to here*/
   text-align: center;

   /*Remove flex layout & add display inline-block*/
   display: inline-block;

}

.dropdown-menu{
   width: 200px;
   padding: 0 20px;
}

`

Then, update the $(window).resize() function.
The below code will check if the item is being moved to a hidden area. Moreover, use .html() to refresh the dropdown menu.

let list = $("#list");
let listItems = $("#list .item");
let dropdownMenu = $("#btns .dropdown-menu");

$(window).resize(function() {
    let listPosition = list.position().top;
    let hiddenItems = listItems.filter(function(){
    return $(this).position().top - listPosition > 0;
  }).clone();
    dropdownMenu.html(hiddenItems);
});


问:
Hibernate HQL and fetching with grouping
We have a hibernate pojo Reporting/ReportingID that has several properties that contain counts, dates, actions, and devices.  The device property mapped to a hibernate pojo called Device (note: I want it to fetch the device so I don't have to query it separately).

So what I have is a HQL that looks like this:

```<code>"SELECT sum(report.deviceTotal), sum(report.settledPricePerDownloadExpense), report.id.device, avg(report.settledPricePerDownloadExpense), report.id.dCampaignActionTypeId " +
"FROM Reporting report " +
"WHERE report.id.dCampaignReportDate between :startDate and :endDate " +
"AND report.id.dCampaignActionTypeId in (:actionIds) " +
"AND report.id.dCampaign.dCampaignId in (:campaigns) " +
"GROUP by report.id.dCampaignActionTypeId, report.id.device " +
"ORDER by 1";
</code>```

I though that that would work, but I get this error:

```<code>Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Column 'dbo.device.device_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1493)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:390)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:340)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:179)
</code>```

What I get from this is is that I have to list every column in the device table in the group by clause which seems wacky?

答:
Writing

```<code>group by something
</code>```

in HQL where something is an entity gets translated into

```<code>group by entity_id1, entity_id2 ...
</code>```

in SQL where entity_id1, entity_id2, etc. are columns to which entity's id properties are mapped. In case of simple (rather than composite / component) identifier there would only be a single column.

This works fine for regular queries and presents obvious problems for "join fetch" selects. There are no workarounds - you will need to explicitly list all properties individually under group by.

The  other approach (which may or may not be suitable - impossible to say without knowing a lot more about your model) is to avoid using join fetch and instead cache your entities (via Session's and / or 2nd level cache) thus retrieving (and grouping by) only entity id.

Body:
We have a hibernate pojo Reporting/ReportingID that has several properties that contain counts, dates, actions, and devices.  The device property mapped to a hibernate pojo called Device (note: I want it to fetch the device so I don't have to query it separately).

So what I have is a HQL that looks like this:

"SELECT sum(report.deviceTotal), sum(report.settledPricePerDownloadExpense), report.id.device, avg(report.settledPricePerDownloadExpense), report.id.dCampaignActionTypeId " +
"FROM Reporting report " +
"WHERE report.id.dCampaignReportDate between :startDate and :endDate " +
"AND report.id.dCampaignActionTypeId in (:actionIds) " +
"AND report.id.dCampaign.dCampaignId in (:campaigns) " +
"GROUP by report.id.dCampaignActionTypeId, report.id.device " +
"ORDER by 1";

I though that that would work, but I get this error:

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Column 'dbo.device.device_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1493)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:390)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:340)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:179)

What I get from this is is that I have to list every column in the device table in the group by clause which seems wacky?

Body:
Writing

group by something

in HQL where something is an entity gets translated into

group by entity_id1, entity_id2 ...

in SQL where entity_id1, entity_id2, etc. are columns to which entity's id properties are mapped. In case of simple (rather than composite / component) identifier there would only be a single column.

This works fine for regular queries and presents obvious problems for "join fetch" selects. There are no workarounds - you will need to explicitly list all properties individually under group by.

The  other approach (which may or may not be suitable - impossible to say without knowing a lot more about your model) is to avoid using join fetch and instead cache your entities (via Session's and / or 2nd level cache) thus retrieving (and grouping by) only entity id.


问:
How to make a batch script to execute from anywhere?
I would like to run my batch script from anywhere, for example:

```<code>C:\>test123
</code>```

And that command line executes my batch script C:\Documents\test123.bat.

I tried to do it with environment variable path, but it doesn't seem to work.

答:
Add your bat to PATH and make sure PATHEXT contains .BAT

How to add your program to the PATH env variable

Note, that the current working directory will be whereever you called it from.
If you want relative paths to where the bat is stored, use %~dp0

Please post the output of echo %PATHEXT% %PATH% and tell us the exact location of your bat file and more error info why it failed in your case?

Body:
I would like to run my batch script from anywhere, for example:

C:\>test123

And that command line executes my batch script C:\Documents\test123.bat.

I tried to do it with environment variable path, but it doesn't seem to work.


问:
Can’t find how to edit push notifications title and content within code - Android Studio
I’ve bought application template and I can’t figure out in code where to change push notification title and content (Firebase as message provider platform). Developer is unreachable and I can’t go further with project.

For example instead push “You have new message” I want to have “You have ONE new message”; I searched through whole code without success.

Also - is there any way push notifications can be translated to multiple languages?

Edit

There is no Firebase Extending Service in source file related to messaging, only to phone authentication.

Sample of code:

```<code>package com.innomalist.taxi.driver.activities.splash

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.databinding.DataBindingUtil
import com.crashlytics.android.Crashlytics
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.AuthUI.IdpConfig.PhoneBuilder
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.iid.FirebaseInstanceId
import com.gun0912.tedpermission.PermissionListener
import com.gun0912.tedpermission.TedPermission
import com.innomalist.taxi.common.components.BaseActivity
import com.innomalist.taxi.common.interfaces.AlertDialogEvent
import com.innomalist.taxi.common.networking.socket.interfaces.ConnectionError
import com.innomalist.taxi.common.networking.socket.interfaces.Namespace
import com.innomalist.taxi.common.networking.socket.interfaces.RemoteResponse
import com.innomalist.taxi.common.networking.socket.interfaces.SocketNetworkDispatcher
import com.innomalist.taxi.common.utils.AlertDialogBuilder
import com.innomalist.taxi.common.utils.AlertDialogBuilder.DialogResult
import com.innomalist.taxi.common.utils.AlertDialogBuilder.show
import com.innomalist.taxi.common.utils.AlerterHelper.showError
import com.innomalist.taxi.common.utils.CommonUtils.isGPSEnabled
import com.innomalist.taxi.common.utils.CommonUtils.isInternetDisabled
import com.innomalist.taxi.common.utils.MyPreferenceManager.Companion.getInstance
import com.innomalist.taxi.driver.R
import com.innomalist.taxi.driver.activities.main.MainActivity
import com.innomalist.taxi.driver.activities.profile.ProfileActivity
import com.innomalist.taxi.driver.databinding.ActivitySplashBinding
import com.innomalist.taxi.driver.networking.http.GetRegisterInfo
import com.innomalist.taxi.driver.networking.http.Login
import com.innomalist.taxi.driver.networking.http.LoginResult
import com.innomalist.taxi.driver.networking.http.RegistrationInfo
import io.fabric.sdk.android.Fabric
import java.lang.Exception

class SplashActivity : BaseActivity() {
    private lateinit var binding: ActivitySplashBinding
    private var SIGN_IN_ACTIVITY = 123
    private var startRequested = false
    private val permissionListener: PermissionListener = object : PermissionListener {
        override fun onPermissionDenied(deniedPermissions: List<String>) {
            show(this@SplashActivity,"It is not possible to run the app as driver without location permission. Given that you have already didn't approved location access you can now go to settings and enabled it. Then you can close app and open it again to access.", AlertDialogBuilder.DialogButton.OK, AlertDialogEvent {
                checkPermissions()
            })
        }
        override fun onPermissionGranted() {
            if(getInstance(applicationContext).token != null) {
                tryConnect(getInstance(applicationContext).token!!)
            } else {
                goToLoginMode()
            }
        }
    }
    private val onLoginClicked = View.OnClickListener {
        startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setAvailableProviders(listOf(PhoneBuilder().build()))
                        .setLogo(R.drawable.logo)
                        .setTheme(currentTheme)
                        .build(),
                SIGN_IN_ACTIVITY)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        isImmersive = true
        super.onCreate(savedInstanceState)
        if (getString(R.string.fabric_key) != "") {
            Fabric.with(this, Crashlytics())
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_splash)
        binding.loginButton.setOnClickListener(onLoginClicked)
        checkPermissions()
    }

    private fun checkPermissions() {
        if (!isGPSEnabled(this)) {
            show(this, getString(R.string.message_enable_gps), AlertDialogBuilder.DialogButton.CANCEL_RETRY, AlertDialogEvent { result: DialogResult ->
                if (result === DialogResult.RETRY) {
                    checkPermissions()
                } else {
                    finishAffinity()
                }
            })
            return
        }
        if (isInternetDisabled(this)) {
            show(this, getString(R.string.message_internet_connection), AlertDialogBuilder.DialogButton.CANCEL_RETRY, AlertDialogEvent { result: DialogResult ->
                if (result === DialogResult.RETRY) {
                    checkPermissions()
                } else {
                    finishAffinity()
                }
            })
            return
        }
        TedPermission.with(this)
                .setPermissionListener(permissionListener)
                .setDeniedMessage(getString(R.string.message_permission_denied))
                .setPermissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .check()
    }

    fun tryConnect(jwtToken: String) {
        FirebaseInstanceId.getInstance().instanceId.addOnCompleteListener {fb ->
            SocketNetworkDispatcher.instance.connect(Namespace.Driver, jwtToken, fb.result?.token ?: "") {
                when (it) {
                    is RemoteResponse.Success -> {
                        startMainActivity()
                    }

                    is RemoteResponse.Error -> {
                        when (it.error) {
                            ConnectionError.RegistrationIncomplete -> {
                                runOnUiThread {
                                    showRegisterForm(jwtToken)
                                }
                            }

                            else -> {
                                runOnUiThread {
                                    goToLoginMode()
                                    try {
                                        it.error.showAlert(this)
                                    } catch (exception: Exception) {

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun showRegisterForm(jwtToken: String) {
        GetRegisterInfo(jwtToken).execute<RegistrationInfo> {
            when(it) {
                is RemoteResponse.Success -> {
                    runOnUiThread {
                        preferences.driver = it.body.driver
                        preferences.services = ArrayList(it.body.services)
                        val intent = Intent(this@SplashActivity, ProfileActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                        startActivity(intent)
                    }
                }

                is RemoteResponse.Error -> {
                    //it.error.showAlert(this)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if(preferences.token != null) {
            tryConnect(preferences.token!!)
        }
    }

    private fun startMainActivity() {
        if (startRequested) return
        startRequested = true
        val intent = Intent(this@SplashActivity, MainActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
    }

    private fun tryLogin(firebaseToken: String) {
        goToLoadingMode()
        Login(firebaseToken).execute<LoginResult> {
            when(it) {
                is RemoteResponse.Success -> {
                    getInstance(applicationContext).driver = it.body.user
                    getInstance(applicationContext).token = it.body.token
                    tryConnect(it.body.token)
                }
                is RemoteResponse.Error -> {
                    showError(this, it.error.localizedDescription)
                }
            }
        }
    }

    private fun goToLoadingMode() {
        binding.loginButton.visibility = View.GONE
        binding.progressBar.visibility = View.VISIBLE
    }

    private fun goToLoginMode() {
        binding.loginButton.visibility = View.VISIBLE
        binding.progressBar.visibility = View.GONE
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SIGN_IN_ACTIVITY) {
            if (resultCode == Activity.RESULT_OK) {
                FirebaseAuth.getInstance().currentUser!!.getIdToken(false).addOnCompleteListener {
                    tryLogin(it.result!!.token!!)
                }
                return
            }
            showError(this@SplashActivity, getString(R.string.login_failed))
            goToLoginMode()
        }
    }
}
</code>```

ADDITIONAL INFO

Let me explain you nature of message: There's TWO apps - driver and passenger: when passenger do something, for example - ask for near driver, all drivers nearby recieves push message - You have one new request. Also, for example - when payment made - passenger recieves message - Payment settled. Wher's this stored, for God's sake :)

GRADLE FILES

There are THREE modules inside of app - common, driver & rider, and FOUR gradle.build files.

Common Module Gradle

```<code>apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'
    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 1
        versionName '1.0.0'
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled true
    }
}

dependencies {
    api 'androidx.multidex:multidex:2.0.1'
    api 'androidx.recyclerview:recyclerview-selection:1.1.0-beta01'
    api 'androidx.constraintlayout:constraintlayout:2.0.0-beta4'
    api 'com.google.android.material:material:1.2.0-alpha03'
    api 'com.google.android.gms:play-services-maps:17.0.0'
    api 'com.google.android.gms:play-services-location:17.0.0'
    api 'com.google.firebase:firebase-messaging:20.1.0'
    api 'com.firebaseui:firebase-ui:6.2.0'
    api('io.socket:socket.io-client:1.0.0') {
        exclude group: 'org.json', module: 'json'
    }
    api('com.crashlytics.sdk.android:crashlytics:2.10.1@aar') {
        transitive = true
    }
    api 'com.google.maps.android:android-maps-utils:0.6.2'
    api 'com.github.medyo:android-about-page:1.2.4'
    api 'com.squareup.moshi:moshi:1.9.2'
    api 'com.squareup.moshi:moshi-kotlin:1.9.2'
    kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.9.2'
    api 'de.psdev.licensesdialog:licensesdialog:2.1.0'
    api 'com.github.tylersuehr7:empty-state-recyclerview:1.0.4'
    api 'com.github.yalantis:ucrop:2.2.4'
    api 'com.github.esafirm.android-image-picker:imagepicker:2.2.0'
    api 'com.github.bumptech.glide:glide:4.10.0'
    api 'com.tapadoo.android:alerter:5.0.0'
    api 'gun0912.ted:tedpermission:2.2.2'
    api 'com.github.stfalcon:chatkit:0.3.3'
    api('com.stripe:stripe-android:12.8.2@aar') {
        transitive = true
    }
    api 'com.github.MAXDeliveryNG:slideview:1.1.0'
    api 'com.braintreepayments.api:drop-in:3.7.1'
    api 'com.airbnb.android:lottie:3.3.1'

    //noinspection LifecycleAnnotationProcessorWithJava8
    kapt 'androidx.lifecycle:lifecycle-compiler:2.2.0'
    api 'androidx.preference:preference-ktx:1.1.0'
    api 'androidx.core:core-ktx:1.1.0'
    api "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    api "org.jetbrains.kotlin:kotlin-script-runtime:1.3.61"
    api 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
    api 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'
}
</code>```

Driver Module Gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'
    defaultConfig {
        applicationId 'com.ldrive.taxi.driver'
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 35
        versionName '3.0.9'
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
    }
    signingConfigs {
        release {
            storeFile file(RELEASE_STORE_FILE)
            storePassword RELEASE_STORE_PASSWORD
            keyAlias RELEASE_KEY_ALIAS
            keyPassword RELEASE_KEY_PASSWORD
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    api project(':common')
    api 'com.diogobernardino:williamchart:3.3.0'
}
apply plugin: 'com.google.gms.google-services'
repositories {
    mavenCentral()
}
</code>```

Passenger/Rider Module Gradle

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'
    defaultConfig {
        applicationId "com.ldrive.taxi.rider"
        minSdkVersion 19
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 35
        versionName "3.0.9"
        vectorDrawables.useSupportLibrary = true
        dexOptions {
            jumboMode true
        }
    }
    if (project.hasProperty("RELEASE_KEY_ALIAS")) {
        signingConfigs {
            release {
                storeFile file(RELEASE_STORE_FILE)
                storePassword RELEASE_STORE_PASSWORD
                keyAlias RELEASE_KEY_ALIAS
                keyPassword RELEASE_KEY_PASSWORD
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    api project(':common')
    implementation 'com.github.Innomalist:floatingsearchview:0.3'
    implementation ('com.google.android.libraries.places:places:2.1.0')
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
    testImplementation 'junit:junit:4.12'
}
configurations {
    all*.exclude group: 'com.google.guava', module: 'listenablefuture'
}
apply plugin: 'com.google.gms.google-services'
</code>```

PROJECT GRADLE

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.61'
    repositories {
        maven { url "https://maven.google.com" }
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
        google()
        maven { url 'https://plugins.gradle.org/m2/'}
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'io.fabric.tools:gradle:1.29.0'
        classpath 'com.google.gms:google-services:4.2.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        maven { url "https://maven.google.com" }
        jcenter()
        mavenCentral()
        google()
        maven { url "https://jitpack.io" }
        maven { url 'https://maven.fabric.io/public' }
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
Try to search for a class that extends FirebaseMessagingService. This is where all FCM service is set.

Edit

This is how I customise my notifications in my own app:

```<code>Intent intent = new Intent(this, BOBusinessHomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

Notification notification =
    new NotificationCompat.Builder(getApplicationContext(), "0")
    .setSmallIcon(R.drawable.business_icon)
    .setContentTitle("A client has posted a new review in your business page!")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setContentIntent(pendingIntent)
    .setAutoCancel(true)
    .build();
mNotificationManager.notify(0, notification);
</code>```

Try to search "Notification" or any type of template similar to above in your project.

Or, try to search callback  method named onMessageReceived().

Explanation

By default, your app won’t display any FCM messages it receives while it’s in the foreground, so when you send a message there’s no guarantee your users will actually see that message.

To act on the messages your app receives while it’s in the foreground, you’ll need to extend the FirebaseMessagingService, override the onMessageReceived method, and then retrieve the message’s content using either getNotification or getData, depending on whether you’re working with data or notification messages, or both.

Body:
I’ve bought application template and I can’t figure out in code where to change push notification title and content (Firebase as message provider platform). Developer is unreachable and I can’t go further with project.

For example instead push “You have new message” I want to have “You have ONE new message”; I searched through whole code without success.

Also - is there any way push notifications can be translated to multiple languages?

Edit

There is no Firebase Extending Service in source file related to messaging, only to phone authentication.

Sample of code:

package com.innomalist.taxi.driver.activities.splash

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.databinding.DataBindingUtil
import com.crashlytics.android.Crashlytics
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.AuthUI.IdpConfig.PhoneBuilder
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.iid.FirebaseInstanceId
import com.gun0912.tedpermission.PermissionListener
import com.gun0912.tedpermission.TedPermission
import com.innomalist.taxi.common.components.BaseActivity
import com.innomalist.taxi.common.interfaces.AlertDialogEvent
import com.innomalist.taxi.common.networking.socket.interfaces.ConnectionError
import com.innomalist.taxi.common.networking.socket.interfaces.Namespace
import com.innomalist.taxi.common.networking.socket.interfaces.RemoteResponse
import com.innomalist.taxi.common.networking.socket.interfaces.SocketNetworkDispatcher
import com.innomalist.taxi.common.utils.AlertDialogBuilder
import com.innomalist.taxi.common.utils.AlertDialogBuilder.DialogResult
import com.innomalist.taxi.common.utils.AlertDialogBuilder.show
import com.innomalist.taxi.common.utils.AlerterHelper.showError
import com.innomalist.taxi.common.utils.CommonUtils.isGPSEnabled
import com.innomalist.taxi.common.utils.CommonUtils.isInternetDisabled
import com.innomalist.taxi.common.utils.MyPreferenceManager.Companion.getInstance
import com.innomalist.taxi.driver.R
import com.innomalist.taxi.driver.activities.main.MainActivity
import com.innomalist.taxi.driver.activities.profile.ProfileActivity
import com.innomalist.taxi.driver.databinding.ActivitySplashBinding
import com.innomalist.taxi.driver.networking.http.GetRegisterInfo
import com.innomalist.taxi.driver.networking.http.Login
import com.innomalist.taxi.driver.networking.http.LoginResult
import com.innomalist.taxi.driver.networking.http.RegistrationInfo
import io.fabric.sdk.android.Fabric
import java.lang.Exception

class SplashActivity : BaseActivity() {
    private lateinit var binding: ActivitySplashBinding
    private var SIGN_IN_ACTIVITY = 123
    private var startRequested = false
    private val permissionListener: PermissionListener = object : PermissionListener {
        override fun onPermissionDenied(deniedPermissions: List<String>) {
            show(this@SplashActivity,"It is not possible to run the app as driver without location permission. Given that you have already didn't approved location access you can now go to settings and enabled it. Then you can close app and open it again to access.", AlertDialogBuilder.DialogButton.OK, AlertDialogEvent {
                checkPermissions()
            })
        }
        override fun onPermissionGranted() {
            if(getInstance(applicationContext).token != null) {
                tryConnect(getInstance(applicationContext).token!!)
            } else {
                goToLoginMode()
            }
        }
    }
    private val onLoginClicked = View.OnClickListener {
        startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setAvailableProviders(listOf(PhoneBuilder().build()))
                        .setLogo(R.drawable.logo)
                        .setTheme(currentTheme)
                        .build(),
                SIGN_IN_ACTIVITY)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        isImmersive = true
        super.onCreate(savedInstanceState)
        if (getString(R.string.fabric_key) != "") {
            Fabric.with(this, Crashlytics())
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_splash)
        binding.loginButton.setOnClickListener(onLoginClicked)
        checkPermissions()
    }

    private fun checkPermissions() {
        if (!isGPSEnabled(this)) {
            show(this, getString(R.string.message_enable_gps), AlertDialogBuilder.DialogButton.CANCEL_RETRY, AlertDialogEvent { result: DialogResult ->
                if (result === DialogResult.RETRY) {
                    checkPermissions()
                } else {
                    finishAffinity()
                }
            })
            return
        }
        if (isInternetDisabled(this)) {
            show(this, getString(R.string.message_internet_connection), AlertDialogBuilder.DialogButton.CANCEL_RETRY, AlertDialogEvent { result: DialogResult ->
                if (result === DialogResult.RETRY) {
                    checkPermissions()
                } else {
                    finishAffinity()
                }
            })
            return
        }
        TedPermission.with(this)
                .setPermissionListener(permissionListener)
                .setDeniedMessage(getString(R.string.message_permission_denied))
                .setPermissions(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .check()
    }

    fun tryConnect(jwtToken: String) {
        FirebaseInstanceId.getInstance().instanceId.addOnCompleteListener {fb ->
            SocketNetworkDispatcher.instance.connect(Namespace.Driver, jwtToken, fb.result?.token ?: "") {
                when (it) {
                    is RemoteResponse.Success -> {
                        startMainActivity()
                    }

                    is RemoteResponse.Error -> {
                        when (it.error) {
                            ConnectionError.RegistrationIncomplete -> {
                                runOnUiThread {
                                    showRegisterForm(jwtToken)
                                }
                            }

                            else -> {
                                runOnUiThread {
                                    goToLoginMode()
                                    try {
                                        it.error.showAlert(this)
                                    } catch (exception: Exception) {

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private fun showRegisterForm(jwtToken: String) {
        GetRegisterInfo(jwtToken).execute<RegistrationInfo> {
            when(it) {
                is RemoteResponse.Success -> {
                    runOnUiThread {
                        preferences.driver = it.body.driver
                        preferences.services = ArrayList(it.body.services)
                        val intent = Intent(this@SplashActivity, ProfileActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                        startActivity(intent)
                    }
                }

                is RemoteResponse.Error -> {
                    //it.error.showAlert(this)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if(preferences.token != null) {
            tryConnect(preferences.token!!)
        }
    }

    private fun startMainActivity() {
        if (startRequested) return
        startRequested = true
        val intent = Intent(this@SplashActivity, MainActivity::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        startActivity(intent)
    }

    private fun tryLogin(firebaseToken: String) {
        goToLoadingMode()
        Login(firebaseToken).execute<LoginResult> {
            when(it) {
                is RemoteResponse.Success -> {
                    getInstance(applicationContext).driver = it.body.user
                    getInstance(applicationContext).token = it.body.token
                    tryConnect(it.body.token)
                }
                is RemoteResponse.Error -> {
                    showError(this, it.error.localizedDescription)
                }
            }
        }
    }

    private fun goToLoadingMode() {
        binding.loginButton.visibility = View.GONE
        binding.progressBar.visibility = View.VISIBLE
    }

    private fun goToLoginMode() {
        binding.loginButton.visibility = View.VISIBLE
        binding.progressBar.visibility = View.GONE
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SIGN_IN_ACTIVITY) {
            if (resultCode == Activity.RESULT_OK) {
                FirebaseAuth.getInstance().currentUser!!.getIdToken(false).addOnCompleteListener {
                    tryLogin(it.result!!.token!!)
                }
                return
            }
            showError(this@SplashActivity, getString(R.string.login_failed))
            goToLoginMode()
        }
    }
}

ADDITIONAL INFO

Let me explain you nature of message: There's TWO apps - driver and passenger: when passenger do something, for example - ask for near driver, all drivers nearby recieves push message - You have one new request. Also, for example - when payment made - passenger recieves message - Payment settled. Wher's this stored, for God's sake :)

GRADLE FILES

There are THREE modules inside of app - common, driver & rider, and FOUR gradle.build files.

Common Module Gradle

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'
    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 1
        versionName '1.0.0'
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled true
    }
}

dependencies {
    api 'androidx.multidex:multidex:2.0.1'
    api 'androidx.recyclerview:recyclerview-selection:1.1.0-beta01'
    api 'androidx.constraintlayout:constraintlayout:2.0.0-beta4'
    api 'com.google.android.material:material:1.2.0-alpha03'
    api 'com.google.android.gms:play-services-maps:17.0.0'
    api 'com.google.android.gms:play-services-location:17.0.0'
    api 'com.google.firebase:firebase-messaging:20.1.0'
    api 'com.firebaseui:firebase-ui:6.2.0'
    api('io.socket:socket.io-client:1.0.0') {
        exclude group: 'org.json', module: 'json'
    }
    api('com.crashlytics.sdk.android:crashlytics:2.10.1@aar') {
        transitive = true
    }
    api 'com.google.maps.android:android-maps-utils:0.6.2'
    api 'com.github.medyo:android-about-page:1.2.4'
    api 'com.squareup.moshi:moshi:1.9.2'
    api 'com.squareup.moshi:moshi-kotlin:1.9.2'
    kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.9.2'
    api 'de.psdev.licensesdialog:licensesdialog:2.1.0'
    api 'com.github.tylersuehr7:empty-state-recyclerview:1.0.4'
    api 'com.github.yalantis:ucrop:2.2.4'
    api 'com.github.esafirm.android-image-picker:imagepicker:2.2.0'
    api 'com.github.bumptech.glide:glide:4.10.0'
    api 'com.tapadoo.android:alerter:5.0.0'
    api 'gun0912.ted:tedpermission:2.2.2'
    api 'com.github.stfalcon:chatkit:0.3.3'
    api('com.stripe:stripe-android:12.8.2@aar') {
        transitive = true
    }
    api 'com.github.MAXDeliveryNG:slideview:1.1.0'
    api 'com.braintreepayments.api:drop-in:3.7.1'
    api 'com.airbnb.android:lottie:3.3.1'

    //noinspection LifecycleAnnotationProcessorWithJava8
    kapt 'androidx.lifecycle:lifecycle-compiler:2.2.0'
    api 'androidx.preference:preference-ktx:1.1.0'
    api 'androidx.core:core-ktx:1.1.0'
    api "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    api "org.jetbrains.kotlin:kotlin-script-runtime:1.3.61"
    api 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
    api 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'
}

Driver Module Gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'
    defaultConfig {
        applicationId 'com.ldrive.taxi.driver'
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 35
        versionName '3.0.9'
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
    }
    signingConfigs {
        release {
            storeFile file(RELEASE_STORE_FILE)
            storePassword RELEASE_STORE_PASSWORD
            keyAlias RELEASE_KEY_ALIAS
            keyPassword RELEASE_KEY_PASSWORD
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    api project(':common')
    api 'com.diogobernardino:williamchart:3.3.0'
}
apply plugin: 'com.google.gms.google-services'
repositories {
    mavenCentral()
}

Passenger/Rider Module Gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'
    defaultConfig {
        applicationId "com.ldrive.taxi.rider"
        minSdkVersion 19
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 35
        versionName "3.0.9"
        vectorDrawables.useSupportLibrary = true
        dexOptions {
            jumboMode true
        }
    }
    if (project.hasProperty("RELEASE_KEY_ALIAS")) {
        signingConfigs {
            release {
                storeFile file(RELEASE_STORE_FILE)
                storePassword RELEASE_STORE_PASSWORD
                keyAlias RELEASE_KEY_ALIAS
                keyPassword RELEASE_KEY_PASSWORD
            }
        }
        buildTypes {
            release {
                signingConfig signingConfigs.release
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled true
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    api project(':common')
    implementation 'com.github.Innomalist:floatingsearchview:0.3'
    implementation ('com.google.android.libraries.places:places:2.1.0')
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
    testImplementation 'junit:junit:4.12'
}
configurations {
    all*.exclude group: 'com.google.guava', module: 'listenablefuture'
}
apply plugin: 'com.google.gms.google-services'

PROJECT GRADLE

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.61'
    repositories {
        maven { url "https://maven.google.com" }
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
        google()
        maven { url 'https://plugins.gradle.org/m2/'}
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'io.fabric.tools:gradle:1.29.0'
        classpath 'com.google.gms:google-services:4.2.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        maven { url "https://maven.google.com" }
        jcenter()
        mavenCentral()
        google()
        maven { url "https://jitpack.io" }
        maven { url 'https://maven.fabric.io/public' }
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
Try to search for a class that extends FirebaseMessagingService. This is where all FCM service is set.

Edit

This is how I customise my notifications in my own app:

Intent intent = new Intent(this, BOBusinessHomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

Notification notification =
    new NotificationCompat.Builder(getApplicationContext(), "0")
    .setSmallIcon(R.drawable.business_icon)
    .setContentTitle("A client has posted a new review in your business page!")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setContentIntent(pendingIntent)
    .setAutoCancel(true)
    .build();
mNotificationManager.notify(0, notification);

Try to search "Notification" or any type of template similar to above in your project.

Or, try to search callback  method named onMessageReceived().

Explanation

By default, your app won’t display any FCM messages it receives while it’s in the foreground, so when you send a message there’s no guarantee your users will actually see that message.

To act on the messages your app receives while it’s in the foreground, you’ll need to extend the FirebaseMessagingService, override the onMessageReceived method, and then retrieve the message’s content using either getNotification or getData, depending on whether you’re working with data or notification messages, or both.


答:
This is a way to PIVOT the RunDater columns and show the Interest per ClientCode.</p>

```<code>DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(RunDater)
               FROM DPI
               FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')

SET @query = 'SELECT ClientCode
,' + @cols + ' FROM
(
   SELECT ClientCode, RunDater, Interest
   FROM DPI
) x
PIVOT
(
   MAX(Interest)
   FOR RunDater IN (' + @cols + ')
) p '

execute(@query)
</code>```

Title: Form pivot table for more than two dynamic column

Body:
I have created this table

CREATE TABLE [DPI]
(
    [ClientCode] [varchar](20) NULL,
    [RunDater] [date] NULL,
    [Debit] [numeric](18, 2) NULL,
    [Credit] [numeric](18, 2) NULL,
    [DayOfDifference] [numeric](18, 0) NULL,
    [Interest] [numeric](18, 2) NULL
 )

Inserted values:

 INSERT INTO DPI (ClientCode, RunDater, Debit, Credit, DayOfDifference, Interest)
 VALUES
 ('Z001','20/01/2001',20,0,0,18)
 ,('Z001','21/01/2001',0,0,0 ,0)
 ,('Z001','22/01/2001',40,20,0 ,0)
 ,('Z001','23/01/2001',0,0,0,0)
 ,('Z001','24/01/2001',0,20,0 ,0)
 ,('Z001','25/01/2001',100,0,0,0)
 ,('Z001','26/01/2001',0,0,0,0)
 ,('Z002','20/01/2001',0,0 ,0,0)
 ,('Z002','21/01/2001',0,0,0,0)
 ,('Z002','22/01/2001',30,20,0,0)
 ,('Z002','23/01/2001',0,0,0 ,0)
 ,('Z002','24/01/2001',0,20,0,0)
  ,('Z002','25/01/2001',100,0,0,0)
 ,('Z002','26/01/2001',0,0,0,0)

I wrote this query for getting the running balance and store in temporary table:

SELECT
    *, SUM(Credit - Debit) OVER (PARTITION BY ClientCode ORDER BY RunDater) AS Amount
INTO #temp
FROM DPI AS Amount

Now my table looks like this:

and want output in this format:

Body:
This is a way to PIVOT the RunDater columns and show the Interest per ClientCode.

DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(RunDater)
               FROM DPI
               FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')

SET @query = 'SELECT ClientCode
,' + @cols + ' FROM
(
   SELECT ClientCode, RunDater, Interest
   FROM DPI
) x
PIVOT
(
   MAX(Interest)
   FOR RunDater IN (' + @cols + ')
) p '

execute(@query)


问:
Commited changes into detached Head and moved to master
I commited my changes into detached head and moved to master. Is it possible to checkout the detached head again?</p>

答:
A good alternative would be to use the git rebase -i or the interactive rebasing in case you want to make changes in a previous commit, delete it, or meld it into other commits.

I commited my changes into detached head and moved to master. Is it
  possible to checkout the detached head again?

Yup it is possible :)