问:
Can you do calculations in the get/set ? c#
Can you do a calculation in the set clause? and it then returns the total when implemented?`</p>
```<code>    public decimal TotalCost
     {
      set
      { this.costTotal = (decimal)prodCost + (decimal)shipping + (decimal)insurance)}
       get
      { return this.costTotal}
     }
</code>```

答:
I suggest the below code for reading and writing your property.</p>
```<code>private decimal totalCost;
public decimal TotalCost
     {
       get { return totalCost = (decimal)prodCost + (decimal)shipping + (decimal)insurance);}
       set { totalCost = value;}
     }
</code>```

Body:
Can you do a calculation in the set clause? and it then returns the total when implemented?`

    public decimal TotalCost
     {
      set
      { this.costTotal = (decimal)prodCost + (decimal)shipping + (decimal)insurance)}
       get
      { return this.costTotal}
     }

Body:
I suggest the below code for reading and writing your property.

private decimal totalCost;
public decimal TotalCost
     {
       get { return totalCost = (decimal)prodCost + (decimal)shipping + (decimal)insurance);}
       set { totalCost = value;}
     }


来源: stackexchange

问:
Firebase subdomain wildcard to one or more project(s)
We are writing a project for schools. We need different subdomains to any school and users should be different. Any email can be registered on different subdomains as other user.

So we want to connect our domain and all subdomains to a project with *.example.com wildcard. We will read subdomains as values. I think we can manage it with the structure below.

Example 1;

```<code>     requestUrl           |       firebaseProject                 |       displayUrl
https://example.com      ==> https://projectMain.firebaseapp.com ==> https://example.com
https://sub1.example.com ==> https://projectSub1.firebaseapp.com ==> https://sub1.example.com
https://sub2.example.com ==> https://projectSub2.firebaseapp.com ==> https://sub2.example.com
</code>```

/// OR

Example 2;

```<code>     requestUrl           |       firebaseProject             |       displayUrl
https://example.com      ==> https://project.firebaseapp.com ==> https://example.com
https://sub1.example.com ==> https://project.firebaseapp.com ==> https://sub1.example.com
https://sub2.example.com ==> https://project.firebaseapp.com ==> https://sub2.example.com
</code>```

Is that posible or not?

答:
An update to the original best answer, Firebase hosting is now available on handling wildcards.

For Example 1:
This can be achieved by multi-hosting provided by Firebase Hosting. Go to the Hosting section of Firebase Console, then click add another page.

```<code>requestUrl      |   firebase sites of same project  |   displayUrl
www.domain.com  =>         www.firebase.app        =>  www.domain.com
xyz.domain.com  =>         xyz.firebase.app        =>  xyz.domain.com
</code>```

For Example 2:
Simply go to Firebase Console and redirect the subdomain to your desired domain and make sure to modify your A records on your DNS provider.

```<code>requestUrlToRedirect     |    firebaseProject
www.domain.com           =>      domain.com
</code>```

ContentLicense: CC BY-SA 3.0

Body:
We are writing a project for schools. We need different subdomains to any school and users should be different. Any email can be registered on different subdomains as other user.

So we want to connect our domain and all subdomains to a project with *.example.com wildcard. We will read subdomains as values. I think we can manage it with the structure below.

Example 1;

     requestUrl           |       firebaseProject                 |       displayUrl
https://example.com      ==> https://projectMain.firebaseapp.com ==> https://example.com
https://sub1.example.com ==> https://projectSub1.firebaseapp.com ==> https://sub1.example.com
https://sub2.example.com ==> https://projectSub2.firebaseapp.com ==> https://sub2.example.com

/// OR

Example 2;

     requestUrl           |       firebaseProject             |       displayUrl
https://example.com      ==> https://project.firebaseapp.com ==> https://example.com
https://sub1.example.com ==> https://project.firebaseapp.com ==> https://sub1.example.com
https://sub2.example.com ==> https://project.firebaseapp.com ==> https://sub2.example.com

Is that posible or not?

Body:
An update to the original best answer, Firebase hosting is now available on handling wildcards.

For Example 1:
This can be achieved by multi-hosting provided by Firebase Hosting. Go to the Hosting section of Firebase Console, then click add another page.

requestUrl      |   firebase sites of same project  |   displayUrl
www.domain.com  =>         www.firebase.app        =>  www.domain.com
xyz.domain.com  =>         xyz.firebase.app        =>  xyz.domain.com

For Example 2:
Simply go to Firebase Console and redirect the subdomain to your desired domain and make sure to modify your A records on your DNS provider.

requestUrlToRedirect     |    firebaseProject
www.domain.com           =>      domain.com

ContentLicense: CC BY-SA 4.0


问:
For every row with the same name, find the 5 lowest number Pandas Python
My data frame looks like this

```<code>Location  week  Number

Austria   1     154
Austria   2     140
Belgium   1     139
Bulgaria  2     110
Bulgaria  1     164
</code>```

the solution should look like this

```<code>Location  week  Number

Austria   3     100
Austria   2     101
Austria   1     102

Bulgaria  2     100
Bulgaria  3     101
Bulgaria  1     102
</code>```

this means that I need to display

Column 1 : I need to group the countries by name

Column 2 : Week (every country has 53 weeks assigned to them)

Column 3 : Show the numbers that occured in each of 53 weeks in an ascending order

I can not get my head around this

答:
another way using .cumcount() and .loc

```<code>con = df.sort_values('Number',ascending=True).groupby('Location').cumcount()

df.loc[con.lt(5)]
</code>```

Body:
My data frame looks like this

Location  week  Number

Austria   1     154
Austria   2     140
Belgium   1     139
Bulgaria  2     110
Bulgaria  1     164

the solution should look like this

Location  week  Number

Austria   3     100
Austria   2     101
Austria   1     102

Bulgaria  2     100
Bulgaria  3     101
Bulgaria  1     102

this means that I need to display

Column 1 : I need to group the countries by name

Column 2 : Week (every country has 53 weeks assigned to them)

Column 3 : Show the numbers that occured in each of 53 weeks in an ascending order

I can not get my head around this

Body:
another way using .cumcount() and .loc

con = df.sort_values('Number',ascending=True).groupby('Location').cumcount()

df.loc[con.lt(5)]


问:
Setting up EC2 instances as Celery Workers with a local computer as the host
Similar to my question here I'm trying to set up multiple amazon EC2 instances to do some multiprocessing. I was thinking of using Celery to manage the workers. Has anyone gotten celery to work on EC2 instances with a local computer as a host?

Does anyone have any good suggestions, tutorials, advice, etc. that may help? I've used celery to do some simple asynchronous processes in django but nothing of this scale (worker and hosts were on the same machine).

Also most of the processing is 'file-based' (ie reading and writing files) ... do you think it would be better to pickle and transmit the contents of the file with celery (most files are 1-2kb of text) or to mirror the filesystem across the EC2 instances and then just have the workers return the results (which are usually 0.5 kb of text).

答:
I've used Amazon SQS for tasks management with Amazon EC2. It's very scalable solution. Boto is the best library for managing Amazon services as I found.

For storing big amount of small files you can use MongoDB GridFS, it will allow you to store gigs of local files. I used MongoDB and got prefect performance for such tasks. The only problem - MongoDB on 32 bit architecture very limited. Amazon has micro-instance and next by cost large instance that supports 64. Micro instance very limited by CPU and memory and if it will not fit you needs you need to set up large, that may cost a lot.

Micro instance on my tasks was able to read/write up to 10 gigs a day without any problems.

Also please take a look at Spot instances. It costs about 3 times less than on demand and you may find them pretty good for background processing.


问:
utf8 charset with Thymeleaf
When using Spring with Thymeleaf all my Cyrillic characters are shown as ????? on pages.

Using

@RequestMapping(value = "/login", method = RequestMethod.GET, produces = "text/html; charset=utf-8")

as it was suggested here: https://stackoverflow.com/a/11866822/1479414 and here: https://stackoverflow.com/a/12023816/1479414 doesn't help.

How to solve this issue?

答:
With Spring WebFlux, I've restricted the view resolver to use text/html; charset=UTF-8 as the only supported content type. I've used a custom WebFluxConfigurer for that (in Kotlin):

