问:
Defining and initialize a class property in PHP Laravel controller
I try defined property for some controller and i get error :

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)

Constant expression contains invalid operations

This my controller code :

namespace App\Http\Controllers...;

```<code>use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Customer;
use App\City;
use Illuminate\Database\Eloquent\Builder;
use Carbon\Carbon;

use Illuminate\Support\Facades\Auth;

class CatalogController extends Controller
{
    protected $user = Auth::user();

    function user() {
       $user = optional(Auth::user())->load(['city']);
       return $user;
    }
}
</code>```

In php.net I read this:

Class member variables may be initialized, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

I assume that this rule is not executed in my code. Am I right?

答:
You should assign your properties in constructor like this

protected $user;

public function __construct()
    {
        $this->user = Auth::user();
    }
```

or through setters...

Edit

However in your case it's not a good idea please see https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors

Body:
I try defined property for some controller and i get error :

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)

Constant expression contains invalid operations

This my controller code :

namespace App\Http\Controllers...;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Customer;
use App\City;
use Illuminate\Database\Eloquent\Builder;
use Carbon\Carbon;

use Illuminate\Support\Facades\Auth;

class CatalogController extends Controller
{
    protected $user = Auth::user();

    function user() {
       $user = optional(Auth::user())->load(['city']);
       return $user;
    }
}

In php.net I read this:

Class member variables may be initialized, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

I assume that this rule is not executed in my code. Am I right?

Body:
You should assign your properties in constructor like this

protected $user;

public function __construct()
    {
        $this->user = Auth::user();
    }

or through setters...

Edit

However in your case it's not a good idea please see https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors


来源: stackexchange

问:
how can i retrive jpa-repository instance from class in spring 2.2.4.RELEASE
i need to retrieve specific instance of jpa-repository from an entity class to call findAll, findOne ecc...

```<code>Entity entity = getRepository(EntityClass).findOne(uriParamValue);
</code>```

In the previous spring version (1.5.X) i was doing it this way:

```<code>public JpaRepository<Entity, Serializable> getRepository(Class<?> javaClass) {
    return (JpaRepository<Entity, Serializable>) repositories.getRepositoryFor(javaClass);
}
</code>```

but in spring 2.2.X the Repository class interfaces has been changed from:

```<code>public Object getRepositoryFor(Class<?> domainClass) {
</code>```

to:

```<code>public Optional<Object> getRepositoryFor(Class<?> domainClass) {
</code>```

and i can't cast "Optional getRepositoryFor(X)" to JpaRepository instance to able to call JpaRepository methods.

Where am I doing wrong?

thanks

答:
I'm not familiar with the getRepositoryFor method, but Optional is a standard Java class intruduced in Java SE 8.
You can check if the value is present and get the actual value from the Optional if it is present. Here is a sample using orElseThrow, but there are also other variants. Checkout the Javadoc.

```<code>public JpaRepository<Entity, Serializable> getRepository(Class<?> javaClass) {
    return (JpaRepository<Entity, Serializable>) repositories.getRepositoryFor(javaClass)
           .orElseThrow(() -> new MyException());
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i need to retrieve specific instance of jpa-repository from an entity class to call findAll, findOne ecc...

Entity entity = getRepository(EntityClass).findOne(uriParamValue);

In the previous spring version (1.5.X) i was doing it this way:

public JpaRepository<Entity, Serializable> getRepository(Class<?> javaClass) {
    return (JpaRepository<Entity, Serializable>) repositories.getRepositoryFor(javaClass);
}

but in spring 2.2.X the Repository class interfaces has been changed from:

public Object getRepositoryFor(Class<?> domainClass) {

to:

public Optional<Object> getRepositoryFor(Class<?> domainClass) {

and i can't cast "Optional getRepositoryFor(X)" to JpaRepository instance to able to call JpaRepository methods.

Where am I doing wrong?

thanks

Body:
I'm not familiar with the getRepositoryFor method, but Optional is a standard Java class intruduced in Java SE 8.
You can check if the value is present and get the actual value from the Optional if it is present. Here is a sample using orElseThrow, but there are also other variants. Checkout the Javadoc.

public JpaRepository<Entity, Serializable> getRepository(Class<?> javaClass) {
    return (JpaRepository<Entity, Serializable>) repositories.getRepositoryFor(javaClass)
           .orElseThrow(() -> new MyException());
}


问:
Regex to validate a twitter url
I'm using the jQuery validation engine to parse my form data:
https://github.com/posabsolute/jQuery-Validation-Engine

What would be the regex to validate a twitter URL (including the http://twitter.com part) Eg:

```<code>http://twitter.com/barackobama
or
http://twitter.com/#!/barackobama
</code>```

ContentLicense: CC BY-SA 3.0

Title: Regex to validate a twitter url

Body:
I'm using the jQuery validation engine to parse my form data:
https://github.com/posabsolute/jQuery-Validation-Engine

What would be the regex to validate a twitter URL (including the http://twitter.com part) Eg:

http://twitter.com/barackobama
or
http://twitter.com/#!/barackobama

Body:
How about:

http:\/\/twitter\.com\/(#!\/)?\w+


问:
Iterate over string with commas
I have two strings:

```<code>x = 'a1,a2,a3'
y = 'b1,b2,b3'
</code>```

I want to concatenate these two string as:

```<code>z = ['a1b1','a1b2','a1b3','a2b1','a2b2','a2b3','a3b1','a3b2','a3b3']
</code>```

I used the code snippet:

```<code>for i in x:
     for j in y:
         z.append(i+j)
</code>```

But the result was not as required. How can I obtain the required result?

Title: Iterate over string with commas

Body:
I have two strings:

x = 'a1,a2,a3'
y = 'b1,b2,b3'

I want to concatenate these two string as:

z = ['a1b1','a1b2','a1b3','a2b1','a2b2','a2b3','a3b1','a3b2','a3b3']

I used the code snippet:

for i in x:
     for j in y:
         z.append(i+j)

But the result was not as required. How can I obtain the required result?

Body:
A very straitghfoward method would be

x = ['a1', 'a2', 'a3']
y = ['b1', 'b2', 'b3']

[(i+j) for i in x for j in y]

#['a1b1', 'a1b2', 'a1b3', 'a2b1', 'a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3']


问:
vim error each time, "programs.py" [New File] Error detected while processing function kite#bufenter[2]
When I try to open a file like programs.py using vim I get the same message and error each time even though I also tried another file.
The line 1 and line 7 is the comment part in programs.py. So it shouldn't have any error.

"programs.py" [New File]
Error detected while processing function kite#bufenter[2]..21_launch_kited[2]..kite#utils#launch_kited[1]..kite#utils#kite_running[9]..kit
e#async#sync[7]..24_on_close_vim[1]..24_async_sync_output:
line    1:
E121: Undefined variable: v:t_list
E15: Invalid expression: type(a:output) == v:t_list
line    7:
E121: Undefined variable: output
E15: Invalid expression: output

答:
Error detected while processing function kite#bufenter

This means you've got an error by autoloaded function which probably originates in the plugin named "kite"?

E121: Undefined variable: v:t_list

This means Vim doesn't have an internal variable named "v:t_list". This must be due to the severely outdated Vim version. (v:t_xxx constants were added to Vim 7.4.2071 in Jul 2016).

Hence, you have two solutions: (1) remove the plugin, or (2) update your Vim to the latest version.


问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答: You know, if you just plummet through the ECMA-334 specification you should be all set. That's the language... but in away, you'll still be limited by your knowledge of the framework and that's experience. Hard earned experience.</p>

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: John Leidegren


问:
How do I add the 'Add To Favourites' Feature into a Tab Bar App?
I'm just wondering what code I would use to add a 'Add To Favourites' feature into my app?

Any help would be awesome!

答: You need some type of persistent storage. Depending on what you're adding, you may be able to use NSUserDefaults, or you might need a .plist or you might need something more robust like Core Data. Really hard to say without knowing your needs.</p>


问:
ViewModel Inputs and Output for a multi-section tableview in RxSwift
I am implementing a screen which is having a multi-section tableview and a submit button.

1.TableView

a. First Section  -  Static Data ( Single Row with amount text input)

b. Second Section -  Dynamic Data (Multiple Rows with banks and radio buttons associate to each bank for selection)

2.Submit Button

Button is  enabled when amount text and bank selection by a radio button is done.

Here is the the code for Tableview DataSource, ViewModel and ViewController.

```<code>       enum PaymentDetailsSections {
            case amountDetailsSection(items: [RowItems])
            case vpaListSection(title: String,items: [RowItems])
        }

        enum RowItems {
            case linkedVPAs(info:String)
            case paymentInfo

        }

        extension PaymentDetailsSections: SectionModelType {
            typealias Item = RowItems
            var items: [RowItems] {
                switch  self {
                case .amountDetailsSection(items: let items):
                    return items.map { $0 }
                case .vpaListSection(title: _, items: let items):
                    return items.map { $0 }

                }
            }
             init(original: PaymentDetailsSections, items: [Item]) {
                switch original {
                case .amountDetailsSection(items: _):
                    self = .amountDetailsSection(items: items)
                case let .vpaListSection(title, _):
                    self = .vpaListSection(title: title, items: items)
                }
            }
        }
        extension PaymentDetailsSections {
            var title: String {
                switch self {
                case .vpaListSection(title: let title, items: _):
                    return title
                case .amountDetailsSection:
                    return  ""
                }
            }
        }

 class PaymentViewModel {

        Struct Input{
          let tableviewFirstSectionTextFieldInput: Observable<String>
          let tableviewSecondSectionSelectAnyBank: Observable<BankSelection>
          let submitButtonOutSideTableView: Observable<Void>
          }

        Struct Output{
          let results: Observable<Any>
        }

      let sections:[PaymentDetailsSections]
      var likedAccountsRowItems = [RowItems]()

      init(_service:Service) {

               let vpas = service.linkedVPAs()

                 for  account  in vpas {
                        self.likedAccountsRowItems.append(RowItems.linkedVPAs(info:account))
                  }

                self.sections = [.amountDetailsSection(items: [.paymentInfo]),
               .vpaListSection(title:"Transfer From", items:likedAccountsRowItems)]
        }

  }

        class PaymentController{

          override func viewDidLoad() {
                super.viewDidLoad()
                viewModel = PaymentViewModel()
                paymentListView.register(UINib(nibName:String(describing: SendMoneyAmountsDetailsCell.self), bundle:nil), forCellReuseIdentifier:String(describing: SendMoneyAmountsDetailsCell.self))
                paymentListView.register(UINib(nibName:String(describing: SendMoneyVPAListCell.self), bundle:nil), forCellReuseIdentifier:String(describing: SendMoneyVPAListCell.self))

                Observable.just(viewModel.sections)
                    .bind(to: paymentListView.rx.items(dataSource: self.datasource())).disposed(by: rx.disposeBag)
                paymentListView.rx.setDelegate(self).disposed(by: rx.disposeBag)
            }
             func datasource() -> RxTableViewSectionedReloadDataSource<PaymentDetailsSections> {
               return RxTableViewSectionedReloadDataSource<PaymentDetailsSections>(
                    configureCell: { dataSource, table, idxPath, _ in
                        switch dataSource[idxPath] {
                        case  .paymentInfo:
                        if let cell = table.dequeueReusableCell(withIdentifier:String(describing:SendMoneyAmountsDetailsCell.self), for: idxPath) as? SendMoneyAmountsDetailsCell {
                            return cell
                            }
                        case .linkedVPAs(_):
                            if let cell =  table.dequeueReusableCell(withIdentifier:String(describing: SendMoneyVPAListCell.self), for: idxPath) as? SendMoneyVPAListCell {
                                return cell
                            }

                        }
                        return UITableViewCell()
                },
                    titleForHeaderInSection: { dataSource, index in
                        let section = dataSource[index]
                        return section.title
                }
                )
                }

        }
</code>```

I couldn't find any solution using binding in ViewModel for input from the ViewController and make Ouput transformation. I would really appreciate any help, and thanks to anyone who contributes in advance!

答:
Subjects are used for two reasons, when you are converting non-Rx code into Rx and when you need to bind the observer before the observable exists. This is an example of the latter case.

```<code>class PaymentViewModel {
    ...
    func output(for input: Input) -> Output {
        // put logic here.
    }
}

class PaymentController: UIViewController {
    ...
    func bind() {
        let input = PaymentViewModel.Input(
            tableviewFirstSectionTextFieldInput: textFieldInputSubject.asObservable(),
            tableviewSecondSectionSelectAnyBank: bankSelectionSubject.asObservable(),
            submitButtonOutSideTableView: submitButton.rx.tap.asObservable()
        )
        let output = viewModel.output(for: input)

        output.buttonEnabled
            .bind(to: submitButton.rx.isEnabled)
            .disposed(by: disposeBag)
    }

    let textFieldInputSubject = PublishSubject<String>()
    let bankSelectionSubject = PublishSubject<BankSelection>()
    ...
}
</code>```

The bind() function needs to be called in viewDidLoad(). The textFieldInputSubject should listen to the text field in the first row and the bankSelectionSubject should listen to the buttons in the section section.

Body:
I am implementing a screen which is having a multi-section tableview and a submit button.

1.TableView

a. First Section  -  Static Data ( Single Row with amount text input)

b. Second Section -  Dynamic Data (Multiple Rows with banks and radio buttons associate to each bank for selection)

2.Submit Button

Button is  enabled when amount text and bank selection by a radio button is done.

Here is the the code for Tableview DataSource, ViewModel and ViewController.

       enum PaymentDetailsSections {
            case amountDetailsSection(items: [RowItems])
            case vpaListSection(title: String,items: [RowItems])
        }

        enum RowItems {
            case linkedVPAs(info:String)
            case paymentInfo

        }

        extension PaymentDetailsSections: SectionModelType {
            typealias Item = RowItems
            var items: [RowItems] {
                switch  self {
                case .amountDetailsSection(items: let items):
                    return items.map { $0 }
                case .vpaListSection(title: _, items: let items):
                    return items.map { $0 }

                }
            }
             init(original: PaymentDetailsSections, items: [Item]) {
                switch original {
                case .amountDetailsSection(items: _):
                    self = .amountDetailsSection(items: items)
                case let .vpaListSection(title, _):
                    self = .vpaListSection(title: title, items: items)
                }
            }
        }
        extension PaymentDetailsSections {
            var title: String {
                switch self {
                case .vpaListSection(title: let title, items: _):
                    return title
                case .amountDetailsSection:
                    return  ""
                }
            }
        }

 class PaymentViewModel {

        Struct Input{
          let tableviewFirstSectionTextFieldInput: Observable<String>
          let tableviewSecondSectionSelectAnyBank: Observable<BankSelection>
          let submitButtonOutSideTableView: Observable<Void>
          }

        Struct Output{
          let results: Observable<Any>
        }

      let sections:[PaymentDetailsSections]
      var likedAccountsRowItems = [RowItems]()

      init(_service:Service) {

               let vpas = service.linkedVPAs()

                 for  account  in vpas {
                        self.likedAccountsRowItems.append(RowItems.linkedVPAs(info:account))
                  }

                self.sections = [.amountDetailsSection(items: [.paymentInfo]),
               .vpaListSection(title:"Transfer From", items:likedAccountsRowItems)]
        }

  }

        class PaymentController{

          override func viewDidLoad() {
                super.viewDidLoad()
                viewModel = PaymentViewModel()
                paymentListView.register(UINib(nibName:String(describing: SendMoneyAmountsDetailsCell.self), bundle:nil), forCellReuseIdentifier:String(describing: SendMoneyAmountsDetailsCell.self))
                paymentListView.register(UINib(nibName:String(describing: SendMoneyVPAListCell.self), bundle:nil), forCellReuseIdentifier:String(describing: SendMoneyVPAListCell.self))

                Observable.just(viewModel.sections)
                    .bind(to: paymentListView.rx.items(dataSource: self.datasource())).disposed(by: rx.disposeBag)
                paymentListView.rx.setDelegate(self).disposed(by: rx.disposeBag)
            }
             func datasource() -> RxTableViewSectionedReloadDataSource<PaymentDetailsSections> {
               return RxTableViewSectionedReloadDataSource<PaymentDetailsSections>(
                    configureCell: { dataSource, table, idxPath, _ in
                        switch dataSource[idxPath] {
                        case  .paymentInfo:
                        if let cell = table.dequeueReusableCell(withIdentifier:String(describing:SendMoneyAmountsDetailsCell.self), for: idxPath) as? SendMoneyAmountsDetailsCell {
                            return cell
                            }
                        case .linkedVPAs(_):
                            if let cell =  table.dequeueReusableCell(withIdentifier:String(describing: SendMoneyVPAListCell.self), for: idxPath) as? SendMoneyVPAListCell {
                                return cell
                            }

                        }
                        return UITableViewCell()
                },
                    titleForHeaderInSection: { dataSource, index in
                        let section = dataSource[index]
                        return section.title
                }
                )
                }

        }

I couldn't find any solution using binding in ViewModel for input from the ViewController and make Ouput transformation. I would really appreciate any help, and thanks to anyone who contributes in advance!

Body:
Subjects are used for two reasons, when you are converting non-Rx code into Rx and when you need to bind the observer before the observable exists. This is an example of the latter case.

class PaymentViewModel {
    ...
    func output(for input: Input) -> Output {
        // put logic here.
    }
}

class PaymentController: UIViewController {
    ...
    func bind() {
        let input = PaymentViewModel.Input(
            tableviewFirstSectionTextFieldInput: textFieldInputSubject.asObservable(),
            tableviewSecondSectionSelectAnyBank: bankSelectionSubject.asObservable(),
            submitButtonOutSideTableView: submitButton.rx.tap.asObservable()
        )
        let output = viewModel.output(for: input)

        output.buttonEnabled
            .bind(to: submitButton.rx.isEnabled)
            .disposed(by: disposeBag)
    }

    let textFieldInputSubject = PublishSubject<String>()
    let bankSelectionSubject = PublishSubject<BankSelection>()
    ...
}

The bind() function needs to be called in viewDidLoad(). The textFieldInputSubject should listen to the text field in the first row and the bankSelectionSubject should listen to the buttons in the section section.


问:
Use tap to test the output of a console.log
I've got a really basic script I'd like to be able to add coverage to using node-tap:

```<code>const chalk = require('chalk')

module.exports = skip = type => console.log(chalk.blue(`Skipping generation of ${type} due to user selection`))
</code>```

All it does is display a console.log message to the user (it's a command-line app).

I've written the following tap test for it:

```<code>// test/hello-world.js
const t = require('tap')

const skip = require('../scripts/skip')

t.test('skip() Returns the expected console message', async t => {
    t.equal(skip('test'), "Skipping generation of test due to user selection`")
    t.end()
})
</code>```

But obviously that fails as I'm not returning that message, I'm returning a console.log. So how do I test this?

答:
check this https://node-tap.org/docs/api/snapshot-testing/

it should be able to solve your problem

Body:
I've got a really basic script I'd like to be able to add coverage to using node-tap:

const chalk = require('chalk')

module.exports = skip = type => console.log(chalk.blue(`Skipping generation of ${type} due to user selection`))

All it does is display a console.log message to the user (it's a command-line app).

I've written the following tap test for it:

// test/hello-world.js
const t = require('tap')

const skip = require('../scripts/skip')

t.test('skip() Returns the expected console message', async t => {
    t.equal(skip('test'), "Skipping generation of test due to user selection`")
    t.end()
})

But obviously that fails as I'm not returning that message, I'm returning a console.log. So how do I test this?


问:
Start an activity from notification depending on application status
I'm trying to setup FirebaseMessagingService and am struggling with navigation logic.

When user taps on a notification an activity which is not the main one should be started.

I know that it is possible to start an activity either by its own like this

```<code>val pendingIntent = PendingIntent.getActivity(this, 0, intent,
    PendingIntent.FLAG_ONE_SHOT)
</code>```

or with a backstack like this

```<code>val pendingIntent = TaskStackBuilder.create(this).run {
    addNextIntentWithParentStack(intent)
    getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT)
}
</code>```

The problem with the first variant is that if the application is not running then when user closes the intent activity the entire app is closed because there is no backstack behind it.

The problem with the second variant is that if the app is running and the current activity is not the parent of the intent activity then when the user closes the intent activity he can't get back to the previous one because it got replaced by the new backstack.

What I need is: when the user closes the intent actvity then start the main one but only if there is no backstack available.

Any idea please how to solve this navigation issue?

答:
Posting a workaround solution for my own question.

Set a flag when starting MainActivity and check for it when finishing the notification activity.

In the MainActivity

```<code>companion object {
    var started: Boolean = false
}
override fun onCreate(savedInstanceState: Bundle?) {
    started = true
</code>```

In the Notification activity

```<code>override fun onBackPressed() {
    if (!MainActivity.started)
        startActivity(Intent(this, MainActivity::class.java))
    super.onBackPressed()
}
</code>```

Body:
I'm trying to setup FirebaseMessagingService and am struggling with navigation logic.

When user taps on a notification an activity which is not the main one should be started.

I know that it is possible to start an activity either by its own like this

val pendingIntent = PendingIntent.getActivity(this, 0, intent,
    PendingIntent.FLAG_ONE_SHOT)

or with a backstack like this

val pendingIntent = TaskStackBuilder.create(this).run {
    addNextIntentWithParentStack(intent)
    getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT)
}

The problem with the first variant is that if the application is not running then when user closes the intent activity the entire app is closed because there is no backstack behind it.

The problem with the second variant is that if the app is running and the current activity is not the parent of the intent activity then when the user closes the intent activity he can't get back to the previous one because it got replaced by the new backstack.

What I need is: when the user closes the intent actvity then start the main one but only if there is no backstack available.

Any idea please how to solve this navigation issue?

Body:
Posting a workaround solution for my own question.

Set a flag when starting MainActivity and check for it when finishing the notification activity.

In the MainActivity

companion object {
    var started: Boolean = false
}
override fun onCreate(savedInstanceState: Bundle?) {
    started = true

In the Notification activity

override fun onBackPressed() {
    if (!MainActivity.started)
        startActivity(Intent(this, MainActivity::class.java))
    super.onBackPressed()
}


问:
How to change browser version in JSOUP?
I'm trying to parse data from amd.com. In Opera browser page looks like that, with cpu's name and link to the page in third column. But when I use JSOUP, it getting me this page (like in IE).

Get-method for a document:

```<code>private Document getDocument(String url) {
        try {
            String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36 OPR/66.0.3515.72";
            return Jsoup.connect(url).userAgent(userAgent).get();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
</code>```

In userAgent I followed the TuyenNTA's advise.

I need to get links to cpus' pages.

答:
The reason may be, that web page is changed dynamically by javascript. Jsoup will not be able to catch these changes. You could try to use jsoup in combination with selenium. Here is an example (you mentioned opera browser in your question, therefore example uses opera driver):</p>

```<code>        // set opera driver location
        System.setProperty("webdriver.opera.driver", "<PATH_TO_operadriver.exe>");
        OperaOptions options = new OperaOptions();
        options.setBinary("<PATH_TO_opera.exe>");
        WebDriver driver = new OperaDriver(options);

        try {
            driver.get("http://amd.com");
            Document doc = Jsoup.parse(driver.getPageSource());
        } finally {
            driver.close();
            driver.quit();
        }
</code>```

Title: How to change browser version in JSOUP?

Body:
I'm trying to parse data from amd.com. In Opera browser page looks like that, with cpu's name and link to the page in third column. But when I use JSOUP, it getting me this page (like in IE).

Get-method for a document:

private Document getDocument(String url) {
        try {
            String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36 OPR/66.0.3515.72";
            return Jsoup.connect(url).userAgent(userAgent).get();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

In userAgent I followed the TuyenNTA's advise.

I need to get links to cpus' pages.

Body:
The reason may be, that web page is changed dynamically by javascript. Jsoup will not be able to catch these changes. You could try to use jsoup in combination with selenium. Here is an example (you mentioned opera browser in your question, therefore example uses opera driver):

        // set opera driver location
        System.setProperty("webdriver.opera.driver", "<PATH_TO_operadriver.exe>");
        OperaOptions options = new OperaOptions();
        options.setBinary("<PATH_TO_opera.exe>");
        WebDriver driver = new OperaDriver(options);

        try {
            driver.get("http://amd.com");
            Document doc = Jsoup.parse(driver.getPageSource());
        } finally {
            driver.close();
            driver.quit();
        }


问:
The behavior of unary & operator when met []
I've been reading C11 6.5.3.2 p3

The unary & operator yields the address of its operand. If the operand has type “type”, the result has
  type “pointer to type”. If the operand is the result of a unary * operator, neither that operator nor
  the & operator is evaluated and the result is as if both were omitted, except that the constraints on
  the operators still apply and the result is not an lvalue. Similarly, if the operand is the result of a []
  operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result
  is as if the & operator were removed and the [] operator were changed to a+ operator. Otherwise,
  the result is a pointer to the object or function designated by its operand.

I can't understand most of this paragraph although reading it repeatedly.

My problem parts are * that is implied by the [], []operator were changed to a + operator, function designated by this operand. This paragraph is talking about & but why does * appear and term "function designated" appear after saying []. And [] operator were changed to a + operator seems trying to say the definition of array : E1[E2] = *((E1) + (E2)) What does these lines mean? I need some help.

答:
[From a comment] I can't sure []'s meaning. It's not written as array[i] just [].

The C standard uses [] to mean the subscript operator. Although it appears in source code as E1[E2], where E1 and E2 stand for expressions, the [ and ] characters are the fundamental way it is recognized, and they designate an operation of array subscripting.

[C 2011, draft N1570, 6.5.3.2 3, discussing the unary & operator] … Similarly, if the operand is the result of a [] operator, neither the & operator nor the unary * that is implied by the [] is evaluated and the result is as if the & operator were removed and the [] operator were changed to a + operator. Otherwise, the result is a pointer to the object or function designated by its operand.

Going back to the [] operator, consider an expression E1[E2]. The definition of the subscript operator, in 6.5.2.1 2, is that it is identical to (*((E1)+(E2))). (In other words, it takes the pointer E1 and adds the subscript E2 to it, then applies * to get the element at that location. Or, since + is commutative, E2 can be the pointer, and E1 can be the subscript.) So “the unary * that is implied by the []” is that * in (*((E1)+(E2))).

So, when we have & applied to E1[E2], this passage tells us to consider it as &(*((E1)+(E2))) and that neither the & nor the * are evaluated, so it is as if it were ((E1)+(E2)).

… why does … [the] term "function designated" appear…

The sentence containing “function designated” is separate. The “Otherwise” tells us it is talking about the situation other than when & is applied to a subscript expression (from the sentence before) or to a unary * expression (from two sentences before). So we just have &E, where E is something other than *E1 or E1[E2]. This sentence says “Otherwise, the result is a pointer to the object or function designated by its operand.” If E is an object, then &E is a pointer to the object. If E is a function, then &E is a pointer to the function.


问:
Handling CORS and CSRF between Spring Boot and Angular
I have a Spring Boot back-end application that runs on port 8888 and an Angular front-end app that runs on 4200.

In my Spring Boot application i've defined the following bean to handle CORS:

```<code>@Bean
public WebMvcConfigurer webMvcConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**");
        }
    };
}
</code>```

And my HttpSecurity configuration looks like this:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors()
        .and()
        .csrf().disable()
        // ... the rest of the config
}
</code>```

With this configuration everything works fine, i can successfully call my API from the Angular app.

But i would like to enable CSRF, so i've changed the security config to the following:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors()
        .and()
        .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        // ... the rest of the config
}
</code>```

And i've added the following HttpInterceptor to my Angular app:

```<code>constructor(private tokenExtractor: HttpXsrfTokenExtractor) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.tokenExtractor.getToken();
    if (token) {
        req = req.clone({ setHeaders: { 'X-XSRF-TOKEN': token } });
    }
    return next.handle(req);
}
</code>```

The problem is tokenExtractor.getToken() always returns null.

The corresponding request and response headers look like this:

The XSRF-TOKEN response cookie is present.

I cannot figure out what the problem is.

I've tried importing the HttpClientXsrfModule in my Angular app, but it doesn't make any difference.

I'd really appreciate any advice.

答:
I'm using this code in my Spring Boot apps and it works great with Angular

@Component
public class SimpleCORSFilter implements Filter {

```<code>@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

    chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}
</code>```

Hope it helps :)

Body:
I have a Spring Boot back-end application that runs on port 8888 and an Angular front-end app that runs on 4200.

In my Spring Boot application i've defined the following bean to handle CORS:

@Bean
public WebMvcConfigurer webMvcConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**");
        }
    };
}

And my HttpSecurity configuration looks like this:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors()
        .and()
        .csrf().disable()
        // ... the rest of the config
}

With this configuration everything works fine, i can successfully call my API from the Angular app.

But i would like to enable CSRF, so i've changed the security config to the following:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors()
        .and()
        .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        // ... the rest of the config
}

And i've added the following HttpInterceptor to my Angular app:

constructor(private tokenExtractor: HttpXsrfTokenExtractor) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.tokenExtractor.getToken();
    if (token) {
        req = req.clone({ setHeaders: { 'X-XSRF-TOKEN': token } });
    }
    return next.handle(req);
}

