问:
How can i multiply specific columns within one dataframe by a lookup to specific columns in another dataframe?
I have 2 dataframes, both have a number of columns that share the same name and both have a single column that acts as a unique identifier. I have created a copy of one of the dataframes but what i would like to do is multiply the columns together that share the same name where the unique identifiers are equal.

I am fairly new to python and im sure many with think this is simple but looking through the documentation im finding this difficult.

The initial 2 dataframes are created by reading an excel file into pandas.

I then create a copy of the first dataframe and i want to multiple the contents of the 2nd dataframe to the contents of the copied dataframe where the unique row is found and the column name matches.

import pandas as pd

# read tables from excel to create dictionary of dataframes where the key is the tab name
all_sheets_df = pd.read_excel("xl_file_name.xlsx", sheet_name=None)
print(all_sheets_df)

# These are the dataframes created from the excel sheets
OrderedDict([('sheet1',
                    cola     colb     colc    uni-id  201801  201802  201803  201804  201805
              0  strings  strings  strings  unique-a       4       3       2       9      10
              1  strings  strings  strings  unique-b       8       1       9       1       6
              2  strings  strings  strings  unique-c       4       3       4       4       3
              3  strings  strings  strings  unique-d       3       9       8       4       4
              4  strings  strings  strings  unique-e       5       4       7       9      10
              5  strings  strings  strings  unique-f       2       3       8       2       1
              6  strings  strings  strings  unique-g       2       4       2       6       8
              7  strings  strings  strings  unique-h       6       2       5       4      10
              8  strings  strings  strings  unique-i       7       1       3      10       8),
             ('sheet2',
                    cola     colb     colc    uni-id    201801    201802    201803  \
              0  strings  strings  strings  unique-d  0.052935  0.928645  0.505045
              1  strings  strings  strings  unique-f  0.776922  0.338918  0.932535
              2  strings  strings  strings  unique-c  0.799160  0.343798  0.145575
              3  strings  strings  strings  unique-a  0.659975  0.308475  0.588496
              4  strings  strings  strings  unique-i  0.450931  0.667722  0.831734
              5  strings  strings  strings  unique-e  0.791060  0.801188  0.781400
              6  strings  strings  strings  unique-b  0.653861  0.649786  0.545784
              7  strings  strings  strings  unique-h  0.849901  0.327025  0.874650
              8  strings  strings  strings  unique-g  0.812554  0.995710  0.042272

                   201804    201805
              0  0.011463  0.980985
              1  0.743247  0.715230
              2  0.313438  0.882728
              3  0.656984  0.864108
              4  0.236997  0.422303
              5  0.603261  0.083762
              6  0.722503  0.170563
              7  0.608704  0.263881
              8  0.702862  0.760257  )])

# create new dataframe as a copy of the first sheet in excel
calculated_dataframe = all_sheets_df.get("sheet1","").copy()

# get list of columns to update (all columns to be updated start with characters '20'
update_cols = [col for col in calculated_dataframe.columns if '20' in col]

# for each row in calculated_dataframe, find row in all_sheets_df.get("sheet2","") where column name 'uni-id' matches 'uni-id' in calculated_dataframe and then for each update_col in update_cols calculate_dataframe value = calculate_dataframe value * all_sheets_df.get("sheet2","") value
# this is the piece im really struggling with.
```

I want to iterate through each row of calculated_dataframe, find the corresponding row in all_sheets_df.get("sheet2","") where the sheet2 column uni-id = calculated_dataframe column uni-id and multiply each column found in the update_cols list together (these columns exist in both dataframes).

Any guidance you can provide would be great!!

答:
You should first use the merge function on your identifier column to have only one df with all the columns.

```<code>df1 = df1.merge(df2, how ='left', on=['identifier_column'])
</code>```

Then your rows with same identifier will already be grouped together, and you only have to multiply the columns as you would do normally :

```<code>df1['column_3'] = df1['column_1'] * df1['column_2']
</code>```

Body:
I have 2 dataframes, both have a number of columns that share the same name and both have a single column that acts as a unique identifier. I have created a copy of one of the dataframes but what i would like to do is multiply the columns together that share the same name where the unique identifiers are equal.

I am fairly new to python and im sure many with think this is simple but looking through the documentation im finding this difficult.

The initial 2 dataframes are created by reading an excel file into pandas.

I then create a copy of the first dataframe and i want to multiple the contents of the 2nd dataframe to the contents of the copied dataframe where the unique row is found and the column name matches.

import pandas as pd

# read tables from excel to create dictionary of dataframes where the key is the tab name
all_sheets_df = pd.read_excel("xl_file_name.xlsx", sheet_name=None)
print(all_sheets_df)

# These are the dataframes created from the excel sheets
OrderedDict([('sheet1',
                    cola     colb     colc    uni-id  201801  201802  201803  201804  201805
              0  strings  strings  strings  unique-a       4       3       2       9      10
              1  strings  strings  strings  unique-b       8       1       9       1       6
              2  strings  strings  strings  unique-c       4       3       4       4       3
              3  strings  strings  strings  unique-d       3       9       8       4       4
              4  strings  strings  strings  unique-e       5       4       7       9      10
              5  strings  strings  strings  unique-f       2       3       8       2       1
              6  strings  strings  strings  unique-g       2       4       2       6       8
              7  strings  strings  strings  unique-h       6       2       5       4      10
              8  strings  strings  strings  unique-i       7       1       3      10       8),
             ('sheet2',
                    cola     colb     colc    uni-id    201801    201802    201803  \
              0  strings  strings  strings  unique-d  0.052935  0.928645  0.505045
              1  strings  strings  strings  unique-f  0.776922  0.338918  0.932535
              2  strings  strings  strings  unique-c  0.799160  0.343798  0.145575
              3  strings  strings  strings  unique-a  0.659975  0.308475  0.588496
              4  strings  strings  strings  unique-i  0.450931  0.667722  0.831734
              5  strings  strings  strings  unique-e  0.791060  0.801188  0.781400
              6  strings  strings  strings  unique-b  0.653861  0.649786  0.545784
              7  strings  strings  strings  unique-h  0.849901  0.327025  0.874650
              8  strings  strings  strings  unique-g  0.812554  0.995710  0.042272

                   201804    201805
              0  0.011463  0.980985
              1  0.743247  0.715230
              2  0.313438  0.882728
              3  0.656984  0.864108
              4  0.236997  0.422303
              5  0.603261  0.083762
              6  0.722503  0.170563
              7  0.608704  0.263881
              8  0.702862  0.760257  )])

# create new dataframe as a copy of the first sheet in excel
calculated_dataframe = all_sheets_df.get("sheet1","").copy()

# get list of columns to update (all columns to be updated start with characters '20'
update_cols = [col for col in calculated_dataframe.columns if '20' in col]

# for each row in calculated_dataframe, find row in all_sheets_df.get("sheet2","") where column name 'uni-id' matches 'uni-id' in calculated_dataframe and then for each update_col in update_cols calculate_dataframe value = calculate_dataframe value * all_sheets_df.get("sheet2","") value
# this is the piece im really struggling with.

I want to iterate through each row of calculated_dataframe, find the corresponding row in all_sheets_df.get("sheet2","") where the sheet2 column uni-id = calculated_dataframe column uni-id and multiply each column found in the update_cols list together (these columns exist in both dataframes).

Any guidance you can provide would be great!!

Body:
You should first use the merge function on your identifier column to have only one df with all the columns.

df1 = df1.merge(df2, how ='left', on=['identifier_column'])

Then your rows with same identifier will already be grouped together, and you only have to multiply the columns as you would do normally :

df1['column_3'] = df1['column_1'] * df1['column_2']


来源: stackexchange

问:
BehaviorSubject doesn't immediately change value
I am creating a custom login service with AuthGuard from Angular. I have a SessionService which have methods such a login() or onUserLoggedIn() which basically returns BehaviorSubject with the current value of user status (logged in/not logged in). Based on this service I created an implementation of AuthGuard implements CanActivate service. I call onUserLoggedIn method and check the current value in subject. The problem here is that in login method value is changed after the AuthGuard call onUserLoggedIn. Therefore in a first attempt I receive false value from BehaviorSubject but when I try the second time, I received a true value.

How can I change the implementation of those two services to achieve current value in a first attempt?

AuthGuard:

```<code>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
    : Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    console.log('auth');

    return this.sessionService.onUserLoggedIn()
      .pipe(
        map(res => {
          console.log('res', res);
          return res;
        }),
        take(1),
        tap(allowed => {
          console.log(allowed);
          if (!allowed) {
            this.router.navigate(['/login']);
          }
        })
      );
  }
</code>```

SessionService:

```<code>private isLoggedIn = new BehaviorSubject(false);

  constructor(private apiService: ApiService) {
  }

  login(user: User): Observable<any> {
    console.log('hello before');
    return this.apiService.post(`${BASE_URL}/login`, user)
      .pipe(
        tap((token: Token) => {
          this.isLoggedIn.next(true);
          localStorage.setItem('token', token.token);
          console.log('hello');
        })
      );
  }

  onUserLoggedIn() {
    return this.isLoggedIn;
  }