class CustomWebFluxConfigurer(
    private val viewResolver: ThymeleafReactiveViewResolver
) : WebFluxConfigurer {
    override fun configureViewResolvers(registry: ViewResolverRegistry) {
        viewResolver.supportedMediaTypes =
            listOf(MediaType.parseMediaType("text/html; charset=UTF-8"))
        registry.viewResolver(viewResolver)
    }
}
```

Title: utf8 charset with Thymeleaf


问:
Update column to add a default and disallow null
I want to update a column with a default value. I do that like so:

```<code>ALTER TABLE  `db`.`tbl` ALTER COLUMN `some_timestamp` SET DEFAULT current_timestamp();
</code>```

that works fine. I also want to add NOT NULL. How do I do that?

答:
Like so:

```<code>ALTER TABLE `db`.`tbl` MODIFY `some_timestamp` TIMESTAMP NOT NULL DEFAULT current_timestamp();
</code>```

ALTER COLUMN is only used for setting defaults in MySQL; MODIFY <colname> <colspec> modifies a column spec but doesn't rename it. To rename also, use CHANGE <oldname> <newname> <colspec> and specify oldname newname

Body:
I want to update a column with a default value. I do that like so:

ALTER TABLE  `db`.`tbl` ALTER COLUMN `some_timestamp` SET DEFAULT current_timestamp();

that works fine. I also want to add NOT NULL. How do I do that?

Body:
Like so:

ALTER TABLE `db`.`tbl` MODIFY `some_timestamp` TIMESTAMP NOT NULL DEFAULT current_timestamp();

ALTER COLUMN is only used for setting defaults in MySQL; MODIFY <colname> <colspec> modifies a column spec but doesn't rename it. To rename also, use CHANGE <oldname> <newname> <colspec> and specify oldname newname


问:
Android stream check if noneMatch not work
I want to check if none elements from my registration form are not filled (all are filled) but my stream does not seem to work when I fill in all those 3 fields.

Here is what I do:

```<code>private boolean checkAllFields(ModelRegistration mRegister) {
    return Stream.of(mRegister.getUsername(), mRegister.getPassword(), mRegister.getPassConfirmation()).noneMatch(TextUtils::isEmpty);
}
</code>```

ModelRegistration.java

```<code>public class ModelRegistration {

    private String username, password, passConfirmation, email;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassConfirmation() {
        return passConfirmation;
    }

    public void setPassConfirmation(String passConfirmation) {
        this.passConfirmation = passConfirmation;
    }

    public ModelRegistration() {
    }

    public ModelRegistration(String username, String password, String email, String passConfirmation) {
        this.username = username;
        this.password = password;
        this.email = email;
        this.passConfirmation = passConfirmation;
    }

    @Override
    public String toString() {
        return "ModelRegistration{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", emailConfirmation='" + passConfirmation + '\'' +
                '}';
    }
}
</code>```

Why doesn't it work?

Here is another use case:

The class where this checkAllFields is located:

ViewModelCredentialsRegister.java

```<code>public class ViewModelCredentialsRegister extends ViewModel {

    private MutableLiveData<Boolean> isPossibleToSendData = new MutableLiveData<>();

    public LiveData<Boolean> getIsPossibleToSendData() {
        if (isPossibleToSendData == null) {
            isPossibleToSendData = new MutableLiveData<>();
            isPossibleToSendData.setValue(false);
        }
        return isPossibleToSendData;
    }

    public void setIsPossibleToSendData(ModelRegistration mRegister) {
        isPossibleToSendData.setValue(checkAllFields(mRegister));
    }

    private boolean checkAllFields(ModelRegistration mRegister) {
        return
                Stream.of(mRegister.getUsername(), mRegister.getPassword(), mRegister.getPassConfirmation()).noneMatch(TextUtils::isEmpty);
    }
}
</code>```

FragmentCredentialsRegister.java

```<code>public class FragmentCredentialsRegister extends Fragment implements TextWatcher {

    private ViewModelCredentialsRegister viewModel;
    private FragmentCredentialsRegisterBinding binding;
    private ModelRegistration modelRegistration = new ModelRegistration();

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setToolbarText();

        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_credentials_register, container, false);
        viewModel = new ViewModelProvider(this).get(ViewModelCredentialsRegister.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        viewModel.getIsPossibleToSendData().observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                binding.bRegistration.setEnabled(aBoolean);
            }
        });

        binding.bRegistration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "yeah", Toast.LENGTH_SHORT).show();
            }
        });

        binding.etUsername.addTextChangedListener(this);
        binding.etPass.addTextChangedListener(this);
        binding.etPass.addTextChangedListener(this);
        binding.etEmail.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence c, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence c, int i, int i1, int i2) {
        if (binding.etUsername.getText().hashCode() == c.hashCode())
            modelRegistration.setUsername(c.toString());
        if (binding.etPass.getText().hashCode() == c.hashCode())
            modelRegistration.setPassword(c.toString());
        if (binding.etPassConfirmation.getText().hashCode() == c.hashCode())
            modelRegistration.setPassConfirmation(c.toString());
        if (binding.etEmail.getText().hashCode() == c.hashCode())
            modelRegistration.setEmail(c.toString());

        viewModel.setIsPossibleToSendData(modelRegistration);
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    private void setToolbarText() {
        ActionBar ab = ((AppCompatActivity) requireActivity()).getSupportActionBar();
        ab.setTitle(getString(R.string.app_name));
        ab.setSubtitle(getString(R.string.register));
    }
}
</code>```

答:
I found a mistake. I was setting         binding.etPass.addTextChangedListener(this);
twice instead of setting third field.</p>

Body:
I want to check if none elements from my registration form are not filled (all are filled) but my stream does not seem to work when I fill in all those 3 fields.

Here is what I do:

private boolean checkAllFields(ModelRegistration mRegister) {
    return Stream.of(mRegister.getUsername(), mRegister.getPassword(), mRegister.getPassConfirmation()).noneMatch(TextUtils::isEmpty);
}

ModelRegistration.java

public class ModelRegistration {

    private String username, password, passConfirmation, email;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassConfirmation() {
        return passConfirmation;
    }

    public void setPassConfirmation(String passConfirmation) {
        this.passConfirmation = passConfirmation;
    }

    public ModelRegistration() {
    }

    public ModelRegistration(String username, String password, String email, String passConfirmation) {
        this.username = username;
        this.password = password;
        this.email = email;
        this.passConfirmation = passConfirmation;
    }

    @Override
    public String toString() {
        return "ModelRegistration{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", emailConfirmation='" + passConfirmation + '\'' +
                '}';
    }
}

Why doesn't it work?

Here is another use case:

The class where this checkAllFields is located:

ViewModelCredentialsRegister.java

public class ViewModelCredentialsRegister extends ViewModel {

    private MutableLiveData<Boolean> isPossibleToSendData = new MutableLiveData<>();

    public LiveData<Boolean> getIsPossibleToSendData() {
        if (isPossibleToSendData == null) {
            isPossibleToSendData = new MutableLiveData<>();
            isPossibleToSendData.setValue(false);
        }
        return isPossibleToSendData;
    }

    public void setIsPossibleToSendData(ModelRegistration mRegister) {
        isPossibleToSendData.setValue(checkAllFields(mRegister));
    }

    private boolean checkAllFields(ModelRegistration mRegister) {
        return
                Stream.of(mRegister.getUsername(), mRegister.getPassword(), mRegister.getPassConfirmation()).noneMatch(TextUtils::isEmpty);
    }
}

FragmentCredentialsRegister.java

public class FragmentCredentialsRegister extends Fragment implements TextWatcher {

    private ViewModelCredentialsRegister viewModel;
    private FragmentCredentialsRegisterBinding binding;
    private ModelRegistration modelRegistration = new ModelRegistration();

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setToolbarText();

        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_credentials_register, container, false);
        viewModel = new ViewModelProvider(this).get(ViewModelCredentialsRegister.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        viewModel.getIsPossibleToSendData().observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                binding.bRegistration.setEnabled(aBoolean);
            }
        });

        binding.bRegistration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(), "yeah", Toast.LENGTH_SHORT).show();
            }
        });

        binding.etUsername.addTextChangedListener(this);
        binding.etPass.addTextChangedListener(this);
        binding.etPass.addTextChangedListener(this);
        binding.etEmail.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence c, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence c, int i, int i1, int i2) {
        if (binding.etUsername.getText().hashCode() == c.hashCode())
            modelRegistration.setUsername(c.toString());
        if (binding.etPass.getText().hashCode() == c.hashCode())
            modelRegistration.setPassword(c.toString());
        if (binding.etPassConfirmation.getText().hashCode() == c.hashCode())
            modelRegistration.setPassConfirmation(c.toString());
        if (binding.etEmail.getText().hashCode() == c.hashCode())
            modelRegistration.setEmail(c.toString());

        viewModel.setIsPossibleToSendData(modelRegistration);
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    private void setToolbarText() {
        ActionBar ab = ((AppCompatActivity) requireActivity()).getSupportActionBar();
        ab.setTitle(getString(R.string.app_name));
        ab.setSubtitle(getString(R.string.register));
    }
}


问:
How to use ssh-add to remove identities (pem files) from the agent
I can add pem files to my SSH agent very easily using ssh-add, like so:

```<code>$ ssh-add /home/jsmith/keys/mytest.pem
</code>```

But I can't seem to remove them:

```<code>$ ssh-add -d /home/jsmith/keys/mytest.pem
Bad key file /home/jsmith/keys/mytest.pem: No such file or directory
</code>```

The pem file still exists though... I haven't moved or changed it in any way.  Why am I having so much trouble removing this pem file from my SSH agent that I just added a moment ago?  What's the correct way to do this?

I want to avoid using ssh-add -D (with a capital "D") because that would delete all of the identities from my SSH agent, and I only want to delete the one I've specified.

答:
If you know the comment associated with the key you can simply get the public key from the agent and pipe it back in to delete it.</p>
```<code>ssh-add -L | grep -F 'test@example.com' | ssh-add -d -
</code>```

Body:
I can add pem files to my SSH agent very easily using ssh-add, like so:

$ ssh-add /home/jsmith/keys/mytest.pem

But I can't seem to remove them:

$ ssh-add -d /home/jsmith/keys/mytest.pem
Bad key file /home/jsmith/keys/mytest.pem: No such file or directory

The pem file still exists though... I haven't moved or changed it in any way.  Why am I having so much trouble removing this pem file from my SSH agent that I just added a moment ago?  What's the correct way to do this?

I want to avoid using ssh-add -D (with a capital "D") because that would delete all of the identities from my SSH agent, and I only want to delete the one I've specified.

Body:
If you know the comment associated with the key you can simply get the public key from the agent and pipe it back in to delete it.

ssh-add -L | grep -F 'test@example.com' | ssh-add -d -


问:
How to select two rows from a joined table
So i have two tables with information below one which is a holiday table which marks the location to and from and etc. and another table that has the information on the locations

holiday_id
location_from
location_to
start_time
end_time

1
21
43
13:00
17:00

Location_id
location_name

21
sydney

43
gold coast

I'd like to have an sql query which will return the names of the location to and from but because location name is under one column im not sure how to do it. any help is appreciated

答:
You can join with the table, twice, using an alias:</p>
```<code>select location_1.location_name, location_2.location_name, other, columns
from holidays
join locations location_1 on holidays.location_from = location_1.location_id
join locations location_2 on holidays.location_to   = location_2.location_id
</code>```

Body:
You can join with the table, twice, using an alias:

select location_1.location_name, location_2.location_name, other, columns
from holidays
join locations location_1 on holidays.location_from = location_1.location_id
join locations location_2 on holidays.location_to   = location_2.location_id


问:
How can we get HeaderId and FooterId from the response we get after batchUpdate request in google docs api using PHP?
I am working on google docs api. I want to insert text into header and footer simultaneously and for that I need header/footer id. So, for that I firstly created header/footer like this-

```<code>$requests[] = new Google_Service_Docs_Request(array(
  "createFooter" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "1",
    ],
    "type" => "DEFAULT",
  ],
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
</code>```

After this, when I print my $response using print_r($response), I can see my footer id.Like this -

```<code>
                    [createFooter] => Google\Service\Docs\CreateFooterResponse Object
                        (
                            [footerId] => kix.vv5nq4qsqioo
                            [internal_gapi_mappings:protected] => Array
                                (
                                )

                            [modelData:protected] => Array
                                (
                                )

                            [processed:protected] => Array
                                (
                                )

                        )

                )
</code>```

but,after this I am unable to get my footer id dynamically. How I can fetch my footer id from this response using PHP.

答:
You can just access the footerId from the response:

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
$footerId = $response->replies[0]->createFooter->footerId;
print($footerId);
```

Ref:

PHP: Objects

PHP: Arrays

Body:
I am working on google docs api. I want to insert text into header and footer simultaneously and for that I need header/footer id. So, for that I firstly created header/footer like this-

$requests[] = new Google_Service_Docs_Request(array(
  "createFooter" => [
    "sectionBreakLocation" => [
      "index" => 0,
      "segmentId" => "1",
    ],
    "type" => "DEFAULT",
  ],
));

$batchUpdateRequest = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
    'requests' => $requests
));

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);