The problem is tokenExtractor.getToken() always returns null.

The corresponding request and response headers look like this:

The XSRF-TOKEN response cookie is present.

I cannot figure out what the problem is.

I've tried importing the HttpClientXsrfModule in my Angular app, but it doesn't make any difference.

I'd really appreciate any advice.

Body:
I'm using this code in my Spring Boot apps and it works great with Angular

@Component
public class SimpleCORSFilter implements Filter {

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

    chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

Hope it helps :)


问:
Update Live Function In Ajax
I am looking for a way to "update" or "change" a live function.  For example:

```<code>$('select[name=someexample]').live('change',function(){
    var url = '/'+escape(this.options[this.selectedIndex].value)+'/<?=$var?>';
    pageload(url);
});
</code>```

Each time "someexample" is changed, it uses ajax to call a page and return the output.  The function above is in the Ajax page as that is where the new variable comes from.

I tried:

```<code>$('select[name=someexample]').die('change');
</code>```

before the live function, but it doesn't seem to remove, so that the new function overrides it.  What happens is that the first live function always stays active.

EDIT

This is resolved.  Instead of the variable, I just read the selected value.

答:
The reason this wasn't working was because .html() was stripping out the javascript.  What was a better solution in this case was instead of using a PHP variable, I set it to read the current select value, which didn't need the function updated.  </p>