</code>```

First attempt goes with printing value:

SessionService.ts:19 hello before

AuthGuard.ts:17 auth

AuthGuard.ts:22 res false

AuthGuard.ts:27 false

SessionService.ts:25 hello

The second one (which I expect to be first):

SessionService.ts:19 hello before

AuthGuard.ts:17 auth

AuthGuard.ts:22 res true

AuthGuard.ts:27 true

SessionService.ts:25 hello

答:
Can you try returning it asObservable?</p>

```<code>onUserLoggedIn() {
        return this.isLoggedIn.asObservable();
      }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating a custom login service with AuthGuard from Angular. I have a SessionService which have methods such a login() or onUserLoggedIn() which basically returns BehaviorSubject with the current value of user status (logged in/not logged in). Based on this service I created an implementation of AuthGuard implements CanActivate service. I call onUserLoggedIn method and check the current value in subject. The problem here is that in login method value is changed after the AuthGuard call onUserLoggedIn. Therefore in a first attempt I receive false value from BehaviorSubject but when I try the second time, I received a true value.

How can I change the implementation of those two services to achieve current value in a first attempt?

AuthGuard:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
    : Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    console.log('auth');

    return this.sessionService.onUserLoggedIn()
      .pipe(
        map(res => {
          console.log('res', res);
          return res;
        }),
        take(1),
        tap(allowed => {
          console.log(allowed);
          if (!allowed) {
            this.router.navigate(['/login']);
          }
        })
      );
  }

SessionService:

private isLoggedIn = new BehaviorSubject(false);

  constructor(private apiService: ApiService) {
  }

  login(user: User): Observable<any> {
    console.log('hello before');
    return this.apiService.post(`${BASE_URL}/login`, user)
      .pipe(
        tap((token: Token) => {
          this.isLoggedIn.next(true);
          localStorage.setItem('token', token.token);
          console.log('hello');
        })
      );
  }

  onUserLoggedIn() {
    return this.isLoggedIn;
  }

First attempt goes with printing value:

SessionService.ts:19 hello before

AuthGuard.ts:17 auth

AuthGuard.ts:22 res false

AuthGuard.ts:27 false

SessionService.ts:25 hello

The second one (which I expect to be first):

SessionService.ts:19 hello before

AuthGuard.ts:17 auth

AuthGuard.ts:22 res true

AuthGuard.ts:27 true

SessionService.ts:25 hello

Body:
Can you try returning it asObservable?

onUserLoggedIn() {
        return this.isLoggedIn.asObservable();
      }


问:
TYPO3: How to set up textfield in custom content element to avoid missing file references in backend filelist?
How to set up textfield in custom content element to avoid missing file references in backend filelist

I have a custom content element with a field of type "text". When I link in this field to a file in fileadmin there is no reference counted in the backend.
How I have to configure the field in my TCA to regard the references from that field in the file list?

My TCA-Config for that field is:

```<code>'my_ext_fiedname' =>
                array(
                    'config' =>
                        array(
                            'type' => 'text',
                            'eval' => 'required',
                            'richtextConfiguration' => 'default',
                            'enableRichtext' => '1',
                        ),
                    'exclude' => '1',
                    'label' => 'title',
                ),
</code>```

答:
Try to avoid using media references in text fields. It has been difficult over the past years to upgrade TYPO3 with such configuration and usages.
If you can't avoid, try using extension rte_ckeditor_image from Christian Opitz which is regularly maintained.</p>

Body:
How to set up textfield in custom content element to avoid missing file references in backend filelist

I have a custom content element with a field of type "text". When I link in this field to a file in fileadmin there is no reference counted in the backend.
How I have to configure the field in my TCA to regard the references from that field in the file list?

My TCA-Config for that field is:

'my_ext_fiedname' =>
                array(
                    'config' =>
                        array(
                            'type' => 'text',
                            'eval' => 'required',
                            'richtextConfiguration' => 'default',
                            'enableRichtext' => '1',
                        ),
                    'exclude' => '1',
                    'label' => 'title',
                ),


问:
Delphi: how to debug Windows Authentication related issues?
I noticed a bug at customer side that I cannot reproduce. It is 99% linked to MS SQL Server  windows authentication.

How is it possible to debug an application when windows authentication is involved?

Is it possible (and if yes how) to use remote debugger (I never tried that)?

As an alternative I can do a special build that logs errors in a file.

答:
Always log your errors with complete stack trace, to give you the idea exactly where the error happened. You can use something like MadExcept which enables the user to send you the error log with all relevant data appended when it happens.

When debugging windows API errors, the single relevant piece of information is the API return code that the API itself returns or you can get it via GetLastError function. Success is usually zero (but not always) and error some positive Integer (DWORD) code. Just look at MSDN what it means. You go on from there. I am pretty sure that just the return error code itself will give you enough info (along with your stack trace etc...) about what is wrong.

If not the more detailed analysis is needed. You can then try to replicate user enviromment or remote debug the app.

Oh and note that Windows APIs do not raise exceptions. You are responsible for checking the return code and raising the exception yourself if you feel the need to. It is an old style "C functional type" of programming.

EDIT:

If you are looking for a simple and free solution you can look at SimpleLog, a logging solution of my own. But MadExcept is way better and is full of different options.

ContentLicense: CC BY-SA 3.0


问:
Corda - How to check if counter party nodes are running?
I have build a CorDapp using "Yo!CorDapp" example (https://github.com/corda/spring-observable-stream), over release-v1 of Corda platform.

The CorDapp has four nodes - Controller node (provides network map service and validating notary service), "node A", "node B" and "node C". Following are the flows defined in the app -

Flow 1: "Node A" sends a trade request to "Node B". "Node C" is also notified.

Flow 2: "Node B" approves the trade request, self-signs it, gets signature from A and closes the trade. "Node C" is also notified.

I want "Node A" to check whether "Node B" is running, so that it can decide to initiate the flow "Flow 1".

Is this possible? If yes, kindly elaborate.

答:
You should be able to check the network map cache:

```<code>serviceHub.networkMapCache.allNodes.map { node -> node.legalIdentities.first() }
</code>```

Check that the party you want to communicate with is in that list.

That said, it should not matter if the counterparty node is up or not. Corda will handle delivery to the node when the counterparty comes back up.

Body:
You should be able to check the network map cache:

serviceHub.networkMapCache.allNodes.map { node -> node.legalIdentities.first() }

Check that the party you want to communicate with is in that list.

That said, it should not matter if the counterparty node is up or not. Corda will handle delivery to the node when the counterparty comes back up.


问:
How to fix FAB inside activity?
I'm trying to add a BottomAppBar to my activity but there's a error : " java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mathmech.cards/com.mathmech.cards.activity.MainActivity}: android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class com.google.android.material.bottomappbar.BottomAppBar"

I tried to follow guides on web but nothing helped

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".activity.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.bottomappbar.BottomAppBar
            android:id="@+id/bottom_app_bar"
            app:fabAlignmentMode="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorPrimary"
            android:gravity="bottom" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            app:layout_anchor="@id/bottom_app_bar"
            android:layout_width="wrap_content"
            android:src="@drawable/ic_add_black_24dp"
            android:layout_height="wrap_content" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

```

<p>EDIT: added styles.xml</p>

<pre class="lang-xml prettyprint-override"><code><resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>
</code>```

答: Instead of using your parent theme as Theme.AppCompat.Light.DarkActionBar, use Theme.MaterialComponents or its descendant.

Title: How to fix FAB inside activity?

Body:
I'm trying to add a BottomAppBar to my activity but there's a error : " java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mathmech.cards/com.mathmech.cards.activity.MainActivity}: android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class com.google.android.material.bottomappbar.BottomAppBar"

I tried to follow guides on web but nothing helped

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".activity.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.bottomappbar.BottomAppBar
            android:id="@+id/bottom_app_bar"
            app:fabAlignmentMode="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/colorPrimary"
            android:gravity="bottom" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            app:layout_anchor="@id/bottom_app_bar"
            android:layout_width="wrap_content"
            android:src="@drawable/ic_add_black_24dp"
            android:layout_height="wrap_content" />

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

EDIT: added styles.xml

<resources>

</resources>


问:
How to use generic type in a value tuple?
Let's presume i have two enums:

```<code>    public enum eFruits : int
    {
        Apple = 1,
        Pear = 2,
        Banana = 3
    }
</code>```

```<code>    public enum eAnimals : int
    {
        Dog = 1,
        Cat = 2,
        Rabbit = 3
    }
</code>```

I would like to use these in dropdownlists/checklists etc; basically as listitems. The current code i have as a tryout is this;

```<code>    public static class EnumHelper
    {
        public static IEnumerable<(int eCode, eFruits eType)> GetFruitTypesAsListItems()
        {
            var enums = new List<(int eCode, eFruits eType)>();
            foreach (var item in (eFruits[])Enum.GetValues(typeof(eFruits)))
            {
                enums.Add(((int)item, item));
            }
            return enums;
        }
    }
</code>```

Two issues with this;

1) I would like to have this in a generic way

2) It doesn't look nice inside a list/dropdown etc. so I'd like to use a ToString override.

Therefore I thought of something like this:

```<code>    public class EnumListItem : Tuple<int, T>
    {
        public EnumListItem(int eCode, T eType)
            : base(eCode, eType)
        { }

        public override string ToString() => $"{base.Item2.ToString()} ({base.Item1})";
    }
</code>```

So in effect;

1) I would like to use a Generic with a Tuple

2) Would like to use a Generic to be able to generate list items based on that Tuple

Is this possible? I'm not sure how the declaration of this would look like. At this point I can't get it to work. Can someone point me in the right direction?

答:
You can try below generic method.

```<code>public static class EnumHelper<T>
{
    public static IEnumerable<(int eCode, T eType)> GetListItem()
    {
        var enums = new List<(int eCode, T eType)>();
        foreach (var item in (T[])Enum.GetValues(typeof(T)))
        {
            enums.Add((Convert.ToInt32(item), item));
        }
        return enums;
    }
}
</code>```

And you can call it like,

```<code>public static void Main(string[] args)
{
    var animals = EnumHelper<eAnimals>.GetListItem();

    var fruits = EnumHelper<eFruits>.GetListItem();
}
</code>```

Output:

Body:
Let's presume i have two enums:

    public enum eFruits : int
    {
        Apple = 1,
        Pear = 2,
        Banana = 3
    }

    public enum eAnimals : int
    {
        Dog = 1,
        Cat = 2,
        Rabbit = 3
    }

I would like to use these in dropdownlists/checklists etc; basically as listitems. The current code i have as a tryout is this;

    public static class EnumHelper
    {
        public static IEnumerable<(int eCode, eFruits eType)> GetFruitTypesAsListItems()
        {
            var enums = new List<(int eCode, eFruits eType)>();
            foreach (var item in (eFruits[])Enum.GetValues(typeof(eFruits)))
            {
                enums.Add(((int)item, item));
            }
            return enums;
        }
    }

Two issues with this;

1) I would like to have this in a generic way

2) It doesn't look nice inside a list/dropdown etc. so I'd like to use a ToString override.

Therefore I thought of something like this:

    public class EnumListItem : Tuple<int, T>
    {
        public EnumListItem(int eCode, T eType)
            : base(eCode, eType)
        { }

        public override string ToString() => $"{base.Item2.ToString()} ({base.Item1})";
    }

So in effect;

1) I would like to use a Generic with a Tuple

2) Would like to use a Generic to be able to generate list items based on that Tuple

Is this possible? I'm not sure how the declaration of this would look like. At this point I can't get it to work. Can someone point me in the right direction?

Body:
You can try below generic method.

public static class EnumHelper<T>
{
    public static IEnumerable<(int eCode, T eType)> GetListItem()
    {
        var enums = new List<(int eCode, T eType)>();
        foreach (var item in (T[])Enum.GetValues(typeof(T)))
        {
            enums.Add((Convert.ToInt32(item), item));
        }
        return enums;
    }
}

And you can call it like,

public static void Main(string[] args)
{
    var animals = EnumHelper<eAnimals>.GetListItem();

    var fruits = EnumHelper<eFruits>.GetListItem();
}

Output:


问:
Fetching JSON response from web not working
I am trying to fetch a json. While the code used to work I changed it a little and now it doesn't work. The code is supposed to exchange money.

```<code>            sendjsonrequest();
            assert tv != null;

            //Request a string response from the URL resource
            StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://free.currencyconverterapi.com/api/v6/convert?q=EUR_ILS&compact=ultra&apiKey=6f4b50fae0c5c91a84bd",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // Display the response string.
                            tv.setText("Response is: " + Float.parseFloat(response) * Float.parseFloat(et1.getText().toString()));
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    tv.setText("Oops! That didn't work!");
                }
            });

            //Instantiate the RequestQueue and add the request to the queue
            RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
            queue.add(stringRequest);
            String str1 = et1.getText().toString();
            str = Float.parseFloat(str1);
            float e = f * str;
            String ef = Float.toString(e);
            tv.setText(ef);
        }
    });

    button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(intent);
        }
    });

}

public void sendjsonrequest() {//sends the request to the website and retrieves specififc data (exchange rate between EUR to ILS)
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                tv1 = response.getString("EUR_ILS");

                f = Float.parseFloat(tv1);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    rq.add(jsonObjectRequest);
}
}
</code>```

答:
Using Retrofit you can easily get response from web.

Please follow below link to set retrofit code:-

https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/

Body:
I am trying to fetch a json. While the code used to work I changed it a little and now it doesn't work. The code is supposed to exchange money.

            sendjsonrequest();
            assert tv != null;

            //Request a string response from the URL resource
            StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://free.currencyconverterapi.com/api/v6/convert?q=EUR_ILS&compact=ultra&apiKey=6f4b50fae0c5c91a84bd",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            // Display the response string.
                            tv.setText("Response is: " + Float.parseFloat(response) * Float.parseFloat(et1.getText().toString()));
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    tv.setText("Oops! That didn't work!");
                }
            });

            //Instantiate the RequestQueue and add the request to the queue
            RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
            queue.add(stringRequest);
            String str1 = et1.getText().toString();
            str = Float.parseFloat(str1);
            float e = f * str;
            String ef = Float.toString(e);
            tv.setText(ef);
        }
    });

    button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(intent);
        }
    });

}

public void sendjsonrequest() {//sends the request to the website and retrieves specififc data (exchange rate between EUR to ILS)
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                tv1 = response.getString("EUR_ILS");

                f = Float.parseFloat(tv1);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    rq.add(jsonObjectRequest);
}
}


问:
Is there a way to make RecyclerView requiresFadingEdge unaffected by paddingTop and paddingBottom
Currently, I need to use paddingTop and paddingBottom of RecyclerView, as I want to avoid complex space calculation, in my first RecyclerView item and last item.

However, I notice that, requiresFadingEdge effect will be affected as well.

This is my XML

```<code><androidx.recyclerview.widget.RecyclerView
    android:requiresFadingEdge="vertical"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"

    android:overScrollMode="always"
    android:background="?attr/recyclerViewBackground"
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false" />
</code>```

When paddingTop and paddingBottom is 40dp

As you can see, the fading effect shift down by 40dp, which is not what I want.

When paddingTop and paddingBottom is 0dp

Fading effect looks fine. But, I need to have non-zero paddingTop and paddingBottom, for my RecyclerView.

Is there a way to make RecyclerView's requiresFadingEdge unaffected by paddingTop and paddingBottom?

答:
I found the best and kind of official solution for this. Override this 3 methods of RecyclerView. Which play most important role for fading edge.

First create your recyclerView.

```<code>public class MyRecyclerView extends RecyclerView {

    // ... required constructor

    @Override
    protected boolean isPaddingOffsetRequired() {
        return true;
    }

    @Override
    protected int getTopPaddingOffset() {
        return -getPaddingTop();
    }

    @Override
    protected int getBottomPaddingOffset() {
        return getPaddingBottom();
    }
}
</code>```

That's it. Use this recyclerview and you will see fadding edge unaffected.

Following content is just for explanation. If you want to know behind the scene.

To understand how this edge effect is working I dig into the class where android:requiresFadingEdge is used, And I found that it's not handled by RecyclerView instead It's handled by View class which is parent for all view.

In onDraw method of View class I found the code for drawing fade edge by using  help of this method isPaddingOffsetRequired. Which used only for handling the fade effect.

According to documentation this method should be overridden by child class If you want to change the behaviour of fading edge. Bydefault It return false. So By returning true we are asking view to apply some offset for edge at the time of view drawing.

Look following snippet of onDraw method of View class to understand the calculation.

```<code>final boolean offsetRequired = isPaddingOffsetRequired();
if (offsetRequired) {
    paddingLeft += getLeftPaddingOffset();
}

int left = mScrollX + paddingLeft;
int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
int top = mScrollY + getFadeTop(offsetRequired);
int bottom = top + getFadeHeight(offsetRequired);

if (offsetRequired) {
    right += getRightPaddingOffset();
    bottom += getBottomPaddingOffset();
}
</code>```

As we can see top variable is initialize using getFadeTop(offsetRequired).

```<code>protected int getFadeTop(boolean offsetRequired) {
    int top = mPaddingTop;
    if (offsetRequired) top += getTopPaddingOffset();
    return top;
}
</code>```

In this method, top is calculated by adding value of topOffSet when offset is needed. So to reverse the effect we need to pass negative value of padding which you are passing. so we need to return -getPaddingTop().

Now for bottom we are not passing negative value because bottom is working on top + height. So passing negative value make fade more shorter from the bottom so we need to add bottom padding to make it proper visible.

You can override this 4 method to play with it. getLeftPaddingOffset(), getRightPaddingOffset(), getTopPaddingOffset(), getBottomPaddingOffset()

Body:
Currently, I need to use paddingTop and paddingBottom of RecyclerView, as I want to avoid complex space calculation, in my first RecyclerView item and last item.

However, I notice that, requiresFadingEdge effect will be affected as well.

This is my XML

<androidx.recyclerview.widget.RecyclerView
    android:requiresFadingEdge="vertical"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"

    android:overScrollMode="always"
    android:background="?attr/recyclerViewBackground"
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false" />

When paddingTop and paddingBottom is 40dp