After this, when I print my $response using print_r($response), I can see my footer id.Like this -

                    [createFooter] => Google\Service\Docs\CreateFooterResponse Object
                        (
                            [footerId] => kix.vv5nq4qsqioo
                            [internal_gapi_mappings:protected] => Array
                                (
                                )

                            [modelData:protected] => Array
                                (
                                )

                            [processed:protected] => Array
                                (
                                )

                        )

                )

but,after this I am unable to get my footer id dynamically. How I can fetch my footer id from this response using PHP.

Body:
You can just access the footerId from the response:

$response = $service->documents->batchUpdate($documentId, $batchUpdateRequest);
$footerId = $response->replies[0]->createFooter->footerId;
print($footerId);

Ref:

PHP: Objects

PHP: Arrays


问:
.NET Deploying Office 2003 Redistributable Primary Interop Assemblies (o2003pia.msi)
Has anyone out there actually succeeded in creating a prerequisitie for o2003.msi?

There are a lot of people out there asking about this, but I cannot find anyone who actually succeeded. I find some extremely complicated solutions where you are required to comple .cpp-files for which the soure may or may not be supplied. I even tried to complie one of those but got configuration error on the target machine... :-(

If I don't install o2003.msi, my Office "Shared Add-In" will throw an exception because office.dll cannot be found. So I would very much like to have it included in my installer.

And a second question, regardless of the outcome of the previous one: what about a machine with Office 2007? 02203.msi complains that Office 2003 is not installed, so there seems to be a lot of things I need to get done in order to create a working installer for an "Office Shared Add-In"... anyone else going through the same nightmare?

Update: It seems to be the PIA for Office.Core / "office.dll" which is the really thing to get on the traget machine. None of the "complicated" solutions (which I know I can get to work if I put some effort in it) talks how to detect this particular file, just PIAs for Word & Excel and then some. These seems to be in place anyway. It's office.dll that is the important file to check for and install o2003pia.msi if it is not properly installed!

答:
This is probably too little too late, but here's a solution I've done for installing our company's office 2003 and 2007 addins using a small bit of C# code. Maybe it could work for you.

I use the Product Codes for both the o2003pia and the o2007pia installations which are:

2003: {91490409-6000-11D3-8CFE-0150048383C9}

2007: {50120000-1105-0000-0000-0000000FF1CE}

Then, by calling the MSI API you can get the install state for each. Here's an example of finding the 2003:

```<code>[DllImport("msi.dll")]
    private static extern MsiInstallState MsiQueryProductState
        (string productGuid);
    [DllImport("msi.dll")]
    private static extern uint MsiGetProductInfo
        (string productGuid, string propertyName, StringBuilder valueBuffer, ref Int32 bufferSize);

    bool IsPia2003Installed()
    {
        MsiInstallState state = MsiQueryProductState("{91490409-6000-11D3-8CFE-0150048383C9}");

        return (state == MsiInstallState.msiInstallStateDefault);
    }
</code>```

If you're trying to accomplish all of this entirely inside the setup project (I assume you're using Visual Studio?) then you can add a "Windows Installer Search" launch condition that checks for the above mentioned ProductCodes. If it's satisfied you can run a custom action that installs the PIAs.

For more information on this solution I'd suggest starting here here.

OwnerDisplayName: danbystrom

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: danbystrom

Body:
This is probably too little too late, but here's a solution I've done for installing our company's office 2003 and 2007 addins using a small bit of C# code. Maybe it could work for you.

I use the Product Codes for both the o2003pia and the o2007pia installations which are:

2003: {91490409-6000-11D3-8CFE-0150048383C9}

2007: {50120000-1105-0000-0000-0000000FF1CE}

Then, by calling the MSI API you can get the install state for each. Here's an example of finding the 2003:

[DllImport("msi.dll")]
    private static extern MsiInstallState MsiQueryProductState
        (string productGuid);
    [DllImport("msi.dll")]
    private static extern uint MsiGetProductInfo
        (string productGuid, string propertyName, StringBuilder valueBuffer, ref Int32 bufferSize);

    bool IsPia2003Installed()
    {
        MsiInstallState state = MsiQueryProductState("{91490409-6000-11D3-8CFE-0150048383C9}");

        return (state == MsiInstallState.msiInstallStateDefault);
    }

If you're trying to accomplish all of this entirely inside the setup project (I assume you're using Visual Studio?) then you can add a "Windows Installer Search" launch condition that checks for the above mentioned ProductCodes. If it's satisfied you can run a custom action that installs the PIAs.

For more information on this solution I'd suggest starting here here.

OwnerDisplayName: Mel Green


问:
How add DropDownList without binding to ViewData?
I do:

```<code>    @Html.DropDownList("ddBrand", (IEnumerable<SelectListItem>)ViewBag.Brands, new {onchange = "JavaScript:Act()"})
</code>```

But when I press submit it needs the field "ddBrand" in View Model.

How can I add DropDownList to View without binding to ViewData? (without adding field "ddBrand" in View Model)

答:
Simply generate the HTML. You can create the options in a for loop. You can give different name to the id and name attributes.

```<code><select id="ddBrand" name="ddBrand">
  <option value="value">Text</option>
</select>
</code>```

Body:
I do:

    @Html.DropDownList("ddBrand", (IEnumerable<SelectListItem>)ViewBag.Brands, new {onchange = "JavaScript:Act()"})

But when I press submit it needs the field "ddBrand" in View Model.

How can I add DropDownList to View without binding to ViewData? (without adding field "ddBrand" in View Model)

Body:
Simply generate the HTML. You can create the options in a for loop. You can give different name to the id and name attributes.

<select id="ddBrand" name="ddBrand">
  <option value="value">Text</option>
</select>


问:
How to get Oracle Server Version using powershell?
I have a requirement in which I need to check whether oracle server installed and if installed, I need to find out the version also using Powershell. I got the below command

```<code>$OracleInstalled = get-wmiobject -Class win32_service | ?{$_.name -like '*ORACLESERV*' }
</code>```

But not sure this is correct or not. This only checks for the service I feel.

Anyone aware of this kindly help me.

答:
It gives:

ExitCode  : 0

Name      : OracleServiceORCL

ProcessId : 1980

StartMode : Auto
State     : Running

Status    : OK

Body:
I have a requirement in which I need to check whether oracle server installed and if installed, I need to find out the version also using Powershell. I got the below command

$OracleInstalled = get-wmiobject -Class win32_service | ?{$_.name -like '*ORACLESERV*' }

But not sure this is correct or not. This only checks for the service I feel.

Anyone aware of this kindly help me.


问:
Pandas dataframe: Check if regex contained in a column matches a string in another column in the same row
Input data is a Pandas dataframe:

```<code>df = pd.DataFrame()
df['strings'] = ['apple','house','hat','train','tan','note']
df['patterns'] = ['\\ba','\\ba','\\ba','n\\b','n\\b','n\\b']
df['group'] = ['1','1','1','2','2','2']

df

    strings patterns    group
0   apple   \ba         1
1   house   \ba         1
2   hat     \ba         1
3   train   n\b         2
4   tan     n\b         2
5   note    n\b         2

</code>```

The patterns column contains regex. \b is a regex pattern that matches on word boundaries. That means \ba would match with 'apple' because a is at the beginning of the word, while it would not match 'hat' because this a is in the middle of the word.

I want to use the regex in the patterns column to check if it matches with the strings column in the same row.

Desired result:

```<code>    strings patterns    group
0   apple   \ba         1
3   train   n\b         2
4   tan     n\b         2
</code>```

I got it to work below using re.search and a for loop that loops line by line. But this is very inefficient. I have millions of rows and this loop takes 5-10 minutes to run.

```<code>import re
for i in range(len(df)):
  pattern = df.at[i,"patterns"]
  test_string = df.at[i,"strings"]
  if re.search(pattern, test_string):
    df.at[i,'match'] = True
  else:
    df.at[i,'match'] = False

df.loc[df.match]
</code>```

Is there a way to do something like re.search(df['patterns'], df['strings'])?

This question appears to be similar: Python Pandas: Check if string in one column is contained in string of another column in the same row

However, the question and answers in the above link are not using regex to match, and I need to use regex to specify word boundaries.

答:
Compiling a regex is costly. In your example, you only have few regexes, so I would try to cache the compiled regex:

```<code>cache = dict()
def check(pattern, string):
    try:
        x = cache[pattern]
    except KeyError:
        x = re.compile(pattern)
        cache[pattern] = x
    return x.search(string)
mask = [bool(check(p, s)) for p, s in zip(df['patterns'], df['strings'])]
print(df.loc[mask])
</code>```

For your tiny dataframe it is slighly longer than @mozway's solution. But if I replicate it up to 60000 line, it saves up to 30% of execution time.

Body:
Input data is a Pandas dataframe:

df = pd.DataFrame()
df['strings'] = ['apple','house','hat','train','tan','note']
df['patterns'] = ['\\ba','\\ba','\\ba','n\\b','n\\b','n\\b']
df['group'] = ['1','1','1','2','2','2']

df

    strings patterns    group
0   apple   \ba         1
1   house   \ba         1
2   hat     \ba         1
3   train   n\b         2
4   tan     n\b         2
5   note    n\b         2

The patterns column contains regex. \b is a regex pattern that matches on word boundaries. That means \ba would match with 'apple' because a is at the beginning of the word, while it would not match 'hat' because this a is in the middle of the word.

I want to use the regex in the patterns column to check if it matches with the strings column in the same row.

Desired result:

    strings patterns    group
0   apple   \ba         1
3   train   n\b         2
4   tan     n\b         2

I got it to work below using re.search and a for loop that loops line by line. But this is very inefficient. I have millions of rows and this loop takes 5-10 minutes to run.

import re
for i in range(len(df)):
  pattern = df.at[i,"patterns"]
  test_string = df.at[i,"strings"]
  if re.search(pattern, test_string):
    df.at[i,'match'] = True
  else:
    df.at[i,'match'] = False

df.loc[df.match]

Is there a way to do something like re.search(df['patterns'], df['strings'])?

This question appears to be similar: Python Pandas: Check if string in one column is contained in string of another column in the same row

However, the question and answers in the above link are not using regex to match, and I need to use regex to specify word boundaries.

Body:
Compiling a regex is costly. In your example, you only have few regexes, so I would try to cache the compiled regex:

cache = dict()
def check(pattern, string):
    try:
        x = cache[pattern]
    except KeyError:
        x = re.compile(pattern)
        cache[pattern] = x
    return x.search(string)
mask = [bool(check(p, s)) for p, s in zip(df['patterns'], df['strings'])]
print(df.loc[mask])

For your tiny dataframe it is slighly longer than @mozway's solution. But if I replicate it up to 60000 line, it saves up to 30% of execution time.


