问:
Ways to imply return values are not meant to be stored
We can use nodiscard attribute to imply that the return value of a function should not be discarded. Are there any attribute (or other ways) to imply some opposite semantics: the return value of the function should only be used temporarily (by "temporary" I mean, not to assign to any variable except local ones)?

As the purpose may not be immediately clear, consider I have a class FooHolder that holds resources Foo; calling FooHolder::getFoo() returns the Foo it is currently holding:

#include <memory>

class Foo {
public:
    Foo& bar() { /* do something */ return *this; }
    const Foo& far() const { /* do something else */ return *this; }
};

class FooHolder {
private:
    std::shared_ptr<Foo> _foo { nullptr };

public:
    FooHolder(): _foo(std::make_shared<Foo>()) {}

    Foo& getFoo() { return *_foo; }
    const Foo& getFoo() const { return *_foo; }
};
```
<p>And we may use it in many ways:</p>
<pre class="lang-cpp prettyprint-override"><code>// Others may try storing some status:
Foo* g_foo = nullptr;

int main() {
    FooHolder foo_holder {};

    // I want to support this:
    foo_holder.getFoo().bar().far() /* chained calls... */ ;

    // Also, maybe this:
    auto& local_foo = foo_holder.getFoo();
    local_foo.bar();
    local_foo.far();

    // But not this, because the Foo instance that FooHolder holds may perish:
    static Foo& static_foo = foo_holder.getFoo();

    // Nor this:
    g_foo = &local_foo;

    return 0;
}
</code>```

So are there ways to prevent (or at least warn about) storing the return value of FooHolder::getFoo()? Or, is it bad practice to return resources by reference?

答:
[...] is it bad practice to return resources by reference?

It depends. There are many examples of methods that return non-const references and they are all fine. For example consider standard container element accessors. However, they are not meant for encapsulation. std::vector::operator[] is not meant to hide the elements from the caller, it is meant to provide direct access to it. Returning a non-const reference is not encapsulation! It is the opposite. Note that std::vector  even grants you access to its data(). Thats not encapsulation either, it is relying on the user to not delete[] some_vect.data() or do other wrong stuff that would break the vector.

You want FooHolder to encapsulate the contained Foo.

This is opposing requirements.

You have basically two choices: A) The caller knows what they are doing. They read documentation. They know that they are not supposed to use FooHolder::getFoo in the wrong way. B) use proper encapsulation: Never give the caller direct access to a non-const Foo:

```<code>class FooHolder {
private:
    std::shared_ptr<Foo> _foo { nullptr };

public:
    FooHolder(): _foo(std::make_shared<Foo>()) {}

    // nope // Foo& getFoo() { return *_foo; }
    // maybe // const Foo& getFoo() const { return *_foo; }

    FooHolder& bar() {
            _foo->bar();
            return *this;
    }
    // ..same for far() ...
};
</code>```

Note that A) is a viable solution. Consider that also things like std::shared_ptr can be used terribly wrong. Users are expected to know how to use it right. The difference is that std::shared_ptr is a standard type with plenty of documentation. Hence, you should think twice if this is the way to go.

So are there ways to prevent (or at least warn about) storing the return value of FooHolder::getFoo()?

No. Once you returned a non-const reference all bets are off. FooHolder is no longer in control of what the caller can do with that reference. You can prevent copies or moves but you cannot prevent holding on to a reference.

Body:
We can use nodiscard attribute to imply that the return value of a function should not be discarded. Are there any attribute (or other ways) to imply some opposite semantics: the return value of the function should only be used temporarily (by "temporary" I mean, not to assign to any variable except local ones)?

As the purpose may not be immediately clear, consider I have a class FooHolder that holds resources Foo; calling FooHolder::getFoo() returns the Foo it is currently holding:

#include <memory>

class Foo {
public:
    Foo& bar() { /* do something */ return *this; }
    const Foo& far() const { /* do something else */ return *this; }
};

class FooHolder {
private:
    std::shared_ptr<Foo> _foo { nullptr };

public:
    FooHolder(): _foo(std::make_shared<Foo>()) {}

    Foo& getFoo() { return *_foo; }
    const Foo& getFoo() const { return *_foo; }
};

And we may use it in many ways:

// Others may try storing some status:
Foo* g_foo = nullptr;

int main() {
    FooHolder foo_holder {};

    // I want to support this:
    foo_holder.getFoo().bar().far() /* chained calls... */ ;

    // Also, maybe this:
    auto& local_foo = foo_holder.getFoo();
    local_foo.bar();
    local_foo.far();

    // But not this, because the Foo instance that FooHolder holds may perish:
    static Foo& static_foo = foo_holder.getFoo();

    // Nor this:
    g_foo = &local_foo;

    return 0;
}

So are there ways to prevent (or at least warn about) storing the return value of FooHolder::getFoo()? Or, is it bad practice to return resources by reference?

Body:
[...] is it bad practice to return resources by reference?

It depends. There are many examples of methods that return non-const references and they are all fine. For example consider standard container element accessors. However, they are not meant for encapsulation. std::vector::operator[] is not meant to hide the elements from the caller, it is meant to provide direct access to it. Returning a non-const reference is not encapsulation! It is the opposite. Note that std::vector  even grants you access to its data(). Thats not encapsulation either, it is relying on the user to not delete[] some_vect.data() or do other wrong stuff that would break the vector.

You want FooHolder to encapsulate the contained Foo.

This is opposing requirements.

You have basically two choices: A) The caller knows what they are doing. They read documentation. They know that they are not supposed to use FooHolder::getFoo in the wrong way. B) use proper encapsulation: Never give the caller direct access to a non-const Foo:

class FooHolder {
private:
    std::shared_ptr<Foo> _foo { nullptr };

public:
    FooHolder(): _foo(std::make_shared<Foo>()) {}

    // nope // Foo& getFoo() { return *_foo; }
    // maybe // const Foo& getFoo() const { return *_foo; }

    FooHolder& bar() {
            _foo->bar();
            return *this;
    }
    // ..same for far() ...
};

Note that A) is a viable solution. Consider that also things like std::shared_ptr can be used terribly wrong. Users are expected to know how to use it right. The difference is that std::shared_ptr is a standard type with plenty of documentation. Hence, you should think twice if this is the way to go.

So are there ways to prevent (or at least warn about) storing the return value of FooHolder::getFoo()?

No. Once you returned a non-const reference all bets are off. FooHolder is no longer in control of what the caller can do with that reference. You can prevent copies or moves but you cannot prevent holding on to a reference.


来源: stackexchange

问:
BulkInsertAsync get TimeOut when inserting one record
i have a problem trying to insert data with BulkInsertAync :

```<code> public async Task Insert(IList<AccountingRecordKeyParsingError> accountingRecordKeyParsingErrors)
        {
            await _context.BulkInsertAsync(accountingRecordKeyParsingErrors);
    }
</code>```