As you can see, the fading effect shift down by 40dp, which is not what I want.

When paddingTop and paddingBottom is 0dp

Fading effect looks fine. But, I need to have non-zero paddingTop and paddingBottom, for my RecyclerView.

Is there a way to make RecyclerView's requiresFadingEdge unaffected by paddingTop and paddingBottom?

Body:
I found the best and kind of official solution for this. Override this 3 methods of RecyclerView. Which play most important role for fading edge.

First create your recyclerView.

public class MyRecyclerView extends RecyclerView {

    // ... required constructor

    @Override
    protected boolean isPaddingOffsetRequired() {
        return true;
    }

    @Override
    protected int getTopPaddingOffset() {
        return -getPaddingTop();
    }

    @Override
    protected int getBottomPaddingOffset() {
        return getPaddingBottom();
    }
}

That's it. Use this recyclerview and you will see fadding edge unaffected.

Following content is just for explanation. If you want to know behind the scene.

To understand how this edge effect is working I dig into the class where android:requiresFadingEdge is used, And I found that it's not handled by RecyclerView instead It's handled by View class which is parent for all view.

In onDraw method of View class I found the code for drawing fade edge by using  help of this method isPaddingOffsetRequired. Which used only for handling the fade effect.

According to documentation this method should be overridden by child class If you want to change the behaviour of fading edge. Bydefault It return false. So By returning true we are asking view to apply some offset for edge at the time of view drawing.

Look following snippet of onDraw method of View class to understand the calculation.

final boolean offsetRequired = isPaddingOffsetRequired();
if (offsetRequired) {
    paddingLeft += getLeftPaddingOffset();
}

int left = mScrollX + paddingLeft;
int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
int top = mScrollY + getFadeTop(offsetRequired);
int bottom = top + getFadeHeight(offsetRequired);

if (offsetRequired) {
    right += getRightPaddingOffset();
    bottom += getBottomPaddingOffset();
}

As we can see top variable is initialize using getFadeTop(offsetRequired).

protected int getFadeTop(boolean offsetRequired) {
    int top = mPaddingTop;
    if (offsetRequired) top += getTopPaddingOffset();
    return top;
}

In this method, top is calculated by adding value of topOffSet when offset is needed. So to reverse the effect we need to pass negative value of padding which you are passing. so we need to return -getPaddingTop().

Now for bottom we are not passing negative value because bottom is working on top + height. So passing negative value make fade more shorter from the bottom so we need to add bottom padding to make it proper visible.

You can override this 4 method to play with it. getLeftPaddingOffset(), getRightPaddingOffset(), getTopPaddingOffset(), getBottomPaddingOffset()


问:
Should I use resource routing even for non-CRUD routes (Rails)?
Is it considered best practice to use resourceful routes in Rails whenever possible, even if the CRUD verbs don't really match the actions being performed (details follow)?

In my Rails app, I'm implementing an OAuth login system using sorcery's external module. I closely followed their official tutorial, which defines the routes for the OAuth methods like this.

# config/routes.rb
post "oauth/callback" => "oauths#callback"
get "oauth/callback" => "oauths#callback" # for use with Github, Facebook
get "oauth/:provider" => "oauths#oauth", :as => :auth_at_provider
```

<p>Basically, <code>auth_at_provider</code> is called when the user clicks the "Login via [Provider Name]" button, and the <code>callback</code> is called once they log in via the external provider.</p>

<p>I left the routes as-is, but a teammate reviewing it suggested we use resource routing, like this for example:</p>

<pre class="lang-rb prettyprint-override"><code>resources :oauth only: [:index, :create, :show]
</code>```

I guess this is technically possible, but for me the singular routes defined in the tutorial are much more intuitive and self-explanatory. So my questions are:

Is it considered better (or common) to use resourceful routes even in cases like this? or

Are resourceful routes just a shorthand for cookie-cutter routes, and should only be used for straightforward controllers?

答:
It is generally considered best practice to use resourceful routing when you're actually doing CRUD on a resource, ie:

```<code>resources :users # for creating, reading, updating, deleting users
</code>```

If you'd have to create an entirely new resource and controller just for one create endpoint (for example), I don't see any harm in breaking the pattern and using non-resourceful routes, but I try to avoid doing so.

You should try to use resourceful routing with names that makes sense, to keep your routes consistent:

```<code>scope path: 'oauth' do
  resource :callback, only: [:show, :update] # use show/update instead of callback method
  resources :providers, only: [:show] # use show instead of auth_at_provider
end
</code>```

So your routes would look like:

```<code>POST oauth/callback
GET  oauth/callback
GET  oauth/providers/:id
</code>```

Body:
Is it considered best practice to use resourceful routes in Rails whenever possible, even if the CRUD verbs don't really match the actions being performed (details follow)?

In my Rails app, I'm implementing an OAuth login system using sorcery's external module. I closely followed their official tutorial, which defines the routes for the OAuth methods like this.

# config/routes.rb
post "oauth/callback" => "oauths#callback"
get "oauth/callback" => "oauths#callback" # for use with Github, Facebook
get "oauth/:provider" => "oauths#oauth", :as => :auth_at_provider

Basically, auth_at_provider is called when the user clicks the "Login via [Provider Name]" button, and the callback is called once they log in via the external provider.

I left the routes as-is, but a teammate reviewing it suggested we use resource routing, like this for example:

resources :oauth only: [:index, :create, :show]

I guess this is technically possible, but for me the singular routes defined in the tutorial are much more intuitive and self-explanatory. So my questions are:

Is it considered better (or common) to use resourceful routes even in cases like this? or

Are resourceful routes just a shorthand for cookie-cutter routes, and should only be used for straightforward controllers?

Body:
It is generally considered best practice to use resourceful routing when you're actually doing CRUD on a resource, ie:

resources :users # for creating, reading, updating, deleting users

If you'd have to create an entirely new resource and controller just for one create endpoint (for example), I don't see any harm in breaking the pattern and using non-resourceful routes, but I try to avoid doing so.

You should try to use resourceful routing with names that makes sense, to keep your routes consistent:

scope path: 'oauth' do
  resource :callback, only: [:show, :update] # use show/update instead of callback method
  resources :providers, only: [:show] # use show instead of auth_at_provider
end

So your routes would look like:

POST oauth/callback
GET  oauth/callback
GET  oauth/providers/:id


问:
PHP: allow_url_include
Quick...possibly stupid question.

When allow_url_include is set to off, does that prohibit other computers from remotely including the files on my site, or does it say that I'm not allowed to remotely include files from other sites?

答: Settings in your php.ini only affect your PHP installation

Title: PHP: allow_url_include


问:
Live filter multiple taxonomy queries
I am creating a front end filter that contains checkboxes the visittors can click to sort posts based on taxonomies. The posts they can filter is a custom post type with 3 taxonomies attached to it.

This is a custom ajax live filter, so that whenever someone clicks a checkbox, the result is returned, no page load and no submit buttons.

The front end works fine, the information that is sent to the endpoint is fine, and if I narrow the query down to only one taxonomy everything works as expected, regardless of the taxonomy i narrow the filter down to. But with multiple taxonomies in the query I run in to problems. This is the first time I am creating something like this, so I hope it's just a minor thing that I haven't thought of, but no matter what I try, the taxonomy filter only filters by the first taxonomy that has a term that is checked.

An example:

Tax 1
Tax 2
Tax 3

If the first checkbox that is clicked belongs to Tax 1, then it will only filter within Tax 1. If I try to click on a checkbox that belongs to Tax 2 or Tax 3, it disregards those terms/tax entirely, and still only filters by the first taxonomy.

I know I am doing something wrong in the query, so I am really hoping someone here on SO can give me some guidence on what I am supposed to do to get this working.

Here is the endpoint (query):

```<code>function myFilter ($data) {

    $checkFylker          = $data['checkFylker'];
    $checkUtstyr          = $data['checkUtstyr'];
    $checkFors            = $data['checkFors'];
    $checkType            = $data['checkType'];

    //return $results;

  //Main $args
  $args = array(
      'post_type'     => 'ml_opp', // Query only "ml_opp" custom posts
      'post_status'   => 'publish', // Query only posts with "publish" status
      'orderby'       => 'date', // Sort posts by date
      'order'         => 'ASC' // ASC
    );

    $args['tax_query'] = array( 'relation'=>'AND' ); // AND means that all conditions of meta_query should be true

    // for taxonomies / utstyr
    if( isset( $checkUtstyr ) )
      $args['tax_query'][] = array(
        array(
          'taxonomy'  => 'ml_utstyr',
          'field'     => 'id',
          'terms'     => $checkUtstyr
        )
      );

    //for taxonomies / forsendelse
    if( isset( $checkFors ) )
      $args['tax_query'][] = array(
        array(
          'taxonomy'  => 'ml_forsendelse',
          'field'     => 'id',
          'terms'     => $checkFors
        )
      );

    // for taxonomies / fylker
    if( isset( $checkFylker ) )
      $args['tax_query'] = array(
        array(
          'taxonomy'  => 'ml_fylk',
          'field'     => 'id',
          'terms'     => $checkFylker
        )
      );

    // for taxonomies / type
    if( isset( $checkType ) )
      $args['tax_query'] = array(
        array(
          'taxonomy'  => 'ml_typ',
          'field'     => 'id',
          'terms'     => $checkType
        )
      );

    $query = new WP_Query( $args );

    if( $query->have_posts() ) :
      while( $query->have_posts() ): $query->the_post();
        echo '<h2>' . $query->post->post_title . '</h2>';
      endwhile;
      wp_reset_postdata();
    else :
      echo 'No posts found';
    endif;

    die();
    }
</code>```