问:
Running Apache (with .htaccess) App Behind Nginx Rerverse Proxy
I've recently begun trying to Dockerize my services and I'm to the point of Dockerizing everything that already has an image built. Now I'm trying to build an image for facileManager (FM) which doesn't yet have one. I've got it mostly working but I'm having an issue when running it behind Nginx. FM is normally an apache-php app and doesn't include install instructions for Nginx. What I've noticed with my container/image is that it works ok when I connect directly to it through a published port but if I try to connect to it through Nginx it errors out complaining about the .htaccess file not working. I'm not an expert in either Apache or Nginx so I did my Googleing but didn't come up with much beyond Wordpress having a similar issue with it's "pretty urls" so I'm hoping someone here can give a hand.

First here is the Github repo for the app: https://github.com/WillyXJ/facileManager/tree/ea159f5f6112727de8422c552aa05b6682aa4d79/server

The .htaccess file specifically is:

```<code><IfModule mod_headers.c>
    <FilesMatch "\.(js|css|txt)$">
        Header set Cache-Control "max-age=7200"
    </FilesMatch>
    <FilesMatch "\.(jpe?g|png|gif|ico)$">
        Header set Cache-Control "max-age=2592000"
    </FilesMatch>
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>
</code>```

The exact error I'm getting is from here:
https://github.com/WillyXJ/facileManager/blob/ea159f5f6112727de8422c552aa05b6682aa4d79/server/fm-includes/init.php#L153

```<code>if (!defined('INSTALL')) {
        if (@dns_get_record($_SERVER['SERVER_NAME'], DNS_A + DNS_AAAA)) {
            $test_output = getPostData($GLOBALS['FM_URL'] . 'admin-accounts.php?verify', array('module_type' => 'CLIENT'));
            $test_output = isSerialized($test_output) ? unserialize($test_output) : $test_output;
            if (strpos($test_output, 'Account is not found.') === false) {
                $message = sprintf(_('The required .htaccess file appears to not work with your Apache configuration which is required by %1s. '
                        . 'AllowOverride None in your configuration may be blocking the use of .htaccess or %s is not resolvable.'),
                        $fm_name, $_SERVER['SERVER_NAME']);
                if ($single_check) {
                    bailOut($message);
                } else {
                    $requirement_check .= displayProgress(_('Test Rewrites'), false, 'display', $message);
                    $error = true;
                }
            } else {
                if (!$single_check) $requirement_check .= displayProgress(_('Test Rewrites'), true, 'display');
            }
        }
    }
</code>```

Nginx config:

```<code>server {
        listen 80;

        server_tokens off;

        location /.well-known/acme-challenge/ {
                root /var/www/certbot;
        }

        location / {
                return 301 https://$host$request_uri;
        }
}

server {
        listen 443 ssl;

        server_name bound.example.com;

        ssl_certificate /etc/nginx/ssl/live/bound.example.com/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/live/bound.example.com/privkey.pem;
        include /etc/nginx/ssl/options-ssl-nginx.conf;
        ssl_dhparam /etc/nginx/ssl/ssl-dhparams.pem;

        location / {
                proxy_pass http://FM.;     <<< Docker service name
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        }
}
</code>```

My Dockerfile/commands run: https://github.com/MeCJay12/facileManager-docker

```<code>FROM php:7.4-apache

ENV TZ=UTC
ENV Version=4.2.0
ARG DEBIAN_FRONTEND=noninteractive
WORKDIR /src

RUN apt-get update \
    && apt-get -qqy install wget libldb-dev libldap2-dev tzdata \
    && wget http://www.facilemanager.com/download/facilemanager-complete-$Version.tar.gz \
    && tar -xvf facilemanager-complete-$Version.tar.gz \
    && mv facileManager/server/* /var/www/html/

RUN ln -s /usr/lib/x86_64-linux-gnu/libldap.so /usr/lib/libldap.so \
    && docker-php-ext-install mysqli ldap \
    && a2enmod rewrite dump_io

COPY php.ini /usr/local/etc/php/php.ini
RUN rm -r /src
</code>```

Bonus question: When accessing this container/image directly through a published port, the images are all broken. I assume it's related since the .htaccess file includes references to images files.

Thanks in advance for the help!

答: Found solution in https://github.com/WillyXJ/facileManager/issues/491. Needed to remove a check in the webapp that wasn't working quite right.</p>

Body:
I've recently begun trying to Dockerize my services and I'm to the point of Dockerizing everything that already has an image built. Now I'm trying to build an image for facileManager (FM) which doesn't yet have one. I've got it mostly working but I'm having an issue when running it behind Nginx. FM is normally an apache-php app and doesn't include install instructions for Nginx. What I've noticed with my container/image is that it works ok when I connect directly to it through a published port but if I try to connect to it through Nginx it errors out complaining about the .htaccess file not working. I'm not an expert in either Apache or Nginx so I did my Googleing but didn't come up with much beyond Wordpress having a similar issue with it's "pretty urls" so I'm hoping someone here can give a hand.

First here is the Github repo for the app: https://github.com/WillyXJ/facileManager/tree/ea159f5f6112727de8422c552aa05b6682aa4d79/server

The .htaccess file specifically is:

<IfModule mod_headers.c>
    <FilesMatch "\.(js|css|txt)$">
        Header set Cache-Control "max-age=7200"
    </FilesMatch>
    <FilesMatch "\.(jpe?g|png|gif|ico)$">
        Header set Cache-Control "max-age=2592000"
    </FilesMatch>
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>

The exact error I'm getting is from here:
https://github.com/WillyXJ/facileManager/blob/ea159f5f6112727de8422c552aa05b6682aa4d79/server/fm-includes/init.php#L153

if (!defined('INSTALL')) {
        if (@dns_get_record($_SERVER['SERVER_NAME'], DNS_A + DNS_AAAA)) {
            $test_output = getPostData($GLOBALS['FM_URL'] . 'admin-accounts.php?verify', array('module_type' => 'CLIENT'));
            $test_output = isSerialized($test_output) ? unserialize($test_output) : $test_output;
            if (strpos($test_output, 'Account is not found.') === false) {
                $message = sprintf(_('The required .htaccess file appears to not work with your Apache configuration which is required by %1s. '
                        . 'AllowOverride None in your configuration may be blocking the use of .htaccess or %s is not resolvable.'),
                        $fm_name, $_SERVER['SERVER_NAME']);
                if ($single_check) {
                    bailOut($message);
                } else {
                    $requirement_check .= displayProgress(_('Test Rewrites'), false, 'display', $message);
                    $error = true;
                }
            } else {
                if (!$single_check) $requirement_check .= displayProgress(_('Test Rewrites'), true, 'display');
            }
        }
    }

Nginx config:

server {
        listen 80;

        server_tokens off;

        location /.well-known/acme-challenge/ {
                root /var/www/certbot;
        }

        location / {
                return 301 https://$host$request_uri;
        }
}

server {
        listen 443 ssl;

        server_name bound.example.com;

        ssl_certificate /etc/nginx/ssl/live/bound.example.com/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/live/bound.example.com/privkey.pem;
        include /etc/nginx/ssl/options-ssl-nginx.conf;
        ssl_dhparam /etc/nginx/ssl/ssl-dhparams.pem;

        location / {
                proxy_pass http://FM.;     <<< Docker service name
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        }
}

My Dockerfile/commands run: https://github.com/MeCJay12/facileManager-docker

FROM php:7.4-apache

ENV TZ=UTC
ENV Version=4.2.0
ARG DEBIAN_FRONTEND=noninteractive
WORKDIR /src