this is my method, when i try to insert a specific record from a .txt i got a timeoutexception from BulkInsert. The data is small (it's just a simple record).

If i cut the .txt in half, the data pass without TimeOut.

If i set the timeout of the bulkinsert on "0" it work but this take a lot of time :

```<code>public async Task Insert(IList<AccountingRecordKeyParsingError> accountingRecordKeyParsingErrors)
        {
            await _context.BulkInsertAsync(accountingRecordKeyParsingErrors, o => o.BulkCopyTimeout = 0);
        }
</code>```

I'm using EF 3.1 & BulkExtensions 3.1

Someone know why i get this timeout for a simple row ?

答:
I recommend forgetting the BulkExtensions this really is nothing which takes long for EF Core, so I suspect You get the error from the obsolete extension.
Obsolete only therein that EF Core does what you're trying to do well, without 'addons'</p>
```<code>    DbSet<AccountingRecordKeyParsingError> _parsingErrors;

    public async Task Insert(IList<AccountingRecordKeyParsingError> accountingRecordKeyParsingErrors)
    {
        await Task.Factory.StartNew(() => {
            _parsingErrors.AddRange(accountingRecordKeyParsingErrors);
            SaveChanges();
        });
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i have a problem trying to insert data with BulkInsertAync :

 public async Task Insert(IList<AccountingRecordKeyParsingError> accountingRecordKeyParsingErrors)
        {
            await _context.BulkInsertAsync(accountingRecordKeyParsingErrors);
    }

this is my method, when i try to insert a specific record from a .txt i got a timeoutexception from BulkInsert. The data is small (it's just a simple record).

If i cut the .txt in half, the data pass without TimeOut.

If i set the timeout of the bulkinsert on "0" it work but this take a lot of time :

public async Task Insert(IList<AccountingRecordKeyParsingError> accountingRecordKeyParsingErrors)
        {
            await _context.BulkInsertAsync(accountingRecordKeyParsingErrors, o => o.BulkCopyTimeout = 0);
        }

I'm using EF 3.1 & BulkExtensions 3.1

Someone know why i get this timeout for a simple row ?

Body:
I recommend forgetting the BulkExtensions this really is nothing which takes long for EF Core, so I suspect You get the error from the obsolete extension.
Obsolete only therein that EF Core does what you're trying to do well, without 'addons'

    DbSet<AccountingRecordKeyParsingError> _parsingErrors;

    public async Task Insert(IList<AccountingRecordKeyParsingError> accountingRecordKeyParsingErrors)
    {
        await Task.Factory.StartNew(() => {
            _parsingErrors.AddRange(accountingRecordKeyParsingErrors);
            SaveChanges();
        });
    }


问:
Is there any valid method to duplicate sockaddr?
Lets assume that I have used getaddrinfo and resolved an address successfully:

```<code>//...
s = getaddrinfo(NULL, argv[1], &hints, &result);
if (s != 0)
    return -1;

if (result != nullptr) {
    // ....
}

freeaddrinfo(result);
</code>```

in this case, result->ai_addr and result->ai_addrlen refer to a sockaddr structure and its size(which is based on its type). Now assume that we want to duplicate this sockaddr in C++. What is the best valid approach to do so? I wrote this code, but I'm not sure if it is UB-free:

```<code>auto deleter = [](void* buf) { if (buf) free(buf); };

auto buf = malloc(result->ai_addrlen);
if (buf) {
    memcpy(buf, result->ai_addr, result->ai_addrlen);
}

std::unique_ptr<sockaddr, decltype(deleter)> myptr(static_cast<sockaddr*>(buf), deleter);
</code>```

Is this a valid C++ code?

答:
It seems valid to me. If you want to avoid dynamic allocations, you could also limit yourself to a union of all supported address families. Something like this:

```<code>union NetworkAddress
{
    sockaddr addr;
    sockaddr_in in4;
    sockaddr_in6 in6;

    static NetworkAddress from_addrinfo(const addrinfo* addr)
    {
        NetworkAddress rtrn;
        if(addr->ai_addrlen <= sizeof(rtrn))
            std::memcpy(&rtrn, addr->ai_addr, addr->ai_addrlen);
        else
            throw std::runtime_error("Unsupported network address");
        return rtrn;
    }
};
</code>```

Alternative: C++ Variant

If you compile for C++17, you could make use of std::variant. Personally, I don't see a big advantage. The sockaddr struct already contains a type tag which you now duplicate.

It is also more painful to use since most C interfaces expect a sockaddr pointer and not the specialized type so you have to do explicit casts.

It also results in less efficient code. For example GCC's implementation of std::visit results in indirect calls for what could be a simple if-else.

Here is an extended case study on how to implement connect with both approaches. Pick what you like best:

Option 1, the union:

```<code>union NetworkAddress
{
    sockaddr addr;
    sockaddr_in in4;
    sockaddr_in6 in6;

    static NetworkAddress from_addrinfo(const addrinfo* addr)
    {
        switch(addr->ai_family) {
        case AF_INET: break;
        case AF_INET6: break;
        default: throw std::runtime_error("Unsupported network address");
        }
        NetworkAddress rtrn;
        if(addr->ai_addrlen <= sizeof(rtrn))
            std::memcpy(&rtrn, addr->ai_addr, addr->ai_addrlen);
        else
            throw std::runtime_error("Unsupported network address");
        return rtrn;
    }
    std::size_t addrlen() const noexcept
    {
        switch(addr.sa_family) {
        case AF_INET: return sizeof(in4);
        case AF_INET6: return sizeof(in6);
        default: return 0; /* fail safe in later call */
        }
    }
    int connect(int socket) const noexcept
    { return ::connect(socket, &addr, addrlen()); }
};
</code>```

Option 2, variant:

```<code>struct NetworkAddress2
{
    using addr_variant = std::variant<sockaddr_in, sockaddr_in6>;
    addr_variant addr;

    explicit NetworkAddress2(const addrinfo* addr)
    {
        switch(addr->ai_family) {
        case AF_INET:
            this->addr = reinterpret_cast<const sockaddr_in&>(*addr);
            break;
        case AF_INET6:
            this->addr = reinterpret_cast<const sockaddr_in6&>(*addr);
            break;
        default:
            throw std::runtime_error("Unsupported network address");
        }
    }
    std::size_t addrlen() const noexcept
    {
        switch(addr.index()) {
        case 0: return sizeof(sockaddr_in);
        case 1: return sizeof(sockaddr_in6);
        default: return 0;
        }
    }
    int connect(int socket) const
    {
#     if __cpp_generic_lambdas >= 201707L
        /* C++20: Use templated lambda */
        return std::visit([socket]<class T>(const T& addr) noexcept -> int {
            return ::connect(socket,
                             reinterpret_cast<const sockaddr*>(&addr),
                             sizeof(T));
        }, addr);
#     else
        const sockaddr* ptr;
        switch(addr.index()) {
        case 0:
            ptr = reinterpret_cast<const sockaddr*>(&std::get<0>(addr));
            break;
        case 1:
            ptr = reinterpret_cast<const sockaddr*>(&std::get<1>(addr));
            break;
        default:
            throw std::bad_variant_access{};
        }
        return ::connect(socket, ptr, addrlen());
#     endif
    }
};
</code>```

Body:
Lets assume that I have used getaddrinfo and resolved an address successfully:

//...
s = getaddrinfo(NULL, argv[1], &hints, &result);
if (s != 0)
    return -1;

if (result != nullptr) {
    // ....
}

freeaddrinfo(result);

in this case, result->ai_addr and result->ai_addrlen refer to a sockaddr structure and its size(which is based on its type). Now assume that we want to duplicate this sockaddr in C++. What is the best valid approach to do so? I wrote this code, but I'm not sure if it is UB-free:

auto deleter = [](void* buf) { if (buf) free(buf); };

auto buf = malloc(result->ai_addrlen);
if (buf) {
    memcpy(buf, result->ai_addr, result->ai_addrlen);
}

std::unique_ptr<sockaddr, decltype(deleter)> myptr(static_cast<sockaddr*>(buf), deleter);

Is this a valid C++ code?

Body:
It seems valid to me. If you want to avoid dynamic allocations, you could also limit yourself to a union of all supported address families. Something like this:

union NetworkAddress
{
    sockaddr addr;
    sockaddr_in in4;
    sockaddr_in6 in6;

    static NetworkAddress from_addrinfo(const addrinfo* addr)
    {
        NetworkAddress rtrn;
        if(addr->ai_addrlen <= sizeof(rtrn))
            std::memcpy(&rtrn, addr->ai_addr, addr->ai_addrlen);
        else
            throw std::runtime_error("Unsupported network address");
        return rtrn;
    }
};

Alternative: C++ Variant

If you compile for C++17, you could make use of std::variant. Personally, I don't see a big advantage. The sockaddr struct already contains a type tag which you now duplicate.

It is also more painful to use since most C interfaces expect a sockaddr pointer and not the specialized type so you have to do explicit casts.

It also results in less efficient code. For example GCC's implementation of std::visit results in indirect calls for what could be a simple if-else.

Here is an extended case study on how to implement connect with both approaches. Pick what you like best:

Option 1, the union:

union NetworkAddress
{
    sockaddr addr;
    sockaddr_in in4;
    sockaddr_in6 in6;

    static NetworkAddress from_addrinfo(const addrinfo* addr)
    {
        switch(addr->ai_family) {
        case AF_INET: break;
        case AF_INET6: break;
        default: throw std::runtime_error("Unsupported network address");
        }
        NetworkAddress rtrn;
        if(addr->ai_addrlen <= sizeof(rtrn))
            std::memcpy(&rtrn, addr->ai_addr, addr->ai_addrlen);
        else
            throw std::runtime_error("Unsupported network address");
        return rtrn;
    }
    std::size_t addrlen() const noexcept
    {
        switch(addr.sa_family) {
        case AF_INET: return sizeof(in4);
        case AF_INET6: return sizeof(in6);
        default: return 0; /* fail safe in later call */
        }
    }
    int connect(int socket) const noexcept
    { return ::connect(socket, &addr, addrlen()); }
};

Option 2, variant:

struct NetworkAddress2
{
    using addr_variant = std::variant<sockaddr_in, sockaddr_in6>;
    addr_variant addr;

    explicit NetworkAddress2(const addrinfo* addr)
    {
        switch(addr->ai_family) {
        case AF_INET:
            this->addr = reinterpret_cast<const sockaddr_in&>(*addr);
            break;
        case AF_INET6:
            this->addr = reinterpret_cast<const sockaddr_in6&>(*addr);
            break;
        default:
            throw std::runtime_error("Unsupported network address");
        }
    }
    std::size_t addrlen() const noexcept
    {
        switch(addr.index()) {
        case 0: return sizeof(sockaddr_in);
        case 1: return sizeof(sockaddr_in6);
        default: return 0;
        }
    }
    int connect(int socket) const
    {
#     if __cpp_generic_lambdas >= 201707L
        /* C++20: Use templated lambda */
        return std::visit([socket]<class T>(const T& addr) noexcept -> int {
            return ::connect(socket,
                             reinterpret_cast<const sockaddr*>(&addr),
                             sizeof(T));
        }, addr);
#     else
        const sockaddr* ptr;
        switch(addr.index()) {
        case 0:
            ptr = reinterpret_cast<const sockaddr*>(&std::get<0>(addr));
            break;
        case 1:
            ptr = reinterpret_cast<const sockaddr*>(&std::get<1>(addr));
            break;
        default:
            throw std::bad_variant_access{};
        }
        return ::connect(socket, ptr, addrlen());
#     endif
    }
};


问:
RadioButton Command property not working with xamarin.forms
RadioButton command property not working after updated from Xamarin.Forms 4.7 to Xamarin.Forms 5.0.0.2337. what are the alternative ways to use command in ViewModel not with codebehind.</p>

答:
Yes,since Xamarin.Forms 5.0.0, the property Command has been removed from RadioButton.

If you want to run a command upon state change then you can use the event CheckedChanged.

```<code>    <RadioButton Content="test">
        <RadioButton.Behaviors>
            <local:EventToCommandBehavior EventName="CheckedChanged" Command="{Binding Source={x:Reference Page}, Path=BindingContext.RadioCommand}"   CommandParameter="V"/>
        </RadioButton.Behaviors>
    </RadioButton>
</code>```

For EventToCommandBehavior.cs, you can refer sample code here: https://github.com/xamarin/xamarin-forms-samples/tree/main/Behaviors/EventToCommandBehavior/EventToCommandBehavior/Behaviors .

Note:

Page is the x:Name of current page.

Body:
Yes,since Xamarin.Forms 5.0.0, the property Command has been removed from RadioButton.

If you want to run a command upon state change then you can use the event CheckedChanged.

    <RadioButton Content="test">
        <RadioButton.Behaviors>
            <local:EventToCommandBehavior EventName="CheckedChanged" Command="{Binding Source={x:Reference Page}, Path=BindingContext.RadioCommand}"   CommandParameter="V"/>
        </RadioButton.Behaviors>
    </RadioButton>

For EventToCommandBehavior.cs, you can refer sample code here: https://github.com/xamarin/xamarin-forms-samples/tree/main/Behaviors/EventToCommandBehavior/EventToCommandBehavior/Behaviors .

Note:

Page is the x:Name of current page.


问:
Swift: pushed ViewController deinit not called
View Controller Structure

Main View Controller -> Table View Controller -> Detail View Controller

They are all embedded in Navigation Controller.

I pushed Detail View Controller by calling pushViewController. When I come back to Table View Controller from Detail View Controller, I realized Detail View Controller deinit() is not called, which causes fatal error at my project.

How can I make DetailViewController to deinit?? Thank you

Part of Table View Controller code where calls pushViewController

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        selectedTilId = thisDayTIL[indexPath.row].id

        if let detailVC = storyboard?.instantiateViewController(withIdentifier: "TILDetailViewController") as? TILDetailViewController {

            detailVC.tilId = selectedTilId
            detailVC.tilViewModel = self.tilViewModel
            detailVC.subjectViewModel = self.subjectViewModel

            self.navigationController?.pushViewController(detailVC, animated: true)
        }

    }
</code>```

Whole Detail View Controller code

```<code>//
//  TILDetailViewController.swift
//

import UIKit
import RxSwift

class TILDetailViewController: UIViewController {

    @IBOutlet weak var tilTitleLabel: UILabel!
    @IBOutlet weak var tilSubjectLabel: UILabel!
    @IBOutlet weak var tilContentLabel: UILabel!

    var til: TIL!
    var tilId: Int!

    var tilViewModel: TILViewModel!
    var subjectViewModel: SubjectViewModel!

    var disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        _ = tilViewModel.allTIL
            .map {
                $0.filter { $0.id == self.tilId }
            }
            .subscribe(onNext: { [weak self] til in
                self?.setLabelText(til[0])
                self?.til = til[0]
            })
            .disposed(by: disposeBag)

        let rightBarButton = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editButtonClicked))

        self.navigationItem.rightBarButtonItem = rightBarButton
    }

    deinit {
        print("DetailVC deinitialized")
    }

    @objc private func editButtonClicked(_ sender: Any) {
        guard let editVC = storyboard?.instantiateViewController(withIdentifier: "TILEditViewController") as? TILEditViewController else {
            return
        }
        editVC.til = til
        editVC.tilViewModel = self.tilViewModel
        editVC.subjectViewModel = self.subjectViewModel

        editVC.modalPresentationStyle = .overFullScreen
        self.present(editVC, animated: true, completion: nil)
    }

    func setLabelText(_ til: TIL) {
        tilTitleLabel.text = til.title
        tilContentLabel.text = til.content
        tilSubjectLabel.text = subjectViewModel.getSubjectNameById(til.subjectId)
    }
}

</code>```

答:
You're holding a strong reference to self in your Detailed VC which prevents it from being deallocated. This is called a retain cycle.

On this line: $0.filter { $0.id == self.tilId }.

Adding [weak self] to your map block will fix this.

Body:
View Controller Structure

Main View Controller -> Table View Controller -> Detail View Controller

They are all embedded in Navigation Controller.

I pushed Detail View Controller by calling pushViewController. When I come back to Table View Controller from Detail View Controller, I realized Detail View Controller deinit() is not called, which causes fatal error at my project.

How can I make DetailViewController to deinit?? Thank you

Part of Table View Controller code where calls pushViewController

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        selectedTilId = thisDayTIL[indexPath.row].id

        if let detailVC = storyboard?.instantiateViewController(withIdentifier: "TILDetailViewController") as? TILDetailViewController {

            detailVC.tilId = selectedTilId
            detailVC.tilViewModel = self.tilViewModel
            detailVC.subjectViewModel = self.subjectViewModel

            self.navigationController?.pushViewController(detailVC, animated: true)
        }

    }