```<code>$('select[name=typetest]').live('change',function(){
    var url = '/'+escape(this.options[this.selectedIndex].value)+'/'+$("select[name=someselect]").val();
    pageload(url);
});
</code>```

Title: Update Live Function In Ajax

Body:
I am looking for a way to "update" or "change" a live function.  For example:

$('select[name=someexample]').live('change',function(){
    var url = '/'+escape(this.options[this.selectedIndex].value)+'/<?=$var?>';
    pageload(url);
});

Each time "someexample" is changed, it uses ajax to call a page and return the output.  The function above is in the Ajax page as that is where the new variable comes from.

I tried:

$('select[name=someexample]').die('change');

before the live function, but it doesn't seem to remove, so that the new function overrides it.  What happens is that the first live function always stays active.

EDIT

This is resolved.  Instead of the variable, I just read the selected value.

Body:
The reason this wasn't working was because .html() was stripping out the javascript.  What was a better solution in this case was instead of using a PHP variable, I set it to read the current select value, which didn't need the function updated.

$('select[name=typetest]').live('change',function(){
    var url = '/'+escape(this.options[this.selectedIndex].value)+'/'+$("select[name=someselect]").val();
    pageload(url);
});


问:
Can I dock a floating action button in a CupertinoTabBar?
I would like to know if there is a way to dock a floating action button in a CupertinoTabBar. I would like to get the results as in the picture below