答:
Your all isset conditions are wrongly interpreted to match the tax_query. See updated below code snippet and compare with yours to find the difference.

```<code>function myFilter ($data) {

    $checkFylker          = $data['checkFylker'];
    $checkUtstyr          = $data['checkUtstyr'];
    $checkFors            = $data['checkFors'];
    $checkType            = $data['checkType'];

    //return $results;

  //Main $args
  $args = array(
      'post_type'     => 'ml_opp', // Query only "ml_opp" custom posts
      'post_status'   => 'publish', // Query only posts with "publish" status
      'orderby'       => 'date', // Sort posts by date
      'order'         => 'ASC' // ASC
    );

    $args['tax_query'] = array( 'relation'=>'AND' ); // AND means that all conditions of meta_query should be true

    // for taxonomies / utstyr
    if( isset( $checkUtstyr ) )
      $args['tax_query'][] = array(
          'taxonomy'  => 'ml_utstyr',
          'field'     => 'id',
          'terms'     => $checkUtstyr
      );

    //for taxonomies / forsendelse
    if( isset( $checkFors ) )
      $args['tax_query'][] = array(
          'taxonomy'  => 'ml_forsendelse',
          'field'     => 'id',
          'terms'     => $checkFors
      );

    // for taxonomies / fylker
    if( isset( $checkFylker ) )
      $args['tax_query'][] = array(
          'taxonomy'  => 'ml_fylk',
          'field'     => 'id',
          'terms'     => $checkFylker
      );

    // for taxonomies / type
    if( isset( $checkType ) )
      $args['tax_query'][] = array(
          'taxonomy'  => 'ml_typ',
          'field'     => 'id',
          'terms'     => $checkType
     );

    $query = new WP_Query( $args );

    if( $query->have_posts() ) :
      while( $query->have_posts() ): $query->the_post();
        echo '<h2>' . $query->post->post_title . '</h2>';
      endwhile;
      wp_reset_postdata();
    else :
      echo 'No posts found';
    endif;
    die();
  }
</code>```

Title: Live filter multiple taxonomy queries

Body:
I am creating a front end filter that contains checkboxes the visittors can click to sort posts based on taxonomies. The posts they can filter is a custom post type with 3 taxonomies attached to it.

This is a custom ajax live filter, so that whenever someone clicks a checkbox, the result is returned, no page load and no submit buttons.

The front end works fine, the information that is sent to the endpoint is fine, and if I narrow the query down to only one taxonomy everything works as expected, regardless of the taxonomy i narrow the filter down to. But with multiple taxonomies in the query I run in to problems. This is the first time I am creating something like this, so I hope it's just a minor thing that I haven't thought of, but no matter what I try, the taxonomy filter only filters by the first taxonomy that has a term that is checked.

An example:

Tax 1
Tax 2
Tax 3

If the first checkbox that is clicked belongs to Tax 1, then it will only filter within Tax 1. If I try to click on a checkbox that belongs to Tax 2 or Tax 3, it disregards those terms/tax entirely, and still only filters by the first taxonomy.

I know I am doing something wrong in the query, so I am really hoping someone here on SO can give me some guidence on what I am supposed to do to get this working.

Here is the endpoint (query):

function myFilter ($data) {

    $checkFylker          = $data['checkFylker'];
    $checkUtstyr          = $data['checkUtstyr'];
    $checkFors            = $data['checkFors'];
    $checkType            = $data['checkType'];

    //return $results;

  //Main $args
  $args = array(
      'post_type'     => 'ml_opp', // Query only "ml_opp" custom posts
      'post_status'   => 'publish', // Query only posts with "publish" status
      'orderby'       => 'date', // Sort posts by date
      'order'         => 'ASC' // ASC
    );

    $args['tax_query'] = array( 'relation'=>'AND' ); // AND means that all conditions of meta_query should be true

    // for taxonomies / utstyr
    if( isset( $checkUtstyr ) )
      $args['tax_query'][] = array(
        array(
          'taxonomy'  => 'ml_utstyr',
          'field'     => 'id',
          'terms'     => $checkUtstyr
        )
      );

    //for taxonomies / forsendelse
    if( isset( $checkFors ) )
      $args['tax_query'][] = array(
        array(
          'taxonomy'  => 'ml_forsendelse',
          'field'     => 'id',
          'terms'     => $checkFors
        )
      );

    // for taxonomies / fylker
    if( isset( $checkFylker ) )
      $args['tax_query'] = array(
        array(
          'taxonomy'  => 'ml_fylk',
          'field'     => 'id',
          'terms'     => $checkFylker
        )
      );

    // for taxonomies / type
    if( isset( $checkType ) )
      $args['tax_query'] = array(
        array(
          'taxonomy'  => 'ml_typ',
          'field'     => 'id',
          'terms'     => $checkType
        )
      );

    $query = new WP_Query( $args );

    if( $query->have_posts() ) :
      while( $query->have_posts() ): $query->the_post();
        echo '
' . $query->post->post_title . '
';
      endwhile;
      wp_reset_postdata();
    else :
      echo 'No posts found';
    endif;

    die();
    }

Body:
Your all isset conditions are wrongly interpreted to match the tax_query. See updated below code snippet and compare with yours to find the difference.

function myFilter ($data) {

    $checkFylker          = $data['checkFylker'];
    $checkUtstyr          = $data['checkUtstyr'];
    $checkFors            = $data['checkFors'];
    $checkType            = $data['checkType'];

    //return $results;

  //Main $args
  $args = array(
      'post_type'     => 'ml_opp', // Query only "ml_opp" custom posts
      'post_status'   => 'publish', // Query only posts with "publish" status
      'orderby'       => 'date', // Sort posts by date
      'order'         => 'ASC' // ASC
    );

    $args['tax_query'] = array( 'relation'=>'AND' ); // AND means that all conditions of meta_query should be true

    // for taxonomies / utstyr
    if( isset( $checkUtstyr ) )
      $args['tax_query'][] = array(
          'taxonomy'  => 'ml_utstyr',
          'field'     => 'id',
          'terms'     => $checkUtstyr
      );

    //for taxonomies / forsendelse
    if( isset( $checkFors ) )
      $args['tax_query'][] = array(
          'taxonomy'  => 'ml_forsendelse',
          'field'     => 'id',
          'terms'     => $checkFors
      );

    // for taxonomies / fylker
    if( isset( $checkFylker ) )
      $args['tax_query'][] = array(
          'taxonomy'  => 'ml_fylk',
          'field'     => 'id',
          'terms'     => $checkFylker
      );

    // for taxonomies / type
    if( isset( $checkType ) )
      $args['tax_query'][] = array(
          'taxonomy'  => 'ml_typ',
          'field'     => 'id',
          'terms'     => $checkType
     );

    $query = new WP_Query( $args );

    if( $query->have_posts() ) :
      while( $query->have_posts() ): $query->the_post();
        echo '<h2>' . $query->post->post_title . '</h2>';
      endwhile;
      wp_reset_postdata();
    else :
      echo 'No posts found';
    endif;
    die();
  }


问:
PostgreSQL invalid byte sequence for encoding utf8 0xbf
I am importing a CSV file which is related to the properties. It has /n between the values. While trying to import it into a table, the following error shows up:

```<code>PostgreSQL invalid byte sequence for encoding utf8 0xbf
</code>```

I tried by simply importing the single column only, but it is not working.
Column values will look like this:

```<code>"Job No 305385917-001: To attached Garage (Single remain).\n10305 - 132 STREET NW
Plan 23AF Blk 84 Lot 14\n2002995 LERTA LTD O/A LIR HOMES DONTON\nHENORA"
</code>```

I want to import the above whole into a single column.

```<code>COPY edmonton.general_filtered (descriptive)
FROM 'D:/property_own/descriptive_details.csv'
DELIMITER ',' CSV HEADER;
</code>```

答:
Your COPY statement is correct, but your data are not in UTF8 encoding.

They are probably in Latin-1 or Windows-1252, where 0xBF is ¿.

Specify the encoding correctly, e.g.:

```<code>COPY edmonton.general_filtered (descriptive)
FROM 'D:/property_own/descriptive_details.csv'
(FORMAT 'csv', HEADER, ENCODING 'WIN1252');
</code>```

Body:
I am importing a CSV file which is related to the properties. It has /n between the values. While trying to import it into a table, the following error shows up:

PostgreSQL invalid byte sequence for encoding utf8 0xbf

I tried by simply importing the single column only, but it is not working.
Column values will look like this:

"Job No 305385917-001: To attached Garage (Single remain).\n10305 - 132 STREET NW
Plan 23AF Blk 84 Lot 14\n2002995 LERTA LTD O/A LIR HOMES DONTON\nHENORA"