Whole Detail View Controller code

//
//  TILDetailViewController.swift
//

import UIKit
import RxSwift

class TILDetailViewController: UIViewController {

    @IBOutlet weak var tilTitleLabel: UILabel!
    @IBOutlet weak var tilSubjectLabel: UILabel!
    @IBOutlet weak var tilContentLabel: UILabel!

    var til: TIL!
    var tilId: Int!

    var tilViewModel: TILViewModel!
    var subjectViewModel: SubjectViewModel!

    var disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        _ = tilViewModel.allTIL
            .map {
                $0.filter { $0.id == self.tilId }
            }
            .subscribe(onNext: { [weak self] til in
                self?.setLabelText(til[0])
                self?.til = til[0]
            })
            .disposed(by: disposeBag)

        let rightBarButton = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editButtonClicked))

        self.navigationItem.rightBarButtonItem = rightBarButton
    }

    deinit {
        print("DetailVC deinitialized")
    }

    @objc private func editButtonClicked(_ sender: Any) {
        guard let editVC = storyboard?.instantiateViewController(withIdentifier: "TILEditViewController") as? TILEditViewController else {
            return
        }
        editVC.til = til
        editVC.tilViewModel = self.tilViewModel
        editVC.subjectViewModel = self.subjectViewModel

        editVC.modalPresentationStyle = .overFullScreen
        self.present(editVC, animated: true, completion: nil)
    }

    func setLabelText(_ til: TIL) {
        tilTitleLabel.text = til.title
        tilContentLabel.text = til.content
        tilSubjectLabel.text = subjectViewModel.getSubjectNameById(til.subjectId)
    }
}


问:
INSERT INTO sql server error : invalid object name
I have this INSERT statement:

```<code>INSERT INTO TBL_VIDEOS (
  TBL_VIDEOS.ID,
  TBL_VIDEOS.TITLE,
  TBL_VIDEOS.V_DESCRIPTION,
  TBL_VIDEOS.UPLOAD_DATE,
  TBL_VIDEOS.V_VIEWS,
  TBL_VIDEOS.USERNAME,
  TBL_VIDEOS.RATING,
  TBL_VIDEOS.V_SOURCE,
  TBL_VIDEOS.FLAG
)
VALUES
('Z8MTRH3LmTVm',
'Why Creativity is the New Economy',
'Dr Richard Florida, one of the world's leading ...
    this stuff does not matter, it is just wasted space',
CURRENT_TIMESTAMP,
0,
1,
0,
'http://www.youtube.com/watch?v=VPX7gowr2vE&feature=g-all-u'
,0)
</code>```

But I get this error message:

Invalid object name 'TBL_VIDEOS'

答:
In my case SQL gave the 'invalid object name' error message while trying to insert values using the below statement:

```<code>IF NOT EXISTS (SELECT 1 FROM [DatabaseName].[SchemaName].[TableName]
WITH (NOLOCK) WHERE col1 = val1)
BEGIN
  INSERT INTO [SchemaName].[TableName] (col1, col2,col3)
  Values(val1, val2, val3)
END
</code>```

To avoid this error I used the below statement to insert the record into the table:

```<code>IF NOT EXISTS (SELECT 1 FROM [DatabaseName].[SchemaName].[TableName]
WITH (NOLOCK) WHERE col1 = val1)
BEGIN
   INSERT INTO SchemaName.TableName (col1, col2,col3)
   Values(val1, val2, val3)
END
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this INSERT statement:

INSERT INTO TBL_VIDEOS (
  TBL_VIDEOS.ID,
  TBL_VIDEOS.TITLE,
  TBL_VIDEOS.V_DESCRIPTION,
  TBL_VIDEOS.UPLOAD_DATE,
  TBL_VIDEOS.V_VIEWS,
  TBL_VIDEOS.USERNAME,
  TBL_VIDEOS.RATING,
  TBL_VIDEOS.V_SOURCE,
  TBL_VIDEOS.FLAG
)
VALUES
('Z8MTRH3LmTVm',
'Why Creativity is the New Economy',
'Dr Richard Florida, one of the world's leading ...
    this stuff does not matter, it is just wasted space',
CURRENT_TIMESTAMP,
0,
1,
0,
'http://www.youtube.com/watch?v=VPX7gowr2vE&feature=g-all-u'
,0)

But I get this error message:

Invalid object name 'TBL_VIDEOS'

Body:
In my case SQL gave the 'invalid object name' error message while trying to insert values using the below statement:

IF NOT EXISTS (SELECT 1 FROM [DatabaseName].[SchemaName].[TableName]
WITH (NOLOCK) WHERE col1 = val1)
BEGIN
  INSERT INTO [SchemaName].[TableName] (col1, col2,col3)
  Values(val1, val2, val3)
END

To avoid this error I used the below statement to insert the record into the table:

IF NOT EXISTS (SELECT 1 FROM [DatabaseName].[SchemaName].[TableName]
WITH (NOLOCK) WHERE col1 = val1)
BEGIN
   INSERT INTO SchemaName.TableName (col1, col2,col3)
   Values(val1, val2, val3)
END


问:
How to extract elements of an array in object type in c#?
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

```<code>int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (<b>of a priory unknown type and I cannot use type conversion in the code </b>
//How can extract elements of obj and use them, e.g. write them on the screen?`
</code>```

答:
In .net 4.0 you could do make unnesscessary use of the dynamic keyword,

```<code>dynamic object obj = array;
Console.Write(obj[0].ToString());
</code>```

Body:
I have an object which contains an array of any type (not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array?
For example:

int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (of a priory unknown type and I cannot use type conversion in the code
//How can extract elements of obj and use them, e.g. write them on the screen?`

Body:
In .net 4.0 you could do make unnesscessary use of the dynamic keyword,

dynamic object obj = array;
Console.Write(obj[0].ToString());


问:
Difference between Special Variable and Global Variable
In GNU CLISP 2.49.92, the following code:

```<code>(defvar i 1)
(defun g ()
  (format T "g0:~d~%" i)
  (setf i 2)
  (format T "g1:~d~%" i))
(defun f ()
  (setf i 3)
  (format T "f0:~d~%" i)
  (g)
  (format T "f1:~d~%" i))
(f)
</code>```

gives the following output:

```<code>f0:3
g0:3
g1:2
f1:2
NIL
</code>```

Similarly, the following code in C:

```<code>#include <stdio.h>

static int i = 1;

int g (void) {
  printf("g0:%d\n", i);
  i = 2;
  printf("g1:%d\n", i);
}

int f (void) {
  i = 3;
  printf("f0:%d\n", i);
  g();
  printf("f1:%d\n", i);
}

int main() {
    f();
    return 0;
}
</code>```

gives the following output:

```<code>f0:3
g0:3
g1:2
f1:2
</code>```

According the the documentation that I found, defvar creates a special variable that is dynamically scoped. On the other hand, C is a statically scoped language. And yet, the two pieces of code give the same output. What then is the difference between a Special Variable and a Global Variable?

答:
In the case you're showing, you're setting an existing binding.  Nothing surprising here.  The interesting part is what happens when you let a special variable.

(defvar *i* 1)

(defun f ()
  (format t "f0: ~a~%" *i*)
  (let ((*i* (1+ *i*)))
    (format t "f1: ~a~%" *i*)
    (g)
    (incf *i*)
    (format t "f2: ~a~%" *i*))
  (format t "f3: ~a~%" *i*))

(defun g ()
  (incf *i*)
  (format t "g: ~a~%" *i*))

(f)
```
<p>which prints:</p>
```f0: 1
f1: 2
g: 3
f2: 4
f3: 1
```

The let of *i* creates a dynamic extent (because *i* was globally declared special by defvar).

Body:
In GNU CLISP 2.49.92, the following code:

(defvar i 1)
(defun g ()
  (format T "g0:~d~%" i)
  (setf i 2)
  (format T "g1:~d~%" i))
(defun f ()
  (setf i 3)
  (format T "f0:~d~%" i)
  (g)
  (format T "f1:~d~%" i))
(f)

gives the following output:

f0:3
g0:3
g1:2
f1:2
NIL

Similarly, the following code in C:

#include <stdio.h>

static int i = 1;

int g (void) {
  printf("g0:%d\n", i);
  i = 2;
  printf("g1:%d\n", i);
}

int f (void) {
  i = 3;
  printf("f0:%d\n", i);
  g();
  printf("f1:%d\n", i);
}

int main() {
    f();
    return 0;
}

gives the following output:

f0:3
g0:3
g1:2
f1:2

According the the documentation that I found, defvar creates a special variable that is dynamically scoped. On the other hand, C is a statically scoped language. And yet, the two pieces of code give the same output. What then is the difference between a Special Variable and a Global Variable?

Body:
In the case you're showing, you're setting an existing binding.  Nothing surprising here.  The interesting part is what happens when you let a special variable.

(defvar *i* 1)

(defun f ()
  (format t "f0: ~a~%" *i*)
  (let ((*i* (1+ *i*)))
    (format t "f1: ~a~%" *i*)
    (g)
    (incf *i*)
    (format t "f2: ~a~%" *i*))
  (format t "f3: ~a~%" *i*))

(defun g ()
  (incf *i*)
  (format t "g: ~a~%" *i*))

(f)

which prints:

f0: 1
f1: 2
g: 3
f2: 4
f3: 1

The let of *i* creates a dynamic extent (because *i* was globally declared special by defvar).


问:
Javascript: HackerRank function within a function is not a function
This is one of those job interview tests on HackerRank that I am embarrassed to say I didn't complete within the allotted 20 minutes, and it's driving me nuts. Basically, you're given the following:

```<code>function myList() {
    // write code here
}

function main() {
    // You can't edit this function. This is just pseudo, from what I can remember
    const obj = myList();
    if (operation === "add")
        obj.add(item);
    else if (operation === "remove")
        obj.remove(item);
    else
        obj.getList();
    // Some more stuff here
}
</code>```

So my first train of thought was to write the following inside myList():

```<code>let objList = [];
function add(item) {
    objList.add(item)
}
// etc., etc.
return {add, remove, getList};
</code>```

Needless to say, the above didn't work, with the error: obj.add is not a function, in the main function.

I tried experimenting with this and the returns (only returning add, with or without {}), but didn't really get anywhere. What could I have done to get this working?

答:
As the answer from Attersson already suggested, you could use a closure inside the myList function. This would allow to only expose the three methods add, remove and getList while the original list cannot be accessed. Here is an example:

function myList() {
  return (() => {
    const obj = {itemList: []}
    const add = (item) => obj.itemList.push(item)
    const remove = (item) => obj.itemList = obj.itemList.filter(i => i !== item)
    const getList = () => obj.itemList
    return {add, remove, getList}
  })()
}
```

Body:
This is one of those job interview tests on HackerRank that I am embarrassed to say I didn't complete within the allotted 20 minutes, and it's driving me nuts. Basically, you're given the following:

function myList() {
    // write code here
}

function main() {
    // You can't edit this function. This is just pseudo, from what I can remember
    const obj = myList();
    if (operation === "add")
        obj.add(item);
    else if (operation === "remove")
        obj.remove(item);
    else
        obj.getList();
    // Some more stuff here
}

So my first train of thought was to write the following inside myList():

let objList = [];
function add(item) {
    objList.add(item)
}
// etc., etc.
return {add, remove, getList};

Needless to say, the above didn't work, with the error: obj.add is not a function, in the main function.

I tried experimenting with this and the returns (only returning add, with or without {}), but didn't really get anywhere. What could I have done to get this working?


问:
R: Read multiple sheets from a XLS file and rbind them with skip rows and setnames
I have multiple sheets in an excel file and I will like to row bind all of them into one single dataframe. The first sheet has 3 rows that I have to skip, which looks something like this.

```<code>unneededrow1
unneededrow2
unneededrow3
Date      Category       CatID       Revenue
1/1/2022  Shop           1           1203
1/1/2022  Online         2           3264
2/1/2022  Shop           1           1423
2/1/2022  Online         2           2464
</code>```

For Sheet2, Sheet3, Sheet4, and and onwards, I have data without column names, which is something like the following.

```<code>3/1/2022  Shop           1           2454
3/1/2022  Online         2           4333
4/1/2022  Shop           1           2234
4/1/2022  Online         2           4565
</code>```

My initial approach was to set colnames = FALSE for all sheets and rbind them but this result in mismatch of data types. I have looked up and tried other solutions but still couldn't achieve what I need. Appreciate any help here and thanks in advance.

答:
Lets have files e.g. doc1.xlsx, doc2.xlsx, doc3.xlsx and so on in the current working directory. Then you can the whole table like this:

```<code>library(tidyverse)
library(readxl)

tibble(path = list.files(".", ".xlsx")) %>%
  mutate(
    has_header = path == "doc1.xlsx",
    data = path %>% map2(has_header, ~ {
      if (.y) {
        read_excel(.x, skip = 3)
      } else {
        read_excel(.x, col_names = c("Date", "Category", "CatID", "Revenue"))
      }
    })
  ) %>%
  pull(data) %>%
  bind_rows()
</code>```

If you have multiple sheets in the same file you can do this instead:

```<code>library(tidyverse)
library(readxl)

path <- "data.xlsx"
tibble(sheet = excel_sheets(path)) %>%
  mutate(
    has_header = sheet == "Sheet1",
    data = sheet %>% map2(has_header, ~ {
      if (.y) {
        read_excel(path, sheet = .x, skip = 3)
      } else {
        read_excel(path, sheet = .x, col_names = c("Date", "Category", "CatID", "Revenue"))
      }
    })
  ) %>%
  pull(data) %>%
  bind_rows()
</code>```

Body:
I have multiple sheets in an excel file and I will like to row bind all of them into one single dataframe. The first sheet has 3 rows that I have to skip, which looks something like this.

unneededrow1
unneededrow2
unneededrow3
Date      Category       CatID       Revenue
1/1/2022  Shop           1           1203
1/1/2022  Online         2           3264
2/1/2022  Shop           1           1423
2/1/2022  Online         2           2464

For Sheet2, Sheet3, Sheet4, and and onwards, I have data without column names, which is something like the following.

3/1/2022  Shop           1           2454
3/1/2022  Online         2           4333
4/1/2022  Shop           1           2234
4/1/2022  Online         2           4565

My initial approach was to set colnames = FALSE for all sheets and rbind them but this result in mismatch of data types. I have looked up and tried other solutions but still couldn't achieve what I need. Appreciate any help here and thanks in advance.

Body:
Lets have files e.g. doc1.xlsx, doc2.xlsx, doc3.xlsx and so on in the current working directory. Then you can the whole table like this:

library(tidyverse)
library(readxl)

tibble(path = list.files(".", ".xlsx")) %>%
  mutate(
    has_header = path == "doc1.xlsx",
    data = path %>% map2(has_header, ~ {
      if (.y) {
        read_excel(.x, skip = 3)
      } else {
        read_excel(.x, col_names = c("Date", "Category", "CatID", "Revenue"))
      }
    })
  ) %>%
  pull(data) %>%
  bind_rows()

If you have multiple sheets in the same file you can do this instead:

library(tidyverse)
library(readxl)

path <- "data.xlsx"
tibble(sheet = excel_sheets(path)) %>%
  mutate(
    has_header = sheet == "Sheet1",
    data = sheet %>% map2(has_header, ~ {
      if (.y) {
        read_excel(path, sheet = .x, skip = 3)
      } else {
        read_excel(path, sheet = .x, col_names = c("Date", "Category", "CatID", "Revenue"))
      }
    })
  ) %>%
  pull(data) %>%
  bind_rows()


问:
C++ : read a csv file and extract some parts
A .csv file is written like this:

```<code>    M9005U00-X30A0S00-1;BAS;X;-0.002;-0.095
    S707RY00-X30AOS00-1;HMV;X;+0.002;+0.081
    W3005U00-X30BOJ00-1;BAS;X;+0.026;-0.138
    H307QZ00-X30BOJ00-1;HMV;X;-0.025;+0.122
    ....
</code>```

now I want to create a function, i.e.

```<code>      double find_and_extract (string sss)
</code>```

when this function is used with a keyword as its parameter, for example

```<code>      find_and_extract (W3005U00-X30BOJ00-1);
</code>```

it will search in the .csv file line by line, find corresponding line (in this case it should be the third line), and extract the certin part "+0.026" in this line, return as a double.

How should I write this function?

edit: Here is the code i've written so far:

```<code>    #include <iostream>
    #include <fstream>
    #include <string>
    #include <stdio.h>
    #include <vector>
    #include <iterator>
    #include <cstdlib>
    #include <cstdio>
    #include <sstream>
    #include <stdlib.h>

    using namespace std;

    void main()
        {
           find_and_extract (W3005U00-X30BOJ00-1);
        }

    double find_and_extract (string sss)
         {
             vector<string> vecarray;
             ifstream infile("C:\\Data\\testdata.csv");
             string temppo;
             string contnt;
             char csv_extract[40];
             stringstream ss;
             vector <string>::iterator ptr;
             while (!infile.eof())
               {
                 infile.getline(csv_extract,40);
                 ss << csv_extract;
                 ss >> contnt;
                 vecarray.push_back(contnt);
                }
             for (ptr=vecarray.begin();ptr!=vecarray.end();ptr++)
             {
                 if ((*ptr).find(sss)==0)
                     temppo = (*ptr).substr(27,6);
             }
             return (strtod(temppo.c_str(),NULL,0));
        }
</code>```

Could anyone help me out to point out the errors?

答:
Seeing as you already have the file as a string, I'd use the Knuth–Morris–Pratt algorithm to find the key, find the position of the 3rd and 4th semi-colons on that line and return the string in between them.

That's just an outline - you'll need to add error handling.

Body:
A .csv file is written like this:

    M9005U00-X30A0S00-1;BAS;X;-0.002;-0.095
    S707RY00-X30AOS00-1;HMV;X;+0.002;+0.081
    W3005U00-X30BOJ00-1;BAS;X;+0.026;-0.138
    H307QZ00-X30BOJ00-1;HMV;X;-0.025;+0.122
    ....

now I want to create a function, i.e.

      double find_and_extract (string sss)

when this function is used with a keyword as its parameter, for example

      find_and_extract (W3005U00-X30BOJ00-1);

it will search in the .csv file line by line, find corresponding line (in this case it should be the third line), and extract the certin part "+0.026" in this line, return as a double.

How should I write this function?

edit: Here is the code i've written so far:

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <stdio.h>
    #include <vector>
    #include <iterator>
    #include <cstdlib>
    #include <cstdio>
    #include <sstream>
    #include <stdlib.h>

    using namespace std;

    void main()
        {
           find_and_extract (W3005U00-X30BOJ00-1);
        }

    double find_and_extract (string sss)
         {
             vector<string> vecarray;
             ifstream infile("C:\\Data\\testdata.csv");
             string temppo;
             string contnt;
             char csv_extract[40];
             stringstream ss;
             vector <string>::iterator ptr;
             while (!infile.eof())
               {
                 infile.getline(csv_extract,40);
                 ss << csv_extract;
                 ss >> contnt;
                 vecarray.push_back(contnt);
                }
             for (ptr=vecarray.begin();ptr!=vecarray.end();ptr++)
             {
                 if ((*ptr).find(sss)==0)
                     temppo = (*ptr).substr(27,6);
             }
             return (strtod(temppo.c_str(),NULL,0));
        }

Could anyone help me out to point out the errors?


问:
How to display Current & Previous Month Name along with Total of Current Revenue per month & Total of Previous Revenue per month through SQL Query?
I have the following tables:

[Revenue Raw Data] consisting of Month_ID,Revenue

and it has the following sample data:

```<code>Month_ID
128
124
123
122
126
120

Revenue
1768077
1767617
1734230
1687976
1686309
</code>```

yt_Calendar_lookup consisting of Month_ID,Month_No,Month_Name

and it has the following sample data:

```<code>Month_No
1
2
3
4
5
6
7
8
9
10
11
12

Month_ID
120
121
122
123
124
125
126
127
128
129
130
131

Month_Name
January
February
March
April
May
June
July
August
September
October
November
December
</code>```

What I am trying to achieve is to display the results for the following 5 columns:

Display Current Month as the first column from the table yt_Calendar_lookup

Display Total Revenue for the Current Month as the second column from the table [Revenue Raw Data]

Display Previous Month as the third column from the table yt_Calendar_lookup

Display Total Revenue for the Previous Month as the fourth column from the table [Revenue Raw Data]

Display Revenue difference between Current Month and Previous Month as the fifth column from the table [Revenue Raw Data]

Initially, this is what I have tried:

```<code>SELECT
    A.[Total Revenue for Current Month]
    , B.[Total Revenue for Previous Month]
    , A.[Total Revenue for current Month] - B.[Total Revenue for previous Month] AS 'Revenue Difference between current Month and previous Month'
FROM (
    SELECT SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Current Month'
    FROM [Revenue Raw Data]
    WHERE Month_ID IN (SELECT MAX(Month_ID) FROM [Revenue Raw Data])
) A, (
    SELECT SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Previous Month'
    FROM [Revenue Raw Data]
    WHERE Month_ID IN (SELECT MAX(Month_ID) - 1 FROM [Revenue Raw Data])
) B
</code>```

With the query above, I could successfully display the following 3 columns:

Total Revenue for Current Month, Total Revenue for Previous Month, Revenue Difference between Current Month and Previous Month

And this is the result I have received:

```<code>Total Revenue for Current Month Total Revenue for Previous Month
21221564                        19973825

Revenue Difference between current Month and previous Month
1247739
</code>```

With the next query, I was trying to display the following 5 columns:

Current Month, Total Revenue for Current Month, Previous Month, Total Revenue for Previous Month, Revenue Difference between Current Month and Previous Month

This is what I have tried:

```<code>    SELECT A.[Current Month],
A.[Total Revenue for Current Month],
    B.[Previous Month],
B.[Total Revenue for Previous Month],
    A.[Total Revenue for current Month] - B.[Total Revenue for previous Month]
    AS 'Revenue Difference between current Month and previous Month'
    FROM
    (SELECT Month_Name
AS 'Current Month',
    SUM(CAST(Revenue AS BIGINT))
    AS 'Total Revenue for Current Month'
    FROM [Revenue Raw Data], yt_Calendar_lookup
    WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
    AND [Revenue Raw Data].Month_ID IN
    (SELECT MAX(Month_ID) FROM [Revenue Raw Data])
    ) A,
    (SELECT Month_Name
AS 'Previous Month',
    SUM(CAST(Revenue AS BIGINT))
    AS 'Total Revenue for Previous Month'
    FROM [Revenue Raw Data], yt_Calendar_lookup
    WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
    AND [Revenue Raw Data].Month_ID IN
(SELECT MAX(Month_ID) - 1 FROM [Revenue Raw Data])
    ) B
</code>```

I received the following error message:

Column 'yt_Calendar_lookup.Month_Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I even tried by adding GROUP BY A.Month_Name,B.Month_Name, and even after that I am receiving the same error message.

I am still trying to figure out on where I am making the mistake for this particular query.

Solution for this particular issue will be highly appreciated.

答:
I finally managed to solve the problem.
As mentioned by one of the StackOverflow user, that all I had to add was GROUP BY Month_Name on both the sub-queries.

This is what I have done:

```<code>SELECT A.[Current Month], A.[Total Revenue for Current Month], B.[Previous Month], B.[Total Revenue for Previous Month],
A.[Total Revenue for current Month] - B.[Total Revenue for previous Month] AS 'Revenue Difference between current Month and previous Month'
FROM
(SELECT Month_Name AS 'Current Month', SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Current Month'
FROM [Revenue Raw Data], yt_Calendar_lookup
WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
AND [Revenue Raw Data].Month_ID IN (SELECT MAX(Month_ID) FROM [Revenue Raw Data])
GROUP BY Month_Name
) A,
(SELECT Month_Name AS 'Previous Month', SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Previous Month'
FROM [Revenue Raw Data], yt_Calendar_lookup
WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
AND [Revenue Raw Data].Month_ID IN (SELECT MAX(Month_ID) - 1 FROM [Revenue Raw Data])
GROUP BY Month_Name
) B
</code>```

And it works perfectly.

Body:
I have the following tables:

[Revenue Raw Data] consisting of Month_ID,Revenue

and it has the following sample data:

Month_ID
128
124
123
122
126
120

Revenue
1768077
1767617
1734230
1687976
1686309

yt_Calendar_lookup consisting of Month_ID,Month_No,Month_Name

and it has the following sample data:

Month_No
1
2
3
4
5
6
7
8
9
10
11
12

Month_ID
120
121
122
123
124
125
126
127
128
129
130
131

Month_Name
January
February
March
April
May
June
July
August
September
October
November
December

What I am trying to achieve is to display the results for the following 5 columns:

Display Current Month as the first column from the table yt_Calendar_lookup

Display Total Revenue for the Current Month as the second column from the table [Revenue Raw Data]

Display Previous Month as the third column from the table yt_Calendar_lookup

Display Total Revenue for the Previous Month as the fourth column from the table [Revenue Raw Data]

Display Revenue difference between Current Month and Previous Month as the fifth column from the table [Revenue Raw Data]

Initially, this is what I have tried:

SELECT
    A.[Total Revenue for Current Month]
    , B.[Total Revenue for Previous Month]
    , A.[Total Revenue for current Month] - B.[Total Revenue for previous Month] AS 'Revenue Difference between current Month and previous Month'
FROM (
    SELECT SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Current Month'
    FROM [Revenue Raw Data]
    WHERE Month_ID IN (SELECT MAX(Month_ID) FROM [Revenue Raw Data])
) A, (
    SELECT SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Previous Month'
    FROM [Revenue Raw Data]
    WHERE Month_ID IN (SELECT MAX(Month_ID) - 1 FROM [Revenue Raw Data])
) B

With the query above, I could successfully display the following 3 columns:

Total Revenue for Current Month, Total Revenue for Previous Month, Revenue Difference between Current Month and Previous Month

And this is the result I have received:

Total Revenue for Current Month Total Revenue for Previous Month
21221564                        19973825

Revenue Difference between current Month and previous Month
1247739

With the next query, I was trying to display the following 5 columns:

Current Month, Total Revenue for Current Month, Previous Month, Total Revenue for Previous Month, Revenue Difference between Current Month and Previous Month

This is what I have tried:

    SELECT A.[Current Month],
A.[Total Revenue for Current Month],
    B.[Previous Month],
B.[Total Revenue for Previous Month],
    A.[Total Revenue for current Month] - B.[Total Revenue for previous Month]
    AS 'Revenue Difference between current Month and previous Month'
    FROM
    (SELECT Month_Name
AS 'Current Month',
    SUM(CAST(Revenue AS BIGINT))
    AS 'Total Revenue for Current Month'
    FROM [Revenue Raw Data], yt_Calendar_lookup
    WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
    AND [Revenue Raw Data].Month_ID IN
    (SELECT MAX(Month_ID) FROM [Revenue Raw Data])
    ) A,
    (SELECT Month_Name
AS 'Previous Month',
    SUM(CAST(Revenue AS BIGINT))
    AS 'Total Revenue for Previous Month'
    FROM [Revenue Raw Data], yt_Calendar_lookup
    WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
    AND [Revenue Raw Data].Month_ID IN
(SELECT MAX(Month_ID) - 1 FROM [Revenue Raw Data])
    ) B

I received the following error message:

Column 'yt_Calendar_lookup.Month_Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I even tried by adding GROUP BY A.Month_Name,B.Month_Name, and even after that I am receiving the same error message.

I am still trying to figure out on where I am making the mistake for this particular query.

Solution for this particular issue will be highly appreciated.

Body:
I finally managed to solve the problem.
As mentioned by one of the StackOverflow user, that all I had to add was GROUP BY Month_Name on both the sub-queries.

This is what I have done:

SELECT A.[Current Month], A.[Total Revenue for Current Month], B.[Previous Month], B.[Total Revenue for Previous Month],
A.[Total Revenue for current Month] - B.[Total Revenue for previous Month] AS 'Revenue Difference between current Month and previous Month'
FROM
(SELECT Month_Name AS 'Current Month', SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Current Month'
FROM [Revenue Raw Data], yt_Calendar_lookup
WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
AND [Revenue Raw Data].Month_ID IN (SELECT MAX(Month_ID) FROM [Revenue Raw Data])
GROUP BY Month_Name
) A,
(SELECT Month_Name AS 'Previous Month', SUM(CAST(Revenue AS BIGINT)) AS 'Total Revenue for Previous Month'
FROM [Revenue Raw Data], yt_Calendar_lookup
WHERE [Revenue Raw Data].Month_ID = yt_Calendar_lookup.Month_ID
AND [Revenue Raw Data].Month_ID IN (SELECT MAX(Month_ID) - 1 FROM [Revenue Raw Data])
GROUP BY Month_Name
) B

And it works perfectly.


问:
The Number Stream detection
How to create a function NumberStream(str) that takes the str parameter being passed which will contain the numbers 2 through 9, and determine if there is a consecutive stream of digits of at least N length where N is the actual digit value.

If so, program should return the string true, otherwise, program should return the string false. For example: if str is "6539923335" then the program should return the string true because there is a consecutive stream of 3's of length 3.

I have written the code but it needs some changes to perform as desired:

```<code>def NumberStream(str):
    global j
    l = len(str)
    count = 0
    res = str[0]
    print("Length of the string is ", l)
    for i in range(l):
        count += 1
        cur_count = 1
        print("Looping")
        for j in range(i+1, l):
            if str[i] != str[j]:
                break
            cur_count += 1
            print(str[i], " and ", str[j], " with cur_count = ", cur_count, " and count = ", count)
        if str[i] == str[j-1] and str[j-1] == cur_count:
            return

print(NumberStream("6539923335"))
</code>```

答:
```<code>from collections import defaultdict
import operator
def NumberStream(string):
    count={}
    for i in range(len(string)-1):
        if string[i]==string[i+1]:
            count[str(i)]=string[i]
            count[str(i+1)]=string[i+1]
    print(count)
    res=defaultdict(int)
    for key, item in count.items():
        res[item]+=1
    print(res)
    stream=0
    for key, item in res.items():
        if int(key)== item:
            stream=key

    if int(stream)> 0:
        return "true"
    else: return "false"

</code>```

This is my solution

Title: The Number Stream detection

Body:
How to create a function NumberStream(str) that takes the str parameter being passed which will contain the numbers 2 through 9, and determine if there is a consecutive stream of digits of at least N length where N is the actual digit value.

If so, program should return the string true, otherwise, program should return the string false. For example: if str is "6539923335" then the program should return the string true because there is a consecutive stream of 3's of length 3.

I have written the code but it needs some changes to perform as desired:

def NumberStream(str):
    global j
    l = len(str)
    count = 0
    res = str[0]
    print("Length of the string is ", l)
    for i in range(l):
        count += 1
        cur_count = 1
        print("Looping")
        for j in range(i+1, l):
            if str[i] != str[j]:
                break
            cur_count += 1
            print(str[i], " and ", str[j], " with cur_count = ", cur_count, " and count = ", count)
        if str[i] == str[j-1] and str[j-1] == cur_count:
            return

print(NumberStream("6539923335"))

Body:
from collections import defaultdict
import operator
def NumberStream(string):
    count={}
    for i in range(len(string)-1):
        if string[i]==string[i+1]:
            count[str(i)]=string[i]
            count[str(i+1)]=string[i+1]
    print(count)
    res=defaultdict(int)
    for key, item in count.items():
        res[item]+=1
    print(res)
    stream=0
    for key, item in res.items():
        if int(key)== item:
            stream=key

    if int(stream)> 0:
        return "true"
    else: return "false"

This is my solution


问:
Boolean operations on segments of a same line
I have been looking for some guidance on a geometry problem
I have 2 segments that lie on the same line and I want to clip both based on any of the boolean operations

```<code>Union, Intersection, Difference, Difference-Rev, Xor
</code>```

The expected result should be a list of segments because cases can return 0,1 or 2 segments

in my current approach, I define a segment as a pair of 2 numbers (coordinates) on the same line

```<code>Segment 1 : (2,13)
Segment 2: (8,16)
</code>```

my first step is make an array of sorted points

```<code>points = [2, 8, 13, 16]
</code>```

second is iterate and label the points by their owner

```<code>Segment 1, Segment 2 or Both
</code>```

Finally, I need to do  a selection given a boolean operation and the labels

But currently I'm stuck on the second step and I don't know how to find the labels and then do the selection given the boolean operation, any help ?

答:
Put triplets [coordinate, begin/end, segment number] in the list.

Sort the list.

Walk through the list. At every point change a code adding or subtracting segment number. So code=3 denotes segement intersection, code=1 corresponds to the first segment only range.

Form resulting ranges depending on operation required and code change. Here I just enumerated operations in your list order.

I'm not sure what to do when end of one segment coinsides with beginning of another. Current sorting puts end before begin, so union will give two separate ranges. If needed, change sign of begin/end field and make code -= p[1] * p[2]

Python code:

```<code>def boolops(s1, s2, op):
    pts = [[s1[0], 1, 1], [s1[1], -1, 1],[s2[0], 1, 2],[s2[1], -1, 2]]
    pts.sort()
    #print(pts)
    res = []
    code = 0
    oldcode = 0
    start = -1
    for p in pts:
        code += p[1] * p[2]
        #print(oldcode, code)
        if op == 0:  # union
            if oldcode == 0 and code:
                start = p[0]
            elif oldcode and code == 0:
                res.append([start, p[0]])
        elif op == 1: #intersection
            if code == 3:
                start = p[0]
            elif oldcode == 3:
                res.append([start, p[0]])
        elif op == 2: #diff s1-s2
            if code == 1:
                start = p[0]
            elif oldcode == 1:
                res.append([start, p[0]])
        elif op == 3: #rev diff s2-s1
            if code == 2:
                start = p[0]
            elif oldcode == 2:
                res.append([start, p[0]])
        elif op == 4: #xor
            if code % 3 > 0:
                start = p[0]
            else:
                res.append([start, p[0]])
        oldcode = code
    return res

print(boolops([2,10],[5,12], 0))
print(boolops([2,5],[10,12], 0))

print(boolops([2,10],[5,12], 1))
print(boolops([2,5],[10,12], 1))

print(boolops([2,10],[5,12], 2))
print(boolops([2,5],[10,12], 2))

print(boolops([2,10],[5,12], 3))
print(boolops([2,5],[10,12], 3))

print(boolops([2,10],[5,12], 4))
print(boolops([2,5],[10,12], 4))

[2, 12]]   #union
[[2, 5], [10, 12]]
[[5, 10]]  #intersection
[]
[[2, 5]]  #diff
[[2, 5]]
[[10, 12]] #revdiff
[[10, 12]]
[[2, 5], [10, 12]]  #xor
[[2, 5], [10, 12]]

#full coverage tests
print(boolops([2,5],[1,6], 0))
print(boolops([2,5],[1,6], 1))
print(boolops([2,5],[1,6], 2))
print(boolops([2,5],[1,6], 3))
print(boolops([2,5],[1,6], 4)

[[1, 6]]
[[2, 5]]
[]
[[1, 2], [5, 6]]
[[1, 2], [5, 6]]
</code>```

)