My screen is organized as follow

CupertinoTabScaffold

CupertinoTabView

CupertinoPageScaffold

CupertinoNavigationBar

Scaffold

CupertinoTabBar

I have tried to add the following code to my Scaffold but the result is not what I want. I understand the issue is that the TabBar is not inside the scaffold hence it is not docked however I am wondering if there is a way to put the floating button somewhere else to get to the result I want

Here is the code

```<code>child: Scaffold(
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: FloatingActionButton.extended(
          backgroundColor: kColorAccent,
          onPressed: () {},
          label: Text('To my Favorites!'),
          icon: Icon(Icons.favorite),
        ),
</code>```

And here is the result I get...

答:
For some of you looking for a code snippet, I'll give you a working example.

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomeState();
  }
}

class HomeState extends State<Home> {
  int _index = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          Navigator.of(context).push(
              // this can also be `MaterialPageRoute`
              CupertinoPageRoute(
                fullscreenDialog: true,
                // typical full screen dialog behavior
                builder: (_) => ModalPage(),
              )
          );
        },
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      bottomNavigationBar: CupertinoTabBar(
        currentIndex: _index,
        onTap: (newIndex) {
          setState(() {
            _index = newIndex;
          });
        },
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.today),
            title: Text("today"),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.timeline),
            title: Text("stats"),
          ),
        ],
      ),
      /**
       * You can use switch here,
       * for the sake of brevity, I only used two tabs
       */
      body: _index == 0 ? Page1() : Page2(),
    );
  }
}
```

Point is

use scaffold. If you use CupertinoTabScaffold, then you'll not be able to use FloatingActionbutton.

you can move FAB into whatever position using floatingActionButtonLocation.

you need StatefulWidget or something similar to that to handle index change.

Body:
I would like to know if there is a way to dock a floating action button in a CupertinoTabBar. I would like to get the results as in the picture below

My screen is organized as follow

CupertinoTabScaffold

CupertinoTabView

CupertinoPageScaffold

CupertinoNavigationBar

Scaffold

CupertinoTabBar

I have tried to add the following code to my Scaffold but the result is not what I want. I understand the issue is that the TabBar is not inside the scaffold hence it is not docked however I am wondering if there is a way to put the floating button somewhere else to get to the result I want

Here is the code

child: Scaffold(
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: FloatingActionButton.extended(
          backgroundColor: kColorAccent,
          onPressed: () {},
          label: Text('To my Favorites!'),
          icon: Icon(Icons.favorite),
        ),

And here is the result I get...

Body:
For some of you looking for a code snippet, I'll give you a working example.

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomeState();
  }
}

class HomeState extends State<Home> {
  int _index = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          Navigator.of(context).push(
              // this can also be `MaterialPageRoute`
              CupertinoPageRoute(
                fullscreenDialog: true,
                // typical full screen dialog behavior
                builder: (_) => ModalPage(),
              )
          );
        },
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      bottomNavigationBar: CupertinoTabBar(
        currentIndex: _index,
        onTap: (newIndex) {
          setState(() {
            _index = newIndex;
          });
        },
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.today),
            title: Text("today"),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.timeline),
            title: Text("stats"),
          ),
        ],
      ),
      /**
       * You can use switch here,
       * for the sake of brevity, I only used two tabs
       */
      body: _index == 0 ? Page1() : Page2(),
    );
  }
}

Point is

use scaffold. If you use CupertinoTabScaffold, then you'll not be able to use FloatingActionbutton.

you can move FAB into whatever position using floatingActionButtonLocation.

you need StatefulWidget or something similar to that to handle index change.


问:
Conditional subquery in where clause
I'm trying to create a query with conditional logic where I only calculate revenue for the most recent records by each month using a datetime column (start_date), but only if there are multiple records in that month from the same account_id.

Here's a basic example of the schema after I join two tables (full schema in sqlfiddle link).

```<code>| account_id | plan_id | start_date           | plan_interval | price |
|------------|---------|----------------------|---------------|-------|
| 1          | 1       | 2018-01-03T14:52:13Z | month         | 39    |
| 1          | 3       | 2018-02-07T11:10:17Z | year          | 999   |
| 1          | 2       | 2018-02-07T11:11:17Z | month         | 99    |
</code>```

In the above example, I would only like to include rows 1 and 3 in my output, as it's the one record from account_id 1 in January and the most recent of two records for account_id 1 in February.

```<code>SELECT
MONTH(start_date) AS month,
SUM(CASE WHEN plan_interval = 'month'
     THEN price * .01
     ELSE (price * .01)/12 END) AS mrr
FROM subscriptions
  JOIN plans
  ON plans.id = subscriptions.plan_id
WHERE Year(start_date) = 2018 AND
  CASE WHEN (account_id = account_id
             AND MONTH(start_date) = MONTH(start_date))
             THEN (SELECT MAX(start_date) FROM subscriptions)
             ELSE (SELECT start_date FROM subscriptions)
             END
GROUP BY month
ORDER BY month ASC;
</code>```

The case statement in the subquery above does not seem to work in doing this. It returns the data without filtering out records when the first condition is met.

Here is an example: sqlfiddle

答:
This query returns the rows that you are asking for in the question:

```<code>SELECT s.*, p.plan_interval, p.price,
       (CASE WHEN p.plan_interval = 'month'
             THEN p.price * 0.01
             ELSE (p.price * 0.01)/12
        END) AS mrr
FROM subscriptions s JOIN
     plans p
     ON p.id = s.plan_id
WHERE YEAR(s.start_date) = 2018 AND
      s.start_date = (SELECT MAX(s2.start_date)
                      FROM subscriptions s2
                      WHERE s2.account_id = s.account_id AND
                            EXTRACT(YEAR_MONTH FROM s2.start_date) = EXTRACT(YEAR_MONTH FROM s.start_date)
                     )
ORDER BY s.start_date ASC;
</code>```

This uses a subquery to get the most recent record for a subscription for each month.

You can then aggregate this however you wish.

Notes about the query:

Table aliases make the query easier to write and to read.

The subquery uses the handy YEAR_MONTH option of EXTRACT(), so it handles both years and months.

For numeric constants between -1 and 1, I always prepend with a 0, so 0.12 rather than .12.  If find that this makes the decimal point more obvious.

Title: Conditional subquery in where clause

Body:
I'm trying to create a query with conditional logic where I only calculate revenue for the most recent records by each month using a datetime column (start_date), but only if there are multiple records in that month from the same account_id.

Here's a basic example of the schema after I join two tables (full schema in sqlfiddle link).

| account_id | plan_id | start_date           | plan_interval | price |
|------------|---------|----------------------|---------------|-------|
| 1          | 1       | 2018-01-03T14:52:13Z | month         | 39    |
| 1          | 3       | 2018-02-07T11:10:17Z | year          | 999   |
| 1          | 2       | 2018-02-07T11:11:17Z | month         | 99    |

In the above example, I would only like to include rows 1 and 3 in my output, as it's the one record from account_id 1 in January and the most recent of two records for account_id 1 in February.

SELECT
MONTH(start_date) AS month,
SUM(CASE WHEN plan_interval = 'month'
     THEN price * .01
     ELSE (price * .01)/12 END) AS mrr
FROM subscriptions
  JOIN plans
  ON plans.id = subscriptions.plan_id
WHERE Year(start_date) = 2018 AND
  CASE WHEN (account_id = account_id
             AND MONTH(start_date) = MONTH(start_date))
             THEN (SELECT MAX(start_date) FROM subscriptions)
             ELSE (SELECT start_date FROM subscriptions)
             END
GROUP BY month
ORDER BY month ASC;

The case statement in the subquery above does not seem to work in doing this. It returns the data without filtering out records when the first condition is met.

Here is an example: sqlfiddle

Body:
This query returns the rows that you are asking for in the question:

SELECT s.*, p.plan_interval, p.price,
       (CASE WHEN p.plan_interval = 'month'
             THEN p.price * 0.01
             ELSE (p.price * 0.01)/12
        END) AS mrr
FROM subscriptions s JOIN
     plans p
     ON p.id = s.plan_id
WHERE YEAR(s.start_date) = 2018 AND
      s.start_date = (SELECT MAX(s2.start_date)
                      FROM subscriptions s2
                      WHERE s2.account_id = s.account_id AND
                            EXTRACT(YEAR_MONTH FROM s2.start_date) = EXTRACT(YEAR_MONTH FROM s.start_date)
                     )
ORDER BY s.start_date ASC;

This uses a subquery to get the most recent record for a subscription for each month.

You can then aggregate this however you wish.

Notes about the query:

Table aliases make the query easier to write and to read.

The subquery uses the handy YEAR_MONTH option of EXTRACT(), so it handles both years and months.

For numeric constants between -1 and 1, I always prepend with a 0, so 0.12 rather than .12.  If find that this makes the decimal point more obvious.


问:
Configuring distcc for makefiles
I am testing distcc and I found this tutorial very easy to follow, I should say that I am able to compile llvm using CMake + Ninja and CMake + Makefiles using distcc and docker with no problems. Since I am particularly interested in Makefiles, I looked at the files produced by CMake + Ninja and all I saw was that distcc is added as a prefix to the compiler (e.g. distcc /usr/bin/gcc). So I thought that if I create a small project using only Makefiles I could possibly add distcc and things will magically work. Well, looks like I am missing something because all I get is:

```<code>$ ./mk.sh image

