问:
CheckBox Show/Hide TextBox WPF
As the title says, Iam trying to show/hide a TextBox in WPF without writing code in MainWindow.xaml.cs file.

Model:

```<code>public class Person
{
    public string Comment { get; set; }
}
</code>```

View:

```<code><Window x:Class="PiedPiper.View.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="Window"
    Title="WPF" Height="400" Width="400">

    <CheckBox Content="Show comment" Name="CommentCheckBox"/>
    <TextBox Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}" Visibility="Hidden" Name="CommentTextBox"></TextBox>
</Grid>
</code>```

ViewModel:

```<code>    public class PersonViewModel : INotifyPropertyChanged
    {
    public PersonViewModel(Person person)
    {
        Comment = person.Comment;
    }

    private string _comment;
    public string Comment
    {
        get { return _comment; }
        set { _comment = value; OnPropertyChanged("Comment"); }
    }

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
</code>```

So the TextBox should be hidden at start, but visible when checkbox is checked. Please help!

Thanks.

答:
The simplest way is to write a custom "BooleanToHiddenVisibilityConverter" and use it (like dkozl said).
It's a really simple converter and it comes in handy in many situations. I think that every descent WPF application should have one.

```<code>public sealed class BooleanToHiddenVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool bValue = false;
        if (value is bool)
        {
            bValue = (bool)value;
        }
        return (bValue) ? Visibility.Visible : Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is Visibility)
        {
            return (Visibility)value == Visibility.Visible;
        }
        return false;
    }
}
</code>```

And use it like dkozl said:

```<code><StackPanel>
    <StackPanel.Resources>
        <BooleanToHiddenVisibilityConverter x:Key="BooleanToHiddenVisibilityConverter"/>
    </StackPanel.Resources>
    <CheckBox Content="Show comment" Name="CommentCheckBox"/>
    <TextBox
        Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}"
        Visibility="{Binding ElementName=CommentCheckBox, Path=IsChecked,
        Converter={StaticResource BooleanToHiddenVisibilityConverter}}"
        Name="CommentTextBox"/>
</StackPanel>
</code>```

Title: CheckBox Show/Hide TextBox WPF

Body:
As the title says, Iam trying to show/hide a TextBox in WPF without writing code in MainWindow.xaml.cs file.

Model:

public class Person
{
    public string Comment { get; set; }
}

View:

<Window x:Class="PiedPiper.View.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="Window"
    Title="WPF" Height="400" Width="400">

    <CheckBox Content="Show comment" Name="CommentCheckBox"/>
    <TextBox Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}" Visibility="Hidden" Name="CommentTextBox"></TextBox>
</Grid>

ViewModel:

    public class PersonViewModel : INotifyPropertyChanged
    {
    public PersonViewModel(Person person)
    {
        Comment = person.Comment;
    }

    private string _comment;
    public string Comment
    {
        get { return _comment; }
        set { _comment = value; OnPropertyChanged("Comment"); }
    }

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

So the TextBox should be hidden at start, but visible when checkbox is checked. Please help!

Thanks.

Body:
The simplest way is to write a custom "BooleanToHiddenVisibilityConverter" and use it (like dkozl said).
It's a really simple converter and it comes in handy in many situations. I think that every descent WPF application should have one.

public sealed class BooleanToHiddenVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool bValue = false;
        if (value is bool)
        {
            bValue = (bool)value;
        }
        return (bValue) ? Visibility.Visible : Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is Visibility)
        {
            return (Visibility)value == Visibility.Visible;
        }
        return false;
    }
}

And use it like dkozl said:

<StackPanel>
    <StackPanel.Resources>
        <BooleanToHiddenVisibilityConverter x:Key="BooleanToHiddenVisibilityConverter"/>
    </StackPanel.Resources>
    <CheckBox Content="Show comment" Name="CommentCheckBox"/>
    <TextBox
        Text="{Binding Comment, UpdateSourceTrigger=PropertyChanged}"
        Visibility="{Binding ElementName=CommentCheckBox, Path=IsChecked,
        Converter={StaticResource BooleanToHiddenVisibilityConverter}}"
        Name="CommentTextBox"/>
</StackPanel>


来源: stackexchange

问:
How can I access local variables from inside a C++11 anonymous function?
I'm doing a simple normalization on a vector (weights), trying to make use of STL algorithms to make the code as clean as possible (I realize this is pretty trivial with for loops):

```<code>float tot = std::accumulate(weights.begin(), weights.end(), 0.0);
std::transform(weights.begin(), weights.end(), [](float x)->float{return(x/tot);});
</code>```

At present, tot is not visible to the anonymous function, so this doesn't compile. What's the best way of making a local variable visible to the anonymous function?

答:
You need a closure.

```<code>float tot = std::accumulate(weights.begin(), weights.end(), 0);
std::transform(weights.begin(), weights.end(), [tot](float x)->float{return(x/tot);});
</code>```

In this case tot is captured by value. C++11 lambdas support capturing by:

value [x]

reference [&x]

any variable currently in scope by reference [&]

same as 3, but by value [=]

You can mix any of the above in a comma separated list [x, &y].

ContentLicense: CC BY-SA 3.0

Body:
I'm doing a simple normalization on a vector (weights), trying to make use of STL algorithms to make the code as clean as possible (I realize this is pretty trivial with for loops):

float tot = std::accumulate(weights.begin(), weights.end(), 0.0);
std::transform(weights.begin(), weights.end(), [](float x)->float{return(x/tot);});

At present, tot is not visible to the anonymous function, so this doesn't compile. What's the best way of making a local variable visible to the anonymous function?

Body:
You need a closure.

float tot = std::accumulate(weights.begin(), weights.end(), 0);
std::transform(weights.begin(), weights.end(), [tot](float x)->float{return(x/tot);});

In this case tot is captured by value. C++11 lambdas support capturing by:

value [x]

reference [&x]

any variable currently in scope by reference [&]

same as 3, but by value [=]

You can mix any of the above in a comma separated list [x, &y].


问:
How to make an text generator
I been stuck in this line of code trying to make a text generator that generates a random text with a vocabulary, like I'm trying to make a code that generates text with the letters ABCDE on uppercase and on lowercase and the numbers 12345, this is my code I been stuck on:

```<code>import string
import random # define the random module
S = 681  # number of characters in the string
#call random.choices() string module to find the string in Uppercase + numeric data.
ran = ''.join(random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase, k = S))
print("Generated text is : " + str(ran)) # print the random data
</code>```

If you could help I will be extremely thankful (I'm spanish so if I speak bad english thats why)

答:
I'm guessing you expect to only generate a string with characters that are [A, B, C, D, E, a, b, c, d, e, 1, 2, 3, 4, 5].

You can easily use a constrained set of characters to use:

ran = ''.join(random.choices("ABCDEabcde12345", k = S))
```
<p>Output for a k=30:</p>
```>>> ''.join(random.choices("ABCDEabcde12345", k=30))
'aCdEaaeC5C52eBaD1d1AC543Ace55c'
```

ContentLicense: CC BY-SA 4.0

Title: How to make an text generator

Body:
I been stuck in this line of code trying to make a text generator that generates a random text with a vocabulary, like I'm trying to make a code that generates text with the letters ABCDE on uppercase and on lowercase and the numbers 12345, this is my code I been stuck on:

import string
import random # define the random module
S = 681  # number of characters in the string
#call random.choices() string module to find the string in Uppercase + numeric data.
ran = ''.join(random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase, k = S))
print("Generated text is : " + str(ran)) # print the random data

If you could help I will be extremely thankful (I'm spanish so if I speak bad english thats why)

Body:
I'm guessing you expect to only generate a string with characters that are [A, B, C, D, E, a, b, c, d, e, 1, 2, 3, 4, 5].

You can easily use a constrained set of characters to use:

ran = ''.join(random.choices("ABCDEabcde12345", k = S))

Output for a k=30:

>>> ''.join(random.choices("ABCDEabcde12345", k=30))
'aCdEaaeC5C52eBaD1d1AC543Ace55c'


问:
Drop rows of df with fewer entries
I'm working currently with pandas in python.

I've got a dataset of customers (user_id on column1) and of the item they bought (column2).

Example dataset:

ID_user
ID_item

0
1

0
2

0
3

1
2

2
1

3
3

...
...

Now I want only to focus on customers, which have bought more than 10 items. How can I create a new dataframe with pandas and drop all other customers with less than 10 items bought?

Thank you very much!

答:
You could first group your dataframe by the column "ID_user" and the .count() method. Afterwards filter out only those values that are bigger 10 with a lambda function.

```<code># Group by column ID_user and the method .count()
df = df.groupby('ID_user').count()
# Only show values for which the lambda function evaluates to True
df = df[lambda row: row["ID_item"] > 10]
</code>```

Or just do it in one line:

```<code>df = df.groupby('ID_user').count()[lambda row: row["ID_item"] > 10]
</code>```

Title: Drop rows of df with fewer entries

Body:
You could first group your dataframe by the column "ID_user" and the .count() method. Afterwards filter out only those values that are bigger 10 with a lambda function.

# Group by column ID_user and the method .count()
df = df.groupby('ID_user').count()
# Only show values for which the lambda function evaluates to True
df = df[lambda row: row["ID_item"] > 10]

Or just do it in one line:

df = df.groupby('ID_user').count()[lambda row: row["ID_item"] > 10]


问:
Await is a reserved word error inside async function
I am struggling to figure out the issue with the following syntax:

```<code>export const sendVerificationEmail = async () =>
  (dispatch) => {
    try {
      dispatch({ type: EMAIL_FETCHING, payload: true });
      await Auth.sendEmailVerification();
      dispatch({ type: EMAIL_FETCHING, payload: false }))
    } catch (error) {
      dispatch({ type: EMAIL_FETCHING, payload: false });
      throw new Error(error);
    }
  };
</code>```

I keep getting error saying:

await is a reserved word

...but isn't it legal within an async function?

The dispatch bit is coming from the react-thunk library.

答:
Solution

Use the await directly inside the scope you are using async and remove the top scope async as it's redundant.

The correct way to write this:

```<code>const sendVerificationEmail = () =>
  async (dispatch) => {
    await Auth.sendEmailVerification();
    // some code..
  };
</code>```

Elaboration

You had the error because you used the await keyword without the async directly in the scope with the await, you had 2 functions there, one inside the other, you had async on the top one but not on the inner one, where it matters.

Wrong way:

```<code>const sendVerificationEmail = async () =>
  // notice that an async before the (dispatch) is missing
  (dispatch) => {
    await Auth.sendEmailVerification();
    // some code..
  };