Body:
I have been looking for some guidance on a geometry problem
I have 2 segments that lie on the same line and I want to clip both based on any of the boolean operations

Union, Intersection, Difference, Difference-Rev, Xor

The expected result should be a list of segments because cases can return 0,1 or 2 segments

in my current approach, I define a segment as a pair of 2 numbers (coordinates) on the same line

Segment 1 : (2,13)
Segment 2: (8,16)

my first step is make an array of sorted points

points = [2, 8, 13, 16]

second is iterate and label the points by their owner

Segment 1, Segment 2 or Both

Finally, I need to do  a selection given a boolean operation and the labels

But currently I'm stuck on the second step and I don't know how to find the labels and then do the selection given the boolean operation, any help ?

Body:
Put triplets [coordinate, begin/end, segment number] in the list.

Sort the list.

Walk through the list. At every point change a code adding or subtracting segment number. So code=3 denotes segement intersection, code=1 corresponds to the first segment only range.

Form resulting ranges depending on operation required and code change. Here I just enumerated operations in your list order.

I'm not sure what to do when end of one segment coinsides with beginning of another. Current sorting puts end before begin, so union will give two separate ranges. If needed, change sign of begin/end field and make code -= p[1] * p[2]

Python code:

def boolops(s1, s2, op):
    pts = [[s1[0], 1, 1], [s1[1], -1, 1],[s2[0], 1, 2],[s2[1], -1, 2]]
    pts.sort()
    #print(pts)
    res = []
    code = 0
    oldcode = 0
    start = -1
    for p in pts:
        code += p[1] * p[2]
        #print(oldcode, code)
        if op == 0:  # union
            if oldcode == 0 and code:
                start = p[0]
            elif oldcode and code == 0:
                res.append([start, p[0]])
        elif op == 1: #intersection
            if code == 3:
                start = p[0]
            elif oldcode == 3:
                res.append([start, p[0]])
        elif op == 2: #diff s1-s2
            if code == 1:
                start = p[0]
            elif oldcode == 1:
                res.append([start, p[0]])
        elif op == 3: #rev diff s2-s1
            if code == 2:
                start = p[0]
            elif oldcode == 2:
                res.append([start, p[0]])
        elif op == 4: #xor
            if code % 3 > 0:
                start = p[0]
            else:
                res.append([start, p[0]])
        oldcode = code
    return res