make[1]: Entering directory '/home/user/sandbox/distcc-makefiles'
Compiling Lib/Print.c
Compiling Boot/Main.c
distcc[16644] ERROR: compile Boot/Main.c on 172.17.0.2/1 failed
distcc[16644] (dcc_build_somewhere) Warning: remote compilation of 'Boot/Main.c' failed, retrying locally
distcc[16644] Warning: failed to distribute Boot/Main.c to 172.17.0.2/1, running locally instead
distcc[16644] (dcc_please_send_email_after_investigation) Warning: remote compilation of 'Boot/Main.c' failed, retried locally and got a different result.
distcc[16643] ERROR: compile Lib/Print.c on 172.17.0.2/1 failed
distcc[16643] (dcc_build_somewhere) Warning: remote compilation of 'Lib/Print.c' failed, retrying locally
distcc[16643] Warning: failed to distribute Lib/Print.c to 172.17.0.2/1, running locally instead
distcc[16643] (dcc_please_send_email_after_investigation) Warning: remote compilation of 'Lib/Print.c' failed, retried locally and got a different result.
make[1]: Leaving directory '/home/user/sandbox/distcc-makefiles'
</code>```

By running the llvm example I discarded all docker connection and distcc configuration issues, I tried to search for any ideas/examples on the internet but most of the people use CMake which is not my case. Suggestions are welcome, I based my demo project on a real project I am working on, so that's how basically the Makefile look like.

I don't know what I am missing...

Versions:

Just for reference:

```<code>$ distcc --version
distcc 3.1 x86_64-pc-linux-gnu
  (protocols 1, 2 and 3) (default port 3632)
  built Oct 19 2017 11:05:18
Copyright (C) 2002, 2003, 2004 by Martin Pool.
Includes miniLZO (C) 1996-2002 by Markus Franz Xaver Johannes Oberhumer.
Portions Copyright (C) 2007-2008 Google.
</code>```

```<code>$ gcc --version
gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Copyright (C) 2017 Free Software Foundation, Inc.
</code>```

```<code>$ make --version
GNU Make 4.1
Built for x86_64-pc-linux-gnu
Copyright (C) 1988-2014 Free Software Foundation, Inc.
</code>```

答:
current distcc maintainer,

I highly recommend using MASQUERADE as documented in the distcc man page.

Title: Configuring distcc for makefiles

Body:
I am testing distcc and I found this tutorial very easy to follow, I should say that I am able to compile llvm using CMake + Ninja and CMake + Makefiles using distcc and docker with no problems. Since I am particularly interested in Makefiles, I looked at the files produced by CMake + Ninja and all I saw was that distcc is added as a prefix to the compiler (e.g. distcc /usr/bin/gcc). So I thought that if I create a small project using only Makefiles I could possibly add distcc and things will magically work. Well, looks like I am missing something because all I get is:

$ ./mk.sh image

make[1]: Entering directory '/home/user/sandbox/distcc-makefiles'
Compiling Lib/Print.c
Compiling Boot/Main.c
distcc[16644] ERROR: compile Boot/Main.c on 172.17.0.2/1 failed
distcc[16644] (dcc_build_somewhere) Warning: remote compilation of 'Boot/Main.c' failed, retrying locally
distcc[16644] Warning: failed to distribute Boot/Main.c to 172.17.0.2/1, running locally instead
distcc[16644] (dcc_please_send_email_after_investigation) Warning: remote compilation of 'Boot/Main.c' failed, retried locally and got a different result.
distcc[16643] ERROR: compile Lib/Print.c on 172.17.0.2/1 failed
distcc[16643] (dcc_build_somewhere) Warning: remote compilation of 'Lib/Print.c' failed, retrying locally
distcc[16643] Warning: failed to distribute Lib/Print.c to 172.17.0.2/1, running locally instead
distcc[16643] (dcc_please_send_email_after_investigation) Warning: remote compilation of 'Lib/Print.c' failed, retried locally and got a different result.
make[1]: Leaving directory '/home/user/sandbox/distcc-makefiles'

By running the llvm example I discarded all docker connection and distcc configuration issues, I tried to search for any ideas/examples on the internet but most of the people use CMake which is not my case. Suggestions are welcome, I based my demo project on a real project I am working on, so that's how basically the Makefile look like.

I don't know what I am missing...

Versions:

Just for reference:

$ distcc --version
distcc 3.1 x86_64-pc-linux-gnu
  (protocols 1, 2 and 3) (default port 3632)
  built Oct 19 2017 11:05:18
Copyright (C) 2002, 2003, 2004 by Martin Pool.
Includes miniLZO (C) 1996-2002 by Markus Franz Xaver Johannes Oberhumer.
Portions Copyright (C) 2007-2008 Google.

$ gcc --version
gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Copyright (C) 2017 Free Software Foundation, Inc.

$ make --version
GNU Make 4.1
Built for x86_64-pc-linux-gnu
Copyright (C) 1988-2014 Free Software Foundation, Inc.


问:
Passing by reference in C++ function
I am writing a simple program to calculate 6^5 using a function. Here's my code

```<code>#include <iostream>
using namespace std;

int raiseToPower(int &base, int exponent){
 for (int i = 1; i < exponent; i = i + 1){
   base= base * base;
   }
 return base;
}

int main() {
 int base = 6;
 cout << "6^5 is " << raiseToPower(base, 5)<< endl;

 return 0;
}
</code>```

The result is

```<code> 6^5 is -683606016
</code>```

instead of 7776

Can you guys explain to me why I got this result?
I am not looking for another way to write this code. I know there are simpler ways but I am trying to understand what went wrong

答:
Your calculation is incorrect. The value of  variable base should not change. Try this:</p>

```<code> int raiseToPower(int &base, int exponent){
   int result = 1;
   for (int i = 1; i <= exponent; i = i + 1){
      result = result * base;
    }
    return result;
 }
</code>```

Title: Passing by reference in C++ function

Body:
I am writing a simple program to calculate 6^5 using a function. Here's my code

#include <iostream>
using namespace std;

int raiseToPower(int &base, int exponent){
 for (int i = 1; i < exponent; i = i + 1){
   base= base * base;
   }
 return base;
}

int main() {
 int base = 6;
 cout << "6^5 is " << raiseToPower(base, 5)<< endl;

 return 0;
}

The result is

 6^5 is -683606016

instead of 7776

Can you guys explain to me why I got this result?
I am not looking for another way to write this code. I know there are simpler ways but I am trying to understand what went wrong

Body:
Your calculation is incorrect. The value of  variable base should not change. Try this:

 int raiseToPower(int &base, int exponent){
   int result = 1;
   for (int i = 1; i <= exponent; i = i + 1){
      result = result * base;
    }
    return result;
 }


问:
Printing to PDF - how to avoid automatic display of screen to request save location?
I'm working on a legacy application and trying to get VB6 to send printed output to a pdf printer (Nitro). The output from the application should end up printed into a pdf file in a specific location/filename.

Issue:

When I make a call to any Printer function, it pops up a dialogue box but I don't see a way for me to set the dialogue box's default path and filename. Is there a way to do this?

Even if i create my own dialogue box, as soon as any function call to Printer happens, it pops up a dialogue box.

Line of code that is popping up the dialogue box:

```<code>'How do I set the dialogue box it opens here to a default filename/location?
Printer.PaintPicture .Picture, .Left + lngAddToLeft, .Top + lngAddToTop, .Width, .Height
</code>```

答:
first you must set your system's default printer to "Nitro's Printer Name"

code below can help u to do this

```<code>Private Sub set_Nitro_As_Default()
 Dim prn As Printer
  If Printers.Count > 0 Then
    For Each prn In Printers
       If prn.DeviceName = [Nitro Printer Name] Then 'printer that u want to use
         Set Printer = prn
         Exit For
       End If
    Next prn
  End If
End Sub
</code>```

to print some text,label or Graphical objects you must add an picturebox to your project .it contains all objects you want to print.

after you prepare all objects such as label or shape and every thing ready for print call this sub to save your picturebox image in a temp bmp file

```<code>'add this declaration on top of your project
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" _
                        (ByVal hwnd As Long, ByVal wMsg As Long, _
                         ByVal wParam As Long, ByVal lParam As Long) As Long

 Private Const WM_PAINT = &HF
 Private Const WM_PRINT = &H317
 Private Const PRF_CLIENT = &H4&    ' Draw the window's client area
 Private Const PRF_CHILDREN = &H10& ' Draw all visible child
 Private Const PRF_OWNED = &H20&    ' Draw all owned windows

'this function save PicBox image in FileName path
'PicBox Contain All thing which you want to print
Public Sub SavePictureBox(PicBox As PictureBox, FileName As String)
  Dim rv As Long
  Dim ar As Boolean

  With PicBox
  'Save ReDraw value
    ar = .AutoRedraw
         .AutoRedraw = True

  'Draw controls to picture box
    rv = SendMessage(.hwnd, WM_PAINT, .hdc, 0)
    rv = SendMessage(.hwnd, WM_PRINT, .hdc, _
                      PRF_CHILDREN Or PRF_CLIENT Or PRF_OWNED)

  'save picture box
      SavePicture .Image, FileName

         .Cls

         'Restore ReDraw
         .AutoRedraw = ar
  End With