</code>```

From this, an error will be generated (the latest error available from Chrome):

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

Reference

Async Functions

An async function is a function declared with the async keyword, and
the await keyword is permitted within it. The async and await keywords
enable asynchronous, promise-based behavior to be written in a cleaner
style, avoiding the need to explicitly configure promise chains.

Body:
I am struggling to figure out the issue with the following syntax:

export const sendVerificationEmail = async () =>
  (dispatch) => {
    try {
      dispatch({ type: EMAIL_FETCHING, payload: true });
      await Auth.sendEmailVerification();
      dispatch({ type: EMAIL_FETCHING, payload: false }))
    } catch (error) {
      dispatch({ type: EMAIL_FETCHING, payload: false });
      throw new Error(error);
    }
  };

I keep getting error saying:

await is a reserved word

...but isn't it legal within an async function?

The dispatch bit is coming from the react-thunk library.

Body:
Solution

Use the await directly inside the scope you are using async and remove the top scope async as it's redundant.

The correct way to write this:

const sendVerificationEmail = () =>
  async (dispatch) => {
    await Auth.sendEmailVerification();
    // some code..
  };

Elaboration

You had the error because you used the await keyword without the async directly in the scope with the await, you had 2 functions there, one inside the other, you had async on the top one but not on the inner one, where it matters.

Wrong way:

const sendVerificationEmail = async () =>
  // notice that an async before the (dispatch) is missing
  (dispatch) => {
    await Auth.sendEmailVerification();
    // some code..
  };

From this, an error will be generated (the latest error available from Chrome):

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

Reference

Async Functions

An async function is a function declared with the async keyword, and
the await keyword is permitted within it. The async and await keywords
enable asynchronous, promise-based behavior to be written in a cleaner
style, avoiding the need to explicitly configure promise chains.


问:
Alternative to binaries in Subversion
Some of my colleagues are convinced that committing build artefacts to the subversion repository is a good idea. The argument is that this way, installation and update on the test machines is easy - just "svn up"!

I'm sure there are weighty arguments against this bad practice, but all I can think of are lame ones like "it takes up more room". What are the best, killer reasons to not do this? And what other approaches should we do instead?

This is for Java code if that makes a difference. Everything is compiled from Eclipse (with no automated PDE builds).

When I say add the build artifacts, I mean a commit would look like this:

```<code>"Added the new Whizbang feature"

 M src/foo/bar/Foo.java
 M bin/Foo.jar
</code>```

Each code change has the corresponding generated jar file.

答:
"committing build artifacts to the subversion repository" can be a good idea if you know why.

It is a good idea for a release management purpose, more specifically for:

1/ Packaging issue

If a build artifact is not just an exe (or a dll or...), but also:

some configuration files

some scripts to start/stop/restart your artifact

some sql to update your database

some sources (compressed into a file) to facilitate debugging

some documentation (javadoc compressed in a file)

then it is a good idea to have a build artifact and all those associated files stored in a VCS.

(Because it is not anymore just a matter of "re-building" the artifact, but also of "retrieving" all those extra files that will make that artifact run)

2/ Deployment issue

Suppose you need to deploy many artifacts in different environment (test, homologation, pre-production, production).

If:

you produce many build artifacts

those artifacts are quite long to recreate from scratch

then having those artifacts in a VCS is a good idea, in order to avoid recreating them.

You can just query them from environment to environment.

But you need to remember:

1/ you cannot store every artifacts you make in the VCS: all the intermediate build you make for continuous integration purpose must not be stored in the VCS (or you end up with a huge repository with many useless versions of the binaries).

Only the versions needed for homologation and production purposes need to be referenced.

For intermediate build, you need an external repository (maven or a shared directory) in order to publish/test quickly those builds.

2/ you should not store them in the same Subversion Repository, since your development is committed (revision number) much more often than your significant builds (the ones deemed worthy of homologation and production deployment)

That means the artifacts stored in that second repository must have a naming convention for the tag (or for a property) in order to easily retrieve the revision number of the development from which they have been built.

OwnerDisplayName: rq

ContentLicense: CC BY-SA 2.5

Title: Alternative to binaries in Subversion

Body:
Some of my colleagues are convinced that committing build artefacts to the subversion repository is a good idea. The argument is that this way, installation and update on the test machines is easy - just "svn up"!

I'm sure there are weighty arguments against this bad practice, but all I can think of are lame ones like "it takes up more room". What are the best, killer reasons to not do this? And what other approaches should we do instead?

This is for Java code if that makes a difference. Everything is compiled from Eclipse (with no automated PDE builds).

When I say add the build artifacts, I mean a commit would look like this:

"Added the new Whizbang feature"

 M src/foo/bar/Foo.java
 M bin/Foo.jar

Each code change has the corresponding generated jar file.

LastEditorDisplayName: rq

OwnerDisplayName: VonC


问:
Check if elements from array are in a string
I want to check if there is one of my elements in my array in an string
Like: ['12', '13', '14'] is my array and my string is '123456789' and if one of my Array elements is in my string then it should be True

Is there a way to do this?

答:
```<code>array = ['12', '13', '14']
string = '12345678'
for item in array:
    print(item in string)