I want to import the above whole into a single column.

COPY edmonton.general_filtered (descriptive)
FROM 'D:/property_own/descriptive_details.csv'
DELIMITER ',' CSV HEADER;

Body:
Your COPY statement is correct, but your data are not in UTF8 encoding.

They are probably in Latin-1 or Windows-1252, where 0xBF is ¿.

Specify the encoding correctly, e.g.:

COPY edmonton.general_filtered (descriptive)
FROM 'D:/property_own/descriptive_details.csv'
(FORMAT 'csv', HEADER, ENCODING 'WIN1252');


问:
Auto-Linking framework not found
I have forked a framework called BTNavigationDropdownMenu (swift project for ios). all worked fine till I tried to add a dependency to the latest version in the branch I created. the problem is the same whether I add the other framework (DYBadge) through a podfile or through Carthage.

Auto-Linking framework not found DYBadge.

It seems to have a problem with a UIView extension that is part of DYBadge.

DYBadge works fine in my main app I'm working on (I also need it in the app target).

errors below. thanks for any hints into the right direction.

ld: warning: Auto-Linking framework not found DYBadge Undefined
  symbols for architecture x86_64:   "(extension in
  DYBadge):__ObjC.UIView.getBadge() -> DYBadge.DYBadge?", referenced
  from:
        Demo.BTNavigationDropdownMenu.updateBadge(text: Swift.String, at: Swift.Int) -> () in BTNavigationDropdownMenu.o ld: symbol(s) not
  found for architecture x86_64 clang: error: linker command failed with
  exit code 1 (use -v to see invocation)

答:
If you are using Carthage and several Projects within one Workspace you have to add a symlink to your Main Carthage Folder. it will depend what structure you have, but for example if you have

Project -> Carthage

Project -> Frameworks -> MyImbaFramework than cd in terminal in MyImbaFramework folder and run

ln -s ../../Carthage Carthage

Title: Auto-Linking framework not found


问:
Replace particular file content in nodejs
I want to replace a particular line using javascript with new content.
This is the file content,

```<code>SERVER=1055@localhost

GROUP_SERVERS=2325@localhost

LINE_IAM_INTERESTED=KTYUIERVW:2800

FILE_PATH="C:\Program Files\somefile\Shared Files\"
</code>```

In this line, LINE_IAM_INTERESTED=KTYUIERVW:2800 .I want to replace KTYUIERVW with KJHTERDY and 2800 with 78945

I have shown what I tried using fs appendfilesync

```<code>
fs.appendFileSync('file_name').toString().split('\n').forEach(function(line){
    app.console.log("called append");
    var sEntry = line.split("=");
    if (sEntry.length == 2) {
      if (sEntry[0] == "LINE_IAM_INTERESTED") {
      app.console.log("found one!!!!");
      }
    }
  });
</code>```

答:
you can try READ -> REPLACE -> WRITE flow:</p>

```<code>fs.writeFileSync('file_name', fs.readFileSync('file_name').replace('KTYUIERVW:2800', 'KJHTERDY:78945'))
</code>```

Body:
I want to replace a particular line using javascript with new content.
This is the file content,

SERVER=1055@localhost

GROUP_SERVERS=2325@localhost

LINE_IAM_INTERESTED=KTYUIERVW:2800

FILE_PATH="C:\Program Files\somefile\Shared Files\"

In this line, LINE_IAM_INTERESTED=KTYUIERVW:2800 .I want to replace KTYUIERVW with KJHTERDY and 2800 with 78945

I have shown what I tried using fs appendfilesync

fs.appendFileSync('file_name').toString().split('\n').forEach(function(line){
    app.console.log("called append");
    var sEntry = line.split("=");
    if (sEntry.length == 2) {
      if (sEntry[0] == "LINE_IAM_INTERESTED") {
      app.console.log("found one!!!!");
      }
    }
  });

Body:
you can try READ -> REPLACE -> WRITE flow:

fs.writeFileSync('file_name', fs.readFileSync('file_name').replace('KTYUIERVW:2800', 'KJHTERDY:78945'))


问:
Analytics Custom Event overridden by GTM? EventLabel always "(not set)"
I have this code triggering on clicking a tab.

```<code>window.ga('send', {
  hitType: 'event',
  eventCategory: 'PDP',
  eventAction: 'ChangeTab',
  eventLabel: 'lorem ipsum',
});
</code>```

I have checked Analytics Real time and it shows up but the Event Label is always "(not set)"..

Is it Google Tag Manager's Click Event that is messing up my event?

If so how do I work around that? No Tag is fired on the Click.

EDIT: Is this the problem that this datalayer variable is defined in GTM?

答:
This was the solution: https://stackoverflow.com/a/51705995/846348

We're including Analytics via GTM and using "Custom Dimension"/"Trackers" whatever that means.

```<code>class AnalyticsHelper {
  static DEBUG = false; // requires https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna

  static analyticsSend(data = {}) {
    if (AnalyticsHelper.DEBUG) {
      window.ga_debug = { trace: true };
    }
    window.ga(() => {
      const trackers = window.ga.getAll();
      const firstTracker = trackers[0];
      const trackerName = firstTracker.a.data.values[':name'];
      window.ga(`${trackerName}.send`, data);
    });
  }
}
</code>```

Body:
I have this code triggering on clicking a tab.

window.ga('send', {
  hitType: 'event',
  eventCategory: 'PDP',
  eventAction: 'ChangeTab',
  eventLabel: 'lorem ipsum',
});

I have checked Analytics Real time and it shows up but the Event Label is always "(not set)"..

Is it Google Tag Manager's Click Event that is messing up my event?

If so how do I work around that? No Tag is fired on the Click.

EDIT: Is this the problem that this datalayer variable is defined in GTM?

Body:
This was the solution: https://stackoverflow.com/a/51705995/846348

We're including Analytics via GTM and using "Custom Dimension"/"Trackers" whatever that means.

class AnalyticsHelper {
  static DEBUG = false; // requires https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna

  static analyticsSend(data = {}) {
    if (AnalyticsHelper.DEBUG) {
      window.ga_debug = { trace: true };
    }
    window.ga(() => {
      const trackers = window.ga.getAll();
      const firstTracker = trackers[0];
      const trackerName = firstTracker.a.data.values[':name'];
      window.ga(`${trackerName}.send`, data);
    });
  }
}


问:
C# strange with DateTime
I got some strange result for:

```<code>Console.WriteLine(new DateTime(1296346155).ToString());
</code>```

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))

答:
If it's Unix time, then the following should yield the expected result;

```<code>DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
Console.WriteLine(baseTime.AddSeconds(1296346155));
</code>```

See Unix Time for more information.

Title: C# strange with DateTime

Body:
I got some strange result for:

Console.WriteLine(new DateTime(1296346155).ToString());

Result is:

01.01.0001 0:02:09

But it is not right!

I parsed value 1296346155 from some file. It said that it is in UTC;

Please explain;)

Thank you for help!)))

Body:
If it's Unix time, then the following should yield the expected result;

DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
Console.WriteLine(baseTime.AddSeconds(1296346155));

See Unix Time for more information.


问:
Change UIView Size for all application Xamarin iOS
I added a bottom navigation bar view to the NavigationController, but now the bottom bar is over all the views from my app. I want to resize the views and rest the size of the bottom bar.

All my views are created programmatically, so i have something like this:

```<code>    public partial class myClass : MyController<myClassModel>
    {
            public override void LoadView()
            {
                base.LoadView();
                CreateControlsViews();
            }

            public override void ViewDidLoad()
            {
                base.ViewDidLoad();
                Binding();
                UpdateFramesView();
            }
    ...
</code>```

And my Controller looks like this:

```<code>public class MyController : MvxViewController
{
    //public override void LoadView()
    //{
    //    base.LoadView();
    //    Can't override this, because some views has nib
    //}

    public override void ViewDidLoad()
    {
          base.ViewDidLoad();
...
</code>```

I tried something like this:

```<code>this.View.Frame = new CGRect(
   0,
   0,
   this.View.Bounds.Width,
   this.View.Bounds.Height - sizeBottomBar);
</code>```

But only seems to work when i use on the LoadView, but that will destroy all the nib files. What can i do?

答:
Was easier than i think, just need to add a new SafeArea.

```<code>this.AdditionalSafeAreaInsets = new UIEdgeInsets(0, 0, aditionalSizeBar, 0);
</code>```

Hope it can help anyone in a future!

Body:
I added a bottom navigation bar view to the NavigationController, but now the bottom bar is over all the views from my app. I want to resize the views and rest the size of the bottom bar.