End Sub
</code>```

you must add some thing like this to your main print command

```<code>private sub iPrint()
   'firstly set your intended printer as default
    call set_Nitro_As_Default
   'set some Generic setting
    Printer.PrintQuality = vbPRPQHigh
    Printer.PaperSize = vbPRPSA4

    for i=1 to [your intended page count]

     'do some thing for Arrange your labels and objects to make it ready to print
     'after prepare your all thing on picturebox
       call SavePictureBox([printed PictureBox], App.path & "\tmp.bmp")

     'print this page
     'note that you can set margin and your printed page size
       Printer.PaintPicture LoadPicture(App.Path & "\tmp.bmp"), 0, 0, _
                            LoadPicture(App.Path & "\tmp.bmp").Width, _
                            LoadPicture(App.Path & "\tmp.bmp").Height, _
                            0, 0, _
                            Printer.Width, _
                            Printer.Height

       Printer.NewPage
     next i

       Printer.EndDoc

end sub
</code>```

its done

Body:
I'm working on a legacy application and trying to get VB6 to send printed output to a pdf printer (Nitro). The output from the application should end up printed into a pdf file in a specific location/filename.

Issue:

When I make a call to any Printer function, it pops up a dialogue box but I don't see a way for me to set the dialogue box's default path and filename. Is there a way to do this?

Even if i create my own dialogue box, as soon as any function call to Printer happens, it pops up a dialogue box.

Line of code that is popping up the dialogue box:

'How do I set the dialogue box it opens here to a default filename/location?
Printer.PaintPicture .Picture, .Left + lngAddToLeft, .Top + lngAddToTop, .Width, .Height

Body:
first you must set your system's default printer to "Nitro's Printer Name"

code below can help u to do this

Private Sub set_Nitro_As_Default()
 Dim prn As Printer
  If Printers.Count > 0 Then
    For Each prn In Printers
       If prn.DeviceName = [Nitro Printer Name] Then 'printer that u want to use
         Set Printer = prn
         Exit For
       End If
    Next prn
  End If
End Sub

to print some text,label or Graphical objects you must add an picturebox to your project .it contains all objects you want to print.

after you prepare all objects such as label or shape and every thing ready for print call this sub to save your picturebox image in a temp bmp file

'add this declaration on top of your project
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" _
                        (ByVal hwnd As Long, ByVal wMsg As Long, _
                         ByVal wParam As Long, ByVal lParam As Long) As Long

 Private Const WM_PAINT = &HF
 Private Const WM_PRINT = &H317
 Private Const PRF_CLIENT = &H4&    ' Draw the window's client area
 Private Const PRF_CHILDREN = &H10& ' Draw all visible child
 Private Const PRF_OWNED = &H20&    ' Draw all owned windows

'this function save PicBox image in FileName path
'PicBox Contain All thing which you want to print
Public Sub SavePictureBox(PicBox As PictureBox, FileName As String)
  Dim rv As Long
  Dim ar As Boolean

  With PicBox
  'Save ReDraw value
    ar = .AutoRedraw
         .AutoRedraw = True

  'Draw controls to picture box
    rv = SendMessage(.hwnd, WM_PAINT, .hdc, 0)
    rv = SendMessage(.hwnd, WM_PRINT, .hdc, _
                      PRF_CHILDREN Or PRF_CLIENT Or PRF_OWNED)

  'save picture box
      SavePicture .Image, FileName

         .Cls

         'Restore ReDraw
         .AutoRedraw = ar
  End With
End Sub

you must add some thing like this to your main print command

private sub iPrint()
   'firstly set your intended printer as default
    call set_Nitro_As_Default
   'set some Generic setting
    Printer.PrintQuality = vbPRPQHigh
    Printer.PaperSize = vbPRPSA4

    for i=1 to [your intended page count]

     'do some thing for Arrange your labels and objects to make it ready to print
     'after prepare your all thing on picturebox
       call SavePictureBox([printed PictureBox], App.path & "\tmp.bmp")

     'print this page
     'note that you can set margin and your printed page size
       Printer.PaintPicture LoadPicture(App.Path & "\tmp.bmp"), 0, 0, _
                            LoadPicture(App.Path & "\tmp.bmp").Width, _
                            LoadPicture(App.Path & "\tmp.bmp").Height, _
                            0, 0, _
                            Printer.Width, _
                            Printer.Height

       Printer.NewPage
     next i

       Printer.EndDoc

end sub

its done


答:
You probably want your loop like this:

```<code>int result = 1;
for (int i = 0; i < exponent; i = i + 1) {
    result = result * base;
}
return result;
</code>```

Also, you are taking your base parameter to raiseToPower by reference - which means you are changing the base variable in main - probably not what you want to do.

Title: Passing by reference in C++ function

Body:
You probably want your loop like this:

int result = 1;
for (int i = 0; i < exponent; i = i + 1) {
    result = result * base;
}
return result;

Also, you are taking your base parameter to raiseToPower by reference - which means you are changing the base variable in main - probably not what you want to do.


问:
Styling a jsx element in react
I have this line of code in my project that generates a certain percentage and shows it on the dashboard.

```<code>   <text
          className="netProfit-circle-text"
          x="50%"
          y="50%"
          dy=".2em"
          textAnchor="middle"
        >
          {`${this.state.percentage}%`}
        </text>
</code>```

What I want to do is to be able to style the "%" and change its size using CSS. How can I do this?
Thanks in advance.

Regards.

答:
You can simply wrap the % in a  with a class:

```<code><text
    className="netProfit-circle-text"
    x="50%"
    y="50%"
    dy=".2em"
    textAnchor="middle"
>
    {this.state.percentage}
    <span class="percentage">%</span>
</text>
</code>```

and then add some styles to it:

span.percentage {
  ...
}
```

Title: Styling a jsx element in react

Body:
I have this line of code in my project that generates a certain percentage and shows it on the dashboard.

   <text
          className="netProfit-circle-text"
          x="50%"
          y="50%"
          dy=".2em"
          textAnchor="middle"
        >
          {`${this.state.percentage}%`}
        </text>

What I want to do is to be able to style the "%" and change its size using CSS. How can I do this?
Thanks in advance.

Regards.

Body:
You can simply wrap the % in a <span> with a class:

<text
    className="netProfit-circle-text"
    x="50%"
    y="50%"
    dy=".2em"
    textAnchor="middle"
>
    {this.state.percentage}
    <span class="percentage">%</span>
</text>

and then add some styles to it:

span.percentage {
  ...
}


问:
Access instance variables from an activity inside a AsyncTask
I have an AsyncTask (in a separate file) which is invoked on an
activity. When I instantiate the AsyncTask, I send the activity as a
param. How can I access the acitivity's instance variables from the
onPostExecute method of the AsyncTask?

Thanks!

答:
You must be careful when passing an Activity or Context to an AsyncTask that is not an inner (non-static) class of an Activity - this is because in this case the lifetime of the Activity/Context and the AsyncTask are different, and if you hold on to an Activity/Context for longer than you should you will cause memory leaks.

Rather than holding onto the Activity or activity context itself in your AsyncTask you should keep a  WeakReference to the Activity. This will ensure that the memory associated with the Activity can be reclaimed by the garbage collector (GC) when needed.

```<code>public class MyTask extends AsyncTask<..., ..., ...> {
    private WeakReference<MyActivity> mParentActivity = null;

    public MyTask(MyActivity parentActivity) {
        mParentActivity = new WeakReference<MyActivity>(parentActivity);
    }

    @Override
    public ... doInBackground(... params) {
        // do some stuff

        // now we do something that requires the context
        if (mParentActivity.get() != null) {
            // the WeakReference is still valid and hasn't been reclaimed
            // by the GC
            final MyActivity parentActivity = mParentActivity.get();
            parentActivity.doSomething();
        }

        // return result
    }
}
</code>```

When passing a Context always try to use the ApplicationContext where possible as this is the longest-lived context.

Body:
You must be careful when passing an Activity or Context to an AsyncTask that is not an inner (non-static) class of an Activity - this is because in this case the lifetime of the Activity/Context and the AsyncTask are different, and if you hold on to an Activity/Context for longer than you should you will cause memory leaks.

Rather than holding onto the Activity or activity context itself in your AsyncTask you should keep a  WeakReference to the Activity. This will ensure that the memory associated with the Activity can be reclaimed by the garbage collector (GC) when needed.

public class MyTask extends AsyncTask<..., ..., ...> {
    private WeakReference<MyActivity> mParentActivity = null;

    public MyTask(MyActivity parentActivity) {
        mParentActivity = new WeakReference<MyActivity>(parentActivity);
    }

    @Override
    public ... doInBackground(... params) {
        // do some stuff

        // now we do something that requires the context
        if (mParentActivity.get() != null) {
            // the WeakReference is still valid and hasn't been reclaimed
            // by the GC
            final MyActivity parentActivity = mParentActivity.get();
            parentActivity.doSomething();
        }

        // return result
    }
}

When passing a Context always try to use the ApplicationContext where possible as this is the longest-lived context.


问:
How to replace multiple strings using PowerShell
I want to replace 4 strings with 4 another ones and write them to file.