</code>```

You can use the "in" operator

Body:
array = ['12', '13', '14']
string = '12345678'
for item in array:
    print(item in string)

You can use the "in" operator


问:
Flutter HTML response instead of json
I am having error, kindly help me with this code, new to Flutter here.
When I'm using https://jsonplaceholder.typicode.com/posts it is working fine, but I am receiving error using my company URL, but when I am using postman to POST the company URL it is working fine, kindly refer to my code and the image below.

Code:

```<code>   Dio dio = Dio();

  Future postData() async{
    const String pathUrl = 'https://202.57.135.121:8443/icbs/ATMInterfaceListener/mobileAppRegistration';
    //const String pathUrl = 'https://jsonplaceholder.typicode.com/posts';

dynamic data = {
  'email': 'darwikf@gkdkkk.com',
  'password': 'test123456',
  'firstName': 'Darwin',
  'middleName': 'D',
  'lastName': 'L',
  'birthDate': 095545,
  'mobile': 1256789,
  'telephone': 12367891,
  'presentAddress': 'mla',
  'permanentAddress': 'mla',
  'country': 'phl',

  // 'title': 'Darwin',
  // 'body': 'Success',
  // 'userId': '1',
};

try{
  var response = await dio.post(pathUrl, data: data, options: Options(
    followRedirects: false,
    validateStatus: (status) => true,
    headers: {
      'Content-type' : 'application/json; charset=UTF-8',
    }
  ));
  return response.data;
}catch(e){
  print(e);
}
</code>```

}`

Image Postman

Image Error

答: I suspect you're running into CORS issues, perhaps because you're trying to connect to a host that isn't the host where the flutter code was being loaded from.  CORS protects you, but it sometimes is hard to avoid. There are solutions... google "flutter cors" and see which ones can  work best for your situation.</p>

Title: Flutter HTML response instead of json

Body:
I am having error, kindly help me with this code, new to Flutter here.
When I'm using https://jsonplaceholder.typicode.com/posts it is working fine, but I am receiving error using my company URL, but when I am using postman to POST the company URL it is working fine, kindly refer to my code and the image below.

Code:

   Dio dio = Dio();

  Future postData() async{
    const String pathUrl = 'https://202.57.135.121:8443/icbs/ATMInterfaceListener/mobileAppRegistration';
    //const String pathUrl = 'https://jsonplaceholder.typicode.com/posts';

dynamic data = {
  'email': 'darwikf@gkdkkk.com',
  'password': 'test123456',
  'firstName': 'Darwin',
  'middleName': 'D',
  'lastName': 'L',
  'birthDate': 095545,
  'mobile': 1256789,
  'telephone': 12367891,
  'presentAddress': 'mla',
  'permanentAddress': 'mla',
  'country': 'phl',

  // 'title': 'Darwin',
  // 'body': 'Success',
  // 'userId': '1',
};

try{
  var response = await dio.post(pathUrl, data: data, options: Options(
    followRedirects: false,
    validateStatus: (status) => true,
    headers: {
      'Content-type' : 'application/json; charset=UTF-8',
    }
  ));
  return response.data;
}catch(e){
  print(e);
}

}`

Image Postman

Image Error


问:
Airflow initdb fails due to invalid syntax
I am new to Airflow. I followed instructions presented here: https://www.youtube.com/watch?v=SYOUbiGtGiU&t=49s

Step 1: Control Panel | Programs and Features | Turn Windows features on or off

Enable : Windows Subsystem for Linux

Step 2: Install Ubuntu from windows store and restart system

Step 3: Install and update PIP

```<code>sudo apt-get install software-properties-common

sudo apt-add-repository universe

sudo apt-get update

sudo apt-get install python-pip
</code>```

Step 4: Install airflow

```<code>export SLUGIFY_USES_TEXT_UNIDECODE=yes

pip install apache-airflow
</code>```

Step 5: Initialize DB

```<code>airflow initdb
</code>```

After that I got an error:

```<code>[2019-09-30 17:46:37,888] {__init__.py:51} INFO - Using executor SequentialExecutor
Traceback (most recent call last):
  File "/usr/local/bin/airflow", line 22, in <module>
    from airflow.bin.cli import CLIFactory
  File "/usr/local/lib/python2.7/dist-packages/airflow/bin/cli.py", line 68, in <module>
    from airflow.www_rbac.app import cached_app as cached_app_rbac
  File "/usr/local/lib/python2.7/dist-packages/airflow/www_rbac/app.py", line 26, in <module>
    from flask_appbuilder import AppBuilder, SQLA
  File "/home/barys_rutman/.local/lib/python2.7/site-packages/flask_appbuilder/__init__.py", line 5, in <module>
    from .base import AppBuilder
  File "/home/barys_rutman/.local/lib/python2.7/site-packages/flask_appbuilder/base.py", line 5, in <module>
    from .api.manager import OpenApiManager
  File "/home/barys_rutman/.local/lib/python2.7/site-packages/flask_appbuilder/api/__init__.py", line 11, in <module>
    from marshmallow_sqlalchemy.fields import Related, RelatedList
  File "/home/barys_rutman/.local/lib/python2.7/site-packages/marshmallow_sqlalchemy/__init__.py", line 1, in <module>
    from .schema import TableSchemaOpts, ModelSchemaOpts, TableSchema, ModelSchema
  File "/home/barys_rutman/.local/lib/python2.7/site-packages/marshmallow_sqlalchemy/schema.py", line 101
    class TableSchema(ma.Schema, metaclass=TableSchemaMeta):
                                          ^
SyntaxError: invalid syntax
</code>```

Any ideas how to fix it?

答:
Try to run

```<code>airflow db init
</code>```

Instead of

```<code>airflow initdb
</code>```

Body:
I am new to Airflow. I followed instructions presented here: https://www.youtube.com/watch?v=SYOUbiGtGiU&t=49s

Step 1: Control Panel | Programs and Features | Turn Windows features on or off

Enable : Windows Subsystem for Linux

Step 2: Install Ubuntu from windows store and restart system

Step 3: Install and update PIP

sudo apt-get install software-properties-common

sudo apt-add-repository universe

sudo apt-get update

sudo apt-get install python-pip

Step 4: Install airflow

export SLUGIFY_USES_TEXT_UNIDECODE=yes

pip install apache-airflow

Step 5: Initialize DB

airflow initdb

After that I got an error:

[2019-09-30 17:46:37,888] {__init__.py:51} INFO - Using executor SequentialExecutor
Traceback (most recent call last):
  File "/usr/local/bin/airflow", line 22, in <module>
    from airflow.bin.cli import CLIFactory
  File "/usr/local/lib/python2.7/dist-packages/airflow/bin/cli.py", line 68, in <module>
    from airflow.www_rbac.app import cached_app as cached_app_rbac
  File "/usr/local/lib/python2.7/dist-packages/airflow/www_rbac/app.py", line 26, in <module>
    from flask_appbuilder import AppBuilder, SQLA
  File "/home/barys_rutman/.local/lib/python2.7/site-packages/flask_appbuilder/__init__.py", line 5, in <module>
    from .base import AppBuilder
  File "/home/barys_rutman/.local/lib/python2.7/site-packages/flask_appbuilder/base.py", line 5, in <module>
    from .api.manager import OpenApiManager
  File "/home/barys_rutman/.local/lib/python2.7/site-packages/flask_appbuilder/api/__init__.py", line 11, in <module>
    from marshmallow_sqlalchemy.fields import Related, RelatedList
  File "/home/barys_rutman/.local/lib/python2.7/site-packages/marshmallow_sqlalchemy/__init__.py", line 1, in <module>
    from .schema import TableSchemaOpts, ModelSchemaOpts, TableSchema, ModelSchema
  File "/home/barys_rutman/.local/lib/python2.7/site-packages/marshmallow_sqlalchemy/schema.py", line 101
    class TableSchema(ma.Schema, metaclass=TableSchemaMeta):
                                          ^
SyntaxError: invalid syntax

Any ideas how to fix it?

Body:
Try to run

airflow db init

Instead of

airflow initdb


问:
docker-compose: how to use minio in- and outside of the docker network
I have the following docker-compose.yml to run a local environment for my Laravel App.

```<code>version: '3'
services:
  app:
    build:
      context: .
      dockerfile: .docker/php/Dockerfile
    ports:
      - 80:80
      - 443:443
    volumes:
      - .:/var/www:delegated
    environment:
      AWS_ACCESS_KEY_ID: minio_access_key
      AWS_SECRET_ACCESS_KEY: minio_secret_key
      AWS_BUCKET: Bucket
      AWS_ENDPOINT: http://s3:9000
    links:
      - database
      - s3
  database:
    image: mariadb:10.3
    ports:
      - 63306:3306
    environment:
      MYSQL_ROOT_PASSWORD: secret
  s3:
    image: minio/minio
    ports:
      - "9000:9000"
    volumes:
      - ./storage/minio:/data
    environment:
      MINIO_ACCESS_KEY: minio_access_key
      MINIO_SECRET_KEY: minio_secret_key
    command: server /data
</code>```

As you can see, I use minio as AWS S3 compatible storage. This works very well but when I generate a url for a file (Storage::disk('s3')->url('some-file.txt')) obviously I get a url like this http://s3:9000/Bucket/some-file.txt which does not work outside of the Docker network.

I've already tried to set AWS_ENDPOINT to http://127.0.0.1:9000 but then Laravel can't connect to the Minio Server...

Is there a way to configure Docker / Laravel / Minio to generate urls which are accessible in- and outside of the Docker network?

答:
Adding the "s3" alias to my local hosts file did not do the trick. But explicitly binding the ports to 127.0.0.1 worked like a charm:</p>
```<code>s3:
    image: minio/minio:RELEASE.2022-02-05T04-40-59Z
    restart: "unless-stopped"
    volumes:
        - s3data:/data
    environment:
        MINIO_ROOT_USER: minio
        MINIO_ROOT_PASSWORD: minio123
    # Allow all incoming hosts to access the server by using 0.0.0.0
    command: server --address 0.0.0.0:9000 --console-address ":9001" /data
    ports:
        # Bind explicitly to 127.0.0.1
        - "127.0.0.1:9000:9000"
        - "9001:9001"
    healthcheck:
        test: ["CMD", "curl", "-f", "http://127.0.0.1:9000/minio/health/live"]
        interval: 30s
        timeout: 20s
        retries: 3
</code>```

Body:
I have the following docker-compose.yml to run a local environment for my Laravel App.

version: '3'
services:
  app:
    build:
      context: .
      dockerfile: .docker/php/Dockerfile
    ports:
      - 80:80
      - 443:443
    volumes:
      - .:/var/www:delegated
    environment:
      AWS_ACCESS_KEY_ID: minio_access_key
      AWS_SECRET_ACCESS_KEY: minio_secret_key
      AWS_BUCKET: Bucket
      AWS_ENDPOINT: http://s3:9000
    links:
      - database
      - s3
  database:
    image: mariadb:10.3
    ports:
      - 63306:3306
    environment:
      MYSQL_ROOT_PASSWORD: secret
  s3:
    image: minio/minio
    ports:
      - "9000:9000"
    volumes:
      - ./storage/minio:/data
    environment:
      MINIO_ACCESS_KEY: minio_access_key
      MINIO_SECRET_KEY: minio_secret_key
    command: server /data

As you can see, I use minio as AWS S3 compatible storage. This works very well but when I generate a url for a file (Storage::disk('s3')->url('some-file.txt')) obviously I get a url like this http://s3:9000/Bucket/some-file.txt which does not work outside of the Docker network.

I've already tried to set AWS_ENDPOINT to http://127.0.0.1:9000 but then Laravel can't connect to the Minio Server...

Is there a way to configure Docker / Laravel / Minio to generate urls which are accessible in- and outside of the Docker network?

Body:
Adding the "s3" alias to my local hosts file did not do the trick. But explicitly binding the ports to 127.0.0.1 worked like a charm:

s3:
    image: minio/minio:RELEASE.2022-02-05T04-40-59Z
    restart: "unless-stopped"
    volumes:
        - s3data:/data
    environment:
        MINIO_ROOT_USER: minio
        MINIO_ROOT_PASSWORD: minio123
    # Allow all incoming hosts to access the server by using 0.0.0.0
    command: server --address 0.0.0.0:9000 --console-address ":9001" /data
    ports:
        # Bind explicitly to 127.0.0.1
        - "127.0.0.1:9000:9000"
        - "9001:9001"
    healthcheck:
        test: ["CMD", "curl", "-f", "http://127.0.0.1:9000/minio/health/live"]
        interval: 30s
        timeout: 20s
        retries: 3


问:
MySQL INSERT ....ON DUPLICATE UPDATE - Adds one to the autoincrement
I keep track of all the http_user_agents that visit me, with a simple hit counter.
The below insert the http_user_agent in the DB, this field is Case Insensitive and is Unique. So when we try to insert it and it finds a DUPLICATE KEY, it adds 1 to the hits field.

The problem is my Auto Increment field still increases even though we did not insert a field. how can i prevent this?

```<code>$sql = "INSERT INTO `db_agency_cloud`.`tblRefHttpUsersAgent` SET `http_users_agent` = :UsersAgent, `created_ts` = NOW() ON DUPLICATE KEY UPDATE `hits` = `hits` + 1";
</code>```

Here is the Table stucture:

```<code>CREATE TABLE `tblRefHttpUsersAgent`
(
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`http_users_agent` varchar(255) NOT NULL,
`hits` int(20) unsigned NOT NULL DEFAULT '1',
`created_ts` datetime NOT NULL,
`activity_ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `http_users_agent` (`http_users_agent`)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
</code>```

答:
INSERT ... ON DUPLICATE KEY UPDATE is described as a "mixed-mode insert" for the purposes of InnoDB's AUTO_INCREMENT handling. Mixed-mode inserts are basically ones where the maximum number of required AUTO_INCREMENT values is known, but the amount that will actually be needed is not.

Mixed-mode inserts get handled specially by default, as described in the MySQL docs:

...for “mixed-mode inserts”... InnoDB will
  allocate more auto-increment values than the number of rows to be
  inserted. However, all values automatically assigned are consecutively
  generated (and thus higher than) the auto-increment value generated by
  the most recently executed previous statement. “Excess” numbers are
  lost.

If you're using InnoDB, your alternatives are:

Avoid INSERT ... ON DUPLICATE KEY UPDATE.

Set the innodb_autoinc_lock_mode parameter to 0, for "traditional" autoincrement lock mode, which guarantees that all INSERT statements will assign consecutive values for AUTO_INCREMENT columns. However, this is accomplished by locking during the statement, so there's a performance loss associated with this setting.

(Recommended) Ignore the gaps in the AUTO_INCREMENT column.

Note: AUTO_INCREMENT handling is totally different under MyISAM, which does not exhibit this behavior.

Body:
I keep track of all the http_user_agents that visit me, with a simple hit counter.
The below insert the http_user_agent in the DB, this field is Case Insensitive and is Unique. So when we try to insert it and it finds a DUPLICATE KEY, it adds 1 to the hits field.

The problem is my Auto Increment field still increases even though we did not insert a field. how can i prevent this?

$sql = "INSERT INTO `db_agency_cloud`.`tblRefHttpUsersAgent` SET `http_users_agent` = :UsersAgent, `created_ts` = NOW() ON DUPLICATE KEY UPDATE `hits` = `hits` + 1";

Here is the Table stucture:

CREATE TABLE `tblRefHttpUsersAgent`
(
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`http_users_agent` varchar(255) NOT NULL,
`hits` int(20) unsigned NOT NULL DEFAULT '1',
`created_ts` datetime NOT NULL,
`activity_ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `http_users_agent` (`http_users_agent`)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;


问:
Change .html URL depending on the active div
I have two html pages: index1.html and index2.html. In index1.html, I have two buttons: Get Started and Login. In index2.html, I have two divs (Sign-up form and Sign-in form), and either one of them is active (by setting them with active class). The default active is the sign-up form:
...</form>, and the other form, which is for signing-in is not yet set as active:
...

Note that index2.html is a double slider page, where it does not scroll down, as the divs are positioned beside each other.

I want my Get Started button from index1.html to redirect to index2.html, but on the active Sign-up form, and I want my Login button from index1.html to redirect to index2.html, but on the active Sign-in form.

The problem is I can't redirect them on a specific active div. The URL of index2.html only goes with "index2.html?#". How do I change the URL depending on the active div? ex. index2.html#sign-up if the Sign-up form is active and index2.html?#sign-in if the Sign-in form is active.

答:
I have tried to simulate and implement a solution on it, Please check https://stackblitz.com/edit/web-platform-uawtkc?file=login.html, hope it helps.

Basically, you would require a bit of JS to mark active on when which element you want to target to activate when navigating from one file to another.


问:
What is the time complexity of Map.prototype.keys()?
I am trying to calculate the time complexity of this particular line in one of my functions:

return [...cache.keys()].sort((a, b) => a - b);
```

This line is supposed to return a sorted Array of the Map's (cache) keys.
I know that Array.prototype.sort() has O(n log n) time complexity. What is the time complexity of Map.prototype.keys()?

答:
Creating the iterator is O(1), iterating all entries and creating an array from them is linear in the size of the collection - O(n).

Depending on the implementation, the number of recently deleted entries might have an impact, but it never should be large enough to change the time complexity to become non-linear.

Body:
I am trying to calculate the time complexity of this particular line in one of my functions:

return [...cache.keys()].sort((a, b) => a - b);

This line is supposed to return a sorted Array of the Map's (cache) keys.
I know that Array.prototype.sort() has O(n log n) time complexity. What is the time complexity of Map.prototype.keys()?


问:
Replace Pandas DataFrame column values based on containing dictionary keys
Here is an example, where column is assigned when the row is a dictionary key: https://stackoverflow.com/a/20250996/12603542

What I am looking for is case, where column is assigned when the row contains a dictionary key.

For example (based on example above):

```<code>import pandas as pd
df = pd.DataFrame({'col1': {0: 'aba', 1: 'abc', 2: 'abx'}})

#gives me a DataFrame
     col1
0    aba #contains 'ba'
1    abc #will NOT be replaced
2    abx #contains 'bx'

dictionary = {'ba': 5, 'bx': 8}

#and I need to get:

     col1
0    5
1    abc
2    8
</code>```

答:
You could use DataFrame.replace with regex parameter set to True and pass the mapping dictionary.

```<code>df.replace(dictionary, regex=True)

#   col2
# 0    5
# 1  abc
# 2    8
</code>```

This usage of df.replace is less known. You can read more about it here.

Body:
Here is an example, where column is assigned when the row is a dictionary key: https://stackoverflow.com/a/20250996/12603542

What I am looking for is case, where column is assigned when the row contains a dictionary key.

For example (based on example above):

import pandas as pd
df = pd.DataFrame({'col1': {0: 'aba', 1: 'abc', 2: 'abx'}})

#gives me a DataFrame
     col1
0    aba #contains 'ba'
1    abc #will NOT be replaced
2    abx #contains 'bx'

dictionary = {'ba': 5, 'bx': 8}

#and I need to get:

     col1
0    5
1    abc
2    8

Body:
You could use DataFrame.replace with regex parameter set to True and pass the mapping dictionary.

df.replace(dictionary, regex=True)

#   col2
# 0    5
# 1  abc
# 2    8

This usage of df.replace is less known. You can read more about it here.


问:
Deleting (12) from Df
I have a bigger df with several columns having values like: 12(1).

df.dtypes shows these columns are objects. I tried

df['Age'] = df['Age'].str.strip()

with out success. Added a code down low but it does not work when I add ()......
Any idea what I could do to change the values in the columns?

```<code>data = {'Name':['Tom', 'Nick', 'Krish', 'Jack'],
        'Age':['20 (1)', '21 (3)', '19 (2)', '18 (1)']}
df = pd.DataFrame(data)
</code>```

答:
Mmh, I'm not sure if I understand your question, but if you want the number only, you could use several ways like:

```<code>df["Age"] = df["Age"].str.extract(r"(^\d+)")
df["Age"] = df["Age"].str.split(" ").str[0]
</code>```

The first way uses regex to say start of line (^) and one or more (+) digits (\d).
The second uses str.split, which splits the string at the first space. .str[0] gets the first position in the list after the split.

If you want to do it for the whole DataFrame, you can use

```<code>df = df.replace(r" ?\(.*\)$", "", regex=True)
</code>```

which looks for an optional space  ?, brackets \( \) (need to be escaped, as they are capture groups otherwise) and some arbitrary text in brackets .*.

Title: Deleting (12) from Df

Body:
I have a bigger df with several columns having values like: 12(1).

df.dtypes shows these columns are objects. I tried

df['Age'] = df['Age'].str.strip()

with out success. Added a code down low but it does not work when I add ()......
Any idea what I could do to change the values in the columns?

data = {'Name':['Tom', 'Nick', 'Krish', 'Jack'],
        'Age':['20 (1)', '21 (3)', '19 (2)', '18 (1)']}
df = pd.DataFrame(data)

Body:
Mmh, I'm not sure if I understand your question, but if you want the number only, you could use several ways like:

df["Age"] = df["Age"].str.extract(r"(^\d+)")
df["Age"] = df["Age"].str.split(" ").str[0]

The first way uses regex to say start of line (^) and one or more (+) digits (\d).
The second uses str.split, which splits the string at the first space. .str[0] gets the first position in the list after the split.

If you want to do it for the whole DataFrame, you can use

df = df.replace(r" ?\(.*\)$", "", regex=True)

which looks for an optional space  ?, brackets \( \) (need to be escaped, as they are capture groups otherwise) and some arbitrary text in brackets .*.


问:
How to include a shared library in gn
I have a BUILD.gn in which I want to include a shared library which is located in usr/lib.
I have taken reference from this topic How to include a shared library in chromium's gn file?

But the .so file is not getting linked with the main function. Below is the BUILD.gn code:-

```<code>executable("check") {
  sources = [ "check.cpp" ]
  deps = [
    ":SampleCheck",
    ]
  lib_dirs = [ "//usr/lib/SampleFile.so" ]
  libs = [ "SampleFile" ]
}
shared_library("SampleCheck") {
  sources = [
    "SampleCheck.h", // Header file for functions
  ]
}
</code>```

But, when executing this I am getting an error:-

```<code>ninja: Entering directory `out'
[0/1] Regenerating ninja files
[1/1] LINK main
FAILED: main
g++ -Wl,-rpath=\$ORIGIN/ -Wl,-rpath-link= -L../usr/lib/SampleFile.so -o main -Wl,--start-group @main.rsp  -Wl,--end-group -lSampleDll.so
/usr/bin/ld: cannot find -lSampleDll.so
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
</code>```

I have surveyed many websites but I am not getting where am i wrong?

答:
This line looks suspicious:

```<code>  lib_dirs = [ "//usr/lib/sampleFile.so" ]
</code>```

GN uses // to denote the root of the GN project, as marked by the presence of a .gn file. lib_dirs is aware of the absolute filesystem to allow constructions like yours; you can just use a single forward slash to indicate the root filesystem.

Additionally, the intent of lib_dirs is to add directories to the linker's search path: https://gn.googlesource.com/gn/+/master/docs/reference.md#var_lib_dirs

You're giving it a file, not a directory.

Instead, try:

```<code>  lib_dirs = [ "/usr/lib" ]
</code>```

That should change your link line to

```<code>g++ -Wl,-rpath=\$ORIGIN/ -Wl,-rpath-link= -L/usr/lib -o main -Wl,--start-group @main.rsp  -Wl,--end-group -lSampleDll.so
</code>```

Which is maybe closer to what you were expecting; the linker sees the required SampleDll.so and will search /usr/lib for it.

Title: How to include a shared library in gn

Body:
I have a BUILD.gn in which I want to include a shared library which is located in usr/lib.
I have taken reference from this topic How to include a shared library in chromium's gn file?

But the .so file is not getting linked with the main function. Below is the BUILD.gn code:-

executable("check") {
  sources = [ "check.cpp" ]
  deps = [
    ":SampleCheck",
    ]
  lib_dirs = [ "//usr/lib/SampleFile.so" ]
  libs = [ "SampleFile" ]
}
shared_library("SampleCheck") {
  sources = [
    "SampleCheck.h", // Header file for functions
  ]
}

But, when executing this I am getting an error:-

ninja: Entering directory `out'
[0/1] Regenerating ninja files
[1/1] LINK main
FAILED: main
g++ -Wl,-rpath=\$ORIGIN/ -Wl,-rpath-link= -L../usr/lib/SampleFile.so -o main -Wl,--start-group @main.rsp  -Wl,--end-group -lSampleDll.so
/usr/bin/ld: cannot find -lSampleDll.so
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

I have surveyed many websites but I am not getting where am i wrong?

Body:
This line looks suspicious:

  lib_dirs = [ "//usr/lib/sampleFile.so" ]

GN uses // to denote the root of the GN project, as marked by the presence of a .gn file. lib_dirs is aware of the absolute filesystem to allow constructions like yours; you can just use a single forward slash to indicate the root filesystem.

Additionally, the intent of lib_dirs is to add directories to the linker's search path: https://gn.googlesource.com/gn/+/master/docs/reference.md#var_lib_dirs

You're giving it a file, not a directory.

Instead, try:

  lib_dirs = [ "/usr/lib" ]

That should change your link line to

g++ -Wl,-rpath=\$ORIGIN/ -Wl,-rpath-link= -L/usr/lib -o main -Wl,--start-group @main.rsp  -Wl,--end-group -lSampleDll.so

Which is maybe closer to what you were expecting; the linker sees the required SampleDll.so and will search /usr/lib for it.


问:
Why doesn't RewriteRequest work even after refering to the link in sitemap?
I have the following rewrite in Boot.boot(). This is based on the instructions found in the URL Rewriting section in the Lift Wiki.

```<code>LiftRules.statefulRewrite.prepend(NamedPF("CreateAndEditRewrite") {
  case RewriteRequest(
        ParsePath("models" :: "createEdit" :: state :: Nil, _, _,_), _, _) => {
      Console.println("Rewriting path: models/createEdit/Create to createEdit.html")
      val rewriteResp = RewriteResponse(
        "models/createEdit" :: Nil, "html" // Use webapp/models/creteEdit.html
      )
      Console.println("Response refers to URL " + rewriteResp.path + " with parameters " + rewriteResp.params.toList.map(x => "" + x.key + "=" + x.value + ", "))
      rewriteResp

  }
})
</code>```

To make sure everything is accessible a made sure SiteMap permitted access to "models/createEdit/create" and "models/createEdit" with the following lines.

```<code>val entries =
     Menu(Loc("models", List(""), "Models"),
         Menu(Loc("createEditM", List("models","createEdit","Create"), "[NEW]Create Model", loggedIn)),
         Menu(Loc("createEditMXX", List("models","createEdit"), "[NEW]Create Model", loggedIn)) ) ::
     User.sitemap

// Build SiteMap
LiftRules.setSiteMap(SiteMap(entries:_*))
LiftRules.passNotFoundToChain = true //if a URL isn't found pass responsability to the container
</code>```

Yet, the second menu option works while the first yelds a "HTTP ERROR 404
Problem accessing /models/createEdit/Create" on the container level.

The following println appear on the console

```<code>Rewriting path: models/createEdit/Create to createEdit.html
Response refers to URL ParsePath(List(models/createEdit),html,true,false) with parameters List()
INFO - Service request (GET) /models/createEdit/Create returned 0, took 11 Milliseconds
</code>```

which means the rewrite was triggered.

I'm using Lift 2.4-M3 with Scala 2.9.0-1.

Anyone has any idea what is the problem?

Thanks.

Edit: changed code sample and added console output to make what is happening clearer.

答:
First, don't use the Rewrite stuff.  It's low level and generally isn't necessary.

If you want a parameterized Menu entry, use Menu.param.  See http://simply.liftweb.net/index-3.2.html#toc-Subsection-3.2.7

Body:
I have the following rewrite in Boot.boot(). This is based on the instructions found in the URL Rewriting section in the Lift Wiki.

LiftRules.statefulRewrite.prepend(NamedPF("CreateAndEditRewrite") {
  case RewriteRequest(
        ParsePath("models" :: "createEdit" :: state :: Nil, _, _,_), _, _) => {
      Console.println("Rewriting path: models/createEdit/Create to createEdit.html")
      val rewriteResp = RewriteResponse(
        "models/createEdit" :: Nil, "html" // Use webapp/models/creteEdit.html
      )
      Console.println("Response refers to URL " + rewriteResp.path + " with parameters " + rewriteResp.params.toList.map(x => "" + x.key + "=" + x.value + ", "))
      rewriteResp

  }
})

To make sure everything is accessible a made sure SiteMap permitted access to "models/createEdit/create" and "models/createEdit" with the following lines.

val entries =
     Menu(Loc("models", List(""), "Models"),
         Menu(Loc("createEditM", List("models","createEdit","Create"), "[NEW]Create Model", loggedIn)),
         Menu(Loc("createEditMXX", List("models","createEdit"), "[NEW]Create Model", loggedIn)) ) ::
     User.sitemap

// Build SiteMap
LiftRules.setSiteMap(SiteMap(entries:_*))
LiftRules.passNotFoundToChain = true //if a URL isn't found pass responsability to the container

Yet, the second menu option works while the first yelds a "HTTP ERROR 404
Problem accessing /models/createEdit/Create" on the container level.

The following println appear on the console

Rewriting path: models/createEdit/Create to createEdit.html
Response refers to URL ParsePath(List(models/createEdit),html,true,false) with parameters List()
INFO - Service request (GET) /models/createEdit/Create returned 0, took 11 Milliseconds

which means the rewrite was triggered.

I'm using Lift 2.4-M3 with Scala 2.9.0-1.

Anyone has any idea what is the problem?

Thanks.

Edit: changed code sample and added console output to make what is happening clearer.


问:
Excel - INDEX / MATCH with different tables and multiple criterias
I have two Excel Sheets

Sheet 1:

Sheet 2:

What I'm trying to accomplish is to get excel to retrieve the date in the top row for the column that contains a value. I think I have found a way to do this without taking the Unique ID in account but I need to be able to add the ID as a criteria into this formula because my formula would only work if all the IDs are in the same order and part of both tables.

This is what I currently got : =INDEX($H$4:$Z$4;MATCH(TRUE;INDEX(H6:Z6>0;0);0))

How can I take into consideration the IDs in a way that excel matches the IDs also?

答:
=IFERROR(EOMONTH(AGGREGATE(14,6,1/(INDEX($H$5:$Z$16,MATCH($G22,$G$5:$G$16,0),)<>"")*($H$4:$Z$4),1),0),"")

Older versions of Excel need this entered with ctrl+shift+enter.

This searches your data for the row where the ID meets the criteria (in this example I used G22 for the ID to match).
Aggregate checks for a non-empty cell in that range and returns the value in the header. EOMONTH then returns the last day of that month.
If there's no values or matching ID's it returns as blank.


问:
MS Access: How to query a second table when value is not found in the first
I have a simple query to find values in a related table. In some cases, the value is null.  In this case, I would like to query a second table.  I looked at the NZ function but it won't allow for another query operation.  I assume I am looking at a nested query or an operation like SQL COALASCE.

I want to first search tbl_bi_item_mstr

```<code>SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_bi_item_mstr.bi_item_nr
FROM tbl_cust_fcst_demd LEFT JOIN tbl_bi_item_mstr ON tbl_cust_fcst_demd.cust_item_nr = tbl_bi_item_mstr.bi_item_nr;
</code>```

For the null values, I would want to find them in tbl_cust_xref

```<code>SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_cust_xref.bi_item_nr
FROM tbl_cust_fcst_demd INNER JOIN tbl_cust_xref ON tbl_cust_fcst_demd.cust_item_nr = tbl_cust_xref.cust_item_nr;
</code>```

答:
Andre's suggestion was helpful. INNER JOIN was required to change to LEFT JOIN or the null values were ignored.</p>
```<code>SELECT d.cust_item_nr, Nz([i].[bi_item_nr],[x].[bi_item_nr]) AS bi_item_nr
FROM (tbl_cust_fcst_demd AS d
LEFT JOIN tbl_bi_item_mstr AS i ON d.cust_item_nr = i.bi_item_nr)
LEFT JOIN tbl_cust_xref AS x ON d.cust_item_nr = x.cust_item_nr
</code>```

Body:
I have a simple query to find values in a related table. In some cases, the value is null.  In this case, I would like to query a second table.  I looked at the NZ function but it won't allow for another query operation.  I assume I am looking at a nested query or an operation like SQL COALASCE.

I want to first search tbl_bi_item_mstr

SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_bi_item_mstr.bi_item_nr
FROM tbl_cust_fcst_demd LEFT JOIN tbl_bi_item_mstr ON tbl_cust_fcst_demd.cust_item_nr = tbl_bi_item_mstr.bi_item_nr;

For the null values, I would want to find them in tbl_cust_xref

SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_cust_xref.bi_item_nr
FROM tbl_cust_fcst_demd INNER JOIN tbl_cust_xref ON tbl_cust_fcst_demd.cust_item_nr = tbl_cust_xref.cust_item_nr;

Body:
Andre's suggestion was helpful. INNER JOIN was required to change to LEFT JOIN or the null values were ignored.

SELECT d.cust_item_nr, Nz([i].[bi_item_nr],[x].[bi_item_nr]) AS bi_item_nr
FROM (tbl_cust_fcst_demd AS d
LEFT JOIN tbl_bi_item_mstr AS i ON d.cust_item_nr = i.bi_item_nr)
LEFT JOIN tbl_cust_xref AS x ON d.cust_item_nr = x.cust_item_nr


问:
Sorting of data from array list
I have a array list consisting of data in the format of

12 August 2011, 11 September 2011

I used my below code to do the sorting:

```<code>Array.Sort(fileNames, delegate(string first, string second)
{

  return DateTime.Compare(Convert.ToDateTime(first), Convert.ToDateTime(second));
});
</code>```

The result I get from the above code is

11 September 2011, 12 August 2011

after sorting

答:
You say that your data is "an array list of strings" - do you mean

```<code>List<string>
</code>```

or

```<code>string[]
</code>```

?

It makes a little bit of a difference in the way you go about implementing the code.  Presuming you have an actual array, then the code is pretty straight forward, albeit not as clean as we would like:

```<code>private void SortButton_Click(object sender, RoutedEventArgs e)
{
    ItemsListBox.ItemsSource = null;
    Array.Sort(items, delegate(string first, string second)
    {
        return DateTime.Compare(Convert.ToDateTime(first), Convert.ToDateTime(second));
    });
    ItemsListBox.ItemsSource = items;
}
</code>```

If, however, you're dealing with a List<string> called "items", then this approach won't work by itself.  You have to juggle around some stuff to make this happen:

```<code>private void SortButton_Click(object sender, RoutedEventArgs e)
{
    ItemsListBox.ItemsSource = null;
    var arrayOfItems = items.ToArray<string>();
    Array.Sort(arrayOfItems, delegate(string first, string second)
    {
        return DateTime.Compare(Convert.ToDateTime(first), Convert.ToDateTime(second));
    });
    items = new List<string>(arrayOfItems);
    ItemsListBox.ItemsSource = items;
}
</code>```

Similar, but different :)  Since the sorting is happening in place, it actually just sorts the array and not the actual List<string> that we were using.

Now - note the clearing of the ItemsSource before and resetting after. I played with it for a bit, but couldn't get it to work properly without doing both of these steps.  I think this is a breakdown somewhere in the data binding infrastructure. I tried using a string[], List and ObservableCollection, but each time had to clear and reset the ItemsSource to get the ListBox to repaint.

Your comments about the Convert.ToDateTime() didn't seem to be a problem for me. I also tried DateTime.Parse() and that worked as well.  The problem turned out to be in the clearing and reassigning of the ListBox.ItemsSource.

Does anyone know why ListBox behaves this way? Is it something simple I'm just forgetting?

Title: Sorting of data from array list

Body:
I have a array list consisting of data in the format of

12 August 2011, 11 September 2011

I used my below code to do the sorting:

Array.Sort(fileNames, delegate(string first, string second)
{

  return DateTime.Compare(Convert.ToDateTime(first), Convert.ToDateTime(second));
});

The result I get from the above code is

11 September 2011, 12 August 2011

after sorting

Body:
You say that your data is "an array list of strings" - do you mean

List<string>

or

string[]

?

It makes a little bit of a difference in the way you go about implementing the code.  Presuming you have an actual array, then the code is pretty straight forward, albeit not as clean as we would like:

private void SortButton_Click(object sender, RoutedEventArgs e)
{
    ItemsListBox.ItemsSource = null;
    Array.Sort(items, delegate(string first, string second)
    {
        return DateTime.Compare(Convert.ToDateTime(first), Convert.ToDateTime(second));
    });
    ItemsListBox.ItemsSource = items;
}

If, however, you're dealing with a List<string> called "items", then this approach won't work by itself.  You have to juggle around some stuff to make this happen:

private void SortButton_Click(object sender, RoutedEventArgs e)
{
    ItemsListBox.ItemsSource = null;
    var arrayOfItems = items.ToArray<string>();
    Array.Sort(arrayOfItems, delegate(string first, string second)
    {
        return DateTime.Compare(Convert.ToDateTime(first), Convert.ToDateTime(second));
    });
    items = new List<string>(arrayOfItems);
    ItemsListBox.ItemsSource = items;
}

Similar, but different :)  Since the sorting is happening in place, it actually just sorts the array and not the actual List<string> that we were using.

Now - note the clearing of the ItemsSource before and resetting after. I played with it for a bit, but couldn't get it to work properly without doing both of these steps.  I think this is a breakdown somewhere in the data binding infrastructure. I tried using a string[], List and ObservableCollection, but each time had to clear and reset the ItemsSource to get the ListBox to repaint.

Your comments about the Convert.ToDateTime() didn't seem to be a problem for me. I also tried DateTime.Parse() and that worked as well.  The problem turned out to be in the clearing and reassigning of the ListBox.ItemsSource.

Does anyone know why ListBox behaves this way? Is it something simple I'm just forgetting?


答:
```<code>import pandas as pd

df = pd.DataFrame([
    ["23(1.1)", "30(1.3)", "32"],
    ["23(1.2)", "31(1.6)", "31(1.2)"],
    ], columns=[f"col{i}" for i in range(1,4)])

selected_cols = ['col1', 'col2']
for col in selected_cols:
    df[col] = df[col].replace(r"\(.*\)", "", regex=True)
</code>```

Title: Deleting (12) from Df


问:
Javascript toggle element display
I have a website with a menu element in a header grid and when the page is first displayd the menu is visible.
I have a hamburger element which I want to use to toggle the menu display when it is clicked.

The CSS for the menu is:

```<code>/*==================================================================*/
/* NAVIGATION */
.main-nav {
    grid-area: N;
    text-transform: uppercase;
}

/* Style the nav links */
.main-nav ul {
    display: grid;
    grid-template-columns: repeat(4,20vw);
}

.main-nav li {
    /* No bullets */
    text-align: center;
    list-style-type: none;
    min-width: 20vw;
}

.main-nav a {
    /* Not italic unlike all other a elements */
    text-decoration: none;
    font-style: normal;
}
</code>```

The hanburger uses a javascript function:

```<code>/* Toggle between showing and hiding the navigation menu links when the user clicks on the hamburger menu / bar icon */
function toggleMenu() {
    let menu = document.getElementById("main-nav");

    if (menu.display == "none"){
        alert("Hidden");
        menu.style.display = "grid";
    }
    else {
        alert("Displayed");
        menu.style.display = "none";
    }

};
</code>```

When the page loads, this function is used in the hamburger's click event listener:

```<code> document.getElementById("hamburger").addEventListener("click", toggleMenu);
</code>```

Now, what happens is this - the page loads, the menu is visible:

I click on the hamburger the alert tells me the menu is currently visible:

Then the menu is hidden:

However, if I now click the hamburger again I get a message telling me that the menu is displayed(!) and it does not re-appear:

So, what I don't understand is why the element's style.display status is incorrect when the menu is clearly display:none;?

Of course, this then means that the function fails to re-show the menu as the status check is incorrect.

If you need any more code let me know but as far as I can see all the code involved is in the question.

Thanks in advance,

Dermot

答:
Try this instead!

function toggleMenu() {
  let menu = document.getElementById("main-nav");

  if (window.getComputedStyle(menu).display == "none") {
    alert("Hidden");
    menu.style.display = "grid";
  } else if (window.getComputedStyle(menu).display == "grid") {
    alert("Displayed");
    menu.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main-nav {
    grid-area: N;
    text-transform: uppercase;
}

/* Style the nav links */
.main-nav ul {
    display: grid;
    grid-template-columns: repeat(4,20vw);
}

.main-nav li {
    /* No bullets */
    text-align: center;
    list-style-type: none;
    min-width: 20vw;
}

.main-nav a {
    /* Not italic unlike all other a elements */
    text-decoration: none;
    font-style: normal;
}</code>```

home

shop

notes

info

  <button onClick="toggleMenu()">☰</button>

```

Title: Javascript toggle element display

Body:
I have a website with a menu element in a header grid and when the page is first displayd the menu is visible.
I have a hamburger element which I want to use to toggle the menu display when it is clicked.

The CSS for the menu is:

/*==================================================================*/
/* NAVIGATION */
.main-nav {
    grid-area: N;
    text-transform: uppercase;
}

/* Style the nav links */
.main-nav ul {
    display: grid;
    grid-template-columns: repeat(4,20vw);
}

.main-nav li {
    /* No bullets */
    text-align: center;
    list-style-type: none;
    min-width: 20vw;
}

.main-nav a {
    /* Not italic unlike all other a elements */
    text-decoration: none;
    font-style: normal;
}

The hanburger uses a javascript function:

/* Toggle between showing and hiding the navigation menu links when the user clicks on the hamburger menu / bar icon */
function toggleMenu() {
    let menu = document.getElementById("main-nav");

    if (menu.display == "none"){
        alert("Hidden");
        menu.style.display = "grid";
    }
    else {
        alert("Displayed");
        menu.style.display = "none";
    }

};

When the page loads, this function is used in the hamburger's click event listener:

 document.getElementById("hamburger").addEventListener("click", toggleMenu);

Now, what happens is this - the page loads, the menu is visible:

I click on the hamburger the alert tells me the menu is currently visible:

Then the menu is hidden:

However, if I now click the hamburger again I get a message telling me that the menu is displayed(!) and it does not re-appear:

So, what I don't understand is why the element's style.display status is incorrect when the menu is clearly display:none;?

Of course, this then means that the function fails to re-show the menu as the status check is incorrect.

If you need any more code let me know but as far as I can see all the code involved is in the question.

Thanks in advance,

Dermot

Body:
Try this instead!

function toggleMenu() {
  let menu = document.getElementById("main-nav");

  if (window.getComputedStyle(menu).display == "none") {
    alert("Hidden");
    menu.style.display = "grid";
  } else if (window.getComputedStyle(menu).display == "grid") {
    alert("Displayed");
    menu.style.display = "none";
  }
}

.main-nav {
    grid-area: N;
    text-transform: uppercase;
}

/* Style the nav links */
.main-nav ul {
    display: grid;
    grid-template-columns: repeat(4,20vw);
}

.main-nav li {
    /* No bullets */
    text-align: center;
    list-style-type: none;
    min-width: 20vw;
}

.main-nav a {
    /* Not italic unlike all other a elements */
    text-decoration: none;
    font-style: normal;
}

<div class="main-nav">
  <ul id="main-nav">
    <li><a class="hoverlink activemenu" href="index.html">home</a></li>
    <li><a class="hoverlink" href="shop.html">shop</a></li>
    <li><a class="hoverlink" href="notes.html">notes</a></li>
    <li><a class="hoverlink" href="info.html">info</a></li>
  </ul>
  <button onClick="toggleMenu()">☰</button>
</div>


问:
android billing inApp/subscription Unable to find explicit activity ProxyBillingActivity
I want to implement subscription billing feature, but when i call launchBillingFlow method, i am getting error like this

android.content.ActivityNotFoundException: Unable to find explicit activity class {com.calendargb/com.android.billingclient.api.ProxyBillingActivity}; have you declared this activity in your AndroidManifest.xml

Here it is my sample

```<code>  BillingFlowParams purchaseParams = BillingFlowParams.newBuilder()
                    .setSku(skuId).setType(billingType).setOldSku(oldSku).build();
  mBillingClient.launchBillingFlow(mActivity, purchaseParams);
</code>```

Should i declare explicit ProxyBillingActivity in manifest file? Thanks in advance!

答:
.class public Lcom/android/billingclient/api/ProxyBillingActivity;
.super Landroid/app/Activity;
.source ""

instance fields

.field private c:Landroid/os/ResultReceiver;

.field private d:Z

direct methods

.method public constructor ()V
.registers 1

```<code>invoke-direct {p0}, Landroid/app/Activity;-><init>()V

return-void
</code>```

.end method

.method private final a()Landroid/content/Intent;
.registers 3

```<code>new-instance v0, Landroid/content/Intent;

const-string v1, "com.android.vending.billing.PURCHASES_UPDATED"

invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

invoke-virtual {p0}, Landroid/app/Activity;->getApplicationContext()Landroid/content/Context;

move-result-object v1

invoke-virtual {v1}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

move-result-object v1

invoke-virtual {v0, v1}, Landroid/content/Intent;->setPackage(Ljava/lang/String;)Landroid/content/Intent;

return-object v0
</code>```

.end method

virtual methods

.method protected onActivityResult(IILandroid/content/Intent;)V
.registers 8

```<code>invoke-super {p0, p1, p2, p3}, Landroid/app/Activity;->onActivityResult(IILandroid/content/Intent;)V

const/4 v0, 0x0

const-string v1, "ProxyBillingActivity"

const/16 v2, 0x64

if-ne p1, v2, :cond_73

invoke-static {p3, v1}, Lc/e/a/b/f/g/a;->a(Landroid/content/Intent;Ljava/lang/String;)Lcom/android/billingclient/api/g;

move-result-object p1

invoke-virtual {p1}, Lcom/android/billingclient/api/g;->b()I

move-result p1

const/4 v2, -0x1

if-ne p2, v2, :cond_1b

if-eqz p1, :cond_19

const/4 p2, -0x1

goto :goto_1b

:cond_19
const/4 p1, 0x0

goto :goto_39

:cond_1b
:goto_1b
new-instance v2, Ljava/lang/StringBuilder;

const/16 v3, 0x55

invoke-direct {v2, v3}, Ljava/lang/StringBuilder;-><init>(I)V

const-string v3, "Activity finished with resultCode "

invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

const-string p2, " and billing\'s responseCode: "

invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {v2, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

move-result-object p2

invoke-static {v1, p2}, Lc/e/a/b/f/g/a;->b(Ljava/lang/String;Ljava/lang/String;)V

:goto_39
iget-object p2, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->c:Landroid/os/ResultReceiver;

if-eqz p2, :cond_49

if-nez p3, :cond_41

const/4 p3, 0x0

goto :goto_45

:cond_41
invoke-virtual {p3}, Landroid/content/Intent;->getExtras()Landroid/os/Bundle;

move-result-object p3

:goto_45
invoke-virtual {p2, p1, p3}, Landroid/os/ResultReceiver;->send(ILandroid/os/Bundle;)V

goto :goto_8e

:cond_49
invoke-direct {p0}, Lcom/android/billingclient/api/ProxyBillingActivity;->a()Landroid/content/Intent;

move-result-object p1

if-eqz p3, :cond_6f

invoke-virtual {p3}, Landroid/content/Intent;->getExtras()Landroid/os/Bundle;

move-result-object p2

if-eqz p2, :cond_5d

invoke-virtual {p3}, Landroid/content/Intent;->getExtras()Landroid/os/Bundle;

move-result-object p2

invoke-virtual {p1, p2}, Landroid/content/Intent;->putExtras(Landroid/os/Bundle;)Landroid/content/Intent;

goto :goto_6f

:cond_5d
const-string p2, "Got null bundle!"

invoke-static {v1, p2}, Lc/e/a/b/f/g/a;->b(Ljava/lang/String;Ljava/lang/String;)V

const/4 p2, 0x6

const-string p3, "RESPONSE_CODE"

invoke-virtual {p1, p3, p2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;

const-string p2, "DEBUG_MESSAGE"

const-string p3, "An internal error occurred."

invoke-virtual {p1, p2, p3}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;

:cond_6f
:goto_6f
invoke-virtual {p0, p1}, Landroid/app/Activity;->sendBroadcast(Landroid/content/Intent;)V

goto :goto_8e

:cond_73
new-instance p2, Ljava/lang/StringBuilder;

const/16 p3, 0x45

invoke-direct {p2, p3}, Ljava/lang/StringBuilder;-><init>(I)V

const-string p3, "Got onActivityResult with wrong requestCode: "

invoke-virtual {p2, p3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {p2, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

const-string p1, "; skipping..."

invoke-virtual {p2, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {p2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

move-result-object p1

invoke-static {v1, p1}, Lc/e/a/b/f/g/a;->b(Ljava/lang/String;Ljava/lang/String;)V

:goto_8e
iput-boolean v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

invoke-virtual {p0}, Landroid/app/Activity;->finish()V

return-void
</code>```

.end method

.method protected onCreate(Landroid/os/Bundle;)V
.registers 14

```<code>invoke-super {p0, p1}, Landroid/app/Activity;->onCreate(Landroid/os/Bundle;)V

const/4 v0, 0x0

const-string v1, "result_receiver"

const-string v2, "ProxyBillingActivity"

if-nez p1, :cond_a6

const-string p1, "Launching Play Store billing flow"

invoke-static {v2, p1}, Lc/e/a/b/f/g/a;->a(Ljava/lang/String;Ljava/lang/String;)V

invoke-virtual {p0}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

move-result-object p1

const-string v3, "BUY_INTENT"

invoke-virtual {p1, v3}, Landroid/content/Intent;->hasExtra(Ljava/lang/String;)Z

move-result p1

const/4 v4, 0x0

if-eqz p1, :cond_27

invoke-virtual {p0}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

move-result-object p1

invoke-virtual {p1, v3}, Landroid/content/Intent;->getParcelableExtra(Ljava/lang/String;)Landroid/os/Parcelable;

move-result-object p1

check-cast p1, Landroid/app/PendingIntent;

goto :goto_4b

:cond_27
invoke-virtual {p0}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

move-result-object p1

const-string v3, "SUBS_MANAGEMENT_INTENT"

invoke-virtual {p1, v3}, Landroid/content/Intent;->hasExtra(Ljava/lang/String;)Z

move-result p1

if-eqz p1, :cond_4a

invoke-virtual {p0}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

move-result-object p1

invoke-virtual {p1, v3}, Landroid/content/Intent;->getParcelableExtra(Ljava/lang/String;)Landroid/os/Parcelable;

move-result-object p1

check-cast p1, Landroid/app/PendingIntent;

invoke-virtual {p0}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

move-result-object v3

invoke-virtual {v3, v1}, Landroid/content/Intent;->getParcelableExtra(Ljava/lang/String;)Landroid/os/Parcelable;

move-result-object v1

check-cast v1, Landroid/os/ResultReceiver;

iput-object v1, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->c:Landroid/os/ResultReceiver;

goto :goto_4b

:cond_4a
move-object p1, v4

:goto_4b
const/4 v1, 0x1

:try_start_4c
iput-boolean v1, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

invoke-virtual {p1}, Landroid/app/PendingIntent;->getIntentSender()Landroid/content/IntentSender;

move-result-object v6

new-instance v8, Landroid/content/Intent;

invoke-direct {v8}, Landroid/content/Intent;-><init>()V

const/16 v7, 0x64

const/4 v9, 0x0

const/4 v10, 0x0

const/4 v11, 0x0

move-object v5, p0

invoke-virtual/range {v5 .. v11}, Landroid/app/Activity;->startIntentSenderForResult(Landroid/content/IntentSender;ILandroid/content/Intent;III)V
:try_end_60
.catch Landroid/content/IntentSender$SendIntentException; {:try_start_4c .. :try_end_60} :catch_61

return-void

:catch_61
move-exception p1

invoke-static {p1}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;

move-result-object p1

invoke-static {p1}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;

move-result-object v1

invoke-virtual {v1}, Ljava/lang/String;->length()I

move-result v1

new-instance v3, Ljava/lang/StringBuilder;

add-int/lit8 v1, v1, 0x35

invoke-direct {v3, v1}, Ljava/lang/StringBuilder;-><init>(I)V

const-string v1, "Got exception while trying to start a purchase flow: "

invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {v3, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

move-result-object p1

invoke-static {v2, p1}, Lc/e/a/b/f/g/a;->b(Ljava/lang/String;Ljava/lang/String;)V

iget-object p1, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->c:Landroid/os/ResultReceiver;

const/4 v1, 0x6

if-eqz p1, :cond_8d

invoke-virtual {p1, v1, v4}, Landroid/os/ResultReceiver;->send(ILandroid/os/Bundle;)V

goto :goto_a0

:cond_8d
invoke-direct {p0}, Lcom/android/billingclient/api/ProxyBillingActivity;->a()Landroid/content/Intent;

move-result-object p1

const-string v2, "RESPONSE_CODE"

invoke-virtual {p1, v2, v1}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;

const-string v1, "DEBUG_MESSAGE"

const-string v2, "An internal error occurred."

invoke-virtual {p1, v1, v2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;

invoke-virtual {p0, p1}, Landroid/app/Activity;->sendBroadcast(Landroid/content/Intent;)V

:goto_a0
iput-boolean v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

invoke-virtual {p0}, Landroid/app/Activity;->finish()V

return-void

:cond_a6
const-string v3, "Launching Play Store billing flow from savedInstanceState"

invoke-static {v2, v3}, Lc/e/a/b/f/g/a;->a(Ljava/lang/String;Ljava/lang/String;)V

const-string v2, "send_cancelled_broadcast_if_finished"

invoke-virtual {p1, v2, v0}, Landroid/os/Bundle;->getBoolean(Ljava/lang/String;Z)Z

move-result v0

iput-boolean v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

invoke-virtual {p1, v1}, Landroid/os/Bundle;->containsKey(Ljava/lang/String;)Z

move-result v0

if-eqz v0, :cond_c1

invoke-virtual {p1, v1}, Landroid/os/Bundle;->getParcelable(Ljava/lang/String;)Landroid/os/Parcelable;

move-result-object p1

check-cast p1, Landroid/os/ResultReceiver;

iput-object p1, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->c:Landroid/os/ResultReceiver;

:cond_c1
return-void
</code>```

.end method

.method protected onDestroy()V
.registers 4

```<code>invoke-super {p0}, Landroid/app/Activity;->onDestroy()V

invoke-virtual {p0}, Landroid/app/Activity;->isFinishing()Z

move-result v0

if-nez v0, :cond_a

return-void

:cond_a
iget-boolean v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

if-nez v0, :cond_f

return-void

:cond_f
invoke-direct {p0}, Lcom/android/billingclient/api/ProxyBillingActivity;->a()Landroid/content/Intent;

move-result-object v0

const/4 v1, 0x1

const-string v2, "RESPONSE_CODE"

invoke-virtual {v0, v2, v1}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;

const-string v1, "DEBUG_MESSAGE"

const-string v2, "Billing dialog closed."

invoke-virtual {v0, v1, v2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;

invoke-virtual {p0, v0}, Landroid/app/Activity;->sendBroadcast(Landroid/content/Intent;)V

return-void
</code>```

.end method

.method protected onSaveInstanceState(Landroid/os/Bundle;)V
.registers 4

```<code>iget-object v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->c:Landroid/os/ResultReceiver;

if-eqz v0, :cond_9

const-string v1, "result_receiver"

invoke-virtual {p1, v1, v0}, Landroid/os/Bundle;->putParcelable(Ljava/lang/String;Landroid/os/Parcelable;)V

:cond_9
iget-boolean v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

const-string v1, "send_cancelled_broadcast_if_finished"

invoke-virtual {p1, v1, v0}, Landroid/os/Bundle;->putBoolean(Ljava/lang/String;Z)V

return-void
</code>```

.end method

Body:
I want to implement subscription billing feature, but when i call launchBillingFlow method, i am getting error like this

android.content.ActivityNotFoundException: Unable to find explicit activity class {com.calendargb/com.android.billingclient.api.ProxyBillingActivity}; have you declared this activity in your AndroidManifest.xml

Here it is my sample

  BillingFlowParams purchaseParams = BillingFlowParams.newBuilder()
                    .setSku(skuId).setType(billingType).setOldSku(oldSku).build();
  mBillingClient.launchBillingFlow(mActivity, purchaseParams);

Should i declare explicit ProxyBillingActivity in manifest file? Thanks in advance!

Body:
.class public Lcom/android/billingclient/api/ProxyBillingActivity;
.super Landroid/app/Activity;
.source ""

instance fields

.field private c:Landroid/os/ResultReceiver;

.field private d:Z

direct methods

.method public constructor ()V
.registers 1

invoke-direct {p0}, Landroid/app/Activity;-><init>()V

return-void

.end method

.method private final a()Landroid/content/Intent;
.registers 3

new-instance v0, Landroid/content/Intent;

const-string v1, "com.android.vending.billing.PURCHASES_UPDATED"

invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

invoke-virtual {p0}, Landroid/app/Activity;->getApplicationContext()Landroid/content/Context;

move-result-object v1

invoke-virtual {v1}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

move-result-object v1

invoke-virtual {v0, v1}, Landroid/content/Intent;->setPackage(Ljava/lang/String;)Landroid/content/Intent;

return-object v0

.end method

virtual methods

.method protected onActivityResult(IILandroid/content/Intent;)V
.registers 8

invoke-super {p0, p1, p2, p3}, Landroid/app/Activity;->onActivityResult(IILandroid/content/Intent;)V

const/4 v0, 0x0

const-string v1, "ProxyBillingActivity"

const/16 v2, 0x64

if-ne p1, v2, :cond_73

invoke-static {p3, v1}, Lc/e/a/b/f/g/a;->a(Landroid/content/Intent;Ljava/lang/String;)Lcom/android/billingclient/api/g;

move-result-object p1

invoke-virtual {p1}, Lcom/android/billingclient/api/g;->b()I

move-result p1

const/4 v2, -0x1

if-ne p2, v2, :cond_1b

if-eqz p1, :cond_19

const/4 p2, -0x1

goto :goto_1b

:cond_19
const/4 p1, 0x0

goto :goto_39

:cond_1b
:goto_1b
new-instance v2, Ljava/lang/StringBuilder;

const/16 v3, 0x55

invoke-direct {v2, v3}, Ljava/lang/StringBuilder;-><init>(I)V

const-string v3, "Activity finished with resultCode "

invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

const-string p2, " and billing\'s responseCode: "

invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {v2, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

move-result-object p2

invoke-static {v1, p2}, Lc/e/a/b/f/g/a;->b(Ljava/lang/String;Ljava/lang/String;)V

:goto_39
iget-object p2, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->c:Landroid/os/ResultReceiver;

if-eqz p2, :cond_49

if-nez p3, :cond_41

const/4 p3, 0x0

goto :goto_45

:cond_41
invoke-virtual {p3}, Landroid/content/Intent;->getExtras()Landroid/os/Bundle;

move-result-object p3

:goto_45
invoke-virtual {p2, p1, p3}, Landroid/os/ResultReceiver;->send(ILandroid/os/Bundle;)V

goto :goto_8e

:cond_49
invoke-direct {p0}, Lcom/android/billingclient/api/ProxyBillingActivity;->a()Landroid/content/Intent;

move-result-object p1

if-eqz p3, :cond_6f

invoke-virtual {p3}, Landroid/content/Intent;->getExtras()Landroid/os/Bundle;

move-result-object p2

if-eqz p2, :cond_5d

invoke-virtual {p3}, Landroid/content/Intent;->getExtras()Landroid/os/Bundle;

move-result-object p2

invoke-virtual {p1, p2}, Landroid/content/Intent;->putExtras(Landroid/os/Bundle;)Landroid/content/Intent;

goto :goto_6f

:cond_5d
const-string p2, "Got null bundle!"

invoke-static {v1, p2}, Lc/e/a/b/f/g/a;->b(Ljava/lang/String;Ljava/lang/String;)V

const/4 p2, 0x6

const-string p3, "RESPONSE_CODE"

invoke-virtual {p1, p3, p2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;

const-string p2, "DEBUG_MESSAGE"

const-string p3, "An internal error occurred."

invoke-virtual {p1, p2, p3}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;

:cond_6f
:goto_6f
invoke-virtual {p0, p1}, Landroid/app/Activity;->sendBroadcast(Landroid/content/Intent;)V

goto :goto_8e

:cond_73
new-instance p2, Ljava/lang/StringBuilder;

const/16 p3, 0x45

invoke-direct {p2, p3}, Ljava/lang/StringBuilder;-><init>(I)V

const-string p3, "Got onActivityResult with wrong requestCode: "

invoke-virtual {p2, p3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {p2, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

const-string p1, "; skipping..."

invoke-virtual {p2, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {p2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

move-result-object p1

invoke-static {v1, p1}, Lc/e/a/b/f/g/a;->b(Ljava/lang/String;Ljava/lang/String;)V

:goto_8e
iput-boolean v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

invoke-virtual {p0}, Landroid/app/Activity;->finish()V

return-void

.end method

.method protected onCreate(Landroid/os/Bundle;)V
.registers 14

invoke-super {p0, p1}, Landroid/app/Activity;->onCreate(Landroid/os/Bundle;)V

const/4 v0, 0x0

const-string v1, "result_receiver"

const-string v2, "ProxyBillingActivity"

if-nez p1, :cond_a6

const-string p1, "Launching Play Store billing flow"

invoke-static {v2, p1}, Lc/e/a/b/f/g/a;->a(Ljava/lang/String;Ljava/lang/String;)V

invoke-virtual {p0}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

move-result-object p1

const-string v3, "BUY_INTENT"

invoke-virtual {p1, v3}, Landroid/content/Intent;->hasExtra(Ljava/lang/String;)Z

move-result p1

const/4 v4, 0x0

if-eqz p1, :cond_27

invoke-virtual {p0}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

move-result-object p1

invoke-virtual {p1, v3}, Landroid/content/Intent;->getParcelableExtra(Ljava/lang/String;)Landroid/os/Parcelable;

move-result-object p1

check-cast p1, Landroid/app/PendingIntent;

goto :goto_4b

:cond_27
invoke-virtual {p0}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

move-result-object p1

const-string v3, "SUBS_MANAGEMENT_INTENT"

invoke-virtual {p1, v3}, Landroid/content/Intent;->hasExtra(Ljava/lang/String;)Z

move-result p1

if-eqz p1, :cond_4a

invoke-virtual {p0}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

move-result-object p1

invoke-virtual {p1, v3}, Landroid/content/Intent;->getParcelableExtra(Ljava/lang/String;)Landroid/os/Parcelable;

move-result-object p1

check-cast p1, Landroid/app/PendingIntent;

invoke-virtual {p0}, Landroid/app/Activity;->getIntent()Landroid/content/Intent;

move-result-object v3

invoke-virtual {v3, v1}, Landroid/content/Intent;->getParcelableExtra(Ljava/lang/String;)Landroid/os/Parcelable;

move-result-object v1

check-cast v1, Landroid/os/ResultReceiver;

iput-object v1, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->c:Landroid/os/ResultReceiver;

goto :goto_4b

:cond_4a
move-object p1, v4

:goto_4b
const/4 v1, 0x1

:try_start_4c
iput-boolean v1, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

invoke-virtual {p1}, Landroid/app/PendingIntent;->getIntentSender()Landroid/content/IntentSender;

move-result-object v6

new-instance v8, Landroid/content/Intent;

invoke-direct {v8}, Landroid/content/Intent;-><init>()V

const/16 v7, 0x64

const/4 v9, 0x0

const/4 v10, 0x0

const/4 v11, 0x0

move-object v5, p0

invoke-virtual/range {v5 .. v11}, Landroid/app/Activity;->startIntentSenderForResult(Landroid/content/IntentSender;ILandroid/content/Intent;III)V
:try_end_60
.catch Landroid/content/IntentSender$SendIntentException; {:try_start_4c .. :try_end_60} :catch_61

return-void

:catch_61
move-exception p1

invoke-static {p1}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;

move-result-object p1

invoke-static {p1}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;

move-result-object v1

invoke-virtual {v1}, Ljava/lang/String;->length()I

move-result v1

new-instance v3, Ljava/lang/StringBuilder;

add-int/lit8 v1, v1, 0x35

invoke-direct {v3, v1}, Ljava/lang/StringBuilder;-><init>(I)V

const-string v1, "Got exception while trying to start a purchase flow: "

invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {v3, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

move-result-object p1

invoke-static {v2, p1}, Lc/e/a/b/f/g/a;->b(Ljava/lang/String;Ljava/lang/String;)V

iget-object p1, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->c:Landroid/os/ResultReceiver;

const/4 v1, 0x6

if-eqz p1, :cond_8d

invoke-virtual {p1, v1, v4}, Landroid/os/ResultReceiver;->send(ILandroid/os/Bundle;)V

goto :goto_a0

:cond_8d
invoke-direct {p0}, Lcom/android/billingclient/api/ProxyBillingActivity;->a()Landroid/content/Intent;

move-result-object p1

const-string v2, "RESPONSE_CODE"

invoke-virtual {p1, v2, v1}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;

const-string v1, "DEBUG_MESSAGE"

const-string v2, "An internal error occurred."

invoke-virtual {p1, v1, v2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;

invoke-virtual {p0, p1}, Landroid/app/Activity;->sendBroadcast(Landroid/content/Intent;)V

:goto_a0
iput-boolean v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

invoke-virtual {p0}, Landroid/app/Activity;->finish()V

return-void

:cond_a6
const-string v3, "Launching Play Store billing flow from savedInstanceState"

invoke-static {v2, v3}, Lc/e/a/b/f/g/a;->a(Ljava/lang/String;Ljava/lang/String;)V

const-string v2, "send_cancelled_broadcast_if_finished"

invoke-virtual {p1, v2, v0}, Landroid/os/Bundle;->getBoolean(Ljava/lang/String;Z)Z

move-result v0

iput-boolean v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

invoke-virtual {p1, v1}, Landroid/os/Bundle;->containsKey(Ljava/lang/String;)Z

move-result v0

if-eqz v0, :cond_c1

invoke-virtual {p1, v1}, Landroid/os/Bundle;->getParcelable(Ljava/lang/String;)Landroid/os/Parcelable;

move-result-object p1

check-cast p1, Landroid/os/ResultReceiver;

iput-object p1, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->c:Landroid/os/ResultReceiver;

:cond_c1
return-void

.end method

.method protected onDestroy()V
.registers 4

invoke-super {p0}, Landroid/app/Activity;->onDestroy()V

invoke-virtual {p0}, Landroid/app/Activity;->isFinishing()Z

move-result v0

if-nez v0, :cond_a

return-void

:cond_a
iget-boolean v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

if-nez v0, :cond_f

return-void

:cond_f
invoke-direct {p0}, Lcom/android/billingclient/api/ProxyBillingActivity;->a()Landroid/content/Intent;

move-result-object v0

const/4 v1, 0x1

const-string v2, "RESPONSE_CODE"

invoke-virtual {v0, v2, v1}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;

const-string v1, "DEBUG_MESSAGE"

const-string v2, "Billing dialog closed."

invoke-virtual {v0, v1, v2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;

invoke-virtual {p0, v0}, Landroid/app/Activity;->sendBroadcast(Landroid/content/Intent;)V

return-void

.end method

.method protected onSaveInstanceState(Landroid/os/Bundle;)V
.registers 4

iget-object v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->c:Landroid/os/ResultReceiver;

if-eqz v0, :cond_9

const-string v1, "result_receiver"

invoke-virtual {p1, v1, v0}, Landroid/os/Bundle;->putParcelable(Ljava/lang/String;Landroid/os/Parcelable;)V

:cond_9
iget-boolean v0, p0, Lcom/android/billingclient/api/ProxyBillingActivity;->d:Z

const-string v1, "send_cancelled_broadcast_if_finished"

invoke-virtual {p1, v1, v0}, Landroid/os/Bundle;->putBoolean(Ljava/lang/String;Z)V

return-void

.end method


问:
Address of operator and r-value
There is code part below and I have a question about that.

Although I expect the compiler error, the ouput of this program is 2 5. From my point of view, &a+1 statement should lead to compiler error. The reason is that (a + 1) firstly is executed due to operator precedence and (a+1) statement points 2 in the array. Then, the address of operator (&) has (a + 1) operand but (a + 1) is an r-value expression and therefore &a+1 should cause a compiler error.

What is my fault?

```<code>int main()
{

    int a[5] = {1,2,3,4,5};

    int *ptr = (int*)(&a+1);

    printf("%d %d", *(a+1), *(ptr-1));

    return 0;
}
</code>```

答:
You seem to be confused about the actual operator precedence.

The unary address-of operator & has higher precedence than the binary addition operator +.  So the in the expression &a+1 the address-of operator is first applied to a which is valid because a is an lvalue, then 1 is added to the result.

The actual precedence rules come from the grammar in the C standard, although it can be tricky for a novice to deduce what they actually are.
A good reference for operator precedence can be found here:

https://en.cppreference.com/w/c/language/operator_precedence

From this chart, you can see that the binary bitwise AND operator & does indeed have lower precedence than the binary addition operator +, but the unary address-of operator & has higher precedence.

Title: Address of operator and r-value

Body:
There is code part below and I have a question about that.

Although I expect the compiler error, the ouput of this program is 2 5. From my point of view, &a+1 statement should lead to compiler error. The reason is that (a + 1) firstly is executed due to operator precedence and (a+1) statement points 2 in the array. Then, the address of operator (&) has (a + 1) operand but (a + 1) is an r-value expression and therefore &a+1 should cause a compiler error.

What is my fault?

int main()
{

    int a[5] = {1,2,3,4,5};

    int *ptr = (int*)(&a+1);

    printf("%d %d", *(a+1), *(ptr-1));

    return 0;
}


问:
Node.js - express - jade - compile SASS/LESS
Anyone have a really newbie guide to nodejs - express - SASS/LESS? I have not been able to get this working. The example I have now is a bareboned as possible..

```<code>var express = require('express'),
    less = require('less'),
    app = express.createServer();

var pub_dir = __dirname + '/public';

app.configure(function(){
    app.use(express.compiler({ src: pub_dir, enable: ['less'] }));
    app.use(express.staticProvider( pub_dir ));
};

app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
</code>```

The file style.css.less is located in pub_dir, I can access that directly, and the styling is

```<code>@brand_color: #4D926F;
body {
  color: @brand_color;
}
</code>```

As far as I understand, the compilation is supposed to happen on start-up, and a css file will be generated in the src-dir, as dest is not specified.

My server runs fine, but regardless of how many ways I have tried messing around with the dirnames, directories and names of the LESS/SASS files (and their respective LESS/SASS content) I cannot get this working. Darn! Help.

答:
Two projects which could make your life easier

Buildr: The (Java|Coffee)Script and (CSS|Less) (Builder|Bundler|Packer|Minifier|Merger|Checker)

DocPad: Pre-processor provider and template empowerer for Express.js apps

Body:
Anyone have a really newbie guide to nodejs - express - SASS/LESS? I have not been able to get this working. The example I have now is a bareboned as possible..

var express = require('express'),
    less = require('less'),
    app = express.createServer();

var pub_dir = __dirname + '/public';

app.configure(function(){
    app.use(express.compiler({ src: pub_dir, enable: ['less'] }));
    app.use(express.staticProvider( pub_dir ));
};

app.configure('development', function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

The file style.css.less is located in pub_dir, I can access that directly, and the styling is

@brand_color: #4D926F;
body {
  color: @brand_color;
}

As far as I understand, the compilation is supposed to happen on start-up, and a css file will be generated in the src-dir, as dest is not specified.

My server runs fine, but regardless of how many ways I have tried messing around with the dirnames, directories and names of the LESS/SASS files (and their respective LESS/SASS content) I cannot get this working. Darn! Help.


问:
Is there a way I can access a static resource in my C# code?
In my App.XAML I have this:

```<code><Application xmlns:converters="clr-namespace:Japanese" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Japanese.App">
<Application.Resources>
        <Color x:Key="TextColor1">#123456</Color>
</code>```

I can access this value in XAML like this:

```<code><Style TargetType="Label">
        <Setter Property="TextColor" Value="{StaticResource TextColor1}" />
</Style>
</code>```

But is there also a way that I can access this in my back end C#

```<code>vm.C1BtnLabelTextColor = phrase.C1 == true ? Color.FromHex("#123456") : Color.FromHex("#0000FF");
</code>```

For example here I would like to replace:

```<code>Color.FromHex("#123456")
</code>```

with the value of the StaticResource

答: This definitely works better especially when you are using MergedDictionaries</p>

Body:
In my App.XAML I have this:

<Application xmlns:converters="clr-namespace:Japanese" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Japanese.App">
<Application.Resources>
        <Color x:Key="TextColor1">#123456</Color>

I can access this value in XAML like this:

But is there also a way that I can access this in my back end C#

vm.C1BtnLabelTextColor = phrase.C1 == true ? Color.FromHex("#123456") : Color.FromHex("#0000FF");

For example here I would like to replace:

Color.FromHex("#123456")

with the value of the StaticResource