问:
Visual Studio code cleanup - where is configuration?
When I open Configure Code Cleanup in VS 2019, there are entries like "Apply expression/block body preferences".

Where are those "preferences"? How can I configure this tool?

答: In the Options dialog box, select Text Editor > [C# or Basic] > Code Style > General.</p>


来源: stackexchange

问:
Joomla module position not appearing
I have created a joomla template on localhost. It was working and all the module positions are displaying their respected modules. However, when I upload the website to a live server I found that jdoc: type="modules" code is not working at all. All other themes are working fine on the server.

Here is the link to my website.

http://www2.adcirrus.com/

Between
I am using XAMPP on my local machine with no extra configuration.

答:
You have to correct this, and see what happens (u missing a ">" sign):

```<code><div class="lower-header" <jdoc:include type="modules" name="lower_header" style="xhtml" />
</code>```

to this:

```<code><div class="lower-header"> <jdoc:include type="modules" name="lower_header" style="xhtml" />
</code>```

the div tag have to be closed.

And that "xhtml" style is defined?

ContentLicense: CC BY-SA 4.0

Title: Joomla module position not appearing

Body:
You have to correct this, and see what happens (u missing a ">" sign):

<div class="lower-header" <jdoc:include type="modules" name="lower_header" style="xhtml" />

to this:

<div class="lower-header"> <jdoc:include type="modules" name="lower_header" style="xhtml" />

the div tag have to be closed.

And that "xhtml" style is defined?

ContentLicense: CC BY-SA 3.0


问:
Find the number of days using date picker and current date
I am Trying to get the difference between the number of days. using date picker dialog with the current date

```<code>datepicker = findViewById(R.id.date_picker_date);
        textView=findViewById(R.id.textView);

        datepicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar cldr = Calendar.getInstance();
                int day = cldr.get(Calendar.DAY_OF_MONTH);
                int month = cldr.get(Calendar.MONTH);
                int year = cldr.get(Calendar.YEAR);

                String date = day + "/" + (month+1) + "/" + year;

                TextView textView=findViewById(R.id.textView);
                textView.setText(date);

                datepicker.setInputType(InputType.TYPE_NULL);
                datepicker.setShowSoftInputOnFocus(false);

                // date picker dialog
                picker = new DatePickerDialog(MainActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
                            {
                                datepicker.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
                            }
                        }, year, month, day);
                picker.show();
</code>```

Not getting the difference between the picking date and current date

答:
Use this method, pass your date in the format "MM/dd/yyyy" and you will get the difference between two dates in days.</p>

```<code>public static String daysDiff(String cDate, String rDate){
        String dayDifference;
        try {
            //Dates to compare
            String CurrentDate = cDate;
            String FinalDate = rDate;

            Date date1;
            Date date2;

            SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");

            //Setting dates
            date1 = dates.parse(CurrentDate);
            date2 = dates.parse(FinalDate);

            //Comparing dates
            long difference = Math.abs(date1.getTime() - date2.getTime());
            long differenceDates = difference / (24 * 60 * 60 * 1000);

            //Convert long to String
            dayDifference = Long.toString(differenceDates);

//            Log.e("hit", "HERE: " + dayDifference);

            return dayDifference;

        } catch (Exception exception) {
//            Log.e("DIDN'T WORK", "exception " + exception);
            return "";
        }
    }
</code>```

Body:
I am Trying to get the difference between the number of days. using date picker dialog with the current date

datepicker = findViewById(R.id.date_picker_date);
        textView=findViewById(R.id.textView);

        datepicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar cldr = Calendar.getInstance();
                int day = cldr.get(Calendar.DAY_OF_MONTH);
                int month = cldr.get(Calendar.MONTH);
                int year = cldr.get(Calendar.YEAR);

                String date = day + "/" + (month+1) + "/" + year;

                TextView textView=findViewById(R.id.textView);
                textView.setText(date);

                datepicker.setInputType(InputType.TYPE_NULL);
                datepicker.setShowSoftInputOnFocus(false);

                // date picker dialog
                picker = new DatePickerDialog(MainActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
                            {
                                datepicker.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
                            }
                        }, year, month, day);
                picker.show();

Not getting the difference between the picking date and current date

Body:
Use this method, pass your date in the format "MM/dd/yyyy" and you will get the difference between two dates in days.

public static String daysDiff(String cDate, String rDate){
        String dayDifference;
        try {
            //Dates to compare
            String CurrentDate = cDate;
            String FinalDate = rDate;

            Date date1;
            Date date2;

            SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");

            //Setting dates
            date1 = dates.parse(CurrentDate);
            date2 = dates.parse(FinalDate);

            //Comparing dates
            long difference = Math.abs(date1.getTime() - date2.getTime());
            long differenceDates = difference / (24 * 60 * 60 * 1000);

            //Convert long to String
            dayDifference = Long.toString(differenceDates);

//            Log.e("hit", "HERE: " + dayDifference);

            return dayDifference;

        } catch (Exception exception) {
//            Log.e("DIDN'T WORK", "exception " + exception);
            return "";
        }
    }


问:
how to get all value from while loop not just 1st iteration?
The final is the numpy array with 4 rows and I need to get all value from nested while loop, but this code just returns 1st row of final or 1st iteration of loop.</p>

```<code>def amir2 (final):
    i = 0
    j = 0
    temp = []
    temp2 = []
    temp3 = []
    while i < len(final):
        while j < len(final):
            cos_lib = coss(final[i] , final[j])
            temp.append(cos_lib)
            j += 1
        temp2.append(temp)
        i += 1
    return temp2
</code>```

答:
You need to provide details on the exact format of the numpy array final and also what you're trying to do in your loop with the coss method.

If final is defined like this:

```<code>final = np.array([[1,2,3],[1,2,3],[1,2,3]], dtype=np.float64)
</code>```

you can get the array using the .shape so you can iterate over all elements of the array as follows:

```<code>for x in range(0, final.shape[0]):
    for y in range(0, final.shape[1]):
        print final[x, y]
</code>```

Body:
The final is the numpy array with 4 rows and I need to get all value from nested while loop, but this code just returns 1st row of final or 1st iteration of loop.

def amir2 (final):
    i = 0
    j = 0
    temp = []
    temp2 = []
    temp3 = []
    while i < len(final):
        while j < len(final):
            cos_lib = coss(final[i] , final[j])
            temp.append(cos_lib)
            j += 1
        temp2.append(temp)
        i += 1
    return temp2

Body:
You need to provide details on the exact format of the numpy array final and also what you're trying to do in your loop with the coss method.

If final is defined like this:

final = np.array([[1,2,3],[1,2,3],[1,2,3]], dtype=np.float64)

you can get the array using the .shape so you can iterate over all elements of the array as follows:

for x in range(0, final.shape[0]):
    for y in range(0, final.shape[1]):
        print final[x, y]


问:
What are Automatic Properties in C# and what is their purpose?
Could someone provide a very simple explanation of Automatic Properties in C#, their purpose, and maybe some examples? Try to keep things in layman's terms, please!</p>

答:
Use below code:

```<code>using System;

class My Class
{
    public string Dummy { get; set; }

    public My Class()
    {
        Dummy = "I'm dummy property";
    }
}

class Program
{
    static void Main()
    {
            var my Class = new My Class();
             Console .Write Line (my Class .Dummy);
    }
}
</code>```

Body:
Use below code:

using System;

class My Class
{
    public string Dummy { get; set; }

    public My Class()
    {
        Dummy = "I'm dummy property";
    }
}

class Program
{
    static void Main()
    {
            var my Class = new My Class();
             Console .Write Line (my Class .Dummy);
    }
}


问:
Dockerfile alpine image apk cannot find Java 8
I wanted to reduce my docker image and switched to an alpine base image instead. This lead to problems bash not finding apt. Turns out, I have to use apk instead. However, it does not seem to find the java version I need. Here is my dockerfile

```<code>#Use alpine golang
FROM golang:alpine

#Get the code from local code commit repo
WORKDIR /go/src/xxx
COPY . /go/src/xxx

#Install Java and cleanup after in the same layer
RUN apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*

#Install dependencies recursively and remove the third_party directory after it has been used for compiling.
RUN go get ./... && go run setup.go && RUN rm -rf third_party
#More commands...

 ---> 32a6b6b5f196
Step 4/8 : RUN apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*
 ---> Running in bc48930e48be
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
v3.9.4-4-gd5dd5c1cd0 [http://dl-cdn.alpinelinux.org/alpine/v3.9/main]
v3.9.4-5-gcfdf5452f1 [http://dl-cdn.alpinelinux.org/alpine/v3.9/community]
OK: 9766 distinct packages available
  openjdk-8-jre-headless (missing):
·[91mERROR: unsatisfiable constraints:
·[0m    required by: world[openjdk-8-jre-headless]
The command '/bin/sh -c apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*' returned a non-zero code: 1
</code>```

I have also tried

```<code>RUN apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*
</code>```

According to https://unix.stackexchange.com/questions/342403/openjdk-8-jre-headless-depends-ca-certificates-java-but-it-is-not-going-to-be but that also fails, not sure if the -t flags fault:

```<code>Step 4/7 : RUN apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*
 ---> Running in 1e2ef22e7c16
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
v3.9.4-4-gd5dd5c1cd0 [http://dl-cdn.alpinelinux.org/alpine/v3.9/main]
v3.9.4-5-gcfdf5452f1 [http://dl-cdn.alpinelinux.org/alpine/v3.9/community]
OK: 9766 distinct packages available
·[91mERROR: unsatisfiable constraints:
·[0m  openjdk-8-jre-headless (missing):
    required by: jessie-backports-0[openjdk-8-jre-headless]
  ca-certificates-java (missing):
    required by: jessie-backports-0[ca-certificates-java]
The command '/bin/sh -c apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*' returned a non-zero code: 3
</code>```