print(boolops([2,10],[5,12], 0))
print(boolops([2,5],[10,12], 0))

print(boolops([2,10],[5,12], 1))
print(boolops([2,5],[10,12], 1))

print(boolops([2,10],[5,12], 2))
print(boolops([2,5],[10,12], 2))

print(boolops([2,10],[5,12], 3))
print(boolops([2,5],[10,12], 3))

print(boolops([2,10],[5,12], 4))
print(boolops([2,5],[10,12], 4))

[2, 12]]   #union
[[2, 5], [10, 12]]
[[5, 10]]  #intersection
[]
[[2, 5]]  #diff
[[2, 5]]
[[10, 12]] #revdiff
[[10, 12]]
[[2, 5], [10, 12]]  #xor
[[2, 5], [10, 12]]

#full coverage tests
print(boolops([2,5],[1,6], 0))
print(boolops([2,5],[1,6], 1))
print(boolops([2,5],[1,6], 2))
print(boolops([2,5],[1,6], 3))
print(boolops([2,5],[1,6], 4)

[[1, 6]]
[[2, 5]]
[]
[[1, 2], [5, 6]]
[[1, 2], [5, 6]]

)


问:
Why is my app running slow on an older version of android
I am building an app for college project, when I tested it on Virtual Device- Pixel 2 API 30 Android 11, it is running smoothly, but when I am testing it on my physical device which is Redmi Note 3 running on Android 6 (Marshmallow) it is sticking.</p>

答: Reason is android version. Try creating a virutal system which has android 6 marshmallow, it will behave same.</p>


问:
How to count 1 bits in an integer in JavaScript
How to count the number of 1 bits in an integer.

So say you have the binary number 11100000. Basically there are 3 boolean flags at the beginning. The corresponding decimal notation for this is 224. Wondering how to take that integer and loop through it somehow to add the number of 1s that it starts with. Something like this:

```<code>var int = 224
var n = 8
var i = 0
var total = 0
while (i++ < n) {
  if (int.getBitAt(i) == 1) {
    total++
  } else {
    break
  }
}
</code>```

I've never really dealt with bits so not sure how to accomplish this in an optimal way (i.e. without converting it to a string '11100000' or other unoptimal ways.