```<code>$file = 'C:\Defender.psd1'
(Get-Content $file) | ForEach-Object {
    $_.replace("'MSFT_MpSignature.cdxml',", "'MSFT_MpSignature.cdxml')")
    $_.replace("'MSFT_MpWDOScan.cdxml')", "")
    $_.replace("'Remove-MpThreat',", "'Remove-MpThreat')")
    $_.replace("'Start-MpWDOScan')", "") `
} | Out-File $file
</code>```

But instead of this every string in the file has been duplicated 4 times. Script will be used for PowerShell 4 and 5.1.

答:
Thanks @Martin Brandl for the answer it was working perfectly except I run into some issues with CI/CD. My pipeline is sensitive to file Encoding. The original file was UTF-8 but "Out-File" changed it to "UCS-2 BOM".

So I had to replace the files save code ot "Set-Content -Path $file" it preserves to original encoding.

Here is the full example:

```<code>$file = 'C:\Defender.psd1'
(Get-Content $file) | ForEach-Object {
    $_.replace("'MSFT_MpSignature.cdxml',", "'MSFT_MpSignature.cdxml')").replace("'MSFT_MpWDOScan.cdxml')", "").replace("'Remove-MpThreat',", "'Remove-MpThreat')").replace("'Start-MpWDOScan')", "") `
} | Set-Content -Path $file
</code>```

Body:
I want to replace 4 strings with 4 another ones and write them to file.

$file = 'C:\Defender.psd1'
(Get-Content $file) | ForEach-Object {
    $_.replace("'MSFT_MpSignature.cdxml',", "'MSFT_MpSignature.cdxml')")
    $_.replace("'MSFT_MpWDOScan.cdxml')", "")
    $_.replace("'Remove-MpThreat',", "'Remove-MpThreat')")
    $_.replace("'Start-MpWDOScan')", "") `
} | Out-File $file

But instead of this every string in the file has been duplicated 4 times. Script will be used for PowerShell 4 and 5.1.

Body:
Thanks @Martin Brandl for the answer it was working perfectly except I run into some issues with CI/CD. My pipeline is sensitive to file Encoding. The original file was UTF-8 but "Out-File" changed it to "UCS-2 BOM".

So I had to replace the files save code ot "Set-Content -Path $file" it preserves to original encoding.

Here is the full example:

$file = 'C:\Defender.psd1'
(Get-Content $file) | ForEach-Object {
    $_.replace("'MSFT_MpSignature.cdxml',", "'MSFT_MpSignature.cdxml')").replace("'MSFT_MpWDOScan.cdxml')", "").replace("'Remove-MpThreat',", "'Remove-MpThreat')").replace("'Start-MpWDOScan')", "") `
} | Set-Content -Path $file


问:
How to write efficient sql query that return latest student score(by date) in each lesson?
the table structure is as follows:

```<code>student lesson  score   Date
Allen   Math    12      9/11/12
Allen   Math    19      9/11/14
Allen   Physics 10      9/11/12
Joe     Physics 15      9/11/12
Joe     Physics 13      9/11/15
</code>```

the result should be:

```<code>student lesson  score   Date
Allen   Math    19      9/11/14
Allen   Physics 10      9/11/12
Joe     Physics 13      9/11/15
</code>```

答:
I think the most generally efficient query is a correlated subquery with the right index:

```<code>select t.*
from t
where t.date = (select max(t2.date)
                from t t2
                where t2.student = t.student and t2.lesson = t.lesson
               );
</code>```

The index you want is on (student, lesson, date).

Note that in some databases, other methods may be a bit faster.  But as a general rule I find that this has good performance.

Body:
the table structure is as follows:

student lesson  score   Date
Allen   Math    12      9/11/12
Allen   Math    19      9/11/14
Allen   Physics 10      9/11/12
Joe     Physics 15      9/11/12
Joe     Physics 13      9/11/15

the result should be:

student lesson  score   Date
Allen   Math    19      9/11/14
Allen   Physics 10      9/11/12
Joe     Physics 13      9/11/15

Body:
I think the most generally efficient query is a correlated subquery with the right index:

select t.*
from t
where t.date = (select max(t2.date)
                from t t2
                where t2.student = t.student and t2.lesson = t.lesson
               );

The index you want is on (student, lesson, date).

Note that in some databases, other methods may be a bit faster.  But as a general rule I find that this has good performance.


问:
takeWhile in Scala for element n+1

Define the function dropWhileSmallerThanFive, it should take a list and discard the first n elements, until the next element (n+1) is greater or equal to 5.

*Use one of Scala's built-in list functions (e.g. takeWhile).

I tried this:

```<code>   def dropWhileSmallerThanFive(xs: List[Int]): List[Int] = xs match {
        case Nil => Nil
        case head :: b :: tail if b >= 5 => head :: (b::tail).takeWhile(_>=5)
        case _ => Nil
    }
</code>```

But it's completly wrong, what should I do?

答:
Welcome to SO! If you are new to Scala, consider the following beginner-friendly resources

Real-time help: gitter.im/scala/scala

Interactive exercises: scala-exercises.org

Tour of Scala: docs.scala-lang.org/tour/tour-of-scala.html

Hello world template: sbt new scala/scala-seed.g8

Online interactive playground: scastie.scala-lang.org

Scala provides List.dropWhile out-of-the-box, or consider the following recursive implementation

```<code>def recDropWhile(l: List[Int], predicate: Int => Boolean): List[Int] = {
  @scala.annotation.tailrec
  def loop(l: List[Int], predicate: Int => Boolean): List[Int] = {
    l match {
      case Nil => Nil
      case head :: tail => if (predicate(head)) loop(tail, predicate) else (head :: tail)
    }
  }
  loop(l, predicate)
}
</code>```

Both output

```<code>val l = List(1,2,3,4,5,6,7,8)
l.dropWhile(_ < 5)       // res3: List[Int] = List(5, 6, 7, 8)
recDropWhile(l, _ < 5)   // res4: List[Int] = List(5, 6, 7, 8)
</code>```

Title: takeWhile in Scala for element n+1

Body:
Define the function dropWhileSmallerThanFive, it should take a list and discard the first n elements, until the next element (n+1) is greater or equal to 5.

*Use one of Scala's built-in list functions (e.g. takeWhile).

I tried this:

   def dropWhileSmallerThanFive(xs: List[Int]): List[Int] = xs match {
        case Nil => Nil
        case head :: b :: tail if b >= 5 => head :: (b::tail).takeWhile(_>=5)
        case _ => Nil
    }

But it's completly wrong, what should I do?

Body:
Welcome to SO! If you are new to Scala, consider the following beginner-friendly resources

Real-time help: gitter.im/scala/scala

Interactive exercises: scala-exercises.org

Tour of Scala: docs.scala-lang.org/tour/tour-of-scala.html

Hello world template: sbt new scala/scala-seed.g8

Online interactive playground: scastie.scala-lang.org

Scala provides List.dropWhile out-of-the-box, or consider the following recursive implementation

def recDropWhile(l: List[Int], predicate: Int => Boolean): List[Int] = {
  @scala.annotation.tailrec
  def loop(l: List[Int], predicate: Int => Boolean): List[Int] = {
    l match {
      case Nil => Nil
      case head :: tail => if (predicate(head)) loop(tail, predicate) else (head :: tail)
    }
  }
  loop(l, predicate)
}

Both output

val l = List(1,2,3,4,5,6,7,8)
l.dropWhile(_ < 5)       // res3: List[Int] = List(5, 6, 7, 8)
recDropWhile(l, _ < 5)   // res4: List[Int] = List(5, 6, 7, 8)


问:
Cannot Find the Top Row After Autofiltering
I have one workbook with two worksheets in it. What I am trying to do is autofilter through a range of unique values that I extracted and placed in a column in the far off reaches of both sheets. I'm then looking to copy and paste the values in the first three columns of the first visible row of what was filtered. I'm including the code below as I've tried a number of ways to approach this, but regardless of what method I use, whether to find the row number of the first row after filtering, using the code below with the union application, or a combination of the two what seems to happen is that when I run the filter below for "Slate Data" and then copy and paste it into the second sheet ("Placement Outlook") always results in whatever is in row 2 on "Slate Data" actual to be copy and pasted in the rows in "Placement Outlook".

The interesting and frustrating part about this is that I will get the desired result when I manually go through the autofilter and separately run the code for copying and pasting below, it's only when that code interacts with the autofilter code that it continues to only always copy and paste row 2 of the "Slate Data" worksheet into the "Placement Outlook" worksheet.

Any help is greatly appreciated!!

```<code>Dim lastrowuic, lastrowarray As Long
lastrowuic = Cells(Rows.Count, "C").End(xlUp).Row
lastrowarray = Cells(Rows.Count, "BP").End(xlUp).Row
Dim uniquesarray As Variant
uniquesarray = Range("C2:C" & lastrowuic)
Dim sdws As Worksheet
Set sdws = ActiveWorkbook.Sheets("Slate Data")
Dim pows As Worksheet
Set pows = ActiveWorkbook.Sheets("Placement Outlook")
Dim firstcell, middlecell, lastcell As Range
Set firstcell = sdws.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 1)
Set middlecell = sdws.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2)
Set lastcell = sdws.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 3)
Set homeport_command_uic = Application.Union(firstcell, middlecell, lastcell)
Dim uic As Integer
uic = 2

Do While sdws.Cells(uic, 68).Value <> ""
    sdws.Range("A1").CurrentRegion.AutoFilter Field:=3, Criteria1:=sdws.Cells(uic, 68)
        If lastcell <> "" Then
        homeport_command_uic.Copy pows.Cells(uic, 2).Offset(1, 0)
        End If

uic = uic + 1
Loop

End Sub

</code>```

答:
Your code does exactly what you explain it does...

I mean, it all the time copies a range extracted only from SHEET SpecialCells(xlCellTypeVisible).

In order to  do what you need, you must refer the necessary cells to the filtered area.

So, you must use (if this is the range you need to filter, like I only suppose):

```<code>uniquesarray.AutoFilter field:=1, Criteria1:="=your criteria", Operator:=xlFilterValues
</code>```

and then, set your necessary cells to be copied in this way:

```<code>Set firstcell = uniquesarray.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 1)
Set middlecell = uniquesarray.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2)
Set lastcell = uniquesarray.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 3)
</code>```

Setting your firstcell in the way you did, returns it with reference to the sheet range, not to the one (I understood) you need...

Do not forget to change "your criteria" whit your real filtering criteria!

Besides all that, it is a good habit to always put Optin Explicit on top of the module code, and properly declare ALL your variables. This will save you from a lot of troubles when/if the code will become bushy.

Body:
I have one workbook with two worksheets in it. What I am trying to do is autofilter through a range of unique values that I extracted and placed in a column in the far off reaches of both sheets. I'm then looking to copy and paste the values in the first three columns of the first visible row of what was filtered. I'm including the code below as I've tried a number of ways to approach this, but regardless of what method I use, whether to find the row number of the first row after filtering, using the code below with the union application, or a combination of the two what seems to happen is that when I run the filter below for "Slate Data" and then copy and paste it into the second sheet ("Placement Outlook") always results in whatever is in row 2 on "Slate Data" actual to be copy and pasted in the rows in "Placement Outlook".

The interesting and frustrating part about this is that I will get the desired result when I manually go through the autofilter and separately run the code for copying and pasting below, it's only when that code interacts with the autofilter code that it continues to only always copy and paste row 2 of the "Slate Data" worksheet into the "Placement Outlook" worksheet.

Any help is greatly appreciated!!

Dim lastrowuic, lastrowarray As Long
lastrowuic = Cells(Rows.Count, "C").End(xlUp).Row
lastrowarray = Cells(Rows.Count, "BP").End(xlUp).Row
Dim uniquesarray As Variant
uniquesarray = Range("C2:C" & lastrowuic)
Dim sdws As Worksheet
Set sdws = ActiveWorkbook.Sheets("Slate Data")
Dim pows As Worksheet
Set pows = ActiveWorkbook.Sheets("Placement Outlook")
Dim firstcell, middlecell, lastcell As Range
Set firstcell = sdws.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 1)
Set middlecell = sdws.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2)
Set lastcell = sdws.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 3)
Set homeport_command_uic = Application.Union(firstcell, middlecell, lastcell)
Dim uic As Integer
uic = 2