RUN apt-get update \
    && apt-get -qqy install wget libldb-dev libldap2-dev tzdata \
    && wget http://www.facilemanager.com/download/facilemanager-complete-$Version.tar.gz \
    && tar -xvf facilemanager-complete-$Version.tar.gz \
    && mv facileManager/server/* /var/www/html/

RUN ln -s /usr/lib/x86_64-linux-gnu/libldap.so /usr/lib/libldap.so \
    && docker-php-ext-install mysqli ldap \
    && a2enmod rewrite dump_io

COPY php.ini /usr/local/etc/php/php.ini
RUN rm -r /src

Bonus question: When accessing this container/image directly through a published port, the images are all broken. I assume it's related since the .htaccess file includes references to images files.

Thanks in advance for the help!


问:
How to dynamically create y axis values for ticks on victory axis?
I have created a victory bar chart to show employee attrition. But y-axis of the chart is showing floating values instead of an integer but as employees' count can not be in floating point I want to show y-axis values in integer number only so the solution for the same is to define custom tick values as

```<code> <VictoryAxis tickValues={[2, 4, 6, 8]}/>
</code>```

But I don't know how I dynamically generate ticks array for my y-axis values.
Here is how my graph looks :

答:
So i was having a similar problem and struggled to find much help anywhere on this. The solution i came to was to ammend the tick using the tickFormat property of the VictoryAxis component.

```<code> < VictoryAxis
     tickFormat = {(t) => (Number.isInteger(t) ? t : null)}
     dependentAxis />
</code>```

This checks that the tick is defined as an integer and if so returns it otherwise sets the tick to be null.

Body:
I have created a victory bar chart to show employee attrition. But y-axis of the chart is showing floating values instead of an integer but as employees' count can not be in floating point I want to show y-axis values in integer number only so the solution for the same is to define custom tick values as

 <VictoryAxis tickValues={[2, 4, 6, 8]}/>

But I don't know how I dynamically generate ticks array for my y-axis values.
Here is how my graph looks :

Body:
So i was having a similar problem and struggled to find much help anywhere on this. The solution i came to was to ammend the tick using the tickFormat property of the VictoryAxis component.

 < VictoryAxis
     tickFormat = {(t) => (Number.isInteger(t) ? t : null)}
     dependentAxis />

This checks that the tick is defined as an integer and if so returns it otherwise sets the tick to be null.


问:
How to create an array of objects with all objects from multiple arrays?
Given de following arrays:

```<code>const classes = [
  {
    students: [
       Student1,
       Student2,
    ]
  },
  {
    students: [
       Student3,
       Student4,
    ]
  }
]
</code>```

What's the best way performance-wise to generate an array of objects with a similar structure to this:

```<code>const allStudents = [
  Student1,
  Student2,
  Student3,
  Student4
]

</code>```

答:
```<code>const classes = [
  {
    students:[
   "Student1",
   "Student2"
    ]
  },
  {
    students:[
   "Student3",
   "Student4"
    ]
  }
]

const n=classes.flatMap(x=>x.students.flatMap(i=>i))
console.log(n)
</code>```

This would be recommended keeping performance in mind it is faster then regular for loop and ... many online sources say flatMap is better in terms of performance

Body:
Given de following arrays:

const classes = [
  {
    students: [
       Student1,
       Student2,
    ]
  },
  {
    students: [
       Student3,
       Student4,
    ]
  }
]

What's the best way performance-wise to generate an array of objects with a similar structure to this:

const allStudents = [
  Student1,
  Student2,
  Student3,
  Student4
]

Body:
const classes = [
  {
    students:[
   "Student1",
   "Student2"
    ]
  },
  {
    students:[
   "Student3",
   "Student4"
    ]
  }
]

const n=classes.flatMap(x=>x.students.flatMap(i=>i))
console.log(n)

This would be recommended keeping performance in mind it is faster then regular for loop and ... many online sources say flatMap is better in terms of performance


问:
JQuery AJAX is not sending UTF-8 to my server, only in IE
I am sending UTF-8, japanese text, to my server.
It works in Firefox.  My access.log and headers are:

```<code>/ajax/?q=%E6%BC%A2%E5%AD%97
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
</code>```

Howeer, in IE8, my access.log says:

```<code>/ajax/?q=??
</code>```

For some reason, IE8 is turning my AJAX call into question marks.  Why!? I added the scriptCharset and ContentType according to some tutorials, but still no luck.

And this is my code:

```<code>$.ajax({
    method:"get",
    url:"/ajax/",
    scriptCharset: "utf-8" ,
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data:"q="+query ...,
    ...
    })
</code>```

答:
I know this is an old post but I had this problem recently and I'd like to contribute just in case someone else has the same problem.
I'm using PHP but I'm sure there's an option on every serverside language. It was just a couple of things:

Make sure you're sending the right headers on your ajax response by adding header('Content-Type: text/html; charset=utf-8'); This must be your first line. If you have any errors saying that headers have been sent already or something like that is because somewhere in your code you are outputing an extra space or something before sending the header so check your code.

When you build your response in your server, make sure you convert all your chars to the correspondig HTML char using echo htmlentities($your-string, null, 'utf-8); Because even after telling IE that you are sending utf-8 data, it seems like IE forgets that or it doesn't simply assume anything so adding this to your code will ensure the right output.

Thanks all for your help.

Body:
I am sending UTF-8, japanese text, to my server.
It works in Firefox.  My access.log and headers are:

/ajax/?q=%E6%BC%A2%E5%AD%97
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Content-Type    application/x-www-form-urlencoded; charset=UTF-8

Howeer, in IE8, my access.log says:

/ajax/?q=??

For some reason, IE8 is turning my AJAX call into question marks.  Why!? I added the scriptCharset and ContentType according to some tutorials, but still no luck.

And this is my code:

$.ajax({
    method:"get",
    url:"/ajax/",
    scriptCharset: "utf-8" ,
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data:"q="+query ...,
    ...
    })


答:
```<code>select a.location_name,b.location_name from table1
left join table2 on table2.Location_id = table1.location_from
left join table2 on table2.Location_id = table1.location_to
</code>```

Title: How to select two rows from a joined table

Body:
So i have two tables with information below one which is a holiday table which marks the location to and from and etc. and another table that has the information on the locations

holiday_id
location_from
location_to
start_time
end_time

1
21
43
13:00
17:00

Location_id
location_name

21
sydney

43
gold coast

I'd like to have an sql query which will return the names of the location to and from but because location name is under one column im not sure how to do it. any help is appreciated


问:
Using RabbitMQ with Celery in Django post_save
I am applying asynchronous task handling using Celery on my Django Project.

My project's logic:,

from frontend side, there is a table with rows each having an upload button. User clicks on it and a payload is sent to backend containing a url that contains a file.

File is recieved in django views. And saved into database, table Run. Immediately object is saved a post_save signal is triggered to run a celery task.

The task to be performed is, fetch a list of runs with specific status. For each run, perform a task of downloading the file.

I would like to perform this asynchronously in case there is more than one run. Keeping in mind user can click upload for more than one row from frontend.

I am setting up RabbitMQ as my broker. I have rabbitMQ installed and running. I have set the CELERY_BROKER_URL='amqp://localhost' too in settings.py. I am a little lost on what I should do next in my configurations, could I get some guidance. I think I need to configure celery worker on my tasks.

Below is my code so far :

views.py #view that saves to database

```<code>class RunsUploadView(APIView):
    serializer_class = RunsURLSerializer

    def post(self, request,  *args, **kwargs):
        crawler_name = self.request.data.get('crawler')
        run_id = self.kwargs.get("run_id")
        run_url = self.request.data.get("run_url")

        run = Run()
        run.name = f"{crawler_name}_{run_id}"
        run.run = run_id
        run.url = run_url
        run.save()

        return Response(model_to_dict(run))
</code>```

models.py # run is saved to table Run then a post_save signal is triggered.

```<code>from django.db import models

class Run(models.Model):
    UPLOAD_STATUS = (
        ("Pending", "pending"),
        ("Running", "running"),
        ("Success", "success"),
        ("Failed", "failed"),
    )
    name = models.CharField(max_length=100)
    run = models.CharField(max_length=100, unique=True)
    url = models.URLField(max_length=1000)
    status = models.CharField(
        max_length=50, choices=UPLOAD_STATUS, default="Pending")
    started_at = models.DateTimeField(null=True)
    done_at = models.DateTimeField(null=True)
</code>```

signals.py #handling the post_save logic after save()

```<code>from django.db.models.signals import post_save
from django.dispatch import receiver
from main.models import Run
from main.tasks import DownloadRun

@receiver(post_save, sender=Run)
def download_file(sender, **kwargs):
    pending_runs = Run.objects.filter(status='Pending') #all pending runs collected, I would need to handle the runs asynchronously.
    for run in pending_runs:
        run.status = "Started"
        run.save()
        DownloadRun(run)
</code>```

Tasks.py #using a class because I am going to update with more functions.

```<code>class DownloadRun:
    def __init__(self, run):
        run_object = model_to_dict(run)
        self.run_url = run_object["url"]

        self.download_run()

    def download_run(self, dest_folder="runs"):
        ""Run file is downloaded from url""
</code>```

答:
I figured out the way forward. I did not configure celery well.

tasks.py

```<code>from celery import shared_task #import shared_task decorator from celery
class DownloadRun:
    def __init__(self, run):
        run_object = model_to_dict(run)
        self.run_url = run_object["url"]

        self.download_run()

    def download_run(self, dest_folder="runs"):
        ""Run file is downloaded from url""

@shared_task
def celery_task(run_id):
    DownloadRun(run_id)
</code>```

signals.py

```<code>from django.db.models.signals import post_save
from django.dispatch import receiver
from main.models import Run
from main.tasks import celery_task #import celery_task from tasks.py

@receiver(post_save, sender=Run)
def download_file(sender, **kwargs):
    pending_runs = Run.objects.filter(status='Pending')
    for run in pending_runs:
        run.status = "Started"
        run.save()
        celery_task.delay(run.run) #call celery delay() to invoke the task (pass the unique key as parameter, could be id, in my case I chose the run)

</code>```

Body:
I am applying asynchronous task handling using Celery on my Django Project.

My project's logic:,

from frontend side, there is a table with rows each having an upload button. User clicks on it and a payload is sent to backend containing a url that contains a file.

File is recieved in django views. And saved into database, table Run. Immediately object is saved a post_save signal is triggered to run a celery task.

The task to be performed is, fetch a list of runs with specific status. For each run, perform a task of downloading the file.

I would like to perform this asynchronously in case there is more than one run. Keeping in mind user can click upload for more than one row from frontend.

I am setting up RabbitMQ as my broker. I have rabbitMQ installed and running. I have set the CELERY_BROKER_URL='amqp://localhost' too in settings.py. I am a little lost on what I should do next in my configurations, could I get some guidance. I think I need to configure celery worker on my tasks.

Below is my code so far :

views.py #view that saves to database

class RunsUploadView(APIView):
    serializer_class = RunsURLSerializer

    def post(self, request,  *args, **kwargs):
        crawler_name = self.request.data.get('crawler')
        run_id = self.kwargs.get("run_id")
        run_url = self.request.data.get("run_url")

        run = Run()
        run.name = f"{crawler_name}_{run_id}"
        run.run = run_id
        run.url = run_url
        run.save()

        return Response(model_to_dict(run))

models.py # run is saved to table Run then a post_save signal is triggered.

from django.db import models

class Run(models.Model):
    UPLOAD_STATUS = (
        ("Pending", "pending"),
        ("Running", "running"),
        ("Success", "success"),
        ("Failed", "failed"),
    )
    name = models.CharField(max_length=100)
    run = models.CharField(max_length=100, unique=True)
    url = models.URLField(max_length=1000)
    status = models.CharField(
        max_length=50, choices=UPLOAD_STATUS, default="Pending")
    started_at = models.DateTimeField(null=True)
    done_at = models.DateTimeField(null=True)

signals.py #handling the post_save logic after save()

from django.db.models.signals import post_save
from django.dispatch import receiver
from main.models import Run
from main.tasks import DownloadRun

@receiver(post_save, sender=Run)
def download_file(sender, **kwargs):
    pending_runs = Run.objects.filter(status='Pending') #all pending runs collected, I would need to handle the runs asynchronously.
    for run in pending_runs:
        run.status = "Started"
        run.save()
        DownloadRun(run)

Tasks.py #using a class because I am going to update with more functions.

class DownloadRun:
    def __init__(self, run):
        run_object = model_to_dict(run)
        self.run_url = run_object["url"]

        self.download_run()

    def download_run(self, dest_folder="runs"):
        ""Run file is downloaded from url""

Body:
I figured out the way forward. I did not configure celery well.

tasks.py

from celery import shared_task #import shared_task decorator from celery
class DownloadRun:
    def __init__(self, run):
        run_object = model_to_dict(run)
        self.run_url = run_object["url"]

        self.download_run()

    def download_run(self, dest_folder="runs"):
        ""Run file is downloaded from url""

@shared_task
def celery_task(run_id):
    DownloadRun(run_id)

signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from main.models import Run
from main.tasks import celery_task #import celery_task from tasks.py

@receiver(post_save, sender=Run)
def download_file(sender, **kwargs):
    pending_runs = Run.objects.filter(status='Pending')
    for run in pending_runs:
        run.status = "Started"
        run.save()
        celery_task.delay(run.run) #call celery delay() to invoke the task (pass the unique key as parameter, could be id, in my case I chose the run)


问:
How to set the dockerfile and environment variables while making lambda in CDK
I have SAM project in template.yml

```<code>Globals:
  Function:
    Timeout: 30
    Environment:
      Variables:
        DBNAME: !Ref DBNAME

Resources:
  MessageFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      Architectures:
        - x86_64
      Events:
        Message:
          Type: Api
          Properties:
            Path: /message
            Method: post
    Metadata:
      Dockerfile: Dockerfile.message
      DockerContext: ./botapp
      DockerTag: python3.9-v1
</code>```

then deploy like this

sam deploy --guided --parameter-overrides DBNAME=mydb

It means I will set environment variables DBNAME=mydb and build image from Dockerfile.message.

It works well for now.

However now I want to move this to cdk

So, in cdk I first wrote this code

```<code>const messageLambda = new lambda.DockerImageFunction(this, "BotLambda", {
  code: lambda.DockerImageCode.fromImageAsset("chatbot-sam/botapp"),
});
</code>```

However I want to set the dockerfile and environment variables.

For example

```<code>const messageLambda = new lambda.DockerImageFunction(this, "BotLambda", {
  code: lambda.DockerImageCode.fromImageAsset(
         "chatbot-sam/botapp",
         dockerfile: Dockerfile.message,
         enviroment_variables: { DBNAME:'mydb'}
       ),
});
</code>```

Above code is not correct, however my idea is ok?

How can I indicate Dockerfile and environment variables?

答:
As you can see in the DockerImageCode.fromImageAsset() docs, you can specify a relative path to the Dockerfile in the file parameter.

As for environment variables for the lambda itself, the docs for lambda.DockerImageFunction explain this as well. You define the environment variable with the environment attribute:

environment?

Type: { [string]: string } (optional, default: No environment
variables.)

Key-value pairs that Lambda caches and makes available for your Lambda
functions.

So it would look like this:

```<code>const messageLambda = new lambda.DockerImageFunction(this, "BotLambda", {
  code: lambda.DockerImageCode.fromImageAsset(
         "chatbot-sam/botapp",
         {
            file: "Dockerfile.message",
         }
       ),
  environment: { DBNAME:'mydb'}
});
</code>```

Body:
I have SAM project in template.yml

Globals:
  Function:
    Timeout: 30
    Environment:
      Variables:
        DBNAME: !Ref DBNAME

Resources:
  MessageFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      Architectures:
        - x86_64
      Events:
        Message:
          Type: Api
          Properties:
            Path: /message
            Method: post
    Metadata:
      Dockerfile: Dockerfile.message
      DockerContext: ./botapp
      DockerTag: python3.9-v1

then deploy like this

sam deploy --guided --parameter-overrides DBNAME=mydb

It means I will set environment variables DBNAME=mydb and build image from Dockerfile.message.

It works well for now.

However now I want to move this to cdk

So, in cdk I first wrote this code

const messageLambda = new lambda.DockerImageFunction(this, "BotLambda", {
  code: lambda.DockerImageCode.fromImageAsset("chatbot-sam/botapp"),
});

However I want to set the dockerfile and environment variables.

For example

const messageLambda = new lambda.DockerImageFunction(this, "BotLambda", {
  code: lambda.DockerImageCode.fromImageAsset(
         "chatbot-sam/botapp",
         dockerfile: Dockerfile.message,
         enviroment_variables: { DBNAME:'mydb'}
       ),
});

Above code is not correct, however my idea is ok?

How can I indicate Dockerfile and environment variables?

Body:
As you can see in the DockerImageCode.fromImageAsset() docs, you can specify a relative path to the Dockerfile in the file parameter.

As for environment variables for the lambda itself, the docs for lambda.DockerImageFunction explain this as well. You define the environment variable with the environment attribute:

environment?

Type: { [string]: string } (optional, default: No environment
variables.)

Key-value pairs that Lambda caches and makes available for your Lambda
functions.

So it would look like this:

const messageLambda = new lambda.DockerImageFunction(this, "BotLambda", {
  code: lambda.DockerImageCode.fromImageAsset(
         "chatbot-sam/botapp",
         {
            file: "Dockerfile.message",
         }
       ),
  environment: { DBNAME:'mydb'}
});


问:
onclick remove, html
I am working with webapp-net to build an application for iOS/android. in my app I have a form with some text fields. I want to have a "X" icon that usually appear on text fields when an input is entered. by clicking on that icon you can remove the whole input in just one click. The icon "X" appears only when an input is entered, when the textfield is empty the icon is not visible. If you could just give me an example of how to do it, I would really appreciate it.</p>

答:
this simple html shows how to have an input field and a X button that calls a clean function when pressed

```<code><input type="text" onkeypress="show();" id="text" /><div id="close" onclick="clean();" style="display:none">x</div>
</code>```

Now the javascript

```<code><script type="text/javascript">
   function show(){
      document.getElementById('close').style.display = ''; //shows the X button when text is entered;
   }

   function clean(){
      document.getElementById('close').style.display = 'none'; //hides the X button
      document.getElementById('text').value = ""; //clears the field
   }
</script>
</code>```

Of course this lacks validations like what type of key is pressed to avoid showing the X button when you press SHIFT or CTRL

Title: onclick remove, html

Body:
this simple html shows how to have an input field and a X button that calls a clean function when pressed

<input type="text" onkeypress="show();" id="text" /><div id="close" onclick="clean();" style="display:none">x</div>

Now the javascript

<script type="text/javascript">
   function show(){
      document.getElementById('close').style.display = ''; //shows the X button when text is entered;
   }

   function clean(){
      document.getElementById('close').style.display = 'none'; //hides the X button
      document.getElementById('text').value = ""; //clears the field
   }
</script>

Of course this lacks validations like what type of key is pressed to avoid showing the X button when you press SHIFT or CTRL


问:
Unread count for Public Dialog in Quickblox
In our application, we are having users join a bunch of public dialogs when they log in to the app for the first time.
From the next time they open the app, we would like to show the unread count but the SDK is always returning the unread count as 0.
Does Quickblox support the unread message count parameter for public dialogs as they do for group dialogs?</p>

答:
You cannot get count of unread messages in public dialogs, turned out it is expected.

Works only for group/private dialogs.


问:
How is CPython implemented?
So I lately came across an explanation for Python's interpreter and compiler (CPython specifically).

Please correct me if I'm wrong. I just want to be sure I understand these specific concepts.

So CPython gets both compiled (to bytecode) and then interpreted (in the PVM)?
And what does the PVM do exactly? Does it read the bytecode line by line, and translate each one to binary instructions that can be executed on a specific computer?
Does this mean that a computer based on an Intel processor needs a different PVM from an AMD-based computer?

答:
Yes, CPython is compiled to bytecode which is then executed by the virtual machine.

The virtual machine executes instructions one-by-one. It's written in C (but you can write it in another language) and looks like a huge if/else statement like "if the current instruction is this, do this; if the instruction is this, do another thing", and so on. Instructions aren't translated to binary - that's why it's called an interpreter.

You can find the list of instructions here: https://docs.python.org/3.10/library/dis.html#python-bytecode-instructions

The implementation of the VM is available here: https://github.com/python/cpython/blob/f71a69aa9209cf67cc1060051b147d6afa379bba/Python/ceval.c#L1718

Bytecode doesn't have a concept of "line": it's just a stream of bytes. The interpreter can read one byte at a time and use another if/else statement to decide what instruction it's looking at. For example:
```<code>curr_byte = read_byte()
if curr_byte == 0x00:
   # Parse instruction with no arguments
   curr_instruction = DO_THING_A;
   args = NULL;
elif curr_byte == 0x01:
   another_byte = read_byte()
   if another_byte == 0x00:
      # Parse a two-byte instruction
      curr_instruction = DO_THING_B;
      args = NULL;
   else:
      # Parse a one-byte instruction
      # with one argument
      curr_instruction = DO_THING_C;
      args = another_byte >> 1; # or whatever
elif curr_byte == ...:
   ... # go on and on and on
</code>```

The entire point of bytecode is that it can be executed by another program (the interpreter, or virtual machine) on almost any hardware. For example, in order to get CPython running on new hardware, you'll need a C toolchain (compiler, linker, assembler etc) for this hardware and a bunch of functions that Python can call to do low-level stuff (allocate memory, output text, do networking etc). Once you have that, write C code that can execute the bytecode - and that's it.

Title: How is CPython implemented?

Body:
Yes, CPython is compiled to bytecode which is then executed by the virtual machine.

The virtual machine executes instructions one-by-one. It's written in C (but you can write it in another language) and looks like a huge if/else statement like "if the current instruction is this, do this; if the instruction is this, do another thing", and so on. Instructions aren't translated to binary - that's why it's called an interpreter.

You can find the list of instructions here: https://docs.python.org/3.10/library/dis.html#python-bytecode-instructions

The implementation of the VM is available here: https://github.com/python/cpython/blob/f71a69aa9209cf67cc1060051b147d6afa379bba/Python/ceval.c#L1718

Bytecode doesn't have a concept of "line": it's just a stream of bytes. The interpreter can read one byte at a time and use another if/else statement to decide what instruction it's looking at. For example:

curr_byte = read_byte()
if curr_byte == 0x00:
   # Parse instruction with no arguments
   curr_instruction = DO_THING_A;
   args = NULL;
elif curr_byte == 0x01:
   another_byte = read_byte()
   if another_byte == 0x00:
      # Parse a two-byte instruction
      curr_instruction = DO_THING_B;
      args = NULL;
   else:
      # Parse a one-byte instruction
      # with one argument
      curr_instruction = DO_THING_C;
      args = another_byte >> 1; # or whatever
elif curr_byte == ...:
   ... # go on and on and on

The entire point of bytecode is that it can be executed by another program (the interpreter, or virtual machine) on almost any hardware. For example, in order to get CPython running on new hardware, you'll need a C toolchain (compiler, linker, assembler etc) for this hardware and a bunch of functions that Python can call to do low-level stuff (allocate memory, output text, do networking etc). Once you have that, write C code that can execute the bytecode - and that's it.


问:
promise catch: how to know if the error comes from promise rejection or from the then statement
Imagine a function that returns a promise (for example fetch from fetch API):

```<code>fetch(...)
.then((response) => {...})
.catch((error) => {...});
</code>```

How can I know if the error inside the catch statement has been originated due to a promise rejection instead from the code inside the then statement?

Something like the following will work:

```<code>let success = false;
fetch(...)
.then((response) => {success = true; ...})
.catch((error) => {if(success) ...});
</code>```

But I want to know if there is a better or more native way to do it. I have also tried to do something like:

```<code>fetch(...)
.catch((promiseError) => {...});
.then((response) => {...})
.catch((thenError) => {...});
</code>```

But I think it doesn't work because response isn't forwarded to the thenstatement (or at least that's what TS says).

Which would be the better way?

答:
then accepts two parameters¹: A function to call on fulfillment, and another to call on rejection. So you can handle the initial rejection earlier:

```<code>fetch(/*...*/)
.then(
    // Fulfillment handler
    (response) => {
        /*...*/
    },
    // Rejection handler for `fetch` promise
    (error) => {
        /*...*/
    }
)
.catch((error) => {
    // This rejection handler only sees errors not handled above
});
</code>```

The first rejection handler (in the then call) is only called for rejections of the promise from fetch, not rejections caused by errors in the fulfillment handler.

The second rejection handler (in the catch call) is called for rejections caused by errors (or rejected promises) from the handlers that come before it (either fulfillment or rejection); it doesn't get called if the original promise is rejected (but it may well get called if the first rejection handler throws an error or returns a promise that is/will be rejected).

So in those cases where you care, you can handle it closer to the source.

Note that all rejection handlers that don't either throw an error or return a promise that is/will be rejected convert rejection (of the original promise) into fulfillment (of the one from then/catch). That can matter for downstream then handlers.

A key thing to understanding this is to remember that then (and its wrappers catch and finally) return a new promise. That's why:

```<code>aPromise.then(onFulfilled).catch(onRejected);
</code>```

is different from

```<code>aPromise.then(onFulfilled, onRejected);
</code>```

The first one hooks up a fulfillment handler to aPromise, and then hooks up a rejection handler to the promise then returns (which means the rejection handler will be called if aPromise rejects or if the fulfillment handler throws an error or returns a promise that rejects). In contrast, the second one only hooks up handlers on aPromise, so errors/rejections from the fulfillment handler do not trigger the rejection handler.

¹ In fact, .catch(fn) is just a wrapper for .then(undefined, fn). :-) spec link

Body:
Imagine a function that returns a promise (for example fetch from fetch API):

fetch(...)
.then((response) => {...})
.catch((error) => {...});

How can I know if the error inside the catch statement has been originated due to a promise rejection instead from the code inside the then statement?

Something like the following will work:

let success = false;
fetch(...)
.then((response) => {success = true; ...})
.catch((error) => {if(success) ...});

But I want to know if there is a better or more native way to do it. I have also tried to do something like:

fetch(...)
.catch((promiseError) => {...});
.then((response) => {...})
.catch((thenError) => {...});

But I think it doesn't work because response isn't forwarded to the thenstatement (or at least that's what TS says).

Which would be the better way?

Body:
then accepts two parameters¹: A function to call on fulfillment, and another to call on rejection. So you can handle the initial rejection earlier:

fetch(/*...*/)
.then(
    // Fulfillment handler
    (response) => {
        /*...*/
    },
    // Rejection handler for `fetch` promise
    (error) => {
        /*...*/
    }
)
.catch((error) => {
    // This rejection handler only sees errors not handled above
});

The first rejection handler (in the then call) is only called for rejections of the promise from fetch, not rejections caused by errors in the fulfillment handler.

The second rejection handler (in the catch call) is called for rejections caused by errors (or rejected promises) from the handlers that come before it (either fulfillment or rejection); it doesn't get called if the original promise is rejected (but it may well get called if the first rejection handler throws an error or returns a promise that is/will be rejected).

So in those cases where you care, you can handle it closer to the source.

Note that all rejection handlers that don't either throw an error or return a promise that is/will be rejected convert rejection (of the original promise) into fulfillment (of the one from then/catch). That can matter for downstream then handlers.

A key thing to understanding this is to remember that then (and its wrappers catch and finally) return a new promise. That's why:

aPromise.then(onFulfilled).catch(onRejected);

is different from

aPromise.then(onFulfilled, onRejected);

The first one hooks up a fulfillment handler to aPromise, and then hooks up a rejection handler to the promise then returns (which means the rejection handler will be called if aPromise rejects or if the fulfillment handler throws an error or returns a promise that rejects). In contrast, the second one only hooks up handlers on aPromise, so errors/rejections from the fulfillment handler do not trigger the rejection handler.

¹ In fact, .catch(fn) is just a wrapper for .then(undefined, fn). :-) spec link


问:
ERC1155 Creating NFT
```<code>pragma solidity ^0.8.0;