All my views are created programmatically, so i have something like this:

    public partial class myClass : MyController<myClassModel>
    {
            public override void LoadView()
            {
                base.LoadView();
                CreateControlsViews();
            }

            public override void ViewDidLoad()
            {
                base.ViewDidLoad();
                Binding();
                UpdateFramesView();
            }
    ...

And my Controller looks like this:

public class MyController : MvxViewController
{
    //public override void LoadView()
    //{
    //    base.LoadView();
    //    Can't override this, because some views has nib
    //}

    public override void ViewDidLoad()
    {
          base.ViewDidLoad();
...

I tried something like this:

this.View.Frame = new CGRect(
   0,
   0,
   this.View.Bounds.Width,
   this.View.Bounds.Height - sizeBottomBar);

But only seems to work when i use on the LoadView, but that will destroy all the nib files. What can i do?

Body:
Was easier than i think, just need to add a new SafeArea.

this.AdditionalSafeAreaInsets = new UIEdgeInsets(0, 0, aditionalSizeBar, 0);

Hope it can help anyone in a future!


问:
newline from user input without pressing enter
First of all, I should mention that I found several closely related questions. Eg here and here. However, neither do I want to use printf nor do I want to use \n (because I know already that it does not work).

Is it possible for the user to enter a newline, probably an escape sequence, without hitting enter?

As an example:

```<code>#include <iostream>
#include <string>

int main () {
    std::string a,b;
    std::cin >> a;
    std::cin >> b;
    std::cout << a << "\n" << b;
}
</code>```

Is it possible for a user to provide a single line of input

```<code>hello ??? world
</code>```

such that the above prints

```<code>hello
world
</code>```

?

答:
You can do like this

std::string a, b;

  std::cin >> a>>b;

  std::cout << a << "\n" << b;

User can give input with space.

Body:
First of all, I should mention that I found several closely related questions. Eg here and here. However, neither do I want to use printf nor do I want to use \n (because I know already that it does not work).

Is it possible for the user to enter a newline, probably an escape sequence, without hitting enter?

As an example:

#include <iostream>
#include <string>

int main () {
    std::string a,b;
    std::cin >> a;
    std::cin >> b;
    std::cout << a << "\n" << b;
}

Is it possible for a user to provide a single line of input

hello ??? world

such that the above prints

hello
world

?


问:
How secure is django's cleaned_data (XSS, CSRF, SQL Injections, HTML/JS Injections, etc)?
Are all these risk handled by django's cleaned_data fields or do I need to implement additional security measures like strip tags?</p>

答:
Handling or preventing these kinds of issues is not the job of form validation.

Form validation only ensures that input data is validated and normalized to the appropriate Python data type, e.g. it ensures that a string entered in a date input is actually a valid date format and converts it to a datetime object.

Form validation does not prevent a user from entering SQL or HTML and it does not  do any escaping (unless you write a custom clean() method, or course).

The protection against the kind of attacks you describe happens in other places:

The template library protects against XSS by treating any template variable as unsafe and escaping it for use in HTML.

The ORM protects against SQL injection by using query parametrization.

The CsrfViewMiddleware protects you against CSRF by requiring a CSRF token for POST request. It is enabled in the default settings file generated by django-admin startproject

For a more detailed description, check out the documentation on Security in Django.


问:
Java 11 and jacorb. ClassNotFoundException: javax.rmi.CORBA.Stub
I am trying to execute my application of java 11 (openjdk) with jacorb 3.9.The application starts executing but crashes complaining about missing :

```<code>javax.rmi.CORBA.Stub
</code>```

I have included all jacorb libraries in the CLASSPATH

```<code>set CLASSPATH = ${JACORB_PATH}/jacorb.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/jacorb-3.9.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/jacorb-omgapi.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/slf4j-api.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/slf4j-jdk14-1.7.14.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/jacorb-services.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/picocontainer.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/wrapper.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/antlr.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/idl.jar:${CLASSPATH}
</code>```

When executing , I get this:

```<code>java.lang.reflect.InvocationTargetException
...
Caused by: java.lang.ClassNotFoundException: javax.rmi.CORBA.Stub
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
</code>```

I have tried also to set up the JDK_JAVA_OPTIONS with:

```<code>--module-path ${JACORB_PATH} --add-modules java.corba
-Dorg.omg.CORBA.ORBClass=org.jacorb.orb.ORB -Dorg.omg.CORBA.ORBSingletonClass=org.jacorb.orb.ORBSingleton
</code>```

But complains about "Two versions of module slf4j.jdk14 found"

The command for executing the program is:

```<code>java -classpath $CLASSPATH myprog.MYPROG
</code>```

The application was originally written for Java 8 and working OK  with jacorb passing the following  parameters to java command:

```<code>-Djava.endorsed.dirs=JACORB_PATH
-Dorg.omg.CORBA.ORBClass=org.jacorb.orb.ORB
-Dorg.omg.CORBA.ORBSingletonClass=org.jacorb.orb.ORBSingleton
</code>```

The application does not use rmi at all. It is a 'classic' CORBA client. It crashes when trying to resolve the initial reference of the naming Service

答:
It seems that the issue have been raised on the project mailing list. A workaround is to add on the classpath next to jacorb-3.8.jar and the sfl4j jars these 2:

jacorb-omgapi-3.8.jar    - from JacORB distribution

jboss-rmi-api_1.0_spec-1.0.6.Final.jar   - from https://github.com/jboss/jboss-rmi-api_spec. This library provides the Java RMI API which was originally used by JacORB from the JRE. (Maven)

Body:
I am trying to execute my application of java 11 (openjdk) with jacorb 3.9.The application starts executing but crashes complaining about missing :

javax.rmi.CORBA.Stub

I have included all jacorb libraries in the CLASSPATH

set CLASSPATH = ${JACORB_PATH}/jacorb.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/jacorb-3.9.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/jacorb-omgapi.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/slf4j-api.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/slf4j-jdk14-1.7.14.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/jacorb-services.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/picocontainer.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/wrapper.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/antlr.jar:${CLASSPATH}
set CLASSPATH = ${JACORB_PATH}/idl.jar:${CLASSPATH}

When executing , I get this:

java.lang.reflect.InvocationTargetException
...
Caused by: java.lang.ClassNotFoundException: javax.rmi.CORBA.Stub
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)

I have tried also to set up the JDK_JAVA_OPTIONS with:

--module-path ${JACORB_PATH} --add-modules java.corba
-Dorg.omg.CORBA.ORBClass=org.jacorb.orb.ORB -Dorg.omg.CORBA.ORBSingletonClass=org.jacorb.orb.ORBSingleton

But complains about "Two versions of module slf4j.jdk14 found"

The command for executing the program is:

java -classpath $CLASSPATH myprog.MYPROG

The application was originally written for Java 8 and working OK  with jacorb passing the following  parameters to java command:

-Djava.endorsed.dirs=JACORB_PATH
-Dorg.omg.CORBA.ORBClass=org.jacorb.orb.ORB
-Dorg.omg.CORBA.ORBSingletonClass=org.jacorb.orb.ORBSingleton

The application does not use rmi at all. It is a 'classic' CORBA client. It crashes when trying to resolve the initial reference of the naming Service


问:
Spring boot set log level for all tests at once (without changing every test)
Is there a way to set the logging level only for tests at once? (Without copying the complete application.yml to test/resources)

Using a specific profile would mean to add this manually to all tests. Using TestPropertySource would also mean to change all tests.

Is there something that i can put into test/resources that just sets logging and take all other properties from default/active profile?

答:
If you're using logback, you can put logback-test.xml in src/test/resources and define all the relevant configurations there

So if you have a regular logback.xml in src/main/resources of the module, the logback-test.xml will override the definitions from the "regular" file

Example:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.myapp" level="INFO"/>
 </configuration>
</code>```

Body:
If you're using logback, you can put logback-test.xml in src/test/resources and define all the relevant configurations there

So if you have a regular logback.xml in src/main/resources of the module, the logback-test.xml will override the definitions from the "regular" file

Example:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="org.springframework" level="ERROR"/>
    <logger name="com.myapp" level="INFO"/>
 </configuration>


问:
Connect k8s pod to iscsi
I'm using a terastation's iscsi capabilities to create storage for my k8s 1.14 cluster (kubeadm, ubuntu 18.04).  I check the iqn:

```<code>iscsiadm --mode node
192.168.2.113:3260,1 iqn.2004-08.jp.buffalo.7403bd2a30a0.drupal-mysql
</code>```

There's no ":".  when I try to use

```<code>volumes:
    - name: iscsi-data
      iscsi:
        targetPortal: 192.168.2.113:3260
        iqn: "iqn.2004-08.jp.buffalo.7403bd2a30a0.drupal-mysql"
        lun: 0
        fsType: xfs
</code>```

i get the error:

```<code>spec.template.spec.volumes[0].iscsi.iqn: Invalid value: "iqn.2004-08.jp.buffalo.7403bd2a30a0.drupal-mysql": must be valid format
</code>```

i know its looking for something that ends in a ":name" but I can't figure out what thats supposed to be for the life of me.  I know the iscsi drive mounts because i can see it on my node and was able to format it using xfs.  I think I'm missing something really simple.

Thanks

答:
iSCSI network storage standard is fully documented in RFC 3720 and  RFC 3721 with an appropriate IQN constructing format for iSCSI names.

iSCSI qualified name (IQN), coressponds to the following form:

iqn.yyyy-mm.naming-authority:unique-name, where:

iqn – the prefix iqn.

yyyy-mm – the year and month when the naming authority was established. For example: 1992-08.

naming-authority – the organizational naming authority string, usually reverse syntax of the Internet domain name of the naming
authority. For example: com.vmware.

unique name – any name you want to use, such as the name of your host. For example: host-1

In the above k8s volume spec case you might try to specify IQN like:

iqn: "iqn.2004-08.jp.buffalo:7403bd2a30a0.drupal-mysql"

Find some relative example about iSCSI volume provisioning in k8s cluster here.

Title: Connect k8s pod to iscsi

Body:
I'm using a terastation's iscsi capabilities to create storage for my k8s 1.14 cluster (kubeadm, ubuntu 18.04).  I check the iqn:

iscsiadm --mode node
192.168.2.113:3260,1 iqn.2004-08.jp.buffalo.7403bd2a30a0.drupal-mysql

There's no ":".  when I try to use

volumes:
    - name: iscsi-data
      iscsi:
        targetPortal: 192.168.2.113:3260
        iqn: "iqn.2004-08.jp.buffalo.7403bd2a30a0.drupal-mysql"
        lun: 0
        fsType: xfs

i get the error:

spec.template.spec.volumes[0].iscsi.iqn: Invalid value: "iqn.2004-08.jp.buffalo.7403bd2a30a0.drupal-mysql": must be valid format

i know its looking for something that ends in a ":name" but I can't figure out what thats supposed to be for the life of me.  I know the iscsi drive mounts because i can see it on my node and was able to format it using xfs.  I think I'm missing something really simple.

Thanks


问:
Detect points anywhere in ARcore
I am using unity, i simply want AR core to draw and measure a distance between 2 points but and its working fine but the points are always on the detected plane ...my need is to detect points anywhere not depending on the detected plane just like this app.
http://armeasure.com
i found something related to feature point but i don't know much as i am new to ARcore.

i tried commenting the trackablehitflag.planewithpolygon in the HElloAR script in example project

```<code>  TrackableHit hit;
            TrackableHitFlags raycastFilter =TrackableHitFlags.FeaturePointWithSurfaceNormal;
           // TrackableHitFlags.PlaneWithinPolygon
            if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit))
            {
                // Use hit pose and camera pose to check if hittest is from the
                // back of the plane, if it is, no need to create the anchor.
             /*   if ((hit.Trackable is DetectedPlane) &&
                    Vector3.Dot(FirstPersonCamera.transform.position - hit.Pose.position,
                        hit.Pose.rotation * Vector3.up) < 0)
                {
                    Debug.Log("Hit at back of the current DetectedPlane");
                }*/
             //   else
             //   {
                    // Choose the Andy model for the Trackable that got hit.
                    GameObject prefab;
                //    if (hit.Trackable is FeaturePoint)
                    //{
                        prefab = AndyPointPrefab;
                   // }
                    //else
                    //{
                  //      prefab = AndyPlanePrefab;
                    //}

                    // Instantiate Andy model at the hit pose.
                    var andyObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);
    }
