问:
Align ImageView to top right corner
I have a RelativeLayout with images next to each other. The number of images will be variable.

```<code>    <RelativeLayout
        android:id="@id/multipleImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/border">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>
</code>```

I want to add another image (the red rectangle) to the top-right corner slightly above the last image .
I tried layout_alignParentEnd but the layout goes full width.
Setting negative layout_marginTop the image goes up but is disappears outside the RelativeLayout.

答:
Try this :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:background="#ff0000" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="25dp"
        android:layout_marginRight="25dp">

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:background="#000000" />

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:background="#000000" />

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:background="#000000" />

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:background="#000000" />

    </LinearLayout>

</RelativeLayout>
</code>```

You can change margin as per your requirement and have desired result

Title: Align ImageView to top right corner

Body:
I have a RelativeLayout with images next to each other. The number of images will be variable.

    <RelativeLayout
        android:id="@id/multipleImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/border">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>

I want to add another image (the red rectangle) to the top-right corner slightly above the last image .
I tried layout_alignParentEnd but the layout goes full width.
Setting negative layout_marginTop the image goes up but is disappears outside the RelativeLayout.

Body:
Try this :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:background="#ff0000" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="25dp"
        android:layout_marginRight="25dp">

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:background="#000000" />

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:background="#000000" />

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:background="#000000" />

        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:background="#000000" />

    </LinearLayout>

</RelativeLayout>

You can change margin as per your requirement and have desired result


来源: stackexchange

问:
Refresh Tableau Live dashboard automatically at Tableau Server in every 5 seconds
I want to refresh Tableau Live dashboard on Server automatically in every 5 seconds. Is it possible without using Extension or JS?</p>

答:
Extensions and JS are the only methods I know of to do this natively with Tableau. You will probably have to look to a 3rd party add on for your browser. Here is one for chrome.

Chrome Auto-Refresh

ContentLicense: CC BY-SA 4.0


问:
What is a headless service, what does it do/accomplish, and what are some legitimate use cases for it?
I've read a couple of passages from some books written on Kubernetes as well as the page on headless services in the docs. But I'm still unsure what it really actually does and why someone would use it. Does anyone have a good understanding of it, what it accomplishes, and why someone would use it?</p>

答:
A Headless service is a service that doesn't have the clusterIP address allocated. This is achieved by setting the clusterIP to None.

What does this mean?: The kube-proxy won't handle these type of services, and therefore no load-balancing or proxying will be provided for a headless service, instead, the DNS response will contain a list of all IP addresses of each endpoint (podIP) that is part of the service.

When do you use it:

You can use it when you don't want to use Kubernetes service discovery mechanism.

Use with stateful set.

Headless service (docs)


问:
Can't install py4jdbc
I have to install py4jdbc module in python on windows 10, but i am having the followings errors when i try to use pip install py4jdbc or from the source:

Error 1: "The executable sbt cannot be found"

Pip Error

Error 2: "the file doesn't exist..."

Error From source

I have sbt already install and in the path.

Is there something i am missing?

答:
It seems py4jdbc was not tested on Windows as it uses a function distutils.spawn.find_executable that on w32 looks only for sbt.exe while you have sbt.bat.

My advice is to try to fix py4jdbc. Download it with pip download py4jdbc (it also downloads dependency py4j), unpack the archive py4jdbc-0.1.6.8.tar.gz and edit setup.py: at line 28 replace 'sbt' with 'sbt.bat'. Install with pip install . (<- the dot at the end means "the current directory".)

Title: Can't install py4jdbc


问:
How do I rotate text in css?
How do I rotate text in CSS to get following output:

The problem I am facing is that when we rotate the text then it breaks the alignment and positions. So what is causing that, and how can I manage them?

HTML:

```<code><div class="mainWrapper">
    <div class="rotateObj">
        <div class="title active">First Text Title</div>
        <div class="content">
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
        </div>
        <div class="title">First Text Title</div>
        <div class="content hide">
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
        </div>
        <div class="title">First Text Title</div>
        <div class="content hide">
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
        </div>
        <div class="title">First Text Title</div>
        <div class="content hide">
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
        </div>
        <div class="title">First Text Title</div>
        <div class="content hide">
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
        </div>
    </div>
</div>
</code>```

CSS:

```<code>    .mainWrapper{margin:0 auto; width:960px; background:#EFEFEF;}
    .rotateObj{position:relative; height:400px;}
    .rotateObj .title{
        float:left;
        background:gray;
        width:50px;
        height:100%;

        /** Rounded Border */
        border-radius:5px;-moz-border-radius:5px;

        /** Rotation */
        -webkit-transform: rotate(-90deg);
        -moz-transform: rotate(-90deg);
        transform:rotate(-90deg);
        filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
    }
    .rotateObj .active{background:green;}
    .rotateObj .content{float:left;width:600px;height:100%;padding:20px;}
    .hide{display:none;}
</code>```

http://jsfiddle.net/koolkabin/yawYM/

答:
You need to use the CSS3 transform property rotate - see here for which browsers support it and the prefix you need to use.

One example for webkit browsers is -webkit-transform: rotate(-90deg);

Edit: The question was changed substantially so I have added a demo that works in Chrome/Safari (as I only included the -webkit- CSS prefixed rules). The problem you have is that you do not want to rotate the title div, but simply the text inside it. If you remove your rotation, the
s are in the correct position and all you need to do is wrap the text in an element and rotate that instead.

There already exists a more customisable widget as part of the jQuery UI - see the accordion demo page. I am sure with some CSS cleverness you should be able to make the accordion vertical and also rotate the title text :-)

Edit 2: I had anticipated the text center problem and have already updated my demo. There is a height/width constraint though, so longer text could still break the layout.

Edit 3: It looks like the horizontal version was part of the original plan but I cannot see any way of configuring it on the demo page. I was incorrect… the new accordion is part of the upcoming jQuery UI 1.9! So you could try the development builds if you want the new functionality.

Hope this helps!

Title: How do I rotate text in css?

Body:
How do I rotate text in CSS to get following output:

The problem I am facing is that when we rotate the text then it breaks the alignment and positions. So what is causing that, and how can I manage them?

HTML:

First Text Title

            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...

First Text Title

            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...

First Text Title

            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...

First Text Title

            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...

First Text Title

            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...
            Here goes my bla bla bla text and more stuffs...

CSS:

    .mainWrapper{margin:0 auto; width:960px; background:#EFEFEF;}
    .rotateObj{position:relative; height:400px;}
    .rotateObj .title{
        float:left;
        background:gray;
        width:50px;
        height:100%;

        /** Rounded Border */
        border-radius:5px;-moz-border-radius:5px;

        /** Rotation */
        -webkit-transform: rotate(-90deg);
        -moz-transform: rotate(-90deg);
        transform:rotate(-90deg);
        filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
    }
    .rotateObj .active{background:green;}
    .rotateObj .content{float:left;width:600px;height:100%;padding:20px;}
    .hide{display:none;}

http://jsfiddle.net/koolkabin/yawYM/

Body:
You need to use the CSS3 transform property rotate - see here for which browsers support it and the prefix you need to use.

One example for webkit browsers is -webkit-transform: rotate(-90deg);

Edit: The question was changed substantially so I have added a demo that works in Chrome/Safari (as I only included the -webkit- CSS prefixed rules). The problem you have is that you do not want to rotate the title div, but simply the text inside it. If you remove your rotation, the <div>s are in the correct position and all you need to do is wrap the text in an element and rotate that instead.

There already exists a more customisable widget as part of the jQuery UI - see the accordion demo page. I am sure with some CSS cleverness you should be able to make the accordion vertical and also rotate the title text :-)

Edit 2: I had anticipated the text center problem and have already updated my demo. There is a height/width constraint though, so longer text could still break the layout.

Edit 3: It looks like the horizontal version was part of the original plan but I cannot see any way of configuring it on the demo page. I was incorrect… the new accordion is part of the upcoming jQuery UI 1.9! So you could try the development builds if you want the new functionality.

Hope this helps!

ContentLicense: CC BY-SA 3.0


问:
How to delete duplicates from one table, but keeping only one record?
Hello SQL query experts!
I have one table called 'mytable' which has 2 columns such as id and title .
I tried to remove duplicates except only one record(row) comparing title.
Below was my choice:

```<code>DELETE FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)
</code>```

error : Error in query (1064): Syntax error near '* FROM `myTable` AS `m1` WHERE `m1`.`id` NOT IN (SELECT MIN(`b`.`id`) as `reco' at line 1
but I faced a trouble and tried to resolve this problem more than 2 hours.
It seems like very simple problem.
But I can't figure it out. So I am asking to stackoverflow!

And mainly, I see something strange.
I tried like this but it has no any error.

```<code>SELECT * FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)
</code>```

When I run this query, I can obtain the list of records(rows) I want to delete from 'myTable' table.

Why do I face a deletion problem although I can obtain the list to delete?

I need your help really.
Thanks everyone!

答:
The syntax:

```<code>DELETE FROM `myTable` AS `m1`
</code>```

is wrong.

It should be:

```<code>DELETE m1 FROM `myTable` AS `m1`
</code>```

but you don't need to alias the table, you can just do

```<code>DELETE FROM `myTable`
</code>```

Also MySql does not allow the direct use of the target table inside a subquery like the one you use with NOT IN, but you can overcome this limitation by enclosing the subquery inside another one:

```<code>DELETE FROM `myTable`
WHERE `id` NOT IN (
  SELECT `recordid`
  FROM (
    SELECT MIN(`id`) as `recordid`
    FROM `myTable`
    GROUP BY `title`
  ) t
)
</code>```

I removed the aliases of the nested subquery because they are not needed.