答: Alpine uses entirely different package repositories than Debian or Ubuntu. The package openjdk-8-jre-headless doesn't exist there. You can check this here and find the correct package that fits your needs.

Body:
I wanted to reduce my docker image and switched to an alpine base image instead. This lead to problems bash not finding apt. Turns out, I have to use apk instead. However, it does not seem to find the java version I need. Here is my dockerfile

#Use alpine golang
FROM golang:alpine

#Get the code from local code commit repo
WORKDIR /go/src/xxx
COPY . /go/src/xxx

#Install Java and cleanup after in the same layer
RUN apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*

#Install dependencies recursively and remove the third_party directory after it has been used for compiling.
RUN go get ./... && go run setup.go && RUN rm -rf third_party
#More commands...

 ---> 32a6b6b5f196
Step 4/8 : RUN apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*
 ---> Running in bc48930e48be
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
v3.9.4-4-gd5dd5c1cd0 [http://dl-cdn.alpinelinux.org/alpine/v3.9/main]
v3.9.4-5-gcfdf5452f1 [http://dl-cdn.alpinelinux.org/alpine/v3.9/community]
OK: 9766 distinct packages available
  openjdk-8-jre-headless (missing):
·[91mERROR: unsatisfiable constraints:
·[0m    required by: world[openjdk-8-jre-headless]
The command '/bin/sh -c apk update && apk add openjdk-8-jre-headless && rm -rf /var/lib/apt/lists/*' returned a non-zero code: 1

I have also tried

RUN apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*

According to https://unix.stackexchange.com/questions/342403/openjdk-8-jre-headless-depends-ca-certificates-java-but-it-is-not-going-to-be but that also fails, not sure if the -t flags fault:

Step 4/7 : RUN apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*
 ---> Running in 1e2ef22e7c16
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz
v3.9.4-4-gd5dd5c1cd0 [http://dl-cdn.alpinelinux.org/alpine/v3.9/main]
v3.9.4-5-gcfdf5452f1 [http://dl-cdn.alpinelinux.org/alpine/v3.9/community]
OK: 9766 distinct packages available
·[91mERROR: unsatisfiable constraints:
·[0m  openjdk-8-jre-headless (missing):
    required by: jessie-backports-0[openjdk-8-jre-headless]
  ca-certificates-java (missing):
    required by: jessie-backports-0[ca-certificates-java]
The command '/bin/sh -c apk update && apk add -t jessie-backports openjdk-8-jre-headless ca-certificates-java && rm -rf /var/lib/apt/lists/*' returned a non-zero code: 3


问:
FormsAuthentication.RedirectFromLoginPage Vs Response.Redirect
This is with reference to a question asked here Login user after signup and here FormsAuthentication.RedirectFromLoginPage reload page.

Though I have answered the first question but i will admit that it's just "programming by co-incidence". If you see, answers to above two questions contradict each other but still both worked for respective users.

I would like to know what is the exact difference between this

```<code>FormsAuthentication.SetAuthCookie(USER_NAME, true);

Response.Redirect("copyPastPage.aspx");
</code>```

And this FormsAuthentication.RedirectFromLoginPage(mainSignUp.UserName, true);

In terms of usage, we can see a logical difference that Response.Redirect can allow redirecting to any URL as against RedirectFromLoginPage would redirect only to the referrer. But that's usage difference.

Is there any fundamental diffence in their way of execution? If not, any thoughts why one would work at times and why other at times? what exactly happens under the hood of each of them?

I have google a bit but could not get any concrete answer.

答:
If you look at the code in RedirectFromLoginPage it does essentially the same

SetAuthCookie

get return URL from query string

Clear return URL

Here is a snippet:

```<code>    HttpContext current = HttpContext.Current;
    string returnUrl = GetReturnUrl(true);
    if (CookiesSupported || IsPathWithinAppRoot(current, returnUrl))
    {
        SetAuthCookie(userName, createPersistentCookie, strCookiePath);
        returnUrl = RemoveQueryStringVariableFromUrl(returnUrl, FormsCookieName);
        if (!CookiesSupported)
        {
            int index = returnUrl.IndexOf("://", StringComparison.Ordinal);
            if (index > 0)
            {
                index = returnUrl.IndexOf('/', index + 3);
                if (index > 0)
                {
                    returnUrl = returnUrl.Substring(index);
                }
            }
        }
</code>```

But it does also check for support for cookie.

Body:
This is with reference to a question asked here Login user after signup and here FormsAuthentication.RedirectFromLoginPage reload page.

Though I have answered the first question but i will admit that it's just "programming by co-incidence". If you see, answers to above two questions contradict each other but still both worked for respective users.

I would like to know what is the exact difference between this

FormsAuthentication.SetAuthCookie(USER_NAME, true);

Response.Redirect("copyPastPage.aspx");

And this FormsAuthentication.RedirectFromLoginPage(mainSignUp.UserName, true);

In terms of usage, we can see a logical difference that Response.Redirect can allow redirecting to any URL as against RedirectFromLoginPage would redirect only to the referrer. But that's usage difference.

Is there any fundamental diffence in their way of execution? If not, any thoughts why one would work at times and why other at times? what exactly happens under the hood of each of them?

I have google a bit but could not get any concrete answer.

Body:
If you look at the code in RedirectFromLoginPage it does essentially the same

SetAuthCookie

get return URL from query string

Clear return URL

Here is a snippet:

    HttpContext current = HttpContext.Current;
    string returnUrl = GetReturnUrl(true);
    if (CookiesSupported || IsPathWithinAppRoot(current, returnUrl))
    {
        SetAuthCookie(userName, createPersistentCookie, strCookiePath);
        returnUrl = RemoveQueryStringVariableFromUrl(returnUrl, FormsCookieName);
        if (!CookiesSupported)
        {
            int index = returnUrl.IndexOf("://", StringComparison.Ordinal);
            if (index > 0)
            {
                index = returnUrl.IndexOf('/', index + 3);
                if (index > 0)
                {
                    returnUrl = returnUrl.Substring(index);
                }
            }
        }

But it does also check for support for cookie.


问:
How can I make sure that all the elements in an array are unique?
I am building a Linq framework for school in Typescript as part of a homework project. I have a problem when it comes to the Select method. I pass the Select an array of properties, but the problem is that Typescript allows duplicate values in the array. Is there a way in Typescript or Javascript to have an array of only unique values?

Right now the Select method looks like this:

In the interface:

```<code> Select: <K extends keyof T>(this: Table<T, U>, ...properties: K[]) => Table<Omit<T, K>, Pick<T, K> & U>
</code>```

The implementation:

```<code>    Select: function <K extends keyof T>(this: Table<T, U>, ...properties: K[]): Table<Omit<T, K>, Pick<T, K> & U> {
        let selection = this.data.First.map(entry => pickMany(entry, properties))

        let result = this.data.map(
            first => first.map(entry => omitMany(entry, properties))
            ,
            second => merge_list_types(second.zip(selection))
        )

        return Table(result)
    }
</code>```

Right now it is possible to say:

customers.Select("name", "name", "age")

As expected the code above will give me a type error, because 'name' is already selected.

答:
You can't ensure array uniqueness in a general way (at least not in a supported general way, you can do some crazy stuff with recursive type alias but they will likely break from a version to another).

We can create a conditional type that ensures uniqueness for up to a number of elements and add more as necessary.

```<code>type Omit<T, K extends PropertyKey> = Pick<T, Extract<keyof T, K>>
type IsUnique<T extends any[]> = UK0<T, "Items are not unique", {}>

type Tail<T extends any[]> = ((...a: T) => void) extends (p: any, ...t: infer P) => void ? P : [];
type UK0<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK1<Tail<T>, TErr, TOk>
type UK1<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK2<Tail<T>, TErr, TOk>
type UK2<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK3<Tail<T>, TErr, TOk>
type UK3<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK4<Tail<T>, TErr, TOk>
type UK4<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK5<Tail<T>, TErr, TOk>
type UK5<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK6<Tail<T>, TErr, TOk>
type UK6<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : "Array to big"

class Table<T, U> {
    Select = function <K extends Array<keyof T>>(this: Table<T, U>, ...properties: K & IsUnique<K>): Table<Omit<T, K[number]>, Pick<T, K[number]> & U> {

        return null!;
    }
}

new Table<{ a: 0, b: 0}, {}>().Select("a") //ok
new Table<{ a: 0, b: 0}, {}>().Select("a", "a") // err
new Table<{ a: 0, b: 0}, {}>().Select("a", "b") //ok
</code>```

A better way would actually to use an object type instead, objects intrinsically do not allow key duplication.

```<code>class Table<T, U> {
    Select = function <K extends Partial<Record<keyof T, true>>>(this: Table<T, U>, properties: K): Table<Omit<T, keyof K>, Pick<T, keyof K> & U> {

        return null!;
    }
}

new Table<{ a: 0, b: 0}, {}>().Select({ a: true }) //ok
new Table<{ a: 0, b: 0}, {}>().Select({ a: true, a: true }) // err
new Table<{ a: 0, b: 0}, {}>().Select({ a: true, b: true }) //ok
</code>```

Body:
I am building a Linq framework for school in Typescript as part of a homework project. I have a problem when it comes to the Select method. I pass the Select an array of properties, but the problem is that Typescript allows duplicate values in the array. Is there a way in Typescript or Javascript to have an array of only unique values?

Right now the Select method looks like this:

In the interface:

 Select: <K extends keyof T>(this: Table<T, U>, ...properties: K[]) => Table<Omit<T, K>, Pick<T, K> & U>

The implementation:

    Select: function <K extends keyof T>(this: Table<T, U>, ...properties: K[]): Table<Omit<T, K>, Pick<T, K> & U> {
        let selection = this.data.First.map(entry => pickMany(entry, properties))

        let result = this.data.map(
            first => first.map(entry => omitMany(entry, properties))
            ,
            second => merge_list_types(second.zip(selection))
        )

        return Table(result)
    }

Right now it is possible to say:

customers.Select("name", "name", "age")

As expected the code above will give me a type error, because 'name' is already selected.

Body:
You can't ensure array uniqueness in a general way (at least not in a supported general way, you can do some crazy stuff with recursive type alias but they will likely break from a version to another).

We can create a conditional type that ensures uniqueness for up to a number of elements and add more as necessary.

type Omit<T, K extends PropertyKey> = Pick<T, Extract<keyof T, K>>
type IsUnique<T extends any[]> = UK0<T, "Items are not unique", {}>

type Tail<T extends any[]> = ((...a: T) => void) extends (p: any, ...t: infer P) => void ? P : [];
type UK0<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK1<Tail<T>, TErr, TOk>
type UK1<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK2<Tail<T>, TErr, TOk>
type UK2<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK3<Tail<T>, TErr, TOk>
type UK3<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK4<Tail<T>, TErr, TOk>
type UK4<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK5<Tail<T>, TErr, TOk>
type UK5<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : UK6<Tail<T>, TErr, TOk>
type UK6<T extends any[], TErr, TOk> = T extends [] ? TOk : T[0] extends Tail<T>[number] ? TErr : "Array to big"

class Table<T, U> {
    Select = function <K extends Array<keyof T>>(this: Table<T, U>, ...properties: K & IsUnique<K>): Table<Omit<T, K[number]>, Pick<T, K[number]> & U> {

        return null!;
    }
}

new Table<{ a: 0, b: 0}, {}>().Select("a") //ok
new Table<{ a: 0, b: 0}, {}>().Select("a", "a") // err
new Table<{ a: 0, b: 0}, {}>().Select("a", "b") //ok

A better way would actually to use an object type instead, objects intrinsically do not allow key duplication.

class Table<T, U> {
    Select = function <K extends Partial<Record<keyof T, true>>>(this: Table<T, U>, properties: K): Table<Omit<T, keyof K>, Pick<T, keyof K> & U> {

        return null!;
    }
}

new Table<{ a: 0, b: 0}, {}>().Select({ a: true }) //ok
new Table<{ a: 0, b: 0}, {}>().Select({ a: true, a: true }) // err
new Table<{ a: 0, b: 0}, {}>().Select({ a: true, b: true }) //ok


问:
Using a play button ('Click Me') over default video poster not working
I have a video . I have placed a text "Click Me" at the center of the video.

My requirement is - on clicking on the "Click Me" or any part of the video , the video should play and "Click Me" disappear.

```<code>.banner-description{
    position: absolute;
    font-weight: bold;
    top : 50%;
    left: 50%;
    background: rebeccapurple;
}
.video-banner{
    position: relative;
}

<body>

    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis laudantium nobis laboriosam quaerat. Quo, veritatis harum nemo eligendi sed dicta fugiat ad. Voluptas ea maxime qui nostrum blanditiis facere natus!
    </div>

    <div class="video-banner">
        <video controls>
            <source src="011-video-files.mp4">
        </video>
        <div class="banner-description">
            <p>Click Me</p>
        </div>
    </div>

    <div>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde explicabo repellat minima magnam totam, temporibus nemo saepe praesentium ipsam a quidem. Mollitia vero impedit architecto quod ex voluptates neque eveniet!
    </div>

</body>
</code>```

The problem is : while clicking on the "Click Me" , nothing happens . And , while clicking on some other part of the video, though video starts "Click Me" dose not disappear

答:
Since you use angular you can use *ngIf or *ngShow and with a (click) event you can trigger it</p>

```<code>    <div (click)="showDescription = !showDescription" class="video-banner">
        <video controls>
            <source src="011-video-files.mp4">
        </video>
        <div *ngIf="showDescription" class="banner-description">
            <p>Click Me</p>
        </div>
    </div>
</code>```

Body:
I have a video . I have placed a text "Click Me" at the center of the video.

My requirement is - on clicking on the "Click Me" or any part of the video , the video should play and "Click Me" disappear.

.banner-description{
    position: absolute;
    font-weight: bold;
    top : 50%;
    left: 50%;
    background: rebeccapurple;
}
.video-banner{
    position: relative;
}

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis laudantium nobis laboriosam quaerat. Quo, veritatis harum nemo eligendi sed dicta fugiat ad. Voluptas ea maxime qui nostrum blanditiis facere natus!

        <video controls>
            <source src="011-video-files.mp4">
        </video>

Click Me

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde explicabo repellat minima magnam totam, temporibus nemo saepe praesentium ipsam a quidem. Mollitia vero impedit architecto quod ex voluptates neque eveniet!

The problem is : while clicking on the "Click Me" , nothing happens . And , while clicking on some other part of the video, though video starts "Click Me" dose not disappear

Body:
Since you use angular you can use *ngIf or *ngShow and with a (click) event you can trigger it

    <div (click)="showDescription = !showDescription" class="video-banner">
        <video controls>
            <source src="011-video-files.mp4">
        </video>
        <div *ngIf="showDescription" class="banner-description">
            <p>Click Me</p>
        </div>
    </div>


问:
Is it possible to get an address from coordinates using google maps?
I'm just curious. Maybe for a future project. I want to know if it's possible to retrieve an address from a giving coordinate via the Google API. </p>

答:
TomTom Maps APIs provides with a Reverse Geocoding end point which gives a structured JSON.

You can try it with the API Explorer.

For example :

```<code>curl -X GET "https://api.tomtom.com/search/2/reverseGeocode/37.8328,-122.27669.json?key=*****" -H "accept: */*"
</code>```

Will get you

```<code>{
  "summary": {
    "queryTime": 6,
    "numResults": 1
  },
  "addresses": [
    {
      "address": {
        "buildingNumber": "1001",
        "streetNumber": "1001",
        "routeNumbers": [],
        "street": "42nd Street",
        "streetName": "42nd Street",
        "streetNameAndNumber": "1001 42nd Street",
        "countryCode": "US",
        "countrySubdivision": "CA",
        "countrySecondarySubdivision": "Alameda",
        "countryTertiarySubdivision": "Oakland",
        "municipality": "Oakland, Emeryville",
        "postalCode": "94608",
        "municipalitySubdivision": "Oakland, Emeryville",
        "country": "United States",
        "countryCodeISO3": "USA",
        "freeformAddress": "1001 42nd Street, Emeryville, CA 94608",
        "boundingBox": {
          "northEast": "37.832893,-122.276230",
          "southWest": "37.832777,-122.277006",
          "entity": "position"
        },
        "countrySubdivisionName": "California",
        "localName": "Emeryville"
      },
      "position": "37.832844,-122.276688"
    }
  ]
}
</code>```

You can get a free API KEY (no credit card needed) and try our tutorials!

Disclosure: I am employed at TomTom.

Body:
TomTom Maps APIs provides with a Reverse Geocoding end point which gives a structured JSON.

You can try it with the API Explorer.

For example :

curl -X GET "https://api.tomtom.com/search/2/reverseGeocode/37.8328,-122.27669.json?key=*****" -H "accept: */*"

Will get you

{
  "summary": {
    "queryTime": 6,
    "numResults": 1
  },
  "addresses": [
    {
      "address": {
        "buildingNumber": "1001",
        "streetNumber": "1001",
        "routeNumbers": [],
        "street": "42nd Street",
        "streetName": "42nd Street",
        "streetNameAndNumber": "1001 42nd Street",
        "countryCode": "US",
        "countrySubdivision": "CA",
        "countrySecondarySubdivision": "Alameda",
        "countryTertiarySubdivision": "Oakland",
        "municipality": "Oakland, Emeryville",
        "postalCode": "94608",
        "municipalitySubdivision": "Oakland, Emeryville",
        "country": "United States",
        "countryCodeISO3": "USA",
        "freeformAddress": "1001 42nd Street, Emeryville, CA 94608",
        "boundingBox": {
          "northEast": "37.832893,-122.276230",
          "southWest": "37.832777,-122.277006",
          "entity": "position"
        },
        "countrySubdivisionName": "California",
        "localName": "Emeryville"
      },
      "position": "37.832844,-122.276688"
    }
  ]
}

You can get a free API KEY (no credit card needed) and try our tutorials!

Disclosure: I am employed at TomTom.


问:
java.util.Prefs throwing BackingStoreException - Why?
I have a system that caches the tiny/simple results of an on-startup SOAP call

I need instances to be able to reload their cache on startup (in case the SOAP service is dead) and ALSO handle the possibility of multiple instances using this cache file

I chose to use java.util.prefs but Java's builtin automatic sync thread is intermittently failing (1% of time using default JVM 30s backing store sync) dumping the following the exception:

```<code>Jan 8, 2010 12:30:07 PM java.util.prefs.FileSystemPreferences syncWorld
WARNING: Couldn't flush user prefs: java.util.prefs.BackingStoreException: Couldn't get file lock.
</code>```

I suspected this bug but this was fixed in 1.5(tiger-b40) and our java 5 on this box is "1.5.0_16-b02".

I now suspect that it might be because we have multiple JVMs sharing this Backing Store, although this doesn't seem to happen on our other machines.

Can anyone confirm this?
What are the risks, if any?

If my approach is flawed what should I be using as an alternative?

答: Instead of using Preferences, just use any serializable Map and make a very simple cache class which serializes and deserializes it to a randomly-generated temporary filename (the filename being generated on first initialisation). Since it is only a cache, you can just catch any exceptions and reset the cache back to its initial state when an exception happens, so it will re-fetch from the original data source (the SOAP service in your case). So there's no need to worry about serialVersionUID or any of that compatibility stuff, if you don't want to.</p>

Body:
I have a system that caches the tiny/simple results of an on-startup SOAP call

I need instances to be able to reload their cache on startup (in case the SOAP service is dead) and ALSO handle the possibility of multiple instances using this cache file

I chose to use java.util.prefs but Java's builtin automatic sync thread is intermittently failing (1% of time using default JVM 30s backing store sync) dumping the following the exception:

Jan 8, 2010 12:30:07 PM java.util.prefs.FileSystemPreferences syncWorld
WARNING: Couldn't flush user prefs: java.util.prefs.BackingStoreException: Couldn't get file lock.

I suspected this bug but this was fixed in 1.5(tiger-b40) and our java 5 on this box is "1.5.0_16-b02".

I now suspect that it might be because we have multiple JVMs sharing this Backing Store, although this doesn't seem to happen on our other machines.

Can anyone confirm this?
What are the risks, if any?

If my approach is flawed what should I be using as an alternative?


问:
How to catch exceptions in JUnit
My JUnit test does not catch the exception because of my return statement in the catch block. When I delete returning statement, the test passes. I want my unit test to work with returning statement if the exception occurs.

I've also tried JUnit 5 stuff but it does not fix the problem.

My method:

```<code>public ArrayList<Action> parsePlaByPlayTable() {
    ArrayList<Action> actions = new ArrayList<>();
    Document document = null;

    try {
      document = Jsoup.connect(url).get();
    } catch (Exception e) {
      log.error(e.getMessage());
      return new ArrayList<>();
    }

    // if the exception occurs and there is no return in the catch block,
    // nullPointerException is thrown here
    Element table = document.getElementById("pbp");

    // more code. . .
}
</code>```

My test:

```<code>  @Test(expected = Exception.class)
  public void testParsePlaByPlayTableInvalidUrl() {
    PlayByPlayActionHtmlParser parser = new PlayByPlayActionHtmlParser("https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
    ArrayList<Action> actions = parser.parsePlaByPlayTable();
  }
</code>```

答:
Because you're swallowing the exception in your catch block and returning an empty list. The only way to check if the exception occured is to assert that the returned list is empty.

```<code>@Test
public void testParsePlaByPlayTableInvalidUrl() {
    PlayByPlayActionHtmlParser parser = new PlayByPlayActionHtmlParser("https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
    ArrayList<Action> actions = parser.parsePlaByPlayTable();
    Assert.assertTrue(actions.isEmpty());
}
</code>```

You also need to remove (expected = Exception.class) from your @Test annotation. Because an exception will never be thrown.

Title: How to catch exceptions in JUnit

Body:
My JUnit test does not catch the exception because of my return statement in the catch block. When I delete returning statement, the test passes. I want my unit test to work with returning statement if the exception occurs.

I've also tried JUnit 5 stuff but it does not fix the problem.

My method:

public ArrayList<Action> parsePlaByPlayTable() {
    ArrayList<Action> actions = new ArrayList<>();
    Document document = null;

    try {
      document = Jsoup.connect(url).get();
    } catch (Exception e) {
      log.error(e.getMessage());
      return new ArrayList<>();
    }

    // if the exception occurs and there is no return in the catch block,
    // nullPointerException is thrown here
    Element table = document.getElementById("pbp");

    // more code. . .
}

My test:

  @Test(expected = Exception.class)
  public void testParsePlaByPlayTableInvalidUrl() {
    PlayByPlayActionHtmlParser parser = new PlayByPlayActionHtmlParser("https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
    ArrayList<Action> actions = parser.parsePlaByPlayTable();
  }

Body:
Because you're swallowing the exception in your catch block and returning an empty list. The only way to check if the exception occured is to assert that the returned list is empty.

@Test
public void testParsePlaByPlayTableInvalidUrl() {
    PlayByPlayActionHtmlParser parser = new PlayByPlayActionHtmlParser("https://www.basketbal-reference.com/oxscores/pbp/201905160GS.html");
    ArrayList<Action> actions = parser.parsePlaByPlayTable();
    Assert.assertTrue(actions.isEmpty());
}

You also need to remove (expected = Exception.class) from your @Test annotation. Because an exception will never be thrown.


问:
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: Chrome version must be between 70 and 73 with ChromeDriver
I am trying to create a webcrawler using Selenium, but I get this error when I try to create the webdriver object.

```<code>selenium.common.exceptions.SessionNotCreatedException: Message: session not created: Chrome version must be between 70 and 73
(Driver info: chromedriver=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387),platform=Windows NT 6.1.7601 SP1 x86_64)
</code>```

I downloaded the latest version of chromedriver (2.45) which requires Chrome 70-73. My current Chrome version is 68.0.3440.106 (Official Build) (64-bit), which is the latest. I tried downloading an "older" chrome version (71) and when I tried installing it, the installer indicated that I had a newer version already installed.

There doesn't seem to be any previous Chromedriver releases available for download, even though the website says there is. I couldn't find them.

I don't quite understand how version 71 is older than 68?

Is there a Chrome version newer than 68 actually available, or an older version of chromedriver i can use with Chrome 68?

Does anyone have any other suggestions?

This is the code that i'm trying to execute:

```<code>import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
user = 'XXXXXXX'
pwd = 'XXXXXXX'
chromedriver = "...\...\...\chromedriver.exe"
driver = webdriver.Chrome(executable_path=chromedriver) # Error occurs at this line
driver.get("http://www.facebook.com")
assert "Facebook" in driver.title
time.sleep(5) # So i can see something!
elem = driver.find_element_by_id("email")
elem.send_keys(user)
time.sleep(5) # So i can see something!
elem = driver.find_element_by_id("pass")
elem.send_keys(pwd)
time.sleep(5) # So i can see something!
elem.send_keys(Keys.RETURN)
driver.close()
</code>```

答:
Just download chromedriver extension 2.8 or 2.9 from here.

Extract it and add this extension to /usr/local/bin

Body:
I am trying to create a webcrawler using Selenium, but I get this error when I try to create the webdriver object.

selenium.common.exceptions.SessionNotCreatedException: Message: session not created: Chrome version must be between 70 and 73
(Driver info: chromedriver=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387),platform=Windows NT 6.1.7601 SP1 x86_64)

I downloaded the latest version of chromedriver (2.45) which requires Chrome 70-73. My current Chrome version is 68.0.3440.106 (Official Build) (64-bit), which is the latest. I tried downloading an "older" chrome version (71) and when I tried installing it, the installer indicated that I had a newer version already installed.

There doesn't seem to be any previous Chromedriver releases available for download, even though the website says there is. I couldn't find them.

I don't quite understand how version 71 is older than 68?

Is there a Chrome version newer than 68 actually available, or an older version of chromedriver i can use with Chrome 68?

Does anyone have any other suggestions?

This is the code that i'm trying to execute:

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
user = 'XXXXXXX'
pwd = 'XXXXXXX'
chromedriver = "...\...\...\chromedriver.exe"
driver = webdriver.Chrome(executable_path=chromedriver) # Error occurs at this line
driver.get("http://www.facebook.com")
assert "Facebook" in driver.title
time.sleep(5) # So i can see something!
elem = driver.find_element_by_id("email")
elem.send_keys(user)
time.sleep(5) # So i can see something!
elem = driver.find_element_by_id("pass")
elem.send_keys(pwd)
time.sleep(5) # So i can see something!
elem.send_keys(Keys.RETURN)
driver.close()


问:
Three Column Layout with Flexbox on responsive
I have a small poll on three layout columns.

On Desktop it looks like this:

My problem is on mobile screen. I have one person under the other and after that questions. See the image below.

What I want to achieve is Person 1 and then questions, Person 2, and then questions, Person 3 and then questions, something like this:

Does anybody have any idea how to solve this?

Here is HTMl:

```<code>  <div class="col-md-12 col-xs-12">
<div class="d-table">
        <div class="d-table-row">
            <div class="d-table-cell align-middle"></div>
            <div class="d-table-cell align-middle">
                <div class="titleMiddle">Person 1</div>
            </div>
            <div class="d-table-cell align-middle">
                <div class="titleMiddle">Person 2</div>
            </div>
            <div class="d-table-cell align-middle">
                <div class="titleMiddle">Person 3</div>
            </div>
        </div>
        <div class="d-table-row">
            <div class="d-table-cell align-middle pb-4">
                <div class="question">

                    <div class="smalltitle">
                        <span class="prefiks">1</span>
                        <span>This is a very nice question</span>
                    </div>
                </div>
            </div>
            <div class="d-table-cell align-middle pb-4">
                <div class="horizontal">
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="1">
                        </div>
                        <div class="answerText">1</div>
                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">
                            <input type="radio" name="name" value="2">
                        </div>
                        <div class="answerText">2</div>
                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="3">
                        </div>

                        <div class="answerText">3</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="4">
                        </div>
                        <div class="answerText">4</div>
                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="5">

                        </div>

                        <div class="answerText">5</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">
                            <input type="radio" name="name" value="6">
                        </div>
                        <div class="answerText">No answer</div>

                    </div>
                </div>
            </div>
            <div class="d-table-cell align-middle pb-4">
                <div class="horizontal">
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="1">

                        </div>

                        <div class="answerText">1</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="2">

                        </div>

                        <div class="answerText">2</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="3">

                        </div>

                        <div class="answerText">3</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="4">

                        </div>

                        <div class="answerText">4</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="5">

                        </div>

                        <div class="answerText">5</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="6">

                        </div>

                        <div class="answerText">No Answer</div>

                    </div>
                </div>

            </div>
            <div class="d-table-cell align-middle pb-4">
                <div class="horizontal">
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="1">

                        </div>

                        <div class="answerText">1</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="2">

                        </div>

                        <div class="answerText">2</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="3">

                        </div>

                        <div class="answerText">3</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="4">

                        </div>

                        <div class="answerText">4</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="5">

                        </div>

                        <div class="answerText">5</div>

                    </div>
                    <div class="answer answerRight">
                        <div class="answerInput">

                            <input type="radio" name="name" value="6">

                        </div>

                        <div class="answerText">No answer</div>

                    </div>
                </div>
            </div>
        </div>
    </div>
  </div>
</code>```

CSS

```<code>.d-table {
    display: table!important;
}
.d-table-row {
    display: table-row !important;
}
* {
    -webkit-font-smoothing: antialiased;

}
*, ::after, ::before {
    box-sizing: inherit;
}

.d-table-cell {
    display: table-cell!important;
}

.align-middle {
    vertical-align: middle!important;
}
.align-middle > div {
    margin-right: 50px;
}
.titleMiddle {
    font-weight: 700;
    margin-bottom: 30px;
}
.pb-4, .py-4 {
    padding-bottom: 1.5rem!important;
}

.smalltitle {
  margin-bottom: 20px;
}

.horizontal {
    display: flex !important;
    flex-direction: row !important;
}

.answer {
  margin-left: 15px;
    margin-bottom: 5px;
    padding: 6px;
}

.answerRight {
      display: flex !important;
    flex-direction: row !important;
    align-items: center;
}
input[type='radio'] {
    width: 13px;
    height: 13px;
    background: white;
    border-radius: 50%!important;
    border: 1px solid #343c49;
    -moz-appearance: none;
    -webkit-appearance: none;
}

input[type='radio']:checked {
    background: #06c;
}

.answerText {
    margin-left: 0.375rem;
}
</code>```

答:
Make different person in different div like this

.d-flex{
    display: flex;
}
.row{
    flex-direction: row;
}
.col{
    flex-direction: column;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="d-flex row">
    <div class="d-flex col">
        <div>Person 1</div>
        <div class=" d-flex row">
            <span>Q1</span>
            <div>
                <input type="radio" name="q1" value="1" >
                <span >1</span>
            </div>
            <div>
                <input type="radio" name="q2" value="2">
                <span >2</span>
            </div>
            <div>
                <input type="radio" name="q3" value="3">
                <span >3</span>
            </div>
        </div>
    </div>
    <div class="d-flex col">
        <div>Person 1</div>
        <div class=" d-flex row">
            <span>Q1</span>
            <div>
                <input type="radio" name="q1" value="1" >
                <span >1</span>
            </div>
            <div>
                <input type="radio" name="q2" value="2">
                <span >2</span>
            </div>
            <div>
                <input type="radio" name="q3" value="3">
                <span >3</span>
            </div>
        </div>
    </div>
</div></code>```

This could be the structure and use media query for responsiveness.

Body:
I have a small poll on three layout columns.

On Desktop it looks like this:

My problem is on mobile screen. I have one person under the other and after that questions. See the image below.

What I want to achieve is Person 1 and then questions, Person 2, and then questions, Person 3 and then questions, something like this:

Does anybody have any idea how to solve this?

Here is HTMl:

Person 1

Person 2

Person 3

                        1
                        This is a very nice question

                            <input type="radio" name="name" value="1">

1

                            <input type="radio" name="name" value="2">

2

                            <input type="radio" name="name" value="3">

3

                            <input type="radio" name="name" value="4">

4

                            <input type="radio" name="name" value="5">

5

                            <input type="radio" name="name" value="6">

No answer

                            <input type="radio" name="name" value="1">

1

                            <input type="radio" name="name" value="2">

2

                            <input type="radio" name="name" value="3">

3

                            <input type="radio" name="name" value="4">

4

                            <input type="radio" name="name" value="5">

5

                            <input type="radio" name="name" value="6">

No Answer

                            <input type="radio" name="name" value="1">

1

                            <input type="radio" name="name" value="2">

2

                            <input type="radio" name="name" value="3">

3

                            <input type="radio" name="name" value="4">

4

                            <input type="radio" name="name" value="5">

5

                            <input type="radio" name="name" value="6">

No answer

CSS

.d-table {
    display: table!important;
}
.d-table-row {
    display: table-row !important;
}
* {
    -webkit-font-smoothing: antialiased;

}
*, ::after, ::before {
    box-sizing: inherit;
}

.d-table-cell {
    display: table-cell!important;
}

.align-middle {
    vertical-align: middle!important;
}
.align-middle > div {
    margin-right: 50px;
}
.titleMiddle {
    font-weight: 700;
    margin-bottom: 30px;
}
.pb-4, .py-4 {
    padding-bottom: 1.5rem!important;
}

.smalltitle {
  margin-bottom: 20px;
}

.horizontal {
    display: flex !important;
    flex-direction: row !important;
}

.answer {
  margin-left: 15px;
    margin-bottom: 5px;
    padding: 6px;
}

.answerRight {
      display: flex !important;
    flex-direction: row !important;
    align-items: center;
}
input[type='radio'] {
    width: 13px;
    height: 13px;
    background: white;
    border-radius: 50%!important;
    border: 1px solid #343c49;
    -moz-appearance: none;
    -webkit-appearance: none;
}

input[type='radio']:checked {
    background: #06c;
}

.answerText {
    margin-left: 0.375rem;
}

Body:
Make different person in different div like this

.d-flex{
    display: flex;
}
.row{
    flex-direction: row;
}
.col{
    flex-direction: column;
}

<div class="d-flex row">
    <div class="d-flex col">
        <div>Person 1</div>
        <div class=" d-flex row">
            <span>Q1</span>
            <div>
                <input type="radio" name="q1" value="1" >
                <span >1</span>
            </div>
            <div>
                <input type="radio" name="q2" value="2">
                <span >2</span>
            </div>
            <div>
                <input type="radio" name="q3" value="3">
                <span >3</span>
            </div>
        </div>
    </div>
    <div class="d-flex col">
        <div>Person 1</div>
        <div class=" d-flex row">
            <span>Q1</span>
            <div>
                <input type="radio" name="q1" value="1" >
                <span >1</span>
            </div>
            <div>
                <input type="radio" name="q2" value="2">
                <span >2</span>
            </div>
            <div>
                <input type="radio" name="q3" value="3">
                <span >3</span>
            </div>
        </div>
    </div>
</div>

This could be the structure and use media query for responsiveness.


问:
Unable to connect to the binlog client in NiFi
I'm building a NiFi dadaflow, and I need to get the data changes from a MySql database, so I want to use the CaptureChangeMySQL processor to do that.

I get the following error when I run the CaptureChangeMySQL processor and I don't see what's causing this :

Failed to process session due to Could not connect binlog client to any of the specified hosts due to: BinaryLogClient was unable to connect in 10000ms: org.apache.nifi.processor.exception.ProcessException: Could not connect binlog client to any of the specified hosts due to: BinaryLogClient was unable to connect in 10000ms

I have the following controller services enabled :

DistributedMapCacheClientService

DistributedMapCacheServer

But I'm not sure if they are properly configured :

DistributedMapCacheServer properties

DistributedMapCacheClientService properties

In MySql, I have enabled the log_bin variable, by default it wasn't. I checked and I have indeed some binlog files created when data change.

So I think the issue is with the controller services and how they connect, it's not clear to me.

I searched for tutorials about how to use this NiFi processor but I couldt not find how to fix this error. I looked mainly at this one : https://community.hortonworks.com/articles/113941/change-data-capture-cdc-with-apache-nifi-version-1-1.html but it did not helped me.

Does anyone have already use this processor to do CDC?

Thank you in advance.

答: I found what was wrong : I was trying to connect to the wrong port for the MySQL Host of the CaptureChangeMySQL processor :x</p>


问:
Why MediaPlayer getDuration() method return -1 on low quality audio?
I updated my app android API-23 to API-28 now MediaPlayer getDuration() method return -1, in api-23 getDuration method working fine but in latest api having issue. when using low quality (i.e 16kbs) of audio. but same time when i use high quality (64kbs to 192kbs) working fine.

```<code>MediaPlayer mp;
// 128kbs working fine in my app
mp.setDataSource(http://www.villopim.com.br/android/Music_02.mp3);
// return actual time
mp.getDuration();

// 16kbs working fine in my app
mp.setDataSource(http://topappstopgames.com/appsdata/islamic/sn002.mp3);
// return -1
mp.getDuration();
</code>```

So how to resolve this issue in latest api.

答: I shift to ExoPlayer now its working. </p>

Body:
I updated my app android API-23 to API-28 now MediaPlayer getDuration() method return -1, in api-23 getDuration method working fine but in latest api having issue. when using low quality (i.e 16kbs) of audio. but same time when i use high quality (64kbs to 192kbs) working fine.

MediaPlayer mp;
// 128kbs working fine in my app
mp.setDataSource(http://www.villopim.com.br/android/Music_02.mp3);
// return actual time
mp.getDuration();

// 16kbs working fine in my app
mp.setDataSource(http://topappstopgames.com/appsdata/islamic/sn002.mp3);
// return -1
mp.getDuration();

So how to resolve this issue in latest api.

Body: I shift to ExoPlayer now its working.


问:
Saving MultiDimensional Arrays to Storage
I am building a puzzle in Swift that I would like to store a multiDimensional  Array to storage.  I have a number of options for this including NSDefaults, Core, Plists, among others.  I know that if I do this in NSDefaults that I am essentially bringing the multiDimensional array back out and saving it each time I make a change.  This could be disk intensive.

The MultiDimensional Array would be: [30x20] in size.  Any recommendations on how best to store this.

I've tried looking at a number of guides and while NSDefaults looks to be the easiest I am concerned about the performance (and I'd like to learn how to do it the right way).

Any guidance is greatly appreciated.  I was able to get Core working, but nothing this complex.

Thank you.

答:
Declare properties as show in above image & set custom Class as Array<Array<Any>> in Attributes model:

Declare properties in CoreDataProperties class like:

  @NSManaged public var routes: Array<Array<Any>> //

Usages:

While using initialise properties like:

<your_rroperty_name> =  obj["routes"] as? [[String]] ?? [[]]


问:
How to update excel cell via SQL by a coordinate?
Is it possible to update an excel file using this SQL query?

```<code>UPDATE [My Sheet] SET B40='17'
</code>```

The B40 is the coordinate of that excel file.
Due to the structure of the existing excel file, I cannot use a table column to update. I only have to use coordinates.

When I run this I get this exception below:

```<code>No value given for one or more required parameters.
</code>```

And my connection string is:

```<code>@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +";Extended Properties='Excel 12.0;HDR=NO;ReadOnly=False;'"
</code>```

There is also a question here but I'm still getting the same error

答:
The usual reason for this error is a missing or misspelled value.

First you check, IS there any Typo error or not?

Body:
Is it possible to update an excel file using this SQL query?

UPDATE [My Sheet] SET B40='17'

The B40 is the coordinate of that excel file.
Due to the structure of the existing excel file, I cannot use a table column to update. I only have to use coordinates.

When I run this I get this exception below:

No value given for one or more required parameters.

And my connection string is:

@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName +";Extended Properties='Excel 12.0;HDR=NO;ReadOnly=False;'"

There is also a question here but I'm still getting the same error


问:
Record Audio on OSX (AVAudioSession not available)
I am looking to capture audio on OSX. I have IOS working with AVAudioSession, but since it is not supported on OSX, I'm having difficulty finding a simple example on OSX to record audio to a file for subsequent playback.

All the examples I find on stackoverflow have been IOS and or not in Swift.

Any help here would be appreciated. A link to a OSX Swift based simple audio capture sample code would be great.

Thanks Tom

答:
AVAudioSession exists to manage iOS audio constraints. These constraints don't exist on macOS, so you don't need AVAudioSession. Hooray!

You can capture audio to a file with AVAudioEngine and AVAudioFile:

```<code>import Cocoa
import AVFoundation

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    let audioEngine = AVAudioEngine()
    var outputFile: AVAudioFile? = nil

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // If sandboxed, don't forget to turn on Microphone in Capabilities > App Sandbox
        let input = audioEngine.inputNode
        let bus = 0
        let inputFormat = input.inputFormat(forBus: bus)

        let outputURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("out.caf")
        print("writing to \(outputURL)")

        outputFile = try! AVAudioFile(forWriting: outputURL, settings: inputFormat.settings, commonFormat: inputFormat.commonFormat, interleaved: inputFormat.isInterleaved)

        input.installTap(onBus: bus, bufferSize: 512, format: inputFormat) { (buffer, time) in
            try! self.outputFile?.write(from: buffer)
        }

        try! audioEngine.start()

        DispatchQueue.main.asyncAfter(deadline: .now()+5) {
            print("Finish")
            self.audioEngine.stop()
            self.outputFile = nil
        }
    }
}
</code>```

Body:
AVAudioSession exists to manage iOS audio constraints. These constraints don't exist on macOS, so you don't need AVAudioSession. Hooray!

You can capture audio to a file with AVAudioEngine and AVAudioFile:

import Cocoa
import AVFoundation

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    let audioEngine = AVAudioEngine()
    var outputFile: AVAudioFile? = nil

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // If sandboxed, don't forget to turn on Microphone in Capabilities > App Sandbox
        let input = audioEngine.inputNode
        let bus = 0
        let inputFormat = input.inputFormat(forBus: bus)

        let outputURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("out.caf")
        print("writing to \(outputURL)")

        outputFile = try! AVAudioFile(forWriting: outputURL, settings: inputFormat.settings, commonFormat: inputFormat.commonFormat, interleaved: inputFormat.isInterleaved)

        input.installTap(onBus: bus, bufferSize: 512, format: inputFormat) { (buffer, time) in
            try! self.outputFile?.write(from: buffer)
        }

        try! audioEngine.start()

        DispatchQueue.main.asyncAfter(deadline: .now()+5) {
            print("Finish")
            self.audioEngine.stop()
            self.outputFile = nil
        }
    }
}


问:
OnCollisionEnter2D() does not call
OnCollisionEnter2D is not calling, what should I do?
Is this because of not adding layer to Edit>Unity Uroject>Phicycs2D? How can I do this?
Thanks for helping me.</p>

答: Try OnTriggerEnter2D() and check the is_trigger box on the collider. Otherwise, make sure that both objects are on the same layer.</p>

Title: OnCollisionEnter2D() does not call


问:
How to automatically remove from SBT snapshot dependencies during release?
Is it possible to exchange snapshot dependency during release with its released version?
For example, I have such dependecy:

libraryDependencies += "com.company" %% "del" % "10.0.12-SNAPSHOT"

During release I'd like such dependency become

libraryDependencies += "com.company" %% "del" % "10.0.12"

Or interrupt release. Ideally if it is some sbt plugin with task, which could be triggered in Jenkins pipeline.

答:
Script to clean, assembly and update snapshots.
When you release maintain a separate copy(remove snapshots) of version.sbt file on your build server.</p>

```<code>import _root_.sbtrelease.ReleasePlugin.autoImport.{ReleaseStep, _}
import _root_.sbtrelease.ReleaseStateTransformations._

conflictManager in ThisBuild := sbt.ConflictManager.latestRevision

releaseProcess := Seq(
  ReleaseStep(releaseStepTaskAggregated(clean in *YourService*)),
  checkSnapshotDependencies,
  inquireVersions,
  setReleaseVersion,
  ReleaseStep(releaseStepTaskAggregated(assembly in *YourService*)),
  setNextVersion
)
</code>```

Body:
Script to clean, assembly and update snapshots.
When you release maintain a separate copy(remove snapshots) of version.sbt file on your build server.

import _root_.sbtrelease.ReleasePlugin.autoImport.{ReleaseStep, _}
import _root_.sbtrelease.ReleaseStateTransformations._

conflictManager in ThisBuild := sbt.ConflictManager.latestRevision

releaseProcess := Seq(
  ReleaseStep(releaseStepTaskAggregated(clean in *YourService*)),
  checkSnapshotDependencies,
  inquireVersions,
  setReleaseVersion,
  ReleaseStep(releaseStepTaskAggregated(assembly in *YourService*)),
  setNextVersion
)


问:
package-lock.json file, package with "optional": true
One of my work mate's PRs contains a package-lock.json update, which added "optional": true:

```<code> "minimist": {
   "version": "0.0.8",
   "bundled": true,
-  "dev": true
+  "dev": true,
+  "optional": true
 },
 "minipass": {
</code>```

I am not sure what this means even after googling around. Could someone please explain?

答:
After a package is removed from dependencies, its dependencies are marked "optional": true in package-lock.json.

It is usually safe to remove such packages either by hand or by

```<code>$ rm -rf package-lock.json node_modules/
$ npm install
</code>```

However, this is not 100% safe, as some packages will be updated to newer versions.

Body:
One of my work mate's PRs contains a package-lock.json update, which added "optional": true:

 "minimist": {
   "version": "0.0.8",
   "bundled": true,
-  "dev": true
+  "dev": true,
+  "optional": true
 },
 "minipass": {

I am not sure what this means even after googling around. Could someone please explain?

Body:
After a package is removed from dependencies, its dependencies are marked "optional": true in package-lock.json.

It is usually safe to remove such packages either by hand or by

$ rm -rf package-lock.json node_modules/
$ npm install

However, this is not 100% safe, as some packages will be updated to newer versions.


问:
Flutter how to detect PageView onTapUp
I used PageView to write a list in the vertical direction. Now when I slide the list up or down (my finger doesn't leave the screen), onPageChanged will execute. Is there a way to detect that the onPageChanged method will only be executed when the finger leaves the screen.Part of the code below：

    SizedBox(
            width: 200,
            height: 200,
            child: PageView(
                controller: pageController,
                scrollDirection: Axis.vertical,
                onPageChanged: (index) {
                  setState(() {
                    pageIndex = index;
                  });
                },
                children: _buildCardList()),
          )

```

like below:

答:
Wrap your page view with a Notification listener like below:</p>

```<code>  SizedBox(
            width: 100,
            height: 100,
            child: NotificationListener<ScrollNotification>(
              onNotification: (notification)
              {
                if(notification is ScrollEndNotification)
                  {

                    var pageIndex = pageController.page;
                  }

              },
              child: PageView(
                  controller: pageController,
                  scrollDirection: Axis.vertical,
                  onPageChanged: (index) {
                  },
                  children: _buildCardList()),
            ),
          )
</code>```

Title: Flutter how to detect PageView onTapUp

Body:
I used PageView to write a list in the vertical direction. Now when I slide the list up or down (my finger doesn't leave the screen), onPageChanged will execute. Is there a way to detect that the onPageChanged method will only be executed when the finger leaves the screen.Part of the code below：

    SizedBox(
            width: 200,
            height: 200,
            child: PageView(
                controller: pageController,
                scrollDirection: Axis.vertical,
                onPageChanged: (index) {
                  setState(() {
                    pageIndex = index;
                  });
                },
                children: _buildCardList()),
          )

like below:

Body:
Wrap your page view with a Notification listener like below:

  SizedBox(
            width: 100,
            height: 100,
            child: NotificationListener<ScrollNotification>(
              onNotification: (notification)
              {
                if(notification is ScrollEndNotification)
                  {

                    var pageIndex = pageController.page;
                  }

              },
              child: PageView(
                  controller: pageController,
                  scrollDirection: Axis.vertical,
                  onPageChanged: (index) {
                  },
                  children: _buildCardList()),
            ),
          )


问:
How to create dynamic UI based on json in iOS
I have to create dynamic UI based on json like Joshfire.

Can anyone help me?

答:
Try jasonette. It’s like an all native aproach to build UI from json
Site:  http://jasonette.com/
Github: https://github.com/Jasonette/JASONETTE-iOS


问:
PHP: compare substrings
Really quick noob question with php:

I'm trying to create a conditional statement where I can check if a variable partially matches a substring.

More specific in my case:

$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.

pseudocode:

```<code><?php if ($cal == "*.cfg")
 {
    echo "Hello ";
 }
?>
</code>```

答:
for simple patterns strpos will do nicely.

```<code>if (strpos ('.cfg', $string) !== false)
{
    // etc
}
</code>```

For more complicated parterns, you want preg_match, which can compare a string against a regular expression.

```<code>if (preg_match ('/.*?\.cfg/', $string))
{
    // etc
}
</code>```

The former offers better performance, but the latter is more flexible.

Title: PHP: compare substrings

Body:
Really quick noob question with php:

I'm trying to create a conditional statement where I can check if a variable partially matches a substring.

More specific in my case:

$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.

pseudocode:

<?php if ($cal == "*.cfg")
 {
    echo "Hello ";
 }
?>

Body:
for simple patterns strpos will do nicely.

if (strpos ('.cfg', $string) !== false)
{
    // etc
}

For more complicated parterns, you want preg_match, which can compare a string against a regular expression.

if (preg_match ('/.*?\.cfg/', $string))
{
    // etc
}

The former offers better performance, but the latter is more flexible.


问:
User plugin. Set relation after create a model
I customize User plugin by Rainlabs.

A User model has relation with user groups. After I create a user I want set his user group (guest, registered etc).

It's not working:

```<code>// also tried beforeCreate
public function afterCreate()
{
    if (something)
       // groups is a relation field name
       $this->groups = 'guest'; // guest is a user group code
    else
       $this->groups = 'registered';
}
</code>```

答:
Solution:</p>

```<code>// User model
public function afterCreate() {
    $this->groups()->add(UserGroup::where('code', 'registered')->first());
    ...
}
</code>```

Body:
I customize User plugin by Rainlabs.

A User model has relation with user groups. After I create a user I want set his user group (guest, registered etc).

It's not working:

// also tried beforeCreate
public function afterCreate()
{
    if (something)
       // groups is a relation field name
       $this->groups = 'guest'; // guest is a user group code
    else
       $this->groups = 'registered';
}

Body:
Solution:

// User model
public function afterCreate() {
    $this->groups()->add(UserGroup::where('code', 'registered')->first());
    ...
}


问:
Android Image and Toolbar(EditText) inside CollapsingToolbarLayout Scrolling
I want to implement the function shown below.

Before scrolling, there is an EditText at the bottom, a logo ImageView in the center, and a right Menu at the top.

During scrolling, the ImageView and the EditText disappear and the Menu remains.

After scrolling, the EditText is reduced to the appropriate size and the Menu is on the right.

However, in my current code, scrollFlag to scroll in CollapsingToolbarLayout does not clicked, nor does it shrink to the proper size.

Here is my Code.

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="260dp"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingStart="16dp"
            android:paddingEnd="16dp"
            android:fitsSystemWindows="true"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/logoImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleType="center"
                android:src="@drawable/app_logo_150x30"
                android:layout_centerInParent="true"/>

            <EditText
                android:id="@+id/searchButton"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:background="#FFFFFF"
                android:hint="@string/menu_search"
                android:textColorHint="@color/colorTextSecondary"
                android:textColor="@color/colorText"
                android:textSize="16sp"
                android:inputType="text"
                android:drawableEnd="@drawable/ic_search_24dp"
                android:paddingEnd="12dp"
                android:paddingStart="12dp"
                android:layout_marginBottom="16dp"
                android:layout_alignParentBottom="true"
                android:focusable="false"
                android:focusableInTouchMode="false"/>

        </RelativeLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/transparent"
            app:layout_collapseMode="pin"
            app:contentInsetLeft="0dp"
            app:contentInsetStart="0dp"
            app:contentInsetRight="0dp"
            app:contentInsetEnd="0dp"
            android:paddingLeft="16dp"
            android:paddingStart="16dp"
            android:paddingRight="16dp"
            android:paddingEnd="16dp">

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

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main"/>
</code>```

How do I make it work as an attached image?

答:
Old post. But still if people looking for answers, just add app:layout_collapseMode="parallax" in imageview.

```<code><ImageView
                android:id="@+id/logoImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleType="center"
                android:src="@drawable/app_logo_150x30"
                app:layout_collapseMode="parallax"
                android:layout_centerInParent="true"/>
</code>```

Import the required settings. Hope it helps.

Body:
I want to implement the function shown below.

Before scrolling, there is an EditText at the bottom, a logo ImageView in the center, and a right Menu at the top.

During scrolling, the ImageView and the EditText disappear and the Menu remains.

After scrolling, the EditText is reduced to the appropriate size and the Menu is on the right.

However, in my current code, scrollFlag to scroll in CollapsingToolbarLayout does not clicked, nor does it shrink to the proper size.

Here is my Code.

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="260dp"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingStart="16dp"
            android:paddingEnd="16dp"
            android:fitsSystemWindows="true"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/logoImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleType="center"
                android:src="@drawable/app_logo_150x30"
                android:layout_centerInParent="true"/>

            <EditText
                android:id="@+id/searchButton"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:background="#FFFFFF"
                android:hint="@string/menu_search"
                android:textColorHint="@color/colorTextSecondary"
                android:textColor="@color/colorText"
                android:textSize="16sp"
                android:inputType="text"
                android:drawableEnd="@drawable/ic_search_24dp"
                android:paddingEnd="12dp"
                android:paddingStart="12dp"
                android:layout_marginBottom="16dp"
                android:layout_alignParentBottom="true"
                android:focusable="false"
                android:focusableInTouchMode="false"/>

        </RelativeLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/transparent"
            app:layout_collapseMode="pin"
            app:contentInsetLeft="0dp"
            app:contentInsetStart="0dp"
            app:contentInsetRight="0dp"
            app:contentInsetEnd="0dp"
            android:paddingLeft="16dp"
            android:paddingStart="16dp"
            android:paddingRight="16dp"
            android:paddingEnd="16dp">

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

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main"/>

How do I make it work as an attached image?

Body:
Old post. But still if people looking for answers, just add app:layout_collapseMode="parallax" in imageview.

<ImageView
                android:id="@+id/logoImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleType="center"
                android:src="@drawable/app_logo_150x30"
                app:layout_collapseMode="parallax"
                android:layout_centerInParent="true"/>

Import the required settings. Hope it helps.


问:
Header grouping of UI Grid Angular
I want to change my header rendering of UI-Grid AngularJS. I know it is easy to implement by just make headerTemplate but i have a situation where i need to make the grouping of headers like this

```<code>{
        name: 'Mapped By',
        enableColumnMenu: false,
        field: 'Mappedby',
        cellClass: 'intrighttextcell',
        width: 102,
        enableCellEdit: false,
        allowCellFocus: false
    },
</code>```

I don't know how can i achieve this functionality in ui-grid.
Here is the plunkr of ui-grid.

答:
// Code goes here

angular.module("temp2", ["ui.grid"]).controller("Temp2Controller", [ "uiGridConstants", Temp2Controller ]);

function Temp2Controller(uiGridConstants) {
  "use strict";
  var $scope = this;

  $scope.gridOptions = {
      headerTemplate: '

',
      superColDefs: [{
          name: 'group1',
          displayName: 'Group 1'
      }, {
          name: 'group2',
          displayName: 'Group 2'
      }],
      columnDefs: [{
          name: 'name',
          displayName: 'Name',
          superCol: 'group1'
      }, {
          name: 'title',
          displayName: 'Title',
          superCol: 'group1'
      }, {
          name: 'age',
          displayName: 'Age',
          superCol: 'group2'
      }],
      data: [{
          name: 'Bob',
          title: 'CEO',
          age: '31'
      }, {
          name: 'Frank',
          title: 'Lowly Developer',
          age: '33'
      }]
  };

}

(function() {
  "use strict";
  angular.module("temp2").directive('superColWidthUpdate', ['$timeout', function ($timeout) {
    return {
      'restrict': 'A',
          'link': function (scope, element) {
          var _colId = scope.col.colDef.superCol,
              _el = jQuery(element);
          _el.on('resize', function () {
              _updateSuperColWidth();
          });
          var _updateSuperColWidth = function () {
              $timeout(function () {
                  var _parentCol = jQuery('.ui-grid-header-cell[col-name="' + _colId + '"]');
                  var _parentWidth = _parentCol.outerWidth(),
                      _width = _el.outerWidth();

                  if (_parentWidth + 1 >= _width) {
                    _parentWidth = _parentWidth + _width;
                  } else {
                    _parentWidth = _width;
                  }

                  _parentCol.css({
                      'min-width': _parentWidth + 'px',
                      'max-width': _parentWidth + 'px',
                      'text-align': "center"
                  });
              }, 0);
          };
          _updateSuperColWidth();
      }
    };
  }]);

})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="temp2" ng-controller="Temp2Controller as temp2">

  <head>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.20/ui-grid.min.css">
    <script data-require="jquery@2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="https://code.angularjs.org/1.4.0/angular.js"></script>
    <script src="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.21/ui-grid.min.js"></script>
    <script src="script.js"></script>
    <script src="super-col-with-update.js"></script>

    <style>
      /* Styles go here */
      .grid {
        width: 700px;
      }
    </style>
  </head>

  <body>
    <div id="grid" ui-grid="temp2.gridOptions" class="grid"></div>
  </body>

</html></code>```

See jsfiddler here.. It will help you in header grouping.

Title: Header grouping of UI Grid Angular

Body:
I want to change my header rendering of UI-Grid AngularJS. I know it is easy to implement by just make headerTemplate but i have a situation where i need to make the grouping of headers like this

{
        name: 'Mapped By',
        enableColumnMenu: false,
        field: 'Mappedby',
        cellClass: 'intrighttextcell',
        width: 102,
        enableCellEdit: false,
        allowCellFocus: false
    },

I don't know how can i achieve this functionality in ui-grid.
Here is the plunkr of ui-grid.

Body:
// Code goes here

angular.module("temp2", ["ui.grid"]).controller("Temp2Controller", [ "uiGridConstants", Temp2Controller ]);

function Temp2Controller(uiGridConstants) {
  "use strict";
  var $scope = this;

  $scope.gridOptions = {
      headerTemplate: '<div class="ui-grid-header custom-ui-grid-header"><div class="ui-grid-top-panel"><div class="ui-grid-header-viewport"><div class="ui-grid-header-canvas" style=""><div class="ui-grid-header-cell-wrapper" style="display: block;" ng-style="colContainer.headerCellWrapperStyle()"><div class="ui-grid-header-cell-row abc" style="display: block; border-bottom: 1px solid;border-bottom-color: #d4d4d4;"><div class="ui-grid-header-cell" ng-repeat="superCol in grid.options.superColDefs track by $index" col-name="{{superCol.name}}"><div class="ui-grid-cell-contents" data-ng-bind="superCol.displayName"></div></div></div><div class="ui-grid-header-cell-row"><div class="ui-grid-header-cell ui-grid-clearfix" ng-repeat="col in colContainer.renderedColumns track by col.colDef.name" ui-grid-header-cell col="col" super-col-width-update render-index="$index"></div></div></div></div></div></div></div>',
      superColDefs: [{
          name: 'group1',
          displayName: 'Group 1'
      }, {
          name: 'group2',
          displayName: 'Group 2'
      }],
      columnDefs: [{
          name: 'name',
          displayName: 'Name',
          superCol: 'group1'
      }, {
          name: 'title',
          displayName: 'Title',
          superCol: 'group1'
      }, {
          name: 'age',
          displayName: 'Age',
          superCol: 'group2'
      }],
      data: [{
          name: 'Bob',
          title: 'CEO',
          age: '31'
      }, {
          name: 'Frank',
          title: 'Lowly Developer',
          age: '33'
      }]
  };

}

(function() {
  "use strict";
  angular.module("temp2").directive('superColWidthUpdate', ['$timeout', function ($timeout) {
    return {
      'restrict': 'A',
          'link': function (scope, element) {
          var _colId = scope.col.colDef.superCol,
              _el = jQuery(element);
          _el.on('resize', function () {
              _updateSuperColWidth();
          });
          var _updateSuperColWidth = function () {
              $timeout(function () {
                  var _parentCol = jQuery('.ui-grid-header-cell[col-name="' + _colId + '"]');
                  var _parentWidth = _parentCol.outerWidth(),
                      _width = _el.outerWidth();

                  if (_parentWidth + 1 >= _width) {
                    _parentWidth = _parentWidth + _width;
                  } else {
                    _parentWidth = _width;
                  }

                  _parentCol.css({
                      'min-width': _parentWidth + 'px',
                      'max-width': _parentWidth + 'px',
                      'text-align': "center"
                  });
              }, 0);
          };
          _updateSuperColWidth();
      }
    };
  }]);

})();

<!DOCTYPE html>
<html ng-app="temp2" ng-controller="Temp2Controller as temp2">

  <head>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.20/ui-grid.min.css">
    <script data-require="jquery@2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="https://code.angularjs.org/1.4.0/angular.js"></script>
    <script src="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.21/ui-grid.min.js"></script>
    <script src="script.js"></script>
    <script src="super-col-with-update.js"></script>

    <style>
      /* Styles go here */
      .grid {
        width: 700px;
      }
    </style>
  </head>

  <body>
    <div id="grid" ui-grid="temp2.gridOptions" class="grid"></div>
  </body>

</html>

See jsfiddler here.. It will help you in header grouping.


问:
How to convert hex form dataframe to human readable form in python
I am trying to fetch varbinary form of data from mssql server and convert it into readable form.

```<code>def fetchdata(self):
    query = 'select * from xlstorage'
    df = pd.read_sql(query, self.conn)
    print(df.to_string())
    print(type(df))
    print(df.all)
</code>```

id                                             xlfile
0   1  b'PK\x03\x04\x14\x00\x06\x00\x08\x00\x00\x00!...
I am getting this kind of dataframe how to convert it into original file formate or string dataframe???

答:
check the struct.unpack() module.
As we don't know what kind of data your string should contain, its hard to tell you, what format characters to use see here

the struct module is used like shown below:

```<code>import struct

string =str(b'\x03\x04\x14\x00\x06\x00\x08\x00')

format = 'hhl'
a = struct.unpack(format, string)

print(a) #=> (1027, 20, 524294)
</code>```

Body:
I am trying to fetch varbinary form of data from mssql server and convert it into readable form.

def fetchdata(self):
    query = 'select * from xlstorage'
    df = pd.read_sql(query, self.conn)
    print(df.to_string())
    print(type(df))
    print(df.all)

id                                             xlfile
0   1  b'PK\x03\x04\x14\x00\x06\x00\x08\x00\x00\x00!...
I am getting this kind of dataframe how to convert it into original file formate or string dataframe???

Body:
check the struct.unpack() module.
As we don't know what kind of data your string should contain, its hard to tell you, what format characters to use see here

the struct module is used like shown below:

import struct

string =str(b'\x03\x04\x14\x00\x06\x00\x08\x00')

format = 'hhl'
a = struct.unpack(format, string)

print(a) #=> (1027, 20, 524294)


问:
How to use distinct in relations query in Laravel
I have a Laravel ORM query that I join 2-3 relation together like below :

$data = AccommodationRoom::with('accommodation.city',
    'accommodation.accommodationFacilities', 'accommodation.gallery')
    ->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    })
    ->whereHas('accommodation', function ($query) use ($searchCity) {
        $query->where('city_id', $searchCity);
    })
    ->limit(10)->get();

return response()->json($data, 200);
```

On the room model, I check if the capacity model has a date and where the city id is what the user gives to the hotels (accommodation). The problem is that when I get the result, I get repeated hotels for each room. For one search I might get ten hotels the same, so I want to make the accommodations unique and show one result (room) per accommodation.

答:
You can use groupBy instead of distinct; because you want to group your results based on one column which is for example accommodation_id:</p>

```<code>$data = AccommodationRoom::with('accommodation.city',
    'accommodation.accommodationFacilities', 'accommodation.gallery')
    ->SELECT('accommodation_id')
    ->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    })
    ->whereHas('accommodation', function ($query) use ($searchCity) {
        $query->where('city_id', $searchCity);
    })
    ->groupBy('accommodation_id')->limit(10)->get();

return response()->json($data, 200);
</code>```

Body:
I have a Laravel ORM query that I join 2-3 relation together like below :

$data = AccommodationRoom::with('accommodation.city',
    'accommodation.accommodationFacilities', 'accommodation.gallery')
    ->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    })
    ->whereHas('accommodation', function ($query) use ($searchCity) {
        $query->where('city_id', $searchCity);
    })
    ->limit(10)->get();

return response()->json($data, 200);

On the room model, I check if the capacity model has a date and where the city id is what the user gives to the hotels (accommodation). The problem is that when I get the result, I get repeated hotels for each room. For one search I might get ten hotels the same, so I want to make the accommodations unique and show one result (room) per accommodation.

Body:
You can use groupBy instead of distinct; because you want to group your results based on one column which is for example accommodation_id:

$data = AccommodationRoom::with('accommodation.city',
    'accommodation.accommodationFacilities', 'accommodation.gallery')
    ->SELECT('accommodation_id')
    ->whereHas('roomCapacityHistory', function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    })
    ->whereHas('accommodation', function ($query) use ($searchCity) {
        $query->where('city_id', $searchCity);
    })
    ->groupBy('accommodation_id')->limit(10)->get();

return response()->json($data, 200);