Do While sdws.Cells(uic, 68).Value <> ""
    sdws.Range("A1").CurrentRegion.AutoFilter Field:=3, Criteria1:=sdws.Cells(uic, 68)
        If lastcell <> "" Then
        homeport_command_uic.Copy pows.Cells(uic, 2).Offset(1, 0)
        End If

uic = uic + 1
Loop

End Sub

Body:
Your code does exactly what you explain it does...

I mean, it all the time copies a range extracted only from SHEET SpecialCells(xlCellTypeVisible).

In order to  do what you need, you must refer the necessary cells to the filtered area.

So, you must use (if this is the range you need to filter, like I only suppose):

uniquesarray.AutoFilter field:=1, Criteria1:="=your criteria", Operator:=xlFilterValues

and then, set your necessary cells to be copied in this way:

Set firstcell = uniquesarray.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 1)
Set middlecell = uniquesarray.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2)
Set lastcell = uniquesarray.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 3)

Setting your firstcell in the way you did, returns it with reference to the sheet range, not to the one (I understood) you need...

Do not forget to change "your criteria" whit your real filtering criteria!

Besides all that, it is a good habit to always put Optin Explicit on top of the module code, and properly declare ALL your variables. This will save you from a lot of troubles when/if the code will become bushy.


问:
Deserializing C data
I'm receiving a struct over a network from a C server to my Python client. The protocol is UDP. I have no control over the server and it's protocols/data formats. It consists of this struct (yes, an IPv4 + port):

```<code>struct ip_s {
    uint8_t i1;
    uint8_t i2;
    uint8_t i3;
    uint8_t i4;
    uint16_t port; // big endian
};
</code>```

Apart from the port which is converted to big-endian the data is sent "as-is", casted to a (char*).

How can I receive this struct to a format that is processable by Python?

Misc info:

Python 2.7 or 3.x

Cross-platform

Preferably solution using only built-in modules

答:
I'm receiving a struct over a network

Stop right there. Don't do that. This technique introduces the following dependencies:

Word order: big-endian or little-endian.

Padding.

Packing.

(2) and (3) in turn depend on:

The compiler.

The compiler version.

The surrounding #pragmas.

The compiler options in effect when the C program was compiled.

That's rather a lot of dependencies. Don't do this. Define an application protocol and use it. Or use something like XDR that solves the problem for you.

Title: Deserializing C data

Body:
I'm receiving a struct over a network from a C server to my Python client. The protocol is UDP. I have no control over the server and it's protocols/data formats. It consists of this struct (yes, an IPv4 + port):

struct ip_s {
    uint8_t i1;
    uint8_t i2;
    uint8_t i3;
    uint8_t i4;
    uint16_t port; // big endian
};

Apart from the port which is converted to big-endian the data is sent "as-is", casted to a (char*).

How can I receive this struct to a format that is processable by Python?

Misc info:

Python 2.7 or 3.x

Cross-platform

Preferably solution using only built-in modules


答:
yes, it's possible. You can render it as two different jsx elements like this:

```<code>    <text
      className="netProfit-circle-text"
      x="50%"
      y="50%"
      dy=".2em"
      textAnchor="middle"
    >
      <text>{this.state.percentage}</text>
      <text className="per-color">%</text>
    </text>
</code>```

Working example: https://codesandbox.io/s/hungry-leftpad-lue55.

Title: Styling a jsx element in react

Body:
yes, it's possible. You can render it as two different jsx elements like this:

    <text
      className="netProfit-circle-text"
      x="50%"
      y="50%"
      dy=".2em"
      textAnchor="middle"
    >
      <text>{this.state.percentage}</text>
      <text className="per-color">%</text>
    </text>

Working example: https://codesandbox.io/s/hungry-leftpad-lue55.


问:
What is the difference between Models and Repository in laravel 5?
I want to know what is the difference between Models and Repository in laravel 5. Both are same or not and what are benefits of repository.</p>

答:
The repository basically allows you to decouple your business logic from your database layer.

Whilst your eloquent model knows how to find all records for a given entity, your repository could wrap that in business-specific logic:

// Eloquent
$users = User::where('active', true)->get();

// Repository
$users = $this->userRepository->getAll(true);

class UserRepository {
    protected $model;

    public function __construct(User $model)
    {
        $this->model = $model;
    }

    public function getAll($active = false)
    {
        if ( $active === true )
        {
            return $this->model->where('active', true)->get();
        }

        return $this->model->all();
    }
}
```

This gives you testability and separation of concerns, your app is no longer tightly coupled to a particular implementation. In doing so, it becomes simpler to switch out the eloquent persistence for talking to a JSON API for example. This becomes easier still when you then you bind an interface to your controllers - something like UserRepositoryInterface - because you can update all uses of that interface just by updating one line in your service provider.

As with anything, though, it's up to you to determine if this is appropriate for your application. Repositories add another layer of complexity to your app that perhaps a small CRUD application won't actually need.

Body:
The repository basically allows you to decouple your business logic from your database layer.

Whilst your eloquent model knows how to find all records for a given entity, your repository could wrap that in business-specific logic:

// Eloquent
$users = User::where('active', true)->get();

// Repository
$users = $this->userRepository->getAll(true);

class UserRepository {
    protected $model;

    public function __construct(User $model)
    {
        $this->model = $model;
    }

    public function getAll($active = false)
    {
        if ( $active === true )
        {
            return $this->model->where('active', true)->get();
        }

        return $this->model->all();
    }
}

This gives you testability and separation of concerns, your app is no longer tightly coupled to a particular implementation. In doing so, it becomes simpler to switch out the eloquent persistence for talking to a JSON API for example. This becomes easier still when you then you bind an interface to your controllers - something like UserRepositoryInterface - because you can update all uses of that interface just by updating one line in your service provider.

As with anything, though, it's up to you to determine if this is appropriate for your application. Repositories add another layer of complexity to your app that perhaps a small CRUD application won't actually need.


问:
Understanding the At-Most-Once-Property in a concurrent program
I am trying to understand the at-most-once property which states:

An attribute of an assignment statement x = e in which either (1) x is not read by another process and e contains at most one reference to a variable changed by another process, or (2) x is not written by another process and e contains no references to variables changed by other processes.

```<code>int x = 0, y = 0;
co x = x+1; // y= y=1; oc;
</code>```

satisfies the property because x is not read by the second process and has no critical section

```<code>int x = 1, y = 1;
co <x = x + y;>
// y = 0;
// x = x - y;
oc
</code>```

I don't understand how this program satisfies the property though. The first statement is an atomic statement so it is not valid anyways but y=0 will affect the third statement x result so I don't understand how this satisfies the property?

答:
I was wondering what this might mean... and it being a particularly wet afternoon, I went and looked and found:

At-Most-Once Property

Andrews deﬁned a condition called at-most-once under which expression evaluations and assignments will appear to be atomic.

A critical reference in an expression is a reference to a variable that is changed by another thread.

An assignment statement x = e satisﬁes the at-most-once property if either:

1.1: e contains at most one critical reference and x is neither read nor written by another thread, or

1.2: e contains no critical references, in which case x may be read or written by other threads.

An expression that is not in an assignment satisﬁes at-most-once property if it contains no more than one critical reference.

This condition is called at-most-once because there can be at most one shared variable, and the shared variable can be referenced at most one time. ...

I think the key to your puzzle is this sentence:

... Assignment statements that satisfy at-most-once property appear to execute atomically even though they are not atomic.

and

... That is, we would get the same results from executing these assignment statements even if we were to somehow prevent the interleaving of their machine instructions so that the assignment statements were forced to execute atomically.

Assuming I have understood correctly:

the <x = x + y;> is an atomic read-modify-write.  So that is already atomic -- it does not need to "appear to execute atomically".

the y = 0 is at-most-once so satisfies (1.2) above and will "appear to execute atomically".  And because it does...

...that implies x = x - y is also at-most-once

...I think.  (Please let us know when you find a definitive answer.)

I'm curious as to what use this is !

Body:
I am trying to understand the at-most-once property which states:

An attribute of an assignment statement x = e in which either (1) x is not read by another process and e contains at most one reference to a variable changed by another process, or (2) x is not written by another process and e contains no references to variables changed by other processes.

int x = 0, y = 0;
co x = x+1; // y= y=1; oc;

satisfies the property because x is not read by the second process and has no critical section

int x = 1, y = 1;
co <x = x + y;>
// y = 0;
// x = x - y;
oc

I don't understand how this program satisfies the property though. The first statement is an atomic statement so it is not valid anyways but y=0 will affect the third statement x result so I don't understand how this satisfies the property?


问:
CSS library to handle cross-browser rotation and transformation
Are there any libraries or plugins you would recommend (preferably for jQuery) that would handle CSS rotation and transformation in a cross browser manner?

So far I've found:

CSS please, however as I understand these are just code snippets. And boy, they are ugly. I'd prefer to have this ugly css styles hidden somewhere within a library and not laying all over the place.

jQuery seems to have a plugin for rotation named (surprise, surprise) jquery-rotate. However we all know, that jquery plugins vary very much in quality. Maybe someone has had experience with this one. EDIT: I overlooked the fact that it actually only handles image rotation.

Rotating a Div Element in jQuery. However it's a little dated, and none of the answers seem to link to a library. Instead there are code snippets or information is provided how to do it all "by hand".

答:
cssSandpaper sounds like exactly what you're after.

I present to you the insane cube: http://www.useragentman.com/tests/cssSandpaper/cube3.html