答:
const num = 42726; // value to count set bits in
const numBytes = 2; // number of bytes used to represent num
let i = 0;
let count = 0;
while (i < numBytes * 8) {
  if (((1 <> i === 1) count++;
  i++;
}
console.log(count); // 9
```

Body:
How to count the number of 1 bits in an integer.

So say you have the binary number 11100000. Basically there are 3 boolean flags at the beginning. The corresponding decimal notation for this is 224. Wondering how to take that integer and loop through it somehow to add the number of 1s that it starts with. Something like this:

var int = 224
var n = 8
var i = 0
var total = 0
while (i++ < n) {
  if (int.getBitAt(i) == 1) {
    total++
  } else {
    break
  }
}

I've never really dealt with bits so not sure how to accomplish this in an optimal way (i.e. without converting it to a string '11100000' or other unoptimal ways.

Body:
const num = 42726; // value to count set bits in
const numBytes = 2; // number of bytes used to represent num
let i = 0;
let count = 0;
while (i < numBytes * 8) {
  if (((1 << i) & num) >> i === 1) count++;
  i++;
}
console.log(count); // 9


问:
How Can I add a file to Azurite [Azure Storage Emulator]
I'm having a hard time figuring out how to add a file to this emulator in order to test azure blob different operations locally.</p>

答:
Azurite needs to be up and run in given ports . then you can access it.

main point is use the connection string as follows

```<code>**"AzureStorage": {
    "ConnectionString": "UseDevelopmentStorage=true;",**
</code>```

Then follow the below github code.
https://github.com/chatchathu199162/BlobUpdate/blob/master/BlobUpdate/BlobUpdate.csproj

Body:
Azurite needs to be up and run in given ports . then you can access it.

main point is use the connection string as follows

**"AzureStorage": {
    "ConnectionString": "UseDevelopmentStorage=true;",**

Then follow the below github code.
https://github.com/chatchathu199162/BlobUpdate/blob/master/BlobUpdate/BlobUpdate.csproj


问:
Components are accessable via console on production?
I recently deployed a website for a friend of mine, written in React, Express, Mongodb, etc... And I can see that I have a console.log on one of the components and wanted to ask if that's normal that a component is accessible via a console.log? (I can access the source code because of that).

And is there a solution for that or just removing ALL console.log before production?

答:
Assuming you used create-react-app to start the project, it generates sourcemaps when you run the build script by default. You can disable this by adding GENERATE_SOURCEMAP=false in your .env file.

As for the console logs, you can either change console.log to console.debug (which only shows in the browser console when you have verbose logging enabled) or you can rely on some linting rule (like this) to prevent the use of console altogether.


问:
Compose UI testing - How do I assert a text color?
I'm trying to test a Text that on my component I can print it in different colors, so on my test I'm verifying it gets the expected color. I was looking for a method to return the color but I did not find any.

From now I'm asserting that the text is correct and the visibility is correct, but when trying to find the method to get the colour I get too deep and I'm looking for a simpler solution.

```<code>composeTestRule.onNode(hasTestTag("testTagForButton"), true)
            .assertExists()
            .assertTextEquals("Testing")
</code>```

I've check that I can do something like .fetchSemanticsNode().layoutInfo.getModifierInfo() to get into the Modifier and perhaps from there I can get the colour, but it's too much maybe. Also I've found this .captureToImage() that perhaps I could get the colour on it, but since I had to put the pixels I decided that it's not the way.

Is there any simple way to get that?

答:
I am by no means a compose expert, but just looking at compose source code, you could utilize their GetTextLayoutResult accessibility semantic action. This will contain all the properties that are used to render the Text on a canvas.

Some quick and dirty extension functions I put up for convenience:

```<code>fun SemanticsNodeInteraction.assertTextColor(
    color: Color
): SemanticsNodeInteraction = assert(isOfColor(color))

private fun isOfColor(color: Color): SemanticsMatcher = SemanticsMatcher(
    "${SemanticsProperties.Text.name} is of color '$color'"
) {
    val textLayoutResults = mutableListOf<TextLayoutResult>()
    it.config.getOrNull(SemanticsActions.GetTextLayoutResult)
        ?.action
        ?.invoke(textLayoutResults)
    return@SemanticsMatcher if (textLayoutResults.isEmpty()) {
        false
    } else {
        textLayoutResults.first().layoutInput.style.color == color
    }
}
</code>```

Which can be then used like this:

```<code>composeTestRule.onNode(hasTestTag("testTagForButton"), true)
            .assertExists()
            .assertTextEquals("Testing")
            .assertTextColor(Color.Black)
</code>```

Body:
I'm trying to test a Text that on my component I can print it in different colors, so on my test I'm verifying it gets the expected color. I was looking for a method to return the color but I did not find any.

From now I'm asserting that the text is correct and the visibility is correct, but when trying to find the method to get the colour I get too deep and I'm looking for a simpler solution.

composeTestRule.onNode(hasTestTag("testTagForButton"), true)
            .assertExists()
            .assertTextEquals("Testing")

I've check that I can do something like .fetchSemanticsNode().layoutInfo.getModifierInfo() to get into the Modifier and perhaps from there I can get the colour, but it's too much maybe. Also I've found this .captureToImage() that perhaps I could get the colour on it, but since I had to put the pixels I decided that it's not the way.

Is there any simple way to get that?

Body:
I am by no means a compose expert, but just looking at compose source code, you could utilize their GetTextLayoutResult accessibility semantic action. This will contain all the properties that are used to render the Text on a canvas.

Some quick and dirty extension functions I put up for convenience:

fun SemanticsNodeInteraction.assertTextColor(
    color: Color
): SemanticsNodeInteraction = assert(isOfColor(color))

private fun isOfColor(color: Color): SemanticsMatcher = SemanticsMatcher(
    "${SemanticsProperties.Text.name} is of color '$color'"
) {
    val textLayoutResults = mutableListOf<TextLayoutResult>()
    it.config.getOrNull(SemanticsActions.GetTextLayoutResult)
        ?.action
        ?.invoke(textLayoutResults)
    return@SemanticsMatcher if (textLayoutResults.isEmpty()) {
        false
    } else {
        textLayoutResults.first().layoutInput.style.color == color
    }
}

Which can be then used like this:

composeTestRule.onNode(hasTestTag("testTagForButton"), true)
            .assertExists()
            .assertTextEquals("Testing")
            .assertTextColor(Color.Black)


问:
How to delete a file from physical directory with JavaScript (Windows/IE Only)?
I am dynamically generating an HTML file for the print option.

After the print window has been opened and the file printed, I want to remove the HTML file from the folder.

I need to do this with JavaScript. For this I am using the following code:

```<code>var myObject = new ActiveXObject("Scripting.FileSystemObject");
var myFolder = myObject.GetFile(strReportFilePath);
myFolder.Delete();`
</code>```

But this only works in IE but not in Firefox, so how do I delete the file with a JavaScript function?

答: You can't. JavaScript is sandboxed. With IE, you are using ActiveX to do the dirty work.</p>

Body:
I am dynamically generating an HTML file for the print option.

After the print window has been opened and the file printed, I want to remove the HTML file from the folder.

I need to do this with JavaScript. For this I am using the following code:

var myObject = new ActiveXObject("Scripting.FileSystemObject");
var myFolder = myObject.GetFile(strReportFilePath);
myFolder.Delete();`

But this only works in IE but not in Firefox, so how do I delete the file with a JavaScript function?


问:
Detect lack of earpiece (speakerphone only) on an Android device
I've got an app which displays a speakerphone toggle button when used on a phone.  The toggle switches audio routing between the phone's earpiece and the speakerphone.  However, when the app is run on a tablet (or any device which lacks an earpiece), I'd like to remove the toggle, since all audio is routed through the speakerphone.

Ideally, I'd like to use some kind of isEarpiecePresent() call, or maybe check a flag on some configuration object to find this information, but I can't find anything of the sort in the API.

I attempted to work around the issue by calling AudioManager.setSpeakerphoneOn(false), then checking AudioManager.isSpeakerphoneOn(), hoping that it would still return true and I could key off of that.  The system returned false, even though audio is still routing through the speaker.

I'm currently thinking of checking for telephony capability, even though that doesn't exactly fit.  Any other ideas?

答:
starting with Android S/12 (API 31) we have new methods for checking built-in earpiece presence. comprehensive copy-pasteable method below, on older system versions it is using reflection from @milosmns answer (thanks!)

```<code>private static Boolean hasEarpiece = null;

public static boolean hasEarpiece(Context context) {
    if (hasEarpiece != null) return hasEarpiece;

    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

    if (Build.VERSION.SDK_INT >= 31) {
        List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
        for (AudioDeviceInfo device : devices) {
            if (device.getType() == AudioDeviceInfo.TYPE_BUILTIN_EARPIECE) {
                hasEarpiece = true;
                break;
            }
        }
        if (hasEarpiece == null) {
            // just for safety
            AudioDeviceInfo currDevice = audioManager.getCommunicationDevice();
            hasEarpiece = currDevice != null &&
                    currDevice.getType() == AudioDeviceInfo.TYPE_BUILTIN_EARPIECE;
        }
        Log.i("EarpieceBuiltInChecker", "hasEarpiece detected:%s", hasEarpiece);
        return hasEarpiece;
    }

    try {
        Method method = AudioManager.class.getMethod("getDevicesForStream", Integer.TYPE);
        Field field = AudioManager.class.getField("DEVICE_OUT_EARPIECE");
        int earpieceFlag = field.getInt(null);
        int bitmaskResult = (int) method.invoke(audioManager, AudioManager.STREAM_VOICE_CALL);

        hasEarpiece = (bitmaskResult & earpieceFlag) == earpieceFlag;
        Log.i("EarpieceBuiltInChecker", "hasEarpiece detected:" + hasEarpiece);
    } catch (Throwable error) {
        hasEarpiece = false;
        Log.i("EarpieceBuiltInChecker", "hasEarpiece detection FAILED!");
    }

    return hasEarpiece;
}
</code>```

my streams are AudioManager.STREAM_VOICE_CALL type (where applicable)

Body:
starting with Android S/12 (API 31) we have new methods for checking built-in earpiece presence. comprehensive copy-pasteable method below, on older system versions it is using reflection from @milosmns answer (thanks!)

private static Boolean hasEarpiece = null;

public static boolean hasEarpiece(Context context) {
    if (hasEarpiece != null) return hasEarpiece;

    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

    if (Build.VERSION.SDK_INT >= 31) {
        List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
        for (AudioDeviceInfo device : devices) {
            if (device.getType() == AudioDeviceInfo.TYPE_BUILTIN_EARPIECE) {
                hasEarpiece = true;
                break;
            }
        }
        if (hasEarpiece == null) {
            // just for safety
            AudioDeviceInfo currDevice = audioManager.getCommunicationDevice();
            hasEarpiece = currDevice != null &&
                    currDevice.getType() == AudioDeviceInfo.TYPE_BUILTIN_EARPIECE;
        }
        Log.i("EarpieceBuiltInChecker", "hasEarpiece detected:%s", hasEarpiece);
        return hasEarpiece;
    }

    try {
        Method method = AudioManager.class.getMethod("getDevicesForStream", Integer.TYPE);
        Field field = AudioManager.class.getField("DEVICE_OUT_EARPIECE");
        int earpieceFlag = field.getInt(null);
        int bitmaskResult = (int) method.invoke(audioManager, AudioManager.STREAM_VOICE_CALL);

        hasEarpiece = (bitmaskResult & earpieceFlag) == earpieceFlag;
        Log.i("EarpieceBuiltInChecker", "hasEarpiece detected:" + hasEarpiece);
    } catch (Throwable error) {
        hasEarpiece = false;
        Log.i("EarpieceBuiltInChecker", "hasEarpiece detection FAILED!");
    }

    return hasEarpiece;
}

my streams are AudioManager.STREAM_VOICE_CALL type (where applicable)


问:
Archunit check method calls
I have a class that has three methods that shouldn't be called from certain classes.

How can I check this with Archunit?

So for example

```<code>public class Foo {

   public void method1() {
   }

   public void method2() {
   }

   public void method3() {
   }
}
</code>```

method1 and method2 should only be called by classes Bar1 and Bar2.

答:
With

```<code>import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static com.tngtech.archunit.lang.conditions.ArchConditions.callMethod;
</code>```

you can use

ArchRule rule = noClasses()
    .that().doNotHaveFullyQualifiedName(Bar1.class.getName())
    .and().doNotHaveFullyQualifiedName(Bar2.class.getName())
    // alternative 1:
    .should().callMethod(Foo.class, "method1")
    .orShould().callMethod(Foo.class, "method2");
    // alternative 2:
    // .should(callMethod(Foo.class, "method1").or(callMethod(Foo.class, "method2")));
```

Title: Archunit check method calls

Body:
I have a class that has three methods that shouldn't be called from certain classes.

How can I check this with Archunit?

So for example

public class Foo {

   public void method1() {
   }

   public void method2() {
   }

   public void method3() {
   }
}

method1 and method2 should only be called by classes Bar1 and Bar2.

Body:
With

import com.tngtech.archunit.lang.ArchRule;

import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static com.tngtech.archunit.lang.conditions.ArchConditions.callMethod;

you can use

ArchRule rule = noClasses()
    .that().doNotHaveFullyQualifiedName(Bar1.class.getName())
    .and().doNotHaveFullyQualifiedName(Bar2.class.getName())
    // alternative 1:
    .should().callMethod(Foo.class, "method1")
    .orShould().callMethod(Foo.class, "method2");
    // alternative 2:
    // .should(callMethod(Foo.class, "method1").or(callMethod(Foo.class, "method2")));


问:
Find lowest element of predicates of the size 2 and ensure that there is only one lowest element?
I am working on a piece of encoding that finds the cell with the lowest coordinates in a grid. This cell will be used as a starting point for a path. Cells are defined with predicate cell(X,Y).

```<code>isLower(X,Y,F,G) :- cell(X,Y), cell(F,G), X<=F, Y<=G.

first(X,Y) :- cell(X,Y), not black(X,Y), cell(F,G), not black(F,G), cell(A,B), not black(A,B), isLower(X,Y,F,G), not isLower(A,B,X,Y).
</code>```

I want to have only one first cell. My problem is that ASP starts giving me a bunch of cells, because first(X,Y) is a predicate and ASP will try to produce as many as it can.

How do I tell the program that it is supposed to find only the lowest element (i.e. the cell with the smallest coordinates)? How can I force it to be only ONE cell?

答:
It is still unclear what exactly you want to achieve, but in case that cell/2 are facts, i would recommend a rule like:

```<code>first(X',Y') :- (X',Y') = #min {(X,Y) : cell(X,Y)}.
</code>```

Body:
I am working on a piece of encoding that finds the cell with the lowest coordinates in a grid. This cell will be used as a starting point for a path. Cells are defined with predicate cell(X,Y).

isLower(X,Y,F,G) :- cell(X,Y), cell(F,G), X<=F, Y<=G.

first(X,Y) :- cell(X,Y), not black(X,Y), cell(F,G), not black(F,G), cell(A,B), not black(A,B), isLower(X,Y,F,G), not isLower(A,B,X,Y).

I want to have only one first cell. My problem is that ASP starts giving me a bunch of cells, because first(X,Y) is a predicate and ASP will try to produce as many as it can.

How do I tell the program that it is supposed to find only the lowest element (i.e. the cell with the smallest coordinates)? How can I force it to be only ONE cell?

Body:
It is still unclear what exactly you want to achieve, but in case that cell/2 are facts, i would recommend a rule like:

first(X',Y') :- (X',Y') = #min {(X,Y) : cell(X,Y)}.


问:
"Symbolic link not allowed or link target not accessible" on fresh installed XAMPP for Linux
I did a fresh-install of XAMPP for Linux (version 1.7.4) on my Ubuntu 11.04 x64 laptop.
Then I made a link in my htdocs folder to my project folder:

```<code>$pwd
/opt/lampp/htdocs
$sudo ln -s /home/petra/projects/webapp webapp
$ls -al
drwxr-xr-x  4 nobody root 4096 2011-08-18 11:58 .
drwxr-xr-x 18 root   root 4096 2011-01-25 15:33 ..
lrwxrwxrwx  1 root   root   26 2011-08-18 11:42 webapp -> /home/petra/projects/webapp
</code>```

When I opened the webapp in the browser using http://localhost/webapp, it only showed "403 Access Forbidden". The error log said:

```<code>$tail -f /opt/lampp/logs/error_log
[Thu Aug 18 11:43:15 2011] [error] [client 127.0.0.1] Symbolic link not allowed or link target not accessible: /opt/lampp/htdocs/webapp
</code>```

Here is the httpd.conf. Strangely, the FollowSymLinks options are already defined (default).

There is a similar question on the XAMPP forum but I think nobody seems to pay attention to it anymore.

Does anyone have an idea how to fix this?

答:
I found out that if I use link from directory outside /home/petra, the web-app is working normally. I guess it's because I use Encrypted Home Directory setting on my Ubuntu.

I just have to move the project directory outside my home directory to make it work.

Body:
I did a fresh-install of XAMPP for Linux (version 1.7.4) on my Ubuntu 11.04 x64 laptop.
Then I made a link in my htdocs folder to my project folder:

$pwd
/opt/lampp/htdocs
$sudo ln -s /home/petra/projects/webapp webapp
$ls -al
drwxr-xr-x  4 nobody root 4096 2011-08-18 11:58 .
drwxr-xr-x 18 root   root 4096 2011-01-25 15:33 ..
lrwxrwxrwx  1 root   root   26 2011-08-18 11:42 webapp -> /home/petra/projects/webapp

When I opened the webapp in the browser using http://localhost/webapp, it only showed "403 Access Forbidden". The error log said:

$tail -f /opt/lampp/logs/error_log
[Thu Aug 18 11:43:15 2011] [error] [client 127.0.0.1] Symbolic link not allowed or link target not accessible: /opt/lampp/htdocs/webapp

Here is the httpd.conf. Strangely, the FollowSymLinks options are already defined (default).

There is a similar question on the XAMPP forum but I think nobody seems to pay attention to it anymore.

Does anyone have an idea how to fix this?


问:
Terraform init Error: Failed to get existing workspaces: S3 bucket does not exist
Hi i have an issue with terraform not being able to see the s3 bucket when i specify it as a backend

```<code>aws --profile terraform s3api create-bucket --bucket "some_name_here" --region "eu-west-2" \
          --create-bucket-configuration LocationConstraint="eu-west-2"
</code>```

terraform init

```<code>Initializing modules...

Initializing the backend...

Error: Failed to get existing workspaces: S3 bucket does not exist.

The referenced S3 bucket must have been previously created. If the S3 bucket
was created within the last minute, please wait for a minute or two and try
again.

Error: NoSuchBucket: The specified bucket does not exist
    status code: 404, request id: QYJT8KP0W4TM986A, host id: a7R1EOOnIhP6YzDcKd66zdyCJ8wk6lVom/tohsc0ipUe5yEJK1/V4bLGX9khi4q4/J7d4BgYXCc=
</code>```

backend.tf

```<code>terraform {
  backend "s3" {
    bucket = "some_name_here"
    key    = "networking/terraform.tfstate"
    region = "eu-west-2"
  }
}
</code>```

provider.tf

```<code>provider "aws" {
  region                  = "eu-west-2"
  shared_credentials_file = "$HOME/.aws/credentials"
  profile                 = "terraform"
}
</code>```

I can see the bucket in the dashboard

答:
It looks like you are using a profile in the command to create the bucket. Therefore, you probably need to export a variable in the environment running terraform to use this same profile. I imagine terraform without this profile or another with sufficient permissions is unable to read from the bucket.

```<code>export AWS_PROFILE=terraform
terraform init
</code>```

Alternatively, you can pass the profile into the backend configuration, like:

```<code>terraform {
  backend "s3" {
    bucket  = "some_name_here"
    key     = "networking/terraform.tfstate"
    profile = "terraform"
    region  = "eu-west-2"
  }
}
</code>```

To summarize, the most simple configuration is:

```<code>terraform {
  backend "s3" {
    bucket  = "some_name_here"
    key     = "networking/terraform.tfstate"
    region  = "eu-west-2"
  }
}

provider "aws" {
  region = "eu-west-2"
}
</code>```

then:

```<code>export AWS_PROFILE=terraform
aws s3api create-bucket --bucket "some_name_here" --region "eu-west-2" --create-bucket-configuration LocationConstraint="eu-west-2"
terraform init
</code>```

Body:
Hi i have an issue with terraform not being able to see the s3 bucket when i specify it as a backend

aws --profile terraform s3api create-bucket --bucket "some_name_here" --region "eu-west-2" \
          --create-bucket-configuration LocationConstraint="eu-west-2"

terraform init

Initializing modules...

Initializing the backend...

Error: Failed to get existing workspaces: S3 bucket does not exist.

The referenced S3 bucket must have been previously created. If the S3 bucket
was created within the last minute, please wait for a minute or two and try
again.

Error: NoSuchBucket: The specified bucket does not exist
    status code: 404, request id: QYJT8KP0W4TM986A, host id: a7R1EOOnIhP6YzDcKd66zdyCJ8wk6lVom/tohsc0ipUe5yEJK1/V4bLGX9khi4q4/J7d4BgYXCc=

backend.tf

terraform {
  backend "s3" {
    bucket = "some_name_here"
    key    = "networking/terraform.tfstate"
    region = "eu-west-2"
  }
}

provider.tf

provider "aws" {
  region                  = "eu-west-2"
  shared_credentials_file = "$HOME/.aws/credentials"
  profile                 = "terraform"
}

I can see the bucket in the dashboard

Body:
It looks like you are using a profile in the command to create the bucket. Therefore, you probably need to export a variable in the environment running terraform to use this same profile. I imagine terraform without this profile or another with sufficient permissions is unable to read from the bucket.

export AWS_PROFILE=terraform
terraform init

Alternatively, you can pass the profile into the backend configuration, like:

terraform {
  backend "s3" {
    bucket  = "some_name_here"
    key     = "networking/terraform.tfstate"
    profile = "terraform"
    region  = "eu-west-2"
  }
}

To summarize, the most simple configuration is:

terraform {
  backend "s3" {
    bucket  = "some_name_here"
    key     = "networking/terraform.tfstate"
    region  = "eu-west-2"
  }
}

provider "aws" {
  region = "eu-west-2"
}

then:

export AWS_PROFILE=terraform
aws s3api create-bucket --bucket "some_name_here" --region "eu-west-2" --create-bucket-configuration LocationConstraint="eu-west-2"
terraform init


问:
What does the expression : Select `(column1|column2|column3)?+.+` from Table in SQL means?
I am trying to convert a SQL Code into Pyspark SQL.
While selecting the columns from a table , the Select Statement has something as below :

```<code>Select a.`(column1|column2|column3)?+.+`,trim(column c)  from Table a;
</code>```

I would like to understand what

```<code>a.`(column1|column2|column3)?+.+`
</code>```

expression resolves to and what it actually implies?  How to address this while converting the sql into pyspark?

答:
That is a way of selecting certain column names using regexps. That regex matches (and excludes) the columns column1, column2 or column3.

It is the Spark's equivalent of the Hive's Quoted Identifiers. See also Spark's documentation.

Be aware that, for enabling this behavior, it is first necessary to run the following command:

```<code>spark.sql("SET spark.sql.parser.quotedRegexColumnNames=true").show(false)
</code>```

Body:
I am trying to convert a SQL Code into Pyspark SQL.
While selecting the columns from a table , the Select Statement has something as below :

Select a.`(column1|column2|column3)?+.+`,trim(column c)  from Table a;

I would like to understand what

a.`(column1|column2|column3)?+.+`

expression resolves to and what it actually implies?  How to address this while converting the sql into pyspark?

Body:
That is a way of selecting certain column names using regexps. That regex matches (and excludes) the columns column1, column2 or column3.

It is the Spark's equivalent of the Hive's Quoted Identifiers. See also Spark's documentation.

Be aware that, for enabling this behavior, it is first necessary to run the following command:

spark.sql("SET spark.sql.parser.quotedRegexColumnNames=true").show(false)


问:
Cat strings from file and compare it with associative bash array
I create associative array for example

declare -A vars=(["Test array here"]="POOLING TESTPOOL ")

And i have file with multiple lines which want to compare with array values and if match print array key.
I try this but it's doesn't work

match="POOLING TESTPOOL"

for key in "${vars[@]}"; do [[ $key = "$match" ]] && printf '%s\n' "${!vars[$key]}" ; done

Also I try glob

for key in "${vars[@]}"; do [[ $key = *"$match"* ]] && printf '%s\n' "${!vars[$key]}" ; done

But every time I got empty string

答:
So if you want cat files and compare string with associative array value
and print its key you can use this nested loop

for i in `cat file.txt`; do for key in "${!vars[@]}"; do if [[ ${vars[$key]} == *"$i"* ]]; then echo $key fi done done

Thanks to @Fravadona to point me.


问:
AI Doc Writer For Android Studio
Is there a plugin in Android studio for Writing comments in a faster way, The Tabnine code completion Plugin is great for Wirting code , but java doc or Other such commenting features are missing, VS code has the Plugin called AI Doc Writer, Is there any thing similar for android studio.</p>

答:
No, you have to do it manually. I also created a request to jetbrains (who developed android studio) for that plugin.

UPDATE: There is one plugin available in jetbrains store. Mintlify Doc Writer.

Title: AI Doc Writer For Android Studio