//import ERC1155 token contract from OpenZeppelin
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";

contract NFTXXX is ERC1155, Ownable {

    uint256 public constant Arcadiy = 0;
    uint256 public constant MAX = 1;

    constructor() ERC1155("http://ipfs.io/ipfs/{id}.json") {
        _mint(msg.sender, Arcadiy, 1, "");
        _mint(msg.sender, MAX, 2, "");
    }

    function mint(address account, uint256 id, uint256 amount) public onlyOwner {
        _mint(account, id, amount, "");
    }

    function burn(address account, uint256 id, uint256 amount) public {
        require(msg.sender == account);
        _burn(account, id, amount);

    }
}
</code>```

Images do not appear on OpenSea(testnet)

There are json files that i use for contract.

```<code>{
"image": "ipfs://bafybeienrrxym2d3b5u7glcvdrz63rztxkue7p4bly4fcsma55nupmxsvy",
"description": "My first plant",
"name": "Cactus Arcadiy"
</code>```

}

```<code>{
"image": "ipfs://bafybeieh4lcllyimopk6pmacjyx4atgdqsywvsia6nuuq6niucdqxwbq5i",
"description": "GoodZone is a banya with pool",
"name": "Banya"
</code>```

}

I think something is wrong with the referense for images ("http://ipfs.io/ipfs/{id}.json"), but i didn't find resolve.

答:
Your image uri from the metadata is working though.

It seems that you treat the http://ipfs.io/ipfs/{id}.json as your NFT's Metadata storage place (actually it is NOT), which might cause error like TOKEN_0 (Arcadiy) would try to retrieve your metadata in http://ipfs.io/ipfs/0.json.

Therefore, you should replace it with your own storage address, i.e., place your NFT Metadata to ipfs again and set the tokenURI to it.

Title: ERC1155 Creating NFT

Body:
pragma solidity ^0.8.0;

//import ERC1155 token contract from OpenZeppelin
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";

contract NFTXXX is ERC1155, Ownable {

    uint256 public constant Arcadiy = 0;
    uint256 public constant MAX = 1;

    constructor() ERC1155("http://ipfs.io/ipfs/{id}.json") {
        _mint(msg.sender, Arcadiy, 1, "");
        _mint(msg.sender, MAX, 2, "");
    }

    function mint(address account, uint256 id, uint256 amount) public onlyOwner {
        _mint(account, id, amount, "");
    }

    function burn(address account, uint256 id, uint256 amount) public {
        require(msg.sender == account);
        _burn(account, id, amount);

    }
}

Images do not appear on OpenSea(testnet)

There are json files that i use for contract.

{
"image": "ipfs://bafybeienrrxym2d3b5u7glcvdrz63rztxkue7p4bly4fcsma55nupmxsvy",
"description": "My first plant",
"name": "Cactus Arcadiy"

}

{
"image": "ipfs://bafybeieh4lcllyimopk6pmacjyx4atgdqsywvsia6nuuq6niucdqxwbq5i",
"description": "GoodZone is a banya with pool",
"name": "Banya"

}

I think something is wrong with the referense for images ("http://ipfs.io/ipfs/{id}.json"), but i didn't find resolve.


问:
Skip a line using BufferedReader (skip, but not read it)
Hi guys I am currently using BufferedReader to read files. I have something like:

```<code>br.readLine() != null
</code>```

for each call loop.

And now what should I do if I want to skip a line. Here, I've read several similar questions other people posted, most of them suggested using readLine().

I know calling readLine() once will cause the pointer to the next line. But this is not preferred as I am considering the reading performance here. Although you seem to skip a line, the system actually read it already, so it is not time-efficiency. What I want is to move the pointer to the next line, without reading it.

Any good idea?

答:
You'll sometimes have a problem skipping the first line with code analysis tools (sonar etc), complaining that you didn't use the value.  In the case of CSV, you may want to skip (i.e. not use) the first row if its headers.  In which case, you could stream the lines and skip perhaps?</p>
```<code>try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
  Stream<String> lines = reader.lines().skip(1);

  lines.forEachOrdered(line -> {

  ...
  });
}
</code>```

Body:
Hi guys I am currently using BufferedReader to read files. I have something like:

br.readLine() != null

for each call loop.

And now what should I do if I want to skip a line. Here, I've read several similar questions other people posted, most of them suggested using readLine().

I know calling readLine() once will cause the pointer to the next line. But this is not preferred as I am considering the reading performance here. Although you seem to skip a line, the system actually read it already, so it is not time-efficiency. What I want is to move the pointer to the next line, without reading it.

Any good idea?

Body:
You'll sometimes have a problem skipping the first line with code analysis tools (sonar etc), complaining that you didn't use the value.  In the case of CSV, you may want to skip (i.e. not use) the first row if its headers.  In which case, you could stream the lines and skip perhaps?

try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
  Stream<String> lines = reader.lines().skip(1);

  lines.forEachOrdered(line -> {

  ...
  });
}


问:
IIB - ODBC DSN configuration errors (Windows)
I previous installed IIB version 9 on Windows 7. The ODBC drivers appear in both "Microsoft ODBC Administrator" (32-bit) and "Data Sources x64 (ODBC)".

I have now installed IIB version 10 (10.0.0.21 Developer edition) alongside it, and the x64 data sources window doesn't show the version 10 drivers.

Additionally, I can create data sources (System DSN) under Version 10.0.0.21 using the 32-bit version of the administrator tool, but when I try to delete the Data Source I get the following messages:

The setup routines for the IBM Integration Bus 10.0.0.21 Developer Edition - DataDirect Technologies 64-BIT Oracle Wire Protoco [sic] ODBC driver could not be found. Please reinstall the driver.

Driver's ConfigDSN, ConfigDriver, or ConfigTranslator failed. Errors Found: Component not found in registry

I can create and delete IIB9 Data Sources just fine, using either tool.

The fact that the name of the driver is cut off in the quote implies to me that there is an issue with some max name length being surpassed, but I don't know if that's true or not. I have tried editing the registry to make the name match that seen in the textbox (in accordance with some instructions I saw online), but it just made the driver details change in the 32-bit UI and still not appear in the 64-bit.

In the registry I have the following:

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\IBM Integration (9.0.0.2) - DataDirect Technologies 7.0 64-BIT Oracle Wire Protocol

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\IBM Integration (9.0.0.2) - DataDirect Technologies 7.0 64-BIT Sybase Wire Protocol

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\IBM Integration Bus 10.0.0.21 Developer Edition - DataDirect Technologies 64-BIT Oracle Wire Protocol

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\IBM Integration Bus 10.0.0.21 Developer Edition - DataDirect Technologies 64-BIT Sybase Wire Protocol

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ODBC\ODBCINST.INI\IBM Integration (9.0.0.6) - DataDirect Technologies 7.1 64-BIT Oracle Wire Protocol

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ODBC\ODBCINST.INI\IBM Integration (9.0.0.6) - DataDirect Technologies 7.1 64-BIT Sybase Wire Protocol

I assume I need to reinstall the IIB ODBC drivers? - If so, can I do that; and if not, what do I need to do to resolve this?

答:
The name of the driver "IBM Integration Bus 10.0.0.n Developer Edition - DataDirect Technologies 64-BIT Oracle Wire Protocol" is too long for Windows to cope with.

You have to go into the Registry and replace it with a shorter name, everywhere that name comes up.
It'll fix this issue and all DSNs will work again.

Registry paths for changing:

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources (modify)

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI (rename)

HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers (modify)

screenshot Registry Editor


问:
python minidom does not close <xml tag>
I'm experiencing a strange behaviour using minidom. I run the following code:

```<code>import os
import sys
from xml.dom import minidom
def generateReleaseXMLFile():
    modelPath = "%./model/"
    # Create the parser
    xsydoc  = minidom.Document()
    # Create the element ScriptModelVersion
    scriptModelVersion  = xsydoc.createElement('ScriptModelVersion')
    # Assign all the attributes
    scriptModelVersion.setAttribute("Major", "1")
    scriptModelVersion.setAttribute("Minor", "2")
    scriptModelVersion.setAttribute("Patch", "3")
    scriptModelVersion.setAttribute("ReseaseDate", "2011-05-20")
    # Append the root to the document
    xsydoc.appendChild(scriptModelVersion)
    # Create the file descriptor
    fdesc = open(modelPath+"Release.xml", "w")
    # Write the file
    fdesc.write(xsydoc.toprettyxml())
    # Close the file
    fdesc.close()
    print xsydoc.toprettyxml()

generateReleaseXMLFile()
</code>```

It generates the following output:

```<code><?xml version="1.0" ?>
<ScriptModelVersion Major="9" Minor="0" Patch="1" ReleaseDate="2011-05-20"/>
</code>```

whithout the xml tag closure.
I really have no idea about why it's keeping the document open. Did anyone experienced the same problem? Or am i simply forgetting somethink really obvious and i simply canot see the problem?

答: The <?xml ... ?> is not a tag, but the XML Declaration. There is not need to close it, your document is in perfect shape.

Title: python minidom does not close <xml tag>

Body:
I'm experiencing a strange behaviour using minidom. I run the following code:

import os
import sys
from xml.dom import minidom
def generateReleaseXMLFile():
    modelPath = "%./model/"
    # Create the parser
    xsydoc  = minidom.Document()
    # Create the element ScriptModelVersion
    scriptModelVersion  = xsydoc.createElement('ScriptModelVersion')
    # Assign all the attributes
    scriptModelVersion.setAttribute("Major", "1")
    scriptModelVersion.setAttribute("Minor", "2")
    scriptModelVersion.setAttribute("Patch", "3")
    scriptModelVersion.setAttribute("ReseaseDate", "2011-05-20")
    # Append the root to the document
    xsydoc.appendChild(scriptModelVersion)
    # Create the file descriptor
    fdesc = open(modelPath+"Release.xml", "w")
    # Write the file
    fdesc.write(xsydoc.toprettyxml())
    # Close the file
    fdesc.close()
    print xsydoc.toprettyxml()

generateReleaseXMLFile()

It generates the following output:

<?xml version="1.0" ?>


问:
How to select two rows from a joined table
So i have two tables with information below one which is a holiday table which marks the location to and from and etc. and another table that has the information on the locations

holiday_id
location_from
location_to
start_time
end_time

1
21
43
13:00
17:00

Location_id
location_name

21
sydney

43
gold coast

I'd like to have an sql query which will return the names of the location to and from but because location name is under one column im not sure how to do it. any help is appreciated

答:
Just need to join to the location table twice. Once for the location_from and again for the location_to:</p>
```<code>SELECT
    h.holiday_id,
    h.location_from,
    locfrom.location_name,
    h.location_to,
    locto.locatin_name,
    h.start_time,
    h.end_time
FROM    Holidays h
INNER JOIN Locations AS locfrom
    ON locfrom.Location_id = h.location_from
INNER JOIN Locations locto
    ON locto.Location_id = h.location_to;
</code>```

Body:
Just need to join to the location table twice. Once for the location_from and again for the location_to:

SELECT
    h.holiday_id,
    h.location_from,
    locfrom.location_name,
    h.location_to,
    locto.locatin_name,
    h.start_time,
    h.end_time
FROM    Holidays h
INNER JOIN Locations AS locfrom
    ON locfrom.Location_id = h.location_from
INNER JOIN Locations locto
    ON locto.Location_id = h.location_to;


问:
How to get password expiry date using C++ win32 API?
I am using C++ with the win32 Api and I want to get the password expiry date for a user using ADSI.

```<code>CoInitialize(NULL);

LPWSTR pszADsPath=L"LDAP://CN=arjun,CN=Users,DC=raja,DC=com";
//HRESULT hr;
IADsUser *pUser;

hr = ADsGetObject(pszADsPath, IID_IADsUser, (void**) &pUser);
if(SUCCEEDED(hr))
{
    DATE expirationDate;
    VariantInit(&var);
    hr = pUser->get_PasswordLastChanged(&expirationDate);
    hr = pUser->get_PasswordExpirationDate(&expirationDate);

    if (SUCCEEDED(hr))
        VariantTimeToSystemTime(expirationDate,&lpExpirationDate);

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

Calling get_PasswordLastChanged will give success and return last changed password date, but I need the expiration date.

Using get_PasswordExpirationDate, I get S_OK (success) but it also gives an error code of -2147463155.

Can anyone explain what is going wrong?

答:
I know this is an old post but I looked for the same thing and came upon this post and for me the OP's code (with a slight change) works. I added ldap url and using port 636. Just in case anyone searches for the same thing :</p>
```<code>CCoInitialize CoInitialize;

if( !CoInitialize.IsSuccessful() )
{
    stringstream Text;
    Text << L"CoInitialize returned <" << CoInitialize.GetMessage() << L">" << endl;
    this->WriteLogThreadSafe( Text.str() );

    // Continue anyway because it could be it was already initialized.
}

LPWSTR pszADsPath=L"LDAP://<YOUR LDAP SERVER>:636/<YOUR DN>";
//HRESULT hr;
IADsUser *pUser;

HRESULT hr = ADsGetObject(pszADsPath, IID_IADsUser, (void**) &pUser);
if(SUCCEEDED(hr))
{
    SYSTEMTIME SystemTime = {};
    DATE expirationDate = {};
    VARIANTARG var = {};
    VariantInit(&var);
    hr = pUser->get_PasswordLastChanged(&expirationDate);
    hr = pUser->get_PasswordExpirationDate(&expirationDate);

    if (SUCCEEDED(hr))
        VariantTimeToSystemTime( expirationDate,&SystemTime );

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

Body:
I am using C++ with the win32 Api and I want to get the password expiry date for a user using ADSI.

CoInitialize(NULL);

LPWSTR pszADsPath=L"LDAP://CN=arjun,CN=Users,DC=raja,DC=com";
//HRESULT hr;
IADsUser *pUser;

hr = ADsGetObject(pszADsPath, IID_IADsUser, (void**) &pUser);
if(SUCCEEDED(hr))
{
    DATE expirationDate;
    VariantInit(&var);
    hr = pUser->get_PasswordLastChanged(&expirationDate);
    hr = pUser->get_PasswordExpirationDate(&expirationDate);

    if (SUCCEEDED(hr))
        VariantTimeToSystemTime(expirationDate,&lpExpirationDate);

    pUser->Release();
}

Calling get_PasswordLastChanged will give success and return last changed password date, but I need the expiration date.

Using get_PasswordExpirationDate, I get S_OK (success) but it also gives an error code of -2147463155.

Can anyone explain what is going wrong?

Body:
I know this is an old post but I looked for the same thing and came upon this post and for me the OP's code (with a slight change) works. I added ldap url and using port 636. Just in case anyone searches for the same thing :

CCoInitialize CoInitialize;

if( !CoInitialize.IsSuccessful() )
{
    stringstream Text;
    Text << L"CoInitialize returned <" << CoInitialize.GetMessage() << L">" << endl;
    this->WriteLogThreadSafe( Text.str() );

    // Continue anyway because it could be it was already initialized.
}

LPWSTR pszADsPath=L"LDAP://<YOUR LDAP SERVER>:636/<YOUR DN>";
//HRESULT hr;
IADsUser *pUser;

HRESULT hr = ADsGetObject(pszADsPath, IID_IADsUser, (void**) &pUser);
if(SUCCEEDED(hr))
{
    SYSTEMTIME SystemTime = {};
    DATE expirationDate = {};
    VARIANTARG var = {};
    VariantInit(&var);
    hr = pUser->get_PasswordLastChanged(&expirationDate);
    hr = pUser->get_PasswordExpirationDate(&expirationDate);

    if (SUCCEEDED(hr))
        VariantTimeToSystemTime( expirationDate,&SystemTime );

    pUser->Release();
}


问:
how can i access the kwargs directly inside a class?
```<code>class Scar:
    def __init__(self,**kwargs):
        self.make=kwargs.get("make")
        self.model=kwargs.get("model")
        self.manufacturing_year=kwargs.get("manufacturing_year")
    def print_details(self):
        print(self.make)
        print(self.model)
        print(self.manufacturing_year)
my_first_car=Scar(make="mahindra")
my_first_car.print_details()
</code>```

why i cant print(kwargs) in print_details as it is a dictionary

答:
class Scar:
    def __init__(self,**kwargs):
        self.make=kwargs.get("make")
        self.model=kwargs.get("model")
        self.manufacturing_year=kwargs.get("manufacturing_year")
        self.init_kwargs = kwargs
        #    ^^^^^^^^^^^ or any name you prefer
    def print_details(self):
        print(self.make)
        print(self.model)
        print(self.manufacturing_year)
        print(self.init_kwargs)  # <--- added this print
my_first_car=Scar(make="mahindra", stack_overflow=True)
my_first_car.print_details()
```
```mahindra
None
None
{'make': 'mahindra', 'stack_overflow': True}
```

Body:
class Scar:
    def __init__(self,**kwargs):
        self.make=kwargs.get("make")
        self.model=kwargs.get("model")
        self.manufacturing_year=kwargs.get("manufacturing_year")
    def print_details(self):
        print(self.make)
        print(self.model)
        print(self.manufacturing_year)
my_first_car=Scar(make="mahindra")
my_first_car.print_details()

why i cant print(kwargs) in print_details as it is a dictionary

Body:
class Scar:
    def __init__(self,**kwargs):
        self.make=kwargs.get("make")
        self.model=kwargs.get("model")
        self.manufacturing_year=kwargs.get("manufacturing_year")
        self.init_kwargs = kwargs
        #    ^^^^^^^^^^^ or any name you prefer
    def print_details(self):
        print(self.make)
        print(self.model)
        print(self.manufacturing_year)
        print(self.init_kwargs)  # <--- added this print
my_first_car=Scar(make="mahindra", stack_overflow=True)
my_first_car.print_details()

mahindra
None
None
{'make': 'mahindra', 'stack_overflow': True}