Body:
Hello SQL query experts!
I have one table called 'mytable' which has 2 columns such as id and title .
I tried to remove duplicates except only one record(row) comparing title.
Below was my choice:

DELETE FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)

error : Error in query (1064): Syntax error near '* FROM `myTable` AS `m1` WHERE `m1`.`id` NOT IN (SELECT MIN(`b`.`id`) as `reco' at line 1
but I faced a trouble and tried to resolve this problem more than 2 hours.
It seems like very simple problem.
But I can't figure it out. So I am asking to stackoverflow!

And mainly, I see something strange.
I tried like this but it has no any error.

SELECT * FROM `myTable` AS `m1`
WHERE `m1`.`id`
NOT IN (SELECT MIN(`b`.`id`) as `recordid` FROM `myTable` AS `b` GROUP BY `b`.`title`)

When I run this query, I can obtain the list of records(rows) I want to delete from 'myTable' table.

Why do I face a deletion problem although I can obtain the list to delete?

I need your help really.
Thanks everyone!

Body:
The syntax:

DELETE FROM `myTable` AS `m1`

is wrong.

It should be:

DELETE m1 FROM `myTable` AS `m1`

but you don't need to alias the table, you can just do

DELETE FROM `myTable`

Also MySql does not allow the direct use of the target table inside a subquery like the one you use with NOT IN, but you can overcome this limitation by enclosing the subquery inside another one:

DELETE FROM `myTable`
WHERE `id` NOT IN (
  SELECT `recordid`
  FROM (
    SELECT MIN(`id`) as `recordid`
    FROM `myTable`
    GROUP BY `title`
  ) t
)

I removed the aliases of the nested subquery because they are not needed.


问:
typescript array of required items
Is there a way to force all elements in array?

Only requirement is "type connection" to main Book type.

I hope there is some way to make tuple type ['id', 'title'] from Book type generically, as suggested in comments. Or at least array length check...

Sandbox.

```<code>type Book = {
  id: string
  title: string
  visible: boolean
  author: string
}

type BookFields = keyof Book

type BookFieldsExtract<ExtractedFields extends BookFields> = Extract<BookFields, ExtractedFields>

const arr: BookFieldsExtract<'id' | 'title'>[] = ['id'] // how to force error if title not inclided in array?
</code>```

Use case:

```<code>type SelectedBookFields = BookFieldsExtract<'id' | 'title'>
type ApiRes = ApiResBook<SelectedBookFields> // {book: {id: string, title: string}}

 const bookFields: SelectedBookFields[] = ['id', 'title'] // i just don't want to forget some fields when making request

  const response = await fetchAPI<ApiReqBookBody, ApiRes>(
    'book',
    { fields: { book: bookFields } }
  ) // response type is {error: true} | {book: {id: string, title: string}}
</code>```

答:
After some search, found a way that works for my use case:</p>

```<code>const bookFields: ['id', 'title'] = ['id', 'title']
type BookFields = typeof bookFields[number] // 'id' | 'title'
</code>```

Title: typescript array of required items

Body:
Is there a way to force all elements in array?

Only requirement is "type connection" to main Book type.

I hope there is some way to make tuple type ['id', 'title'] from Book type generically, as suggested in comments. Or at least array length check...

Sandbox.

type Book = {
  id: string
  title: string
  visible: boolean
  author: string
}

type BookFields = keyof Book

type BookFieldsExtract<ExtractedFields extends BookFields> = Extract<BookFields, ExtractedFields>

const arr: BookFieldsExtract<'id' | 'title'>[] = ['id'] // how to force error if title not inclided in array?

Use case:

type SelectedBookFields = BookFieldsExtract<'id' | 'title'>
type ApiRes = ApiResBook<SelectedBookFields> // {book: {id: string, title: string}}

 const bookFields: SelectedBookFields[] = ['id', 'title'] // i just don't want to forget some fields when making request

  const response = await fetchAPI<ApiReqBookBody, ApiRes>(
    'book',
    { fields: { book: bookFields } }
  ) // response type is {error: true} | {book: {id: string, title: string}}

Body:
After some search, found a way that works for my use case:

const bookFields: ['id', 'title'] = ['id', 'title']
type BookFields = typeof bookFields[number] // 'id' | 'title'


问:
Change case of a file on Windows?
There are a couple of files in our git-controlled codebase that I'd like to rename.  Specifically, I just want to change the case of the file, so that sourceCode.java becomes SourceCode.java, for example.  The catch: I'm on a Windows box, and the filesystem thinks those are the same file name.

How can I get Windows and Git to recognize that change and check it in?
The change of the file name should not be ignored, but committed to git.

答:
In my opinion one simple way is missing. You can do this for a single file, a specific directory or even the whole repository. Just rename your files in any way you like before and than execute these commands:

```<code>git rm --cached <file name or directory>
git add <file name or directory>
</code>```

If you want to affect also the sub-directories, you have to use the -r flag:

```<code>git rm -r --cached <directory>
git add <directory>
</code>```

Title: Change case of a file on Windows?

Body:
In my opinion one simple way is missing. You can do this for a single file, a specific directory or even the whole repository. Just rename your files in any way you like before and than execute these commands:

git rm --cached <file name or directory>
git add <file name or directory>

If you want to affect also the sub-directories, you have to use the -r flag:

git rm -r --cached <directory>
git add <directory>


问:
open a link in new tab in selenium
I am trying to open a link in new tab.

Trial1

```<code>Actions action = new Actions(Driver).KeyDown(Keys.Control).KeyDown(Keys.Shift).Click(FindElement(xxx).KeyUp(Keys.Control).KeyUp(Keys.Shift);
         action.Build().Perform();
</code>```

This code opens the link in new tab at the same time opens another blank window

Trial2 - right click the link and choose the first option "open link new tab"

```<code>      action.ContextClick(FindElement(xxx).SendKeys(Keys.ArrowDown).SendKeys(Keys.Enter).Build().Perform();
</code>```

This opens the link in new window instead of new tab

答:
So what you need to do is first open a new tab using JS executor:

```<code>((JavascriptExecutor)driver).executeScript("window.open()");
</code>```

or

```<code>((JavascriptExecutor)driver).executeScript("window.open('the new link here', '_blank')");
</code>```

If you did not use the secon method continue with the following: switch to the new window and navigate to the link

```<code>driver.switchTo().window(here the window handle);
driver.get("here is the link");
</code>```

Title: open a link in new tab in selenium

Body:
I am trying to open a link in new tab.

Trial1