</code>```

after disabling the points were not even instantiating on the featurepoint hit flag

答:
For placing the points, there are several ways to add points not on a place, For example you can place an anchor anywhere in your view relative to the camera, independently of a plane.

The problem is the depth of the point. In the picture below all lines are exactly the same length from a 2D point of view, but clearly the user is probably trying to measure items at different depths.

When you place an anchor relative to the camera you have to explicitly specify the depth. For example, you place it at the centre of the camera preview at a depth of 2 meters.

If you are able to ensure that each anchor the user adds is at a known depth, or with a depth value specified, then you should be able to add the anchors with a 3d world coordinate and do your measurement. Unfortunately, for real work applications this is not usually possible as there user will not know the depth and current devices do not have depth sensors.

There are frameworks that are looking at adding depth sensing to devices that have just a camera - e.g. smartphones with no dedicated depth sensing hardware. One (commercial) example is 6D: https://www.6d.ai

Title: Detect points anywhere in ARcore

Body:
I am using unity, i simply want AR core to draw and measure a distance between 2 points but and its working fine but the points are always on the detected plane ...my need is to detect points anywhere not depending on the detected plane just like this app.
http://armeasure.com
i found something related to feature point but i don't know much as i am new to ARcore.

i tried commenting the trackablehitflag.planewithpolygon in the HElloAR script in example project

  TrackableHit hit;
            TrackableHitFlags raycastFilter =TrackableHitFlags.FeaturePointWithSurfaceNormal;
           // TrackableHitFlags.PlaneWithinPolygon
            if (Frame.Raycast(touch.position.x, touch.position.y, raycastFilter, out hit))
            {
                // Use hit pose and camera pose to check if hittest is from the
                // back of the plane, if it is, no need to create the anchor.
             /*   if ((hit.Trackable is DetectedPlane) &&
                    Vector3.Dot(FirstPersonCamera.transform.position - hit.Pose.position,
                        hit.Pose.rotation * Vector3.up) < 0)
                {
                    Debug.Log("Hit at back of the current DetectedPlane");
                }*/
             //   else
             //   {
                    // Choose the Andy model for the Trackable that got hit.
                    GameObject prefab;
                //    if (hit.Trackable is FeaturePoint)
                    //{
                        prefab = AndyPointPrefab;
                   // }
                    //else
                    //{
                  //      prefab = AndyPlanePrefab;
                    //}

                    // Instantiate Andy model at the hit pose.
                    var andyObject = Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);
    }

after disabling the points were not even instantiating on the featurepoint hit flag


问:
Video is much faster than audio when muxed in GStreamer
I am trying to learn to record X11 windows' contents to do game screencasts for Youtube. This should be a fairly trivial task, but it already ate a full evening. Now I have learned a bit about muxing and queueing (using gst-launch), but the problem remains: When I mux an audio and video into an avi, video plays several times faster than audio in the resultant file. This means that video ends soon and comes to still, while audio continues to babble in the background.

This is my filter chain that causes the issue:

```<code>gst-launch-1.0 ximagesrc xid=$XID ! video/x-raw,framerate=30/1 ! videoconvert !
    x264enc ! queue ! avimux name=mux ! queue ! filesink location=out.avi
    pulsesrc device=$DEV ! queue ! audioconvert !
    lamemp3enc bitrate=192 ! queue ! mux.
</code>```

However, the issue vanishes when I just have video, and it is played with perfectly normal speed:

```<code>ximagesrc xid=0x0820000b ! video/x-raw,framerate=30/1 ! videoconvert !
    x264enc ! avimux ! filesink location=out.avi
</code>```

I would also appreciate if you correct me on the usage of ! queue !. Where is it needed? In the current setup I almost never get warnings that samples were dropped.

Update: I would prefer to use mp4 muxer, but it produces unplayable files lacking moov atom. Youtube recommends putting it at the beginning of file, any chance I can force that with mp4 muxer?

答:
gst-launch-1.0 ximagesrc xid=$XID ! video/x-raw,framerate=30/1 ! queue !
  videoconvert ! videorate ! queue ! x264enc ! queue ! avimux name=mux !
  queue ! filesink location=out.avi     pulsesrc device=$DEV ! queue !
  audioconvert ! queue ! lamemp3enc bitrate=192 ! queue ! mux.

The above pipeline should play the audio video at proper speed.

I would also appreciate if you correct me on the usage of ! queue !.
  Where is it needed? In the current setup I almost never get warnings
  that samples were dropped.

queue are just buffers, these need to be used in places where one element is slower and one is faster, so for example video generating (ximagesrc) is much faster compared with  x264enc (software encoding), so you would add a queue in between them so as to buffers aren’t dropped.

gst-launch-1.0 ximagesrc  ! video/x-raw,framerate=30/1 ! queue !
  videoconvert !  queue ! x264enc key-int-max=5 ! queue ! mp4mux
  name=mux reserved-bytes-per-sec=100
  reserved-max-duration=20184000000000
  reserved-moov-update-period=100000000 ! queue ! filesink
  location=out.mp4 audiotestsrc ! queue ! audioconvert ! queue !
  lamemp3enc bitrate=192 ! queue ! mux.

The above pipeline would create a mp4 file mp4mux, but the moov atom will be at end itself also note make sure you change mp4mux properties as per your need.

Body:
I am trying to learn to record X11 windows' contents to do game screencasts for Youtube. This should be a fairly trivial task, but it already ate a full evening. Now I have learned a bit about muxing and queueing (using gst-launch), but the problem remains: When I mux an audio and video into an avi, video plays several times faster than audio in the resultant file. This means that video ends soon and comes to still, while audio continues to babble in the background.

This is my filter chain that causes the issue:

gst-launch-1.0 ximagesrc xid=$XID ! video/x-raw,framerate=30/1 ! videoconvert !
    x264enc ! queue ! avimux name=mux ! queue ! filesink location=out.avi
    pulsesrc device=$DEV ! queue ! audioconvert !
    lamemp3enc bitrate=192 ! queue ! mux.

However, the issue vanishes when I just have video, and it is played with perfectly normal speed:

ximagesrc xid=0x0820000b ! video/x-raw,framerate=30/1 ! videoconvert !
    x264enc ! avimux ! filesink location=out.avi

I would also appreciate if you correct me on the usage of ! queue !. Where is it needed? In the current setup I almost never get warnings that samples were dropped.

Update: I would prefer to use mp4 muxer, but it produces unplayable files lacking moov atom. Youtube recommends putting it at the beginning of file, any chance I can force that with mp4 muxer?