Actions action = new Actions(Driver).KeyDown(Keys.Control).KeyDown(Keys.Shift).Click(FindElement(xxx).KeyUp(Keys.Control).KeyUp(Keys.Shift);
         action.Build().Perform();

This code opens the link in new tab at the same time opens another blank window

Trial2 - right click the link and choose the first option "open link new tab"

      action.ContextClick(FindElement(xxx).SendKeys(Keys.ArrowDown).SendKeys(Keys.Enter).Build().Perform();

This opens the link in new window instead of new tab

Body:
So what you need to do is first open a new tab using JS executor:

((JavascriptExecutor)driver).executeScript("window.open()");

or

((JavascriptExecutor)driver).executeScript("window.open('the new link here', '_blank')");

If you did not use the secon method continue with the following: switch to the new window and navigate to the link

driver.switchTo().window(here the window handle);
driver.get("here is the link");


问:
Installing curl inside nginx docker image
The following Dockerfile few lines suppose to install curl inside the nginx custom image to run under ubuntu.

The second group of code is an attempt to convert the task to do the same but to run on Amazon Linux.

Any suggestion as to what would be the yum equivalent to the rest of the apt-get command?

-no-install-recommends curl && rm -rf /var/lib/apt/lists/*

```<code>//Dockerfile for ubuntu
FROM nginx
RUN apt-get update && apt-get install -y -no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*
</code>```

//Dockerfile for Amazon linux
FROM nginx
RUN yum update && yum install -y curl
```

答:
For Nginx image use Debian as OS use below : -</p>

```<code>FROM nginx
RUN apt-get update && apt-get install -y curl && apt-get clean
</code>```

Body:
The following Dockerfile few lines suppose to install curl inside the nginx custom image to run under ubuntu.

The second group of code is an attempt to convert the task to do the same but to run on Amazon Linux.

Any suggestion as to what would be the yum equivalent to the rest of the apt-get command?

-no-install-recommends curl && rm -rf /var/lib/apt/lists/*

//Dockerfile for ubuntu
FROM nginx
RUN apt-get update && apt-get install -y -no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*

//Dockerfile for Amazon linux
FROM nginx
RUN yum update && yum install -y curl

Body:
For Nginx image use Debian as OS use below : -

FROM nginx
RUN apt-get update && apt-get install -y curl && apt-get clean


问:
Injecting viewmodels into fragment when multiple instances of fragment exist
I am using the Toothpick dependency injection framework for an Android application and I'm having problems injecting android viewmodels into fragments when multiple instances of the same fragment exists on the backstack. I would like each fragment instance to get its own viewmodel instance, but the problem is that only a single viewmodel is created and shared across all fragment instances.

I have created a sample project demonstrating the issue. A single activity contains a single fragment with an android viewmodel. Multiple instances of this activity is created and placed on the activity backstack.

This is my Activity:

```<code>class MainActivity : FragmentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_layout)
    }
}
</code>```

it contains this layout:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/main_fragment"
        android:name="no.knowit.android.tptest.MainFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>
</code>```

MainFragment:

```<code>class MainFragment : Fragment() {

    companion object {
        const val TAG = "MainFragment"
    }

    @Inject
    lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openScope()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val v =  inflater.inflate(R.layout.main_fragment_layout, container, false)
        v.findViewById<Button>(R.id.spawn_button).setOnClickListener {
            Log.i(TAG, "spawn")
            val i = Intent(context, MainActivity::class.java)
            startActivity(i)
        }
        return v
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.i(TAG, "fragment  " + System.identityHashCode(this))
        Log.i(TAG, "viewModel " + System.identityHashCode(viewModel))
        Log.i(TAG, "liveData  " + System.identityHashCode(viewModel.myLiveData))
    }

    protected fun openScope() {
        val scope = KTP.openScopes(ApplicationScope::class.java)
            .openSubScope(ViewModelScope::class.java)
        installViewModelBindings(scope)

        scope.closeOnViewModelCleared(this)
            .openSubScope(activity!!)
            .closeOnDestroy(activity!!)
            .openSubScope(this)
            .closeOnDestroy(this)

        scope.inject(this)
    }

    private fun installViewModelBindings(scope: Scope) {
        scope.installViewModelBinding<MainViewModel>(this)
    }
}
</code>```

MainViewModel:

```<code>class MainViewModel : ViewModel() {

    @Inject
    lateinit var myLiveData: MyLiveData
}
</code>```

MyLiveData:

```<code>class MyLiveData @Inject constructor(): LiveData<Int>() {
}
</code>```

Output:

```<code>2020-02-18 09:12:56.325 23253-23253/no.knowit.android.tptest I/MainFragment: fragment  45659892
2020-02-18 09:12:56.326 23253-23253/no.knowit.android.tptest I/MainFragment: viewModel 236316818
2020-02-18 09:12:56.326 23253-23253/no.knowit.android.tptest I/MainFragment: liveData  241221950
2020-02-18 09:13:03.472 23253-23253/no.knowit.android.tptest I/MainFragment: spawn
2020-02-18 09:13:03.632 23253-23253/no.knowit.android.tptest I/MainFragment: fragment  8599012
2020-02-18 09:13:03.632 23253-23253/no.knowit.android.tptest I/MainFragment: viewModel 236316818
2020-02-18 09:13:03.632 23253-23253/no.knowit.android.tptest I/MainFragment: liveData  241221950
2020-02-18 09:13:05.194 23253-23253/no.knowit.android.tptest I/MainFragment: spawn
2020-02-18 09:13:05.289 23253-23253/no.knowit.android.tptest I/MainFragment: fragment  130024810
2020-02-18 09:13:05.289 23253-23253/no.knowit.android.tptest I/MainFragment: viewModel 236316818
2020-02-18 09:13:05.289 23253-23253/no.knowit.android.tptest I/MainFragment: liveData  241221950
2020-02-18 09:13:06.436 23253-23253/no.knowit.android.tptest I/MainFragment: spawn
</code>```

As you can see, new fragments are created, but share the same viewmodel and livedata.
I want to create a new viewmodel/livedata for each fragment, and these viewmodels should exist in the viewmodel scope. How can I accomplish this?

答:
You could use a custom ViewModelFactory

```<code>@Singleton
class ViewModelFactory @Inject constructor() :
            ViewModelProvider.NewInstanceFactory() {

            override fun <T : ViewModel> create(modelClass: Class<T>) =
                Toothpick.openScope(ApplicationScope::class.java).getInstance(modelClass) as T
        }
</code>```

and use it in your fragments/activities

```<code>@Inject
lateinit var viewModelFactory: ViewModelFactory

val mainViewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel::class.java)
</code>```

Body:
I am using the Toothpick dependency injection framework for an Android application and I'm having problems injecting android viewmodels into fragments when multiple instances of the same fragment exists on the backstack. I would like each fragment instance to get its own viewmodel instance, but the problem is that only a single viewmodel is created and shared across all fragment instances.

I have created a sample project demonstrating the issue. A single activity contains a single fragment with an android viewmodel. Multiple instances of this activity is created and placed on the activity backstack.

This is my Activity:

class MainActivity : FragmentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_layout)
    }
}

it contains this layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/main_fragment"
        android:name="no.knowit.android.tptest.MainFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

MainFragment:

class MainFragment : Fragment() {

    companion object {
        const val TAG = "MainFragment"
    }

    @Inject
    lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openScope()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val v =  inflater.inflate(R.layout.main_fragment_layout, container, false)
        v.findViewById<Button>(R.id.spawn_button).setOnClickListener {
            Log.i(TAG, "spawn")
            val i = Intent(context, MainActivity::class.java)
            startActivity(i)
        }
        return v
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.i(TAG, "fragment  " + System.identityHashCode(this))
        Log.i(TAG, "viewModel " + System.identityHashCode(viewModel))
        Log.i(TAG, "liveData  " + System.identityHashCode(viewModel.myLiveData))
    }

    protected fun openScope() {
        val scope = KTP.openScopes(ApplicationScope::class.java)
            .openSubScope(ViewModelScope::class.java)
        installViewModelBindings(scope)

        scope.closeOnViewModelCleared(this)
            .openSubScope(activity!!)
            .closeOnDestroy(activity!!)
            .openSubScope(this)
            .closeOnDestroy(this)

        scope.inject(this)
    }

    private fun installViewModelBindings(scope: Scope) {
        scope.installViewModelBinding<MainViewModel>(this)
    }
}

MainViewModel:

class MainViewModel : ViewModel() {

    @Inject
    lateinit var myLiveData: MyLiveData
}

MyLiveData:

class MyLiveData @Inject constructor(): LiveData<Int>() {
}

Output:

2020-02-18 09:12:56.325 23253-23253/no.knowit.android.tptest I/MainFragment: fragment  45659892
2020-02-18 09:12:56.326 23253-23253/no.knowit.android.tptest I/MainFragment: viewModel 236316818
2020-02-18 09:12:56.326 23253-23253/no.knowit.android.tptest I/MainFragment: liveData  241221950
2020-02-18 09:13:03.472 23253-23253/no.knowit.android.tptest I/MainFragment: spawn
2020-02-18 09:13:03.632 23253-23253/no.knowit.android.tptest I/MainFragment: fragment  8599012
2020-02-18 09:13:03.632 23253-23253/no.knowit.android.tptest I/MainFragment: viewModel 236316818
2020-02-18 09:13:03.632 23253-23253/no.knowit.android.tptest I/MainFragment: liveData  241221950
2020-02-18 09:13:05.194 23253-23253/no.knowit.android.tptest I/MainFragment: spawn
2020-02-18 09:13:05.289 23253-23253/no.knowit.android.tptest I/MainFragment: fragment  130024810
2020-02-18 09:13:05.289 23253-23253/no.knowit.android.tptest I/MainFragment: viewModel 236316818
2020-02-18 09:13:05.289 23253-23253/no.knowit.android.tptest I/MainFragment: liveData  241221950
2020-02-18 09:13:06.436 23253-23253/no.knowit.android.tptest I/MainFragment: spawn

As you can see, new fragments are created, but share the same viewmodel and livedata.
I want to create a new viewmodel/livedata for each fragment, and these viewmodels should exist in the viewmodel scope. How can I accomplish this?

Body:
You could use a custom ViewModelFactory

@Singleton
class ViewModelFactory @Inject constructor() :
            ViewModelProvider.NewInstanceFactory() {

            override fun <T : ViewModel> create(modelClass: Class<T>) =
                Toothpick.openScope(ApplicationScope::class.java).getInstance(modelClass) as T
        }

and use it in your fragments/activities

@Inject
lateinit var viewModelFactory: ViewModelFactory

val mainViewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel::class.java)


问:
Why isn't flatlist not able to map through and display the data?
I am using Zomato API to get the list of restaurants, data is in the form of the array which has object restaurants in which there are different restaurant objects and then their name and other details.

It's my first time using a flat List and I am not able to display this data.

Goal: Use the search bar to display the list of restaurants in the city using flatlist.

```<code>import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { SearchBar } from 'react-native-elements';
import { FlatList } from 'react-native-gesture-handler';

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = { search: '', data: [] };
    }

    componentDidMount() {
        fetch('https://developers.zomato.com/api/v2.1/search', {
            method: 'GET',
            headers: {
                'user-key': '999999999999999999999999999'
            },
            params: JSON.stringify({
                entity_type: 'city',
                q: {this.state.search}
            }),
        }).then((response) => response.json())
            .then((responseJson) => { return this.setState({ data: responseJson.restaurants }) })
            .catch((error) => { console.warn(error) }
            );
    }

    render() {
        let data = this.state.data;
        let name = data.map(p => p.restaurant.name)
        console.warn("Check Data", name)
        return (
            <View>
                <SearchBar
                    round
                    searchIcon={{ size: 24 }}
                    placeholder='Search'
                    onChangeText={search => { this.setState({ search }) }}
                    value={this.state.search}
                />
//Using this method to display the data if any

                {name.length != 0 ?
                    <FlatList
                        data={name}
                        keyExtractor={(x, i) => x + i}
                        renderItem={({ name }) => <Text>{name}-DATA</Text>}
                    />
                    : <View style={{height:"100%", width:"100%", alignItems:"center",
                                      justifyContent:"center"}}>
                        <Text>No data found</Text>
                    </View>
                }

            </View>
        );
    }
}

export default Main;
</code>```

Maybe the way I declared state is wrong, or maybe the way I'm storing the data in the state is wrong.
I got the names of the restaurant in the console.warn successfully.

答:
Try replacing the renderItem from FlatList to

```<code>renderItem={({ item }) => <Text>{item}-DATA</Text>}
</code>```

Also, replace the condition to use double equals like name.length !== 0

Body:
I am using Zomato API to get the list of restaurants, data is in the form of the array which has object restaurants in which there are different restaurant objects and then their name and other details.

It's my first time using a flat List and I am not able to display this data.

Goal: Use the search bar to display the list of restaurants in the city using flatlist.

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { SearchBar } from 'react-native-elements';
import { FlatList } from 'react-native-gesture-handler';

class Main extends Component {
    constructor(props) {
        super(props);
        this.state = { search: '', data: [] };
    }

    componentDidMount() {
        fetch('https://developers.zomato.com/api/v2.1/search', {
            method: 'GET',
            headers: {
                'user-key': '999999999999999999999999999'
            },
            params: JSON.stringify({
                entity_type: 'city',
                q: {this.state.search}
            }),
        }).then((response) => response.json())
            .then((responseJson) => { return this.setState({ data: responseJson.restaurants }) })
            .catch((error) => { console.warn(error) }
            );
    }

    render() {
        let data = this.state.data;
        let name = data.map(p => p.restaurant.name)
        console.warn("Check Data", name)
        return (
            <View>
                <SearchBar
                    round
                    searchIcon={{ size: 24 }}
                    placeholder='Search'
                    onChangeText={search => { this.setState({ search }) }}
                    value={this.state.search}
                />
//Using this method to display the data if any

                {name.length != 0 ?
                    <FlatList
                        data={name}
                        keyExtractor={(x, i) => x + i}
                        renderItem={({ name }) => <Text>{name}-DATA</Text>}
                    />
                    : <View style={{height:"100%", width:"100%", alignItems:"center",
                                      justifyContent:"center"}}>
                        <Text>No data found</Text>
                    </View>
                }

            </View>
        );
    }
}

export default Main;

Maybe the way I declared state is wrong, or maybe the way I'm storing the data in the state is wrong.
I got the names of the restaurant in the console.warn successfully.

Body:
Try replacing the renderItem from FlatList to

renderItem={({ item }) => <Text>{item}-DATA</Text>}

Also, replace the condition to use double equals like name.length !== 0


问:
Create LINQ request
I have some collections:

Dictionary<InvoceHeader, List<InvoiceHierarchy>> where

```<code>public class InvoceHeader
{
    public int InvoiceId { get; set; }
    public string DocumentNumber { get; set; }
    public string DocumentDate { get; set; }
    public string DocumentReference { get; set; }
}

public class InvoiceHierarchi
{
    public string SerialNumber { get; set; }
    public string ProductCode { get; set; }
    public string Certificate { get; set; }
    public string Description { get; set; }
}
</code>```

I need to write a LINQ request to get such a collection from the original collection --> Dictionary<string, List<string>>, where key --> InvoceHeader.DocumentNumber, value --> List two elements from InvoiceHierarchi such as the SerialNumber and Certificate.

答:
Try following :</p>

```<code>   class Program
    {
        static void Main(string[] args)
        {
            List<InvoceHeader> headers = new List<InvoceHeader>();
            List<InvoiceHierarchi> hierarchi = new List<InvoiceHierarchi>();

            var query = (from header in headers
                         join hierarch in hierarchi on header.DocumentNumber equals hierarch.Certificate
                         select new { header = header, hierarch = hierarch }
                         ).ToList();

            Dictionary<string, object> dict = query
                .GroupBy(x => x.header.DocumentNumber, y => new { header = y.header, hierachi = y.hierarch })
                .ToDictionary(x => x.Key, y => (object)y.ToList());

        }

    }
    public class InvoceHeader
    {
        public int InvoiceId { get; set; }
        public string DocumentNumber { get; set; }
        public string DocumentDate { get; set; }
        public string DocumentReference { get; set; }
    }

    public class InvoiceHierarchi
    {
        public string SerialNumber { get; set; }
        public string ProductCode { get; set; }
        public string Certificate { get; set; }
        public string Description { get; set; }
    }
</code>```

Title: Create LINQ request

Body:
I have some collections:

Dictionary<InvoceHeader, List<InvoiceHierarchy>> where

public class InvoceHeader
{
    public int InvoiceId { get; set; }
    public string DocumentNumber { get; set; }
    public string DocumentDate { get; set; }
    public string DocumentReference { get; set; }
}

public class InvoiceHierarchi
{
    public string SerialNumber { get; set; }
    public string ProductCode { get; set; }
    public string Certificate { get; set; }
    public string Description { get; set; }
}

I need to write a LINQ request to get such a collection from the original collection --> Dictionary<string, List<string>>, where key --> InvoceHeader.DocumentNumber, value --> List two elements from InvoiceHierarchi such as the SerialNumber and Certificate.

Body:
Try following :

   class Program
    {
        static void Main(string[] args)
        {
            List<InvoceHeader> headers = new List<InvoceHeader>();
            List<InvoiceHierarchi> hierarchi = new List<InvoiceHierarchi>();

            var query = (from header in headers
                         join hierarch in hierarchi on header.DocumentNumber equals hierarch.Certificate
                         select new { header = header, hierarch = hierarch }
                         ).ToList();

            Dictionary<string, object> dict = query
                .GroupBy(x => x.header.DocumentNumber, y => new { header = y.header, hierachi = y.hierarch })
                .ToDictionary(x => x.Key, y => (object)y.ToList());

        }

    }
    public class InvoceHeader
    {
        public int InvoiceId { get; set; }
        public string DocumentNumber { get; set; }
        public string DocumentDate { get; set; }
        public string DocumentReference { get; set; }
    }

    public class InvoiceHierarchi
    {
        public string SerialNumber { get; set; }
        public string ProductCode { get; set; }
        public string Certificate { get; set; }
        public string Description { get; set; }
    }


问:
Month End Date Range where most recent day = system date
I am trying to generate a range of 'last day of the month' dates from a given start date (01/01/2019) to the system date (sysdate).
I am able to generate the date range for this using the below query:

```<code>select last_day(add_months (trunc (to_date('01/01/2019','MM/DD/YYYY'), 'MM'), Level - 1))

Month   FROM Dual

CONNECT BY Level <= MONTHS_BETWEEN(sysdate, to_date('01/01/2019','MM/DD/YYYY')) + 1

order by month
</code>```

I am trying to get the last record to equal the sysdate so I can calculate running balances - how can I go about adding this to the above query?

Example output of the solution:

```<code>+------------------------+
|         MONTH          |
+------------------------+
| 1/31/2019 12:00:00 AM  |
| 2/28/2019 12:00:00 AM  |
| 3/31/2019 12:00:00 AM  |
| 4/30/2019 12:00:00 AM  |
| 5/31/2019 12:00:00 AM  |
| 6/30/2019 12:00:00 AM  |
| 7/31/2019 12:00:00 AM  |
| 8/31/2019 12:00:00 AM  |
| 9/30/2019 12:00:00 AM  |
| 10/31/2019 12:00:00 AM |
| 11/30/2019 12:00:00 AM |
| 12/31/2019 12:00:00 AM |
| 1/31/2020 12:00:00 AM  |
| 2/25/2020 12:00:00 AM  |
+------------------------+
</code>```

Body:
I am trying to generate a range of 'last day of the month' dates from a given start date (01/01/2019) to the system date (sysdate).
I am able to generate the date range for this using the below query:

select last_day(add_months (trunc (to_date('01/01/2019','MM/DD/YYYY'), 'MM'), Level - 1))

Month   FROM Dual

CONNECT BY Level <= MONTHS_BETWEEN(sysdate, to_date('01/01/2019','MM/DD/YYYY')) + 1

order by month

I am trying to get the last record to equal the sysdate so I can calculate running balances - how can I go about adding this to the above query?

Example output of the solution:

+------------------------+
|         MONTH          |
+------------------------+
| 1/31/2019 12:00:00 AM  |
| 2/28/2019 12:00:00 AM  |
| 3/31/2019 12:00:00 AM  |
| 4/30/2019 12:00:00 AM  |
| 5/31/2019 12:00:00 AM  |
| 6/30/2019 12:00:00 AM  |
| 7/31/2019 12:00:00 AM  |
| 8/31/2019 12:00:00 AM  |
| 9/30/2019 12:00:00 AM  |
| 10/31/2019 12:00:00 AM |
| 11/30/2019 12:00:00 AM |
| 12/31/2019 12:00:00 AM |
| 1/31/2020 12:00:00 AM  |
| 2/25/2020 12:00:00 AM  |
+------------------------+

Body:
If I understood you correctly, you'd want today's date in the last line. If so, use CASE (lines #13 - 19).

Lines #1 - 12 represent your current query.

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> WITH your_data
  2       AS (    SELECT LAST_DAY (
  3                         ADD_MONTHS (
  4                            TRUNC (TO_DATE ('01/01/2019', 'MM/DD/YYYY'), 'MM'),
  5                            LEVEL - 1))
  6                         Month
  7                 FROM DUAL
  8           CONNECT BY LEVEL <=
  9                           MONTHS_BETWEEN (
 10                              SYSDATE,
 11                              TO_DATE ('01/01/2019', 'MM/DD/YYYY'))
 12                         + 1)
 13    SELECT CASE
 14              WHEN TRUNC (month, 'mm') = TRUNC (SYSDATE, 'mm')
 15              THEN
 16                 TRUNC (SYSDATE)
 17              ELSE
 18                 month
 19           END
 20              month
 21      FROM your_data
 22  ORDER BY month;

MONTH
-------------------
31.01.2019 00:00:00
28.02.2019 00:00:00
31.03.2019 00:00:00
30.04.2019 00:00:00
31.05.2019 00:00:00
30.06.2019 00:00:00
31.07.2019 00:00:00
31.08.2019 00:00:00
30.09.2019 00:00:00
31.10.2019 00:00:00
30.11.2019 00:00:00
31.12.2019 00:00:00
31.01.2020 00:00:00
18.02.2020 00:00:00

14 rows selected.

SQL>


问:
angular CDK drag & drop: nested droplist
I'm trying to build a demo app where I can plan students and their desks. When a classroom has too many desks I can put them in another classroom. I can then plan the students on said desks. I'm using cdkDropListGroup because the amount of classrooms is a dynamic.

When I drop a desk with students on the 'not assigned' student list, the desk remains in the class room, but the students drop into the list as expected.
However when I try to drop the students on the desks, the predicate, which only allows products to be dropped in the list, doesn't allow them. When I remove the predicate however, the student are dropped in the classrooms list instead of the desks...

Dropping desks with students works properly:

Dropping students on desks fails:

I need help with dropping the students specifically on the desks instead of the classrooms, causing dropStudent to trigger.

I thought raising the container for the desks to a higher Z-Index might help but that didn't work.

references:

docs

similar question stackoverflow

Stackblitz example where I'm stuck

答:
You need to use the cdkDropListConnectedTo option on the not assigned students lists, and add all instances of the desk lists. That's beacuse the CdkDropListGroup only looks at sibling lists, not at children:

You need to add a template reference to your desk droplist, so you can query this in your component ts, or you can use the a string of IDs. I think the template reference is more versatile, but for the sake of example I'll use the ids:

```<code><div cdkDropList
      id="{{studentList.listName}}"
      [cdkDropListData]="studentList.student"
      class="example-list"
      (cdkDropListDropped)="returnStudent($event)"
      [cdkDropListEnterPredicate]="userReturnPredicate"
      [cdkDropListConnectedTo]="desks">
  <div  *ngFor="let person of studentList.student"
        class="example-box"
        cdkDrag
        [cdkDragData]="person">
    {{person.userName}}
  </div>
</div>
</code>```

As you can see the cdkDropListConnectedTo has desks binded. In your component you can define desks like this:

```<code>desks: string[] = [];

this.desks = this.projectLists.map(
  (list) => list.products.map((product) => product.productName)
).flat(2);
</code>```

To make it work with ViewChildren, you need something like this in your ngAfterViewInit:

```<code>ngAfterViewInit(): void {
  this.deskLists.changes.pipe(
    startWith(true),
    tap(() => {
      this.desks = this.deskLists.toArray();
      this.cd.markForCheck();
      this.cd.detectChanges();
    }),
  ).subscribe();
}
</code>```

working example

Body:
You need to use the cdkDropListConnectedTo option on the not assigned students lists, and add all instances of the desk lists. That's beacuse the CdkDropListGroup only looks at sibling lists, not at children:

You need to add a template reference to your desk droplist, so you can query this in your component ts, or you can use the a string of IDs. I think the template reference is more versatile, but for the sake of example I'll use the ids:

<div cdkDropList
      id="{{studentList.listName}}"
      [cdkDropListData]="studentList.student"
      class="example-list"
      (cdkDropListDropped)="returnStudent($event)"
      [cdkDropListEnterPredicate]="userReturnPredicate"
      [cdkDropListConnectedTo]="desks">
  <div  *ngFor="let person of studentList.student"
        class="example-box"
        cdkDrag
        [cdkDragData]="person">
    {{person.userName}}
  </div>
</div>

As you can see the cdkDropListConnectedTo has desks binded. In your component you can define desks like this:

desks: string[] = [];

this.desks = this.projectLists.map(
  (list) => list.products.map((product) => product.productName)
).flat(2);

To make it work with ViewChildren, you need something like this in your ngAfterViewInit:

ngAfterViewInit(): void {
  this.deskLists.changes.pipe(
    startWith(true),
    tap(() => {
      this.desks = this.deskLists.toArray();
      this.cd.markForCheck();
      this.cd.detectChanges();
    }),
  ).subscribe();
}

working example


问:
TypeError: Cannot read property 'innerHTML' of null | Vue Utils - Jest Framework | Can't able to run test case for this
I am using Vue utils jest framework for cover my vue.js. while run its shown error like this. Please refer screen shot.

my vue code is below

```<code>  <div id="tile" class="tile" data-scale="2.4" @mouseover="cursorEnters" @mouseout="cursorLeaves" @mousemove="cursorMove($event)" :data-image="imageUrl"
  >
</code>```

my js code is below

```<code>mounted() {
   this.initializationImageZoom();
},
initializationImageZoom() {
  const tile = document.querySelector('#tile');
  tile.innerHTML += '<div id="photo" class="photo"></div>';
  tile.children[0].style.backgroundImage = 'url(' + this.imageUrl + ')';
},
</code>```

Below my test case

```<code>import { shallowMount } from '@vue/test-utils';

const imageUrl = "https://i.ytimg.com/vi/ETsekJKsr3M/maxresdefault.jpg";

let wrapper;
const ImageZoom = require('./ImageZoom.vue').default;

beforeEach(() => {
  wrapper = shallowMount(ImageZoom, {
    propsData: {
      imageUrl,
    }
  });
});

afterEach(() => {
  wrapper.destroy();
});

describe('NoRecords.vue', () => {
  it('should have props (imageUrl) type as Object', () => {
    expect(typeof wrapper.vm.imageUrl).toBe('string');
 });
});
</code>```

While rendering the vue component by test case. its shown error like that (Refer screen shot)

答:
You can try this:

```<code>import { shallowMount } from '@vue/test-utils';

const imageUrl = "https://i.ytimg.com/vi/ETsekJKsr3M/maxresdefault.jpg";

// Creating #tile div

let tile = document.createElement('div')
tile.setAttribute("id", "tile")
let children = document.createElement('div')
tile.appendChild(children)
document.body.appendChild(tile)

let wrapper;
const ImageZoom = require('./ImageZoom.vue').default;

beforeEach(() => {
  wrapper = shallowMount(ImageZoom, {
    propsData: {
      imageUrl,
    }
  });
});

afterEach(() => {
  wrapper.destroy();
});

describe('NoRecords.vue', () => {
  it('should have props (imageUrl) type as Object', () => {
    expect(typeof wrapper.vm.imageUrl).toBe('string');
 });
});
</code>```

I just create a div element in the body so that jest dont throw an error.

Body:
I am using Vue utils jest framework for cover my vue.js. while run its shown error like this. Please refer screen shot.

my vue code is below

my js code is below

mounted() {
   this.initializationImageZoom();
},
initializationImageZoom() {
  const tile = document.querySelector('#tile');
  tile.innerHTML += '

';
  tile.children[0].style.backgroundImage = 'url(' + this.imageUrl + ')';
},

Below my test case

import { shallowMount } from '@vue/test-utils';

const imageUrl = "https://i.ytimg.com/vi/ETsekJKsr3M/maxresdefault.jpg";

let wrapper;
const ImageZoom = require('./ImageZoom.vue').default;

beforeEach(() => {
  wrapper = shallowMount(ImageZoom, {
    propsData: {
      imageUrl,
    }
  });
});

afterEach(() => {
  wrapper.destroy();
});

describe('NoRecords.vue', () => {
  it('should have props (imageUrl) type as Object', () => {
    expect(typeof wrapper.vm.imageUrl).toBe('string');
 });
});

While rendering the vue component by test case. its shown error like that (Refer screen shot)

Body:
You can try this:

import { shallowMount } from '@vue/test-utils';

const imageUrl = "https://i.ytimg.com/vi/ETsekJKsr3M/maxresdefault.jpg";

// Creating #tile div

let tile = document.createElement('div')
tile.setAttribute("id", "tile")
let children = document.createElement('div')
tile.appendChild(children)
document.body.appendChild(tile)

let wrapper;
const ImageZoom = require('./ImageZoom.vue').default;

beforeEach(() => {
  wrapper = shallowMount(ImageZoom, {
    propsData: {
      imageUrl,
    }
  });
});

afterEach(() => {
  wrapper.destroy();
});

describe('NoRecords.vue', () => {
  it('should have props (imageUrl) type as Object', () => {
    expect(typeof wrapper.vm.imageUrl).toBe('string');
 });
});

I just create a div element in the body so that jest dont throw an error.


问:
IE 11 failed to create file object from byte array in Angular
Can anybody tell me why IE11 is throwing error
In other browsers working only in IE getting error "object doesn't support this action"</p>

```<code>let file = new File([files], newFileName, { type: Constants.FILECONTENTTYPE, lastModified: Date.now() });
                let uploadDocument = new UploadDocument();
                uploadDocument.fileName = newFileName;
                uploadDocument.fileItem = file;
                this.fileList = [];
                this.mergedFileList.forEach(fileItem => {
                    this.fileList.push(fileItem);
                });
</code>```

答:
You need to add import 'core-js/es6/object'; to your polyfill.ts file.

IE11 was released before ES6 so it doesn't implement the same methods for objects, arrays, dates, ... than modern browsers (ES7).

You can also import ES7 methods with import 'core-js/es7/object'; but i think in your case ES6 is enought.

Body:
Can anybody tell me why IE11 is throwing error
In other browsers working only in IE getting error "object doesn't support this action"

let file = new File([files], newFileName, { type: Constants.FILECONTENTTYPE, lastModified: Date.now() });
                let uploadDocument = new UploadDocument();
                uploadDocument.fileName = newFileName;
                uploadDocument.fileItem = file;
                this.fileList = [];
                this.mergedFileList.forEach(fileItem => {
                    this.fileList.push(fileItem);
                });


问:
Cannot detec dbgshim path for execute path Rider Dotnet core
With the latests update for Rider and Dotnet Core 2.1 There is a bug where you cannot debug your solution.

The error shows something in the lines of:
"Cannot detec dbgshim path for execute path"

答:
Since none of the solutions here worked for me, I found a solution that worked for me:

When I discovered all the installed .NET Core SDKs on my Windows Machine (via Add / Remove Progams), I found out that .NET Core 3.1 (which is the version that did not work with the debugger anymore) was installed multiple times (probably by visual studio etc.)

So what I did to get debugging working again:

Uninstalled Visual Studio

Uninstalled all .NET Core 3.X.X Versions of Runtime and/or SDK

Reinstalled a fresh .NET Core 3.X.X

I also reinstalled Rider several times before, but I guess that is not really neccessary.

I hope this helps people facing the same problem!


问:
How to make CSS height 100% scrollable?
I want to make the two-tone background. 50% of left side is in the main background color and 50% right side in another color (say pink). I could accomplish that but now facing another problem. When the mouse cursor is on the pink background color, the page becomes unscrollable. How to fix this and make it scrollable?

html code

html,
body {
  margin: 0;
  overflow: scroll;
  height: 100%;
  background-color: #f5f5f5;
}

#background {
  position: fixed;
  top: 0px;
  left: 50%;
  width: 50%;
  height: 100%;
  background-color: pink;
  z-index: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="background"></div>
</body></code>```

答:
Why not using background gradient  with single div without
  positioning like below

html,
body {
  margin: 0;
  overflow: scroll;
  height: 100%;
   background-image: linear-gradient(to right, #f5f5f5 50% , pink 50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="background"></div>
</body></code>```

Title: How to make CSS height 100% scrollable?

Body:
Why not using background gradient  with single div without
  positioning like below

html,
body {
  margin: 0;
  overflow: scroll;
  height: 100%;
   background-image: linear-gradient(to right, #f5f5f5 50% , pink 50%);
}

<body>
  <div id="background"></div>
</body>


问:
Why cast the result of pre-incrementation to void in comma separator context?
Looking at std::for_each_n's possible implementation:

```<code>template<class InputIt, class Size, class UnaryFunction>
InputIt for_each_n(InputIt first, Size n, UnaryFunction f)
{
    for (Size i = 0; i < n; ++first, (void) ++i) {
        f(*first);
    }
    return first;
}
</code>```

I noticed that the part where we typically see i++ (or, the preferred ++i) consists of two operations:

++first

(void) ++i

separated by a comma. While most of it makes sense, the (void) cast seems a little surprising to me. All I can guess is that there could be an overloaded operator , that takes the deduced type of InputIt and Size which would result in some surprising side-effects. Could that be the reason? If yes, are we sure that cast to void solves that issue entirely?

答:
Could that be the reason?

Handling the evil overload of operator comma is indeed a good reason.

I don't see other (valid) reasons.

If yes, are we sure that cast to void solves that issue entirely?

Yes, we cannot overload operator comma with void (neither with conversion to void).

Body:
Looking at std::for_each_n's possible implementation:

template<class InputIt, class Size, class UnaryFunction>
InputIt for_each_n(InputIt first, Size n, UnaryFunction f)
{
    for (Size i = 0; i < n; ++first, (void) ++i) {
        f(*first);
    }
    return first;
}

I noticed that the part where we typically see i++ (or, the preferred ++i) consists of two operations:

++first

(void) ++i

separated by a comma. While most of it makes sense, the (void) cast seems a little surprising to me. All I can guess is that there could be an overloaded operator , that takes the deduced type of InputIt and Size which would result in some surprising side-effects. Could that be the reason? If yes, are we sure that cast to void solves that issue entirely?


问:
Is it possible to get color gradients under curve in matplotlib?
I happened to see a beautiful graph on this page which is shown below:

Is it possible to get such color gradients in matplotlib?

答:
I've tried something :

```<code>import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

xData = range(100)
yData = range(100)
plt.plot(xData, yData)

NbData = len(xData)
MaxBL = [[MaxBL] * NbData for MaxBL in range(100)]
Max = [np.asarray(MaxBL[x]) for x in range(100)]

for x in range (50, 100):
  plt.fill_between(xData, Max[x], yData, where=yData >Max[x], facecolor='red', alpha=0.02)

for x in range (0, 50):
  plt.fill_between(xData, yData, Max[x], where=yData <Max[x], facecolor='green', alpha=0.02)

plt.fill_between([], [], [], facecolor='red', label="x > 50")
plt.fill_between([], [], [], facecolor='green', label="x < 50")

plt.legend(loc=4, fontsize=12)
plt.show()
fig.savefig('graph.png')
</code>```

.. and the result:

Of course the gradient could go down to 0 by changing the range of feel_between function.

Body:
I've tried something :

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

xData = range(100)
yData = range(100)
plt.plot(xData, yData)

NbData = len(xData)
MaxBL = [[MaxBL] * NbData for MaxBL in range(100)]
Max = [np.asarray(MaxBL[x]) for x in range(100)]

for x in range (50, 100):
  plt.fill_between(xData, Max[x], yData, where=yData >Max[x], facecolor='red', alpha=0.02)

for x in range (0, 50):
  plt.fill_between(xData, yData, Max[x], where=yData <Max[x], facecolor='green', alpha=0.02)

plt.fill_between([], [], [], facecolor='red', label="x > 50")
plt.fill_between([], [], [], facecolor='green', label="x < 50")

plt.legend(loc=4, fontsize=12)
plt.show()
fig.savefig('graph.png')

.. and the result:

Of course the gradient could go down to 0 by changing the range of feel_between function.


问:
Django DateTimeField auto_now_add attribute is not working
I have a model Alerte (below) that is updated in a function like this

```<code>Alerte.objects.create(
                asp_ale_loc = site,
                asp_ale_typ = 1, # activation de l'alerte
                # asp_ale_dat = timezone.now() -> replaced by auto_now_add
            )
</code>```

I have modified asp_ale_dat format from DateField to DateTimeField and add auto_now_add as an attribute

I have run makemigrations and migrate

but when I create an Alerte object, asp_ale_dat is empty

and if I use timezone.now(), the only date is registered, not time...

```<code>class Alerte(models.Model):

    asp_ale_cle = models.AutoField(primary_key=True)
    asp_ale_loc = models.CharField("Site concerned by alert", max_length=10, null=True, blank=True)
    asp_ale_typ = models.IntegerField("Operation type on alert", null=True, blank=True,)
    asp_ale_dat = models.DateTimeField("Operation date on alert", null=True, blank=True,auto_now_add=True)
</code>```

答:
I see no reason why that wouldn't work, and indeed I'm unable to reproduce this:</p>

```<code>$ pip install django
Successfully installed asgiref-3.2.3 django-3.0.3 pytz-2019.3 sqlparse-0.3.0
$ django-admin startproject so60281850 .
$ subl so60281850/settings.py  # add so60281850 to INSTALLED_APPS
$ subl so60281850/models.py  # add in the model definition
$ python manage.py makemigrations so60281850
Migrations for 'so60281850':
  so60281850/migrations/0001_initial.py
    - Create model Alerte
$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, so60281850
$ python manage.py shell
>>> from so60281850.models import Alerte
>>> a = Alerte.objects.create(asp_ale_loc='foo', asp_ale_typ=1)
>>> a.asp_ale_dat
datetime.datetime(2020, 2, 18, 13, 28, 49, 420520, tzinfo=<UTC>)
>>>
$
</code>```

Body:
I have a model Alerte (below) that is updated in a function like this

Alerte.objects.create(
                asp_ale_loc = site,
                asp_ale_typ = 1, # activation de l'alerte
                # asp_ale_dat = timezone.now() -> replaced by auto_now_add
            )

I have modified asp_ale_dat format from DateField to DateTimeField and add auto_now_add as an attribute

I have run makemigrations and migrate

but when I create an Alerte object, asp_ale_dat is empty

and if I use timezone.now(), the only date is registered, not time...

class Alerte(models.Model):

    asp_ale_cle = models.AutoField(primary_key=True)
    asp_ale_loc = models.CharField("Site concerned by alert", max_length=10, null=True, blank=True)
    asp_ale_typ = models.IntegerField("Operation type on alert", null=True, blank=True,)
    asp_ale_dat = models.DateTimeField("Operation date on alert", null=True, blank=True,auto_now_add=True)

Body:
I see no reason why that wouldn't work, and indeed I'm unable to reproduce this:

$ pip install django
Successfully installed asgiref-3.2.3 django-3.0.3 pytz-2019.3 sqlparse-0.3.0
$ django-admin startproject so60281850 .
$ subl so60281850/settings.py  # add so60281850 to INSTALLED_APPS
$ subl so60281850/models.py  # add in the model definition
$ python manage.py makemigrations so60281850
Migrations for 'so60281850':
  so60281850/migrations/0001_initial.py
    - Create model Alerte
$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, so60281850
$ python manage.py shell
>>> from so60281850.models import Alerte
>>> a = Alerte.objects.create(asp_ale_loc='foo', asp_ale_typ=1)
>>> a.asp_ale_dat
datetime.datetime(2020, 2, 18, 13, 28, 49, 420520, tzinfo=<UTC>)
>>>
$


问:
Unable to Resolve Module in React Native App for linked library
I have a problem "Unable to resolve module".

// Please, read the question before publish comments with links for first result from google.

This is the import line where I got the error:

```<code>import Interactor from 'react-native-native-orientation-interactor';
</code>```

What I did:

Create a react-native library

Run npm link inside the library folder

Run npm link react-native-native-orientation-interactor inside a demo react-native app

Add import statement

Got the error with import.

If I press Cmd+B on import statement I can open a file from node_modules folder. Also I can see my library (as a link) inside node_modules.

But I didn't find any solution for me.

Upd1: I added my library as a dependency in package.json

```<code>  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-native-orientation-interactor": "*"
  },
</code>```

答:
1 - First of all you have written double native in react-native-native-orientation-interaction

2 - Another thing is, don't add dependencies manually..
Use Proper installation guide like

npm install --save react-native-orientation-interactor
or
yarn add react-native-orientation-interactor

then link the dependency.

3 - And actually I didn't get any module named 'react-native-orientation-interaction'.

react-native-orientation

here is the one of valid module dependency.
always read the whole proper Documentation.( Correct me if I am wrong)

Body:
I have a problem "Unable to resolve module".

// Please, read the question before publish comments with links for first result from google.

This is the import line where I got the error:

import Interactor from 'react-native-native-orientation-interactor';

What I did:

Create a react-native library

Run npm link inside the library folder

Run npm link react-native-native-orientation-interactor inside a demo react-native app

Add import statement

Got the error with import.

If I press Cmd+B on import statement I can open a file from node_modules folder. Also I can see my library (as a link) inside node_modules.

But I didn't find any solution for me.

Upd1: I added my library as a dependency in package.json

  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-native-orientation-interactor": "*"
  },


问:
SwiftUI List freezes on @ObservedObject update
I have the List which automatically fetches more data near the end:

```<code>struct AdCardListView: View {
    @ObservedObject var model: AdListViewModel = AdListViewModel()

    var body: some View {
        List { ForEach(self.model.adArray.enumerated().map({ $0 }), id: \.element.id) { index, ad in
                AdCardView(ad: ad)
                    .onAppear {
                        DispatchQueue.main.async {
                            let count = self.model.adArray.count
                            if index >= count - 5 { //5 Views to the end, start loading more.
                                self.model.fetch(count: count)
                            }
                        }
                }
                }
            }
    }
}
</code>```

Model looking like:

```<code>final class AdListViewModel: ObservableObject {
    @Published var adArray = [Ad]()
    ...
 func fetch(count: Int = 0) {
    ...
    DispatchQueue.main.async {
        self.adArray.append(contentsOf: newAds) //<-- problem here
    }
    ...
}
</code>```

My problem: every @Published/@ObservedObject modification I have a little freeze when scroll list. Also, I found that List recalculates the body of all visible views + a few views above and below.

But I can't determine what leads to hangs of scrolling and fix it (maybe freeze is a transfer to a distance equal to (scrolling speed * rendering time)?

Why SwiftUI recalculate bodies on the existing views? They have not changed!

Can you help me?

答:
Recreation of the body should not be an issue.I doubt that the performance issue is related with the update animations of the List.

Did you try adding .id(UUID()) modifier to your List so that animations are discarded and the list is recreated after updates.

Body:
I have the List which automatically fetches more data near the end:

struct AdCardListView: View {
    @ObservedObject var model: AdListViewModel = AdListViewModel()

    var body: some View {
        List { ForEach(self.model.adArray.enumerated().map({ $0 }), id: \.element.id) { index, ad in
                AdCardView(ad: ad)
                    .onAppear {
                        DispatchQueue.main.async {
                            let count = self.model.adArray.count
                            if index >= count - 5 { //5 Views to the end, start loading more.
                                self.model.fetch(count: count)
                            }
                        }
                }
                }
            }
    }
}

Model looking like:

final class AdListViewModel: ObservableObject {
    @Published var adArray = [Ad]()
    ...
 func fetch(count: Int = 0) {
    ...
    DispatchQueue.main.async {
        self.adArray.append(contentsOf: newAds) //<-- problem here
    }
    ...
}

My problem: every @Published/@ObservedObject modification I have a little freeze when scroll list. Also, I found that List recalculates the body of all visible views + a few views above and below.

But I can't determine what leads to hangs of scrolling and fix it (maybe freeze is a transfer to a distance equal to (scrolling speed * rendering time)?

Why SwiftUI recalculate bodies on the existing views? They have not changed!

Can you help me?


问:
Overloading a function using templates
I am trying to define a function using templates and I want the typename to be either int or anEnum (a specific enum I had defined). I have tried the following but I have failed:

```<code>template <int | anEnum T> // or <int T, anEnum T> or <int, anEnum T>
bool isFunction(const T &aVariable){}
</code>```

What I am trying to do is to use templates, instead of defining two overloaded functions.
I'd prefer the function to be called as the following, without the programmer having to consider the type

```<code>isFunction(aVariable) // and not isFunction<int> (aVariable) nor isFunction<anEnum> (aVariable)
</code>```

Basically, I want this function to be templated for int and aNum types. I have searched for this, but could not find the answer. What may I be missing? Thank you,

答:
I've improved https://stackoverflow.com/a/60271100/12894563 answer. 'If constexpr' can help in this situation:

```<code>template <typename T>
struct always_false : std::false_type {};

template <typename T>
bool isFunction(const T& aVariable)
{
    if constexpr(std::is_same_v<T, int> || std::is_same_v<T, anEnum>)
    {
        std::cout << "int\n";
        // put your code here
        return true;
    }
    else
    {
        static_assert(always_false<T>::value, "You should declare non-template function or write if constexpr branch for your type");
        return false;
    }
}

bool isFunction(std::string_view)
{
    std::cout << "std::string_view\n";
    return true;
}

int main()
{
    isFunction(std::string_view("1L"));
    isFunction(1);
    //isFunction(1L); // will produce an error message from static_assert
}
</code>```

isFunction(1L) will fail becuase there is no overloaded function or 'if constexpr' branch.

UPDATE:
Fixed missed

```<code>template <typename T>
struct always_false : std::false_type {};
</code>```

https://godbolt.org/z/eh4pVn

Title: Overloading a function using templates

Body:
I am trying to define a function using templates and I want the typename to be either int or anEnum (a specific enum I had defined). I have tried the following but I have failed:

template <int | anEnum T> // or <int T, anEnum T> or <int, anEnum T>
bool isFunction(const T &aVariable){}

What I am trying to do is to use templates, instead of defining two overloaded functions.
I'd prefer the function to be called as the following, without the programmer having to consider the type

isFunction(aVariable) // and not isFunction<int> (aVariable) nor isFunction<anEnum> (aVariable)

Basically, I want this function to be templated for int and aNum types. I have searched for this, but could not find the answer. What may I be missing? Thank you,

Body:
I've improved https://stackoverflow.com/a/60271100/12894563 answer. 'If constexpr' can help in this situation:

template <typename T>
struct always_false : std::false_type {};

template <typename T>
bool isFunction(const T& aVariable)
{
    if constexpr(std::is_same_v<T, int> || std::is_same_v<T, anEnum>)
    {
        std::cout << "int\n";
        // put your code here
        return true;
    }
    else
    {
        static_assert(always_false<T>::value, "You should declare non-template function or write if constexpr branch for your type");
        return false;
    }
}

bool isFunction(std::string_view)
{
    std::cout << "std::string_view\n";
    return true;
}

int main()
{
    isFunction(std::string_view("1L"));
    isFunction(1);
    //isFunction(1L); // will produce an error message from static_assert
}

isFunction(1L) will fail becuase there is no overloaded function or 'if constexpr' branch.

UPDATE:
Fixed missed

template <typename T>
struct always_false : std::false_type {};

https://godbolt.org/z/eh4pVn


问:
Is Ext-GWT still a nightmare?
Just got back reading a question from 2 years ago here.

From there and several other places on the internet i concluded that developing with Ext-GWT was sucky.

My question is, with the release of GXT 3, whether it is still the condition now?

答: In our current project we have been using Ext-GWT 2 for about a year without any major complaint. It's sometimes a bit buggy but generally works.</p>

Title: Is Ext-GWT still a nightmare?


问:
android recyclerview removing all items conflicts with item decoration of first item
in order to remove all items from recyclerview, I'm using the below code:

```<code>    int size = recyclerViewAdapter.getItemCount();
    recyclerViewAdapter.clearList();
    recyclerViewAdapter.notifyItemRangeRemoved(0, size);
</code>```

the recycler view is using the following ItemDecoration:

```<code>public class CollectionsDecoration extends RecyclerView.ItemDecoration {
    private int margin;

    public CollectionsDecoration(Context context) {
        margin = MeasurementsComputer.getPX(5, context);
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        outRect.left = 0;
        outRect.right = 0;
        outRect.bottom = 0;
        if (parent.getChildAdapterPosition(view) == 0)
            outRect.top = 15 * margin;
        else
            outRect.top = 0;
    }
}
</code>```

as you can see, the first item has a larger top margin. the problem is that when I run the above code to remove all items, all items including the first item gets the top margin of zero, and then they get removed and hided. why the item decoration of first item is not respected at the time of removing?

答:
If I understand correctly, you want to keep item decoration when you remove all items?
In that case, you can try adding separate view on top, and when the list is empty, set its visibility to View.VISIBLE, and when the list is not empty, set it to View.INVISIBLE. </p>

<p>Example of custom view as a decorator: </p>

```<code>
    <View
            android:id="@+id/dividerView"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#E3E4E5" />
</code>```

Body:
in order to remove all items from recyclerview, I'm using the below code:

    int size = recyclerViewAdapter.getItemCount();
    recyclerViewAdapter.clearList();
    recyclerViewAdapter.notifyItemRangeRemoved(0, size);

the recycler view is using the following ItemDecoration:

public class CollectionsDecoration extends RecyclerView.ItemDecoration {
    private int margin;

    public CollectionsDecoration(Context context) {
        margin = MeasurementsComputer.getPX(5, context);
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        outRect.left = 0;
        outRect.right = 0;
        outRect.bottom = 0;
        if (parent.getChildAdapterPosition(view) == 0)
            outRect.top = 15 * margin;
        else
            outRect.top = 0;
    }
}

as you can see, the first item has a larger top margin. the problem is that when I run the above code to remove all items, all items including the first item gets the top margin of zero, and then they get removed and hided. why the item decoration of first item is not respected at the time of removing?

Body:
If I understand correctly, you want to keep item decoration when you remove all items?
In that case, you can try adding separate view on top, and when the list is empty, set its visibility to View.VISIBLE, and when the list is not empty, set it to View.INVISIBLE.

Example of custom view as a decorator:

    <View
            android:id="@+id/dividerView"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#E3E4E5" />


问:
Default filename appears truncated in Windows IFileDialog
When using the Windows IFileDialog interface to launch File browser dialog, I face an issue if the default filename provided exceeds certain number of characters.

The filename appears truncated, although it is simply wrapped around so that we can only see last few characters. It seems the issue lies with the Windows file browser dialog. Whenever the default filename provided exceeds 12-13 characters, it gets wrapped around.

Has anyone encountered such an issue? Is there any workaround?

OS detail:

Windows 10, Version 1709 (OS Build 16299.1625)

Dialog snapshot:

Code snippet shared below:

This is the function that gets called from an MFC application when a button - "BrowseFile" is clicked.

```<code>void CCustomFileBrowserNewDlg::OnBnClickedBrowseFile()
{
    IFileDialog* pfd = nullptr;
    IID id = CLSID_FileSaveDialog;

    const COMDLG_FILTERSPEC c_rgSaveTypes[] =
    {
        {L"Word Document (*.doc)",       L"*.doc"},
        {L"Web Page (*.htm; *.html)",    L"*.htm;*.html"},
        {L"Text Document (*.txt)",       L"*.txt"},
    };

    HRESULT hr = CoCreateInstance(id, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd));
    if (SUCCEEDED(hr))
    {
        hr = pfd->SetFileTypes(ARRAYSIZE(c_rgSaveTypes), c_rgSaveTypes);
        if (SUCCEEDED(hr))
        {
            hr = pfd->SetFileTypeIndex(1);
            if (SUCCEEDED(hr))
            {
                //pfd->SetFileName(L"Filename.txt");       // This is okay
                pfd->SetFileName(L"SomeLongFilename.txt"); // This name gets wrapped around
                pfd->Show(::GetActiveWindow());
            }
        }

        pfd->Release();
    }
}
</code>```

答:
Few errors in your example. An example that you provided is of save dialog and screenshot is open dialog.

The issue that you are talking about will never reproducible on save dialog because filter combo box and save button are on the next line of default text edit control.

Now your problem is specific to open dialog and default text is not truncating its hiding towards left due to less space availability in the same line. i.e. since file name static text, default text edit control and filter combo box are on the same line, windows interpret this as less availability of space for default text and wrap the text towards left. If you scroll text cursor towards file name static control then you will get complete text. You may raise this concern to MSDN.

Now, a workaround to your problem is to show open file dialog in maximize mode. One way to do this is once a dialog is open then maximize it. Next onwards dialog will open in maximize mode.

Body:
When using the Windows IFileDialog interface to launch File browser dialog, I face an issue if the default filename provided exceeds certain number of characters.

The filename appears truncated, although it is simply wrapped around so that we can only see last few characters. It seems the issue lies with the Windows file browser dialog. Whenever the default filename provided exceeds 12-13 characters, it gets wrapped around.

Has anyone encountered such an issue? Is there any workaround?

OS detail:

Windows 10, Version 1709 (OS Build 16299.1625)

Dialog snapshot:

Code snippet shared below:

This is the function that gets called from an MFC application when a button - "BrowseFile" is clicked.

void CCustomFileBrowserNewDlg::OnBnClickedBrowseFile()
{
    IFileDialog* pfd = nullptr;
    IID id = CLSID_FileSaveDialog;

    const COMDLG_FILTERSPEC c_rgSaveTypes[] =
    {
        {L"Word Document (*.doc)",       L"*.doc"},
        {L"Web Page (*.htm; *.html)",    L"*.htm;*.html"},
        {L"Text Document (*.txt)",       L"*.txt"},
    };

    HRESULT hr = CoCreateInstance(id, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd));
    if (SUCCEEDED(hr))
    {
        hr = pfd->SetFileTypes(ARRAYSIZE(c_rgSaveTypes), c_rgSaveTypes);
        if (SUCCEEDED(hr))
        {
            hr = pfd->SetFileTypeIndex(1);
            if (SUCCEEDED(hr))
            {
                //pfd->SetFileName(L"Filename.txt");       // This is okay
                pfd->SetFileName(L"SomeLongFilename.txt"); // This name gets wrapped around
                pfd->Show(::GetActiveWindow());
            }
        }

        pfd->Release();
    }
}


问:
Injecting JSON parameter in nativeQuery
This works when

```<code>@Query(
  value = "SELECT * FROM person WHERE school = :schoolId AND details @> '{\"id\":\"1234\",\"name\":\"John\"}'",
  nativeQuery = true
)
</code>```

I am passing @Param("schoolId") String schoolId

But when I pass the JSON as a param, it fails with

```<code>org.springframework.dao.InvalidDataAccessResourceUsageException, could not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract ResultSet

org.postgresql.util.PSQLException: ERROR: operator does not exist: jsonb @> character varying
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

@Query(value = "SELECT * FROM person WHERE school = :schoolId AND details @> :details", nativeQuery = true)

@Param("schoolId") String schoolId, @Param("details") String details
</code>```

答:
Thanks for this.

Just in addition to the solution, you can also do the cast as:

details @> :details::jsonb

I'm using version 11 of postgres, not sure when it was introduced.

Title: Injecting JSON parameter in nativeQuery

Body:
This works when

@Query(
  value = "SELECT * FROM person WHERE school = :schoolId AND details @> '{\"id\":\"1234\",\"name\":\"John\"}'",
  nativeQuery = true
)

I am passing @Param("schoolId") String schoolId

But when I pass the JSON as a param, it fails with

org.springframework.dao.InvalidDataAccessResourceUsageException, could not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract ResultSet

org.postgresql.util.PSQLException: ERROR: operator does not exist: jsonb @> character varying
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

@Query(value = "SELECT * FROM person WHERE school = :schoolId AND details @> :details", nativeQuery = true)

@Param("schoolId") String schoolId, @Param("details") String details


问:
Which is the Hash function with minimal collsion for strings with length < 255 Chars and relatively fast enough?
We get Transactional Data with a transaction id of length < 255 chars and is always UNIQUE.

But the limitation here is we aren't allowed to store the transaction id in our database.

Hence to uniquely identify a transaction we thought of using a hash fn to generate a hash using transaction id as the input.

So that, we do not save duplicate transactions as it would corrupt the metadata that we want to calculate. Ex: Averages, Standard Deviations, etc.

For a large amounts of transaction data coming into the system, which is the hash fn you would recommend that has lower collision probabilty and is fast enough ?

By Fast enough i mean, generate a hash in < 100 ns.

The Provider of this transactions data hasn't faced the same problem cause they are the generators and we are the first consumers.

I also looked up a few answers on StackOverFlow which suggested that SHA-512 is a bit faster than SHA-256 on 64 bit systems.

Also, is there a better approach for solving this ?

Thank you

答:
<s>Do not (ab)use a hash function for this. Hashing is good for protecting passwords, or for hash maps, where you have a secondary criteria to validate, that an object is in fact the object you expect. But using a hash as a presumably unique key (when it is not guaranteed to be) is inherently risky.</s>

As corrently mentioned, the likelyhood for SHA256-collisions is infinitesimal, so you could do that, at a low risk.

Because a hash function does not (and can never) guarantee absolute non-collision, there might be alternatives.

Question: Can you store the transaction timestamp? - if so, you could couple the timestamp with a numeric postfix, to achieve an internal id (different from the transaction id you originally have). This is way superior to a hash, in terms of uniqueness. It comes with the benefit of being exceedingly fast. But you'd have to store that postfix with the original object to be able to reproduce this internal id.

Essentially what you need is a function to determine a (definetly) unique key from a transaction object, based on attributes that you are allowed to store. Assuming you are allowed to store the timestamp and a numeric postfix, the following example is a possible solution.

In case you get timestamp-collisions, you increase the numeric postfix, so you'd get:

2020-02-18-14-26-15-420-0 (postfic here is -0)
2020-02-18-14-26-15-420-1 (postfic here is -1)
2020-02-18-14-26-15-420-2 (postfic here is -2)
2020-02-18-14-26-15-423-0 (postfic here is -2)
```

Here some transactions have arrived at the same time. However they are still uniquely identifiable.

Body:
<s>Do not (ab)use a hash function for this. Hashing is good for protecting passwords, or for hash maps, where you have a secondary criteria to validate, that an object is in fact the object you expect. But using a hash as a presumably unique key (when it is not guaranteed to be) is inherently risky.</s>

As corrently mentioned, the likelyhood for SHA256-collisions is infinitesimal, so you could do that, at a low risk.

Because a hash function does not (and can never) guarantee absolute non-collision, there might be alternatives.

Question: Can you store the transaction timestamp? - if so, you could couple the timestamp with a numeric postfix, to achieve an internal id (different from the transaction id you originally have). This is way superior to a hash, in terms of uniqueness. It comes with the benefit of being exceedingly fast. But you'd have to store that postfix with the original object to be able to reproduce this internal id.

Essentially what you need is a function to determine a (definetly) unique key from a transaction object, based on attributes that you are allowed to store. Assuming you are allowed to store the timestamp and a numeric postfix, the following example is a possible solution.

In case you get timestamp-collisions, you increase the numeric postfix, so you'd get:

2020-02-18-14-26-15-420-0 (postfic here is -0)
2020-02-18-14-26-15-420-1 (postfic here is -1)
2020-02-18-14-26-15-420-2 (postfic here is -2)
2020-02-18-14-26-15-423-0 (postfic here is -2)

Here some transactions have arrived at the same time. However they are still uniquely identifiable.