问:
ReactRouter "on change" event?
I want to install an analytics handler on my single page app, and would like to capture every route change under the main route. I recognize that ReactRouter offers an onEnter route event; however, this would require me to separately install the handler on each route. I could create a subclass of Route that automatically has onEnter populated, but then I would not be able to override onEnter and still keep the analytics tracking handler.

What would be the best way to listen for any change within a given root Route?

答:
React: v15.x, React Router: v4.x

components/core/App.js:

```<code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter } from 'react-router-dom';

class LocationListener extends Component {
  static contextTypes = {
    router: PropTypes.object
  };

  componentDidMount() {
    this.handleLocationChange(this.context.router.history.location);
    this.unlisten =
this.context.router.history.listen(this.handleLocationChange);
  }

  componentWillUnmount() {
    this.unlisten();
  }

  handleLocationChange(location) {
    // your staff here
    console.log(`- - - location: '${location.pathname}'`);
  }

  render() {
    return this.props.children;
  }
}

export class App extends Component {
  ...

  render() {
    return (
      <BrowserRouter>
        <LocationListener>
         ...
        </LocationListener>
      </BrowserRouter>
    );
  }
}
</code>```

index.js:

```<code>import App from 'components/core/App';

render(<App />, document.querySelector('#root'));
</code>```

Title: ReactRouter "on change" event?

Body:
React: v15.x, React Router: v4.x

components/core/App.js:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter } from 'react-router-dom';

class LocationListener extends Component {
  static contextTypes = {
    router: PropTypes.object
  };

  componentDidMount() {
    this.handleLocationChange(this.context.router.history.location);
    this.unlisten =
this.context.router.history.listen(this.handleLocationChange);
  }

  componentWillUnmount() {
    this.unlisten();
  }

  handleLocationChange(location) {
    // your staff here
    console.log(`- - - location: '${location.pathname}'`);
  }

  render() {
    return this.props.children;
  }
}

export class App extends Component {
  ...

  render() {
    return (
      <BrowserRouter>
        <LocationListener>
         ...
        </LocationListener>
      </BrowserRouter>
    );
  }
}

index.js:

import App from 'components/core/App';

render(<App />, document.querySelector('#root'));


来源: stackexchange

问:
Angular 2 Pipe Binding Cause ExpressionChangedAfterItHasBeenCheckedError
I updated Angular 2 project to Angular 4. I am using Pipe like below.

```<code><input  type="text" class="form-control" [ngModel]="customerSearchText | isnumber" (ngModelChange)="customerSearchText=$event">
</code>```

customerSearchText declaration

```<code>public customerSearchText: number;
</code>```

isnumber.pipe

```<code>@Pipe({ name: 'isnumber'})
export class IsNumberPipe implements PipeTransform {
  transform(val: string): any {
    if(!val) return '';
    val=val.toString();
    return WrappedValue.wrap(val.replace(/\D/g, ''))
  }
}
</code>```

When I used like this I am getting error.

```<code>Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '[object Object]'. Current value: '4'
</code>```

When I deleted pipe from my input, error gone. But I want control  is input number.

How can i solve this problem?

答:
I think this is happening due to the immediate assignment you have with the (ngModelChange) event. Try calling a function defined in your component instead of directly doing the assignment in the template for that event, like this,

in template,

```<code><input  type="text" class="form-control" [ngModel]="customerSearchText | isnumber" (ngModelChange)="inputChanged($event)">
</code>```

in your component,

```<code>inputChanged(value: string): void {
   this.customerSearchText = value;
}
</code>```

Hope it helps.

If it didn't fix, then try wrapping your '' (empty string) return in your pipe with WrappedValue.wrap as in return WrappedValue.wrap('');.

ContentLicense: CC BY-SA 3.0

Body:
I updated Angular 2 project to Angular 4. I am using Pipe like below.

<input  type="text" class="form-control" [ngModel]="customerSearchText | isnumber" (ngModelChange)="customerSearchText=$event">

customerSearchText declaration

public customerSearchText: number;

isnumber.pipe

@Pipe({ name: 'isnumber'})
export class IsNumberPipe implements PipeTransform {
  transform(val: string): any {
    if(!val) return '';
    val=val.toString();
    return WrappedValue.wrap(val.replace(/\D/g, ''))
  }
}

When I used like this I am getting error.

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '[object Object]'. Current value: '4'

When I deleted pipe from my input, error gone. But I want control  is input number.

How can i solve this problem?

Body:
I think this is happening due to the immediate assignment you have with the (ngModelChange) event. Try calling a function defined in your component instead of directly doing the assignment in the template for that event, like this,

in template,

<input  type="text" class="form-control" [ngModel]="customerSearchText | isnumber" (ngModelChange)="inputChanged($event)">

in your component,

inputChanged(value: string): void {
   this.customerSearchText = value;
}

Hope it helps.

If it didn't fix, then try wrapping your '' (empty string) return in your pipe with WrappedValue.wrap as in return WrappedValue.wrap('');.


问:
Syntax for Templated Member Functions
Consider the following code:

```<code>template <typename Datatype>
class MyClass
{
    void doStuff();

    template <typename AnotherDatatype>
    void doTemplateStuff(AnotherDatatype Argument);
};

template <typename Datatype>
void MyClass<Datatype>::doStuff()
{
    // ...
}

template <typename Datatype>
template <typename AnotherDatatype>
void MyClass<Datatype>::doTemplateStuff(AnotherDatatype Argument)
{
    // ...
}
</code>```

The implementation for the second member function, doTemplateStuff, will not compile if I condense it like this:

```<code>template <typename Datatype, typename AnotherDatatype>
void MyClass<Datatype>::doTemplateStuff(AnotherDatatype Argument)
{
    // ...
}
</code>```

Why is this?  Shouldn't separating template information by commas have the same effect as putting each typename on its own line?  Or is there some subtle difference I'm not aware of...?

(Also, if someone can think of a better title please let me know.)

答:
Putting comma's between the template declaration tells the compiler to expect two template parameters.  In your case, because the object is a template object when you declare the function as you do you're violating your own declaration.  It's looking for that second template in the MyClass object, referencing the actual class declaration and realizing that it's an error.

Hence,

```<code>template<typename T, typename V>
struct Foo{
    void bar();
};

template<typename T, typename V>
void Foo<T,V>::bar(){...}
</code>```

is what it's expecting to see.

```<code>template<typename T>
struct Foo{
    void bar();
}

template<typename T, typename V>
void Foo<T>::bar(){...}
</code>```

is an error.  It's wondering where that other template parameter came from.

If you want to do this you'll need to write the function right there:

```<code>template<typename T>
struct Foo{
    template<typename V>
    void bar(const V& _anInputValue){
        cout << _anInputValue;
    }

    void baz();
};

template<typename T>
void Foo<T>::baz(){
    cout << "Another function.";
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Syntax for Templated Member Functions

Body:
Consider the following code:

template <typename Datatype>
class MyClass
{
    void doStuff();

    template <typename AnotherDatatype>
    void doTemplateStuff(AnotherDatatype Argument);
};

template <typename Datatype>
void MyClass<Datatype>::doStuff()
{
    // ...
}

template <typename Datatype>
template <typename AnotherDatatype>
void MyClass<Datatype>::doTemplateStuff(AnotherDatatype Argument)
{
    // ...
}

The implementation for the second member function, doTemplateStuff, will not compile if I condense it like this:

template <typename Datatype, typename AnotherDatatype>
void MyClass<Datatype>::doTemplateStuff(AnotherDatatype Argument)
{
    // ...
}

Why is this?  Shouldn't separating template information by commas have the same effect as putting each typename on its own line?  Or is there some subtle difference I'm not aware of...?

(Also, if someone can think of a better title please let me know.)

Body:
Putting comma's between the template declaration tells the compiler to expect two template parameters.  In your case, because the object is a template object when you declare the function as you do you're violating your own declaration.  It's looking for that second template in the MyClass object, referencing the actual class declaration and realizing that it's an error.

Hence,

template<typename T, typename V>
struct Foo{
    void bar();
};

template<typename T, typename V>
void Foo<T,V>::bar(){...}

is what it's expecting to see.

template<typename T>
struct Foo{
    void bar();
}

template<typename T, typename V>
void Foo<T>::bar(){...}

is an error.  It's wondering where that other template parameter came from.

If you want to do this you'll need to write the function right there:

template<typename T>
struct Foo{
    template<typename V>
    void bar(const V& _anInputValue){
        cout << _anInputValue;
    }

    void baz();
};

template<typename T>
void Foo<T>::baz(){
    cout << "Another function.";
}


问:
Adding flat html/css/js to drupal - not maintaining styling
I'm developing some JS animated components to add to a Drupal site. I typically work in JS and never Drupal, so the framework is where I'm having confusion. When I add the code into a WYSIWYG and preview, the components lose a lot of their styling - spacing, text color, font, etc. Is there anything Drupal specific that I need to ensure I do to make it so my components look the same when I view them locally vs on Drupal? </p>

<p>I've also heard about 'iframing'. Would this be an alternative that could fix this issue? </p>

答:
Please specify what version of Drupal you are using.

I would recommend to create a module to add this JS/CSS.
Using the WYSIWYG to full html but having code, functionality into the Database can be a pain if your are having from dev environment and moving this then to production.

Body:
I'm developing some JS animated components to add to a Drupal site. I typically work in JS and never Drupal, so the framework is where I'm having confusion. When I add the code into a WYSIWYG and preview, the components lose a lot of their styling - spacing, text color, font, etc. Is there anything Drupal specific that I need to ensure I do to make it so my components look the same when I view them locally vs on Drupal?

I've also heard about 'iframing'. Would this be an alternative that could fix this issue?


问:
error : curl: (52) Empty reply from server , when ingesting data into druid
I found this : curl: (7) Failed to connect to localhost port 8090: Connection refused . But, not able to resolve the issue.

I tried using the public ip of my machine but then it gave me another error : "curl: (52) Empty reply from server" .

I also tried 0.0.0.0 as it was mentioned in some other posts. But same issue. Do i need to do something else ?

here is the command I execute to run my docker image : "docker run -t -p 8000:8000 -p 8090:8090 $IMAGE_ID"

and this is the command I use to ingest batch data into druid :

"curl -X 'POST' -H 'Content-Type:application/json' -d @./../druid/stb_ad_trait/index.json $MY_MACHINE_IP:8090/druid/indexer/v1/task" .

Any idea please ?

答:
In the official dockerised image the Coordinator works as both the Coordinator and the Overlord.
See for a reference:
https://github.com/druid-io/docker-druid/blob/master/supervisord.conf#L30

Perhaps that is the case with your setup as well? If so, simply use the Coordinator port (8081) instead of the Overlord port (8090).

http://host:8081/druid/indexer/v1/supervisor


问:
How to find FIRST and FOLLOW set of a recursive grammar?
Suppose I have the following CFG:

S->aACD|BcAe

A->b | EPSILON

B->cf | d

C->fe

Now I apply the FIRST rule on the CFG:

FIRST(S)=FIRST(aAcd) U FIRST(BcAe)

={a} U FIRST(BcAe)

= {a} U FIRST(B)-{EPSILON} U FIRST(cAe)

= {a} U FIRST(B)-{EPSILON} U {c}

= {a} U FIRST(Cf) U FIRST(d) -{EPSILON} U {c}

= {a,f,d,c,EPSILON}

FIRST(A)=FIRST(b) U FIRST(EPSILON)= ={B,EPSILON}

FIRST(B)=FIRST(Cf) U FIRST(d)={d,f}

FIRST(C)=FIRST(fe)={F}

Now I apply the FOLLOW rule on the CFG:

FOLLOW(S)={$}

FOLLOW(A)={c,e}

FOLLOW(B)={c}

FOLLOW(C)={f}

Is there any wrong? If it is wrong please show me how to do it.

答:
Your work above (question) suggest that you are not good in basic concepts. So you can make use of the this tutorial.

Grammer :

S->aACD|BcAe

A->b | EPSILON

B->cf | d

C->fe

No production means EPSILON so,

D-> EPSILON

On applying first rule :

FIRST(A)=FIRST(b) U FIRST(EPSILON)= ={b,EPSILON}

FIRST(B)=FIRST(cf) U FIRST(d)={c} U {d} = {c,d}

FIRST(C)=FIRST(fe)={f}

FIRST(D)={EPSILON}

FIRST(S)=FIRST(aACD) U FIRST(BcAe)

={a} U FIRST(BcAe)

= {a} U FIRST(B)

= {a} U {c,d}

= {a,c,d}

on applying follow rule :

FOLLOW(S)={$}

FOLLOW(A)= FIRST(C) U FIRST(e) = {f,e}

FOLLOW(B)={c}

FOLLOW(C)={$}

FOLLOW(D)={$}


问:
How to reference subquery in the WHERE clause
I have a SQL query (T-SQL) in which I have a subquery in the SELECT statement.

Here is a reduced version:

```<code>SELECT
    p.id AS id,
    (SELECT
        jobs_without_price.id
    FROM
        st_job jobs_without_price
    WHERE
        jobs_without_price.person_id = p.id
    AND
        jobs_without_price.price IS NULL
    FOR XML AUTO, ROOT('jobs')) AS JobsWithoutPrice
FROM
    st_person p
WHERE
    JobsWithoutPrice IS NOT NULL
GROUP BY
    p.id
</code>```

The problem is that SSMS tells me

Invalid column name 'JobsWithoutPrice'.

This is almost certainly because SQL doesn't allow aliases in WHERE clauses, but how else can I use the result of this subquery to filter the results?

[The full query has more table joins and much more in the SELECT statement, all of which pertains to a single person record, whereas the subquery reports back multiple records, which is why it's in a subquery.]

答:
The scope of table aliases when used in a subquery or common table expression (CTE) is limited to that subquery. They cannot be referenced by an outer query. Consider the following query:

```<code>declare @table table (id int identity, col1 varchar(10));
insert @table(col1) values ('aaa'),('bbb'),('ccc');

select *
from
(
  -- I can reference table aliases for this query in here
  select sub1.id, sub1.col1, sub2.x
  from @table sub1
  join (select 'xxx' as x) sub2 on sub1.col1 <> sub2.x
  where sub2.x is not null
) innerQuery
where innerQuery.col1 is not null -- this is ok
--where sub1.col1 is not null     -- this will fail
</code>```

Note my comments. Here we have and inner and outer query. The inner query one lives between the brackets, the outer query references the inner query. My inner query has two column aliases: sub1 and sub2. I can reference sub1 or sub2 anywhere inside the two parentheses. Sub1 and sub2 are not valid outside of those parentheses.

Body:
I have a SQL query (T-SQL) in which I have a subquery in the SELECT statement.

Here is a reduced version:

SELECT
    p.id AS id,
    (SELECT
        jobs_without_price.id
    FROM
        st_job jobs_without_price
    WHERE
        jobs_without_price.person_id = p.id
    AND
        jobs_without_price.price IS NULL
    FOR XML AUTO, ROOT('jobs')) AS JobsWithoutPrice
FROM
    st_person p
WHERE
    JobsWithoutPrice IS NOT NULL
GROUP BY
    p.id

The problem is that SSMS tells me

Invalid column name 'JobsWithoutPrice'.

This is almost certainly because SQL doesn't allow aliases in WHERE clauses, but how else can I use the result of this subquery to filter the results?

[The full query has more table joins and much more in the SELECT statement, all of which pertains to a single person record, whereas the subquery reports back multiple records, which is why it's in a subquery.]

Body:
The scope of table aliases when used in a subquery or common table expression (CTE) is limited to that subquery. They cannot be referenced by an outer query. Consider the following query:

declare @table table (id int identity, col1 varchar(10));
insert @table(col1) values ('aaa'),('bbb'),('ccc');

select *
from
(
  -- I can reference table aliases for this query in here
  select sub1.id, sub1.col1, sub2.x
  from @table sub1
  join (select 'xxx' as x) sub2 on sub1.col1 <> sub2.x
  where sub2.x is not null
) innerQuery
where innerQuery.col1 is not null -- this is ok
--where sub1.col1 is not null     -- this will fail

Note my comments. Here we have and inner and outer query. The inner query one lives between the brackets, the outer query references the inner query. My inner query has two column aliases: sub1 and sub2. I can reference sub1 or sub2 anywhere inside the two parentheses. Sub1 and sub2 are not valid outside of those parentheses.


问:
How to scroll to top of the first post loaded with Ajax Pagination and Infinite Scroll plugin by Malinky?
I'm using Ajax Pagination and Infinite Scroll plugin by Malinky inside the WordPress blog that I'm currently working on. Plugin is set to load more button paging type.
I need to set it so that after the load more button is clicked, the first new loaded post is scrolled to the top of the viewport.
Unfortunately, the plugin is not very well documented and I can't find a way to select the first loaded post in order to apply animation to it inside the callback.
I've tried adding class 'anchor' to the last post both inside and outside the callback with $('article').last().addClass('anchor');and then doing $('html, body').animate to the $('article.anchor:nth-last-of-type(2)')inside the callback in order to scroll to the bottom of the second last .anchor element, which is the element after which the first new loaded post is positioned, but for some reason the animation seems to not work with any nth- pseudo class. It only works with last-of-type, which is useless to me.
Is there a way to make this work somehow?

答:
I've added class div-anchor to the last article outside of callback and to last loaded article inside callback with $('article').last().addClass('anchor'); and I used :eq(-2) instead of :nth-last-of-type(2) and this seems to work

```<code>$('html, body').animate({ scrollTop: $('article.div-anchor:eq(-2)').offset().top + $('article.div-anchor:eq(-2)').outerHeight(true) - $('.header').outerHeight(true) - $('#wpadminbar').outerHeight(true) }, 500);
</code>```

Body:
I've added class div-anchor to the last article outside of callback and to last loaded article inside callback with $('article').last().addClass('anchor'); and I used :eq(-2) instead of :nth-last-of-type(2) and this seems to work

$('html, body').animate({ scrollTop: $('article.div-anchor:eq(-2)').offset().top + $('article.div-anchor:eq(-2)').outerHeight(true) - $('.header').outerHeight(true) - $('#wpadminbar').outerHeight(true) }, 500);


问:
TypeError: cannot concatenate a ninNDFrame object while trying to concat
enter image description hereThis is my code and I am trying to concatenate on axis=0 or append but I get this error. All the columns are the same and even the datatypes are same.

Although when doing a pd.read_csv() I have to specify encoding=ISO-8859-1
Do you think that could be the reason for it?
Although the type is a dataframe

```<code>declinedataforclassification=declinedata[['amount_requested','Risk_Score','dti','State','emp_length','policy_code','app_month']]
loandataforclassification=loandata[['loan_amnt','Risk_Score','dti','addr_state','emp_length','policy_code','issue_month']]
loandataforclassification=loandataforclassification.rename(columns={'loan_amnt':'amount_requested','addr_state':'State','issue_month':'app_month'})
declinedataforclassification['status']=0
loandataforclassification['status']=1
loandataforclassification['amount_requested']=loandataforclassification['amount_requested'].astype(float)

resultdata = loandataforclassification.append('declinedataforclassification',ignore_index=True)
</code>```

答:
```<code>resultdata = loandataforclassification.append(declinedataforclassification,ignore_index=True)
</code>```

<p>should work for you. You're trying to append a string to a data frame right now. </p>

Body:
enter image description hereThis is my code and I am trying to concatenate on axis=0 or append but I get this error. All the columns are the same and even the datatypes are same.

Although when doing a pd.read_csv() I have to specify encoding=ISO-8859-1
Do you think that could be the reason for it?
Although the type is a dataframe

declinedataforclassification=declinedata[['amount_requested','Risk_Score','dti','State','emp_length','policy_code','app_month']]
loandataforclassification=loandata[['loan_amnt','Risk_Score','dti','addr_state','emp_length','policy_code','issue_month']]
loandataforclassification=loandataforclassification.rename(columns={'loan_amnt':'amount_requested','addr_state':'State','issue_month':'app_month'})
declinedataforclassification['status']=0
loandataforclassification['status']=1
loandataforclassification['amount_requested']=loandataforclassification['amount_requested'].astype(float)

resultdata = loandataforclassification.append('declinedataforclassification',ignore_index=True)

Body:
resultdata = loandataforclassification.append(declinedataforclassification,ignore_index=True)

should work for you. You're trying to append a string to a data frame right now.


问:
use string "includes()" in switch Javascript case
In Javascript, is there a way to achieve something similar to this ?

```<code>const databaseObjectID = "someId"; // like "product/217637"

switch(databaseObjectID) {
    case includes('product'): actionOnProduct(databaseObjectID); break;
    case includes('user'): actionOnUser(databaseObjectID); break;
    // .. a long list of different object types
}
</code>```

This is more a curiosity question to understand the possibilities of switch / case, as in this particular case I have solved my problem using const type = databaseObjectID.split('/')[0]; and apply the switch case on type

答:
Sorry, I'm a noob so someone will probably have to clean this up, but here is the idea.  Pass to a function to check and return a category then use the switch.

```<code>function classify(string){
  var category = categorize(string);
  switch (category) {
    case 'product':
      console.log('this is a product');
      break;
    case 'user':
      console.log('this is a user');
      break;
    default:
      console.log('category undefined');
  }
}

function categorize(string){
  if (string.includes('product')){
    return 'product';
  }
  if (string.includes('user')){
    return 'user';
  }
}

classify("product789");
classify("user123");
classify("test567");
</code>```

Sorry, as well, for not matching your example.

Body:
In Javascript, is there a way to achieve something similar to this ?

const databaseObjectID = "someId"; // like "product/217637"

switch(databaseObjectID) {
    case includes('product'): actionOnProduct(databaseObjectID); break;
    case includes('user'): actionOnUser(databaseObjectID); break;
    // .. a long list of different object types
}

This is more a curiosity question to understand the possibilities of switch / case, as in this particular case I have solved my problem using const type = databaseObjectID.split('/')[0]; and apply the switch case on type

Body:
Sorry, I'm a noob so someone will probably have to clean this up, but here is the idea.  Pass to a function to check and return a category then use the switch.

function classify(string){
  var category = categorize(string);
  switch (category) {
    case 'product':
      console.log('this is a product');
      break;
    case 'user':
      console.log('this is a user');
      break;
    default:
      console.log('category undefined');
  }
}

function categorize(string){
  if (string.includes('product')){
    return 'product';
  }
  if (string.includes('user')){
    return 'user';
  }
}

classify("product789");
classify("user123");
classify("test567");

Sorry, as well, for not matching your example.


问:
regex substitute several special characters with other special characters in Textwrangler
The character  ̈ (unicode 0x308) cannot be represented in the “Western (ISO Latin 9)” encoding.

I need to replace several (3) of this special characters in many txt-files. Ideal would be one single regex command for the TEXTWRANGLER editor application I run on my Mac so I can use in the find&replace function of Textwrangler (similar to BBedit).

Here are the 3 special chars:

ä into ä

ö into ö

ü into ü

(please note the first letter persists of two chars (e.g. the a and the  ̈ unicode 0x308) and therefore it is not WESTERN ISO LATIN compatibel.

I tried regex (groups) but I was not successfull:
In TEXTWRANGLER I use the find&replace function (incl. grep=regex option)

FIND: (ä|ö|ü)+

REPLACE: \1ä , \2ö , \3ü

any idea?

答:
Brief

I've just tested this with Notepad++, although I'm not sure if this will work in any Mac text editor alternatives.

This method is a conditional replacement using a dictionary in regex. It's more of a hack, but it does work assuming it's supported by the text editor. Once you're done remove the dictionary from the bottom of the file.

Code

See regex in use here

```<code>(ä|ö|ü)(?=[\s\S]*Dictionary:[\s\S]*\1=([^\s=:]+))
</code>```

Replacement

```<code>\2
</code>```

Results

Input

```<code>ä into a
ö into o
ü into u
</code>```

Input - Modified

This input includes the dictionary at the end

```<code>ä into a
ö into o
ü into u

Dictionary:
ä=a
ö=o
ü=u
</code>```

Output

```<code>a into a
o into o
u into u

Dictionary:
ä=a
ö=o
ü=u
</code>```

Explanation

(ä|ö|ü) Capture either character in the group into capture group 1

(?=[\s\S]*Dictionary:[\s\S]*\1=([^\s=:]+)) Positive lookahead ensuring what follows matches

[\s\S]* Match any character any number of times

Dictionary: Match Dictionary: literally (this can be changed to anything, but you should make sure this is a unique string that won't be present anywhere else in your input)

[\s\S]* Match any character any number of times

\1 Match the same text as most recently matched by the first capture group

= Match the equal sign character = literally

([^\s=:]+) Capture one or more of any character not present in the set (not whitespace, = or :) into capture group 2

Body:
Brief

I've just tested this with Notepad++, although I'm not sure if this will work in any Mac text editor alternatives.

This method is a conditional replacement using a dictionary in regex. It's more of a hack, but it does work assuming it's supported by the text editor. Once you're done remove the dictionary from the bottom of the file.

Code

See regex in use here

(ä|ö|ü)(?=[\s\S]*Dictionary:[\s\S]*\1=([^\s=:]+))

Replacement

\2

Results

Input

ä into a
ö into o
ü into u

Input - Modified

This input includes the dictionary at the end

ä into a
ö into o
ü into u

Dictionary:
ä=a
ö=o
ü=u

Output

a into a
o into o
u into u

Dictionary:
ä=a
ö=o
ü=u

Explanation

(ä|ö|ü) Capture either character in the group into capture group 1

(?=[\s\S]*Dictionary:[\s\S]*\1=([^\s=:]+)) Positive lookahead ensuring what follows matches

[\s\S]* Match any character any number of times

Dictionary: Match Dictionary: literally (this can be changed to anything, but you should make sure this is a unique string that won't be present anywhere else in your input)

[\s\S]* Match any character any number of times

\1 Match the same text as most recently matched by the first capture group

= Match the equal sign character = literally

([^\s=:]+) Capture one or more of any character not present in the set (not whitespace, = or :) into capture group 2


问:
Rails 3 Routes with match and the :as option, not matching
I have a match route with the as option specified:

```<code>match ':major(/node/:id)/:minor' => 'nodes#show', :constraints => {:major => /(measure|change|analysis|report|manage|)/}, :as => :minor_section
</code>```

when i use it with:

```<code>minor_section_path('manage', @node.id.to_s, 'overview')
</code>```

I get the following error:

```<code>No route matches {:controller=>"nodes", :action=>"show", :major=>"manage", :id=>"4d23522bcae8ab0316000120", :minor=>"overview"}
</code>```

any one got any thoughts it looks right to me

many thanks

答: Broken regular expression: Get rid of the extra pipe (|) after "manage" in your constraint.</p>

Body:
I have a match route with the as option specified:

match ':major(/node/:id)/:minor' => 'nodes#show', :constraints => {:major => /(measure|change|analysis|report|manage|)/}, :as => :minor_section

when i use it with:

minor_section_path('manage', @node.id.to_s, 'overview')

I get the following error:

No route matches {:controller=>"nodes", :action=>"show", :major=>"manage", :id=>"4d23522bcae8ab0316000120", :minor=>"overview"}

any one got any thoughts it looks right to me

many thanks


问:
Kafka Streams application deployment - embedded vs application management frameworks
I'm pretty new to Kafka Streams. Right now I'm trying to understand the basic principles of this system.

This is a quote from the following article https://www.confluent.io/blog/introducing-kafka-streams-stream-processing-made-simple/

```<code>You just use the library in your app, and start as many instances of the app as you like, and Kafka will partition up and balance the work over these instances.
</code>```

Right now it is not clear to me how it works. Where will the business logic(computation tasks) of Kafka Streams be executed? It will be executed inside of my application, or it is just a client for Kafka cluster and this client will only prepare tasks that will be executed on Kafka cluster? If no, how to properly scale the computation power of my Kafka Streams application? Is it possible to execute inside Yarn or something like this? This way is it a good idea to implement the Kafka Streams application as an embedded component of the core application(let's say web application in my case) or it should be implemented as a separate service and deployed to Yarn/Mesos(if it is possible) separately from the main web application? Also, how to prepare Kafka Streams application to be ready deploy with Yarn/Mesos application management frameworks?

答:
You stream processing code is running inside your applications -- it's not running in the Kafka cluster.

You can deploy anyway you like: Yarn/Mesos/kubernetes/WAR/Chef whatever. The idea is to embed it directly into your application to avoid setting up a processing cluster.

You don't need to prepare Kafka Streams for a deployment method -- it's completely agnostic to how it gets deployed. For Yarn/Mesos you would deploy it as any other Java application within the framework.

Body:
I'm pretty new to Kafka Streams. Right now I'm trying to understand the basic principles of this system.

This is a quote from the following article https://www.confluent.io/blog/introducing-kafka-streams-stream-processing-made-simple/

You just use the library in your app, and start as many instances of the app as you like, and Kafka will partition up and balance the work over these instances.

Right now it is not clear to me how it works. Where will the business logic(computation tasks) of Kafka Streams be executed? It will be executed inside of my application, or it is just a client for Kafka cluster and this client will only prepare tasks that will be executed on Kafka cluster? If no, how to properly scale the computation power of my Kafka Streams application? Is it possible to execute inside Yarn or something like this? This way is it a good idea to implement the Kafka Streams application as an embedded component of the core application(let's say web application in my case) or it should be implemented as a separate service and deployed to Yarn/Mesos(if it is possible) separately from the main web application? Also, how to prepare Kafka Streams application to be ready deploy with Yarn/Mesos application management frameworks?


问:
Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?
Before anything, please note that I have found several similar questions on Stack Overflow and articles all over the web, but none of those helped me fix my issue:

PG Error could not connect to server: Connection refused Is the server running on port 5432?

PG::ConnectionBad - could not connect to server: Connection refused

psql: could not connect to server: Connection refused

Now, here is the issue:

I have a Rails app that works like a charm.

With my collaborator, we use GitHub to work together.

We have a master and an mvp branches.

I recently updated my git version with Homebrew (Mac).

We use Foreman to start our app locally.

Now, when I try to launch the app locally, I get the following error:

```<code>PG::ConnectionBad at /
could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
</code>```

I tried to reboot my computers several times.

I also checked the content of /usr/local/var/postgres:

```<code>PG_VERSION      pg_dynshmem     pg_multixact    pg_snapshots    pg_tblspc       postgresql.conf
base            pg_hba.conf     pg_notify       pg_stat         pg_twophase     postmaster.opts
global          pg_ident.conf   pg_replslot     pg_stat_tmp     pg_xlog         server.log
pg_clog         pg_logical      pg_serial       pg_subtrans     postgresql.auto.conf
</code>```

As you can see, there is no postmaster.pid file in there.

Any idea how I could fix this?

答:
Most likely it's because your system shutdown unexpectedly

Try

```<code>postgres -D /usr/local/var/postgres
</code>```

You might see

```<code>FATAL:  lock file "postmaster.pid" already exists
HINT:  Is another postmaster (PID 449) running in data directory "/usr/local/var/postgres"?
</code>```

Then try

```<code>kill -9 PID
</code>```

example

```<code>kill -9 419
</code>```

And it should start postgres normally

Body:
Before anything, please note that I have found several similar questions on Stack Overflow and articles all over the web, but none of those helped me fix my issue:

PG Error could not connect to server: Connection refused Is the server running on port 5432?

PG::ConnectionBad - could not connect to server: Connection refused

psql: could not connect to server: Connection refused

Now, here is the issue:

I have a Rails app that works like a charm.

With my collaborator, we use GitHub to work together.

We have a master and an mvp branches.

I recently updated my git version with Homebrew (Mac).

We use Foreman to start our app locally.

Now, when I try to launch the app locally, I get the following error:

PG::ConnectionBad at /
could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

I tried to reboot my computers several times.

I also checked the content of /usr/local/var/postgres:

PG_VERSION      pg_dynshmem     pg_multixact    pg_snapshots    pg_tblspc       postgresql.conf
base            pg_hba.conf     pg_notify       pg_stat         pg_twophase     postmaster.opts
global          pg_ident.conf   pg_replslot     pg_stat_tmp     pg_xlog         server.log
pg_clog         pg_logical      pg_serial       pg_subtrans     postgresql.auto.conf

As you can see, there is no postmaster.pid file in there.

Any idea how I could fix this?

Body:
Most likely it's because your system shutdown unexpectedly

Try

postgres -D /usr/local/var/postgres

You might see

FATAL:  lock file "postmaster.pid" already exists
HINT:  Is another postmaster (PID 449) running in data directory "/usr/local/var/postgres"?

Then try

kill -9 PID

example

kill -9 419

And it should start postgres normally


问:
Do Anaconda Cloud packages come with their dependencies?
Do Anaconda cloud packages manually pulled from their website come with all of the packages dependencies?

For example, I have package A that I need for a python project. It has a dependency tree like below:

```<code>pip show package_A
Name: package_A
Version: 1.0.1
Requires: package_X, package_Y

pip show package_X
Name: package_X
Version: 2.0.2
Requires:

pip show package_Y
Name:package_Y
Version: 3.0.3
Requires: package_M

pip show package_M
Name: package_M
Version: 4.0.4
Requires:
</code>```

So if I wanted to manually pull down package_A from the anaconda cloud site, would I need to pull the *.tar.bz2 files for all packages or would the package_A-1.0.1-py36hafb9ca4_1.tar.bz2 file have all of the dependencies also?

I use pip to show the dependencies, but I will be using conda to install. SOmething like:

```<code>conda install /libs/package_A-1.0.1-py36hafb9ca4_1.tar.bz2
</code>```

答:
'conda install' command will resolve and install all dependencies automatically provided this was configured within the package.  You can check package dependencies by running -

```<code>conda info package_A=1.0.1=py36hafb9ca4_1
</code>```

However, if you you install directly from tarballs there is no dependency check. To install local packages you can use the option "--use-local"

```<code>conda install --use-local package_A=1.0.1=py36hafb9ca4_1
</code>```

Body:
Do Anaconda cloud packages manually pulled from their website come with all of the packages dependencies?

For example, I have package A that I need for a python project. It has a dependency tree like below:

pip show package_A
Name: package_A
Version: 1.0.1
Requires: package_X, package_Y

pip show package_X
Name: package_X
Version: 2.0.2
Requires:

pip show package_Y
Name:package_Y
Version: 3.0.3
Requires: package_M

pip show package_M
Name: package_M
Version: 4.0.4
Requires:

So if I wanted to manually pull down package_A from the anaconda cloud site, would I need to pull the *.tar.bz2 files for all packages or would the package_A-1.0.1-py36hafb9ca4_1.tar.bz2 file have all of the dependencies also?

I use pip to show the dependencies, but I will be using conda to install. SOmething like:

conda install /libs/package_A-1.0.1-py36hafb9ca4_1.tar.bz2

Body:
'conda install' command will resolve and install all dependencies automatically provided this was configured within the package.  You can check package dependencies by running -

conda info package_A=1.0.1=py36hafb9ca4_1

However, if you you install directly from tarballs there is no dependency check. To install local packages you can use the option "--use-local"

conda install --use-local package_A=1.0.1=py36hafb9ca4_1


问:
How to parse an input string, like a calculator, to grab the operator and operands?
I am brand new to the Go programming language and I am trying to build a very simple calculator. The issues I am running into is if someone enters in 4+2 or 5/10 or 100-25 to the command line how do I grab the operator and operands out of this string in order to perform the equation?

This is what I have so far, but this just grabs the entire string

```<code>package main

import (
"bufio"
"fmt"
"os"
"stack" //stack code works perfectly
)

func main() {

// Read a line from stdin.
scanner := bufio.NewScanner(os.Stdin)

for scanner.Scan() {
    line := scanner.Text()
    // fmt.Println(line)

    //Separate the string based on operator and operands

    // Push all of the characters onto the stack.
    s := stack.New()
    for i := 0; i < len(line); i++ {
        if err := s.Push(line[i]); err != nil {
            panic("Push failed")
        }
    }
</code>```

答:
Some pointers for you.

To get operands from your line try strings.FieldsFunc().

Convert your operands to float64 try strconv.ParseFloat() or fmt.Sscanf().

Figure out what operation +, -, /, * you have. Perhaps with strings.ContainsRune().

Perform operation on operands and present results.

Have fun!

Body:
I am brand new to the Go programming language and I am trying to build a very simple calculator. The issues I am running into is if someone enters in 4+2 or 5/10 or 100-25 to the command line how do I grab the operator and operands out of this string in order to perform the equation?

This is what I have so far, but this just grabs the entire string

package main

import (
"bufio"
"fmt"
"os"
"stack" //stack code works perfectly
)

func main() {

// Read a line from stdin.
scanner := bufio.NewScanner(os.Stdin)

for scanner.Scan() {
    line := scanner.Text()
    // fmt.Println(line)

    //Separate the string based on operator and operands

    // Push all of the characters onto the stack.
    s := stack.New()
    for i := 0; i < len(line); i++ {
        if err := s.Push(line[i]); err != nil {
            panic("Push failed")
        }
    }


问:
How do I parse unknown encoding file?
I am trying to parse a file with extension with vmd (Vocaloid Motion Data 0002). I do not know what encoding it uses. I have attempted using UTF-8, UTF-16, CS_ASCII and Windows-31j (Shift JIS), but none of them worked (but based on what I know, most of UTF-8 should resolve since the byte is 2 for most of characters).

```<code>String testFile = rawFilePath+"/test.vmd";
BufferedWriter bw = null;
FileWriter fw = null;
fw = new FileWriter(outputPath+"/newFile.txt");
bw = new BufferedWriter(fw);
BufferedReader fBr = new BufferedReader(new InputStreamReader(
    new FileInputStream(testFile), "UTF-8"));  //US-ASCII windows-31j
int count=0;
String line;
while ((line = fBr.readLine()) != null) {
    System.out.println(line);
    bw.write(line);
    bw.write("\r\n");
    count++;
    if(count > 3) { //print small portion of a larger file for testing
        break;
    }
    ...
}
</code>```

Both print and the output file writes something like this:

```<code>???~?N ??????????P ?Z???^?[    ??kkkkkkkk
</code>```

I was wondering if this is an encoding issue, or some other issue?  How do I parse readable data from this?

答: You may want to examine it as a byte stream. And during that inspection, decode the first few bytes by hand, according to how encoding is done. See https://en.wikipedia.org/wiki/Byte_order_mark for some good information on starting to work with UTF encoding.

Title: How do I parse unknown encoding file?

Body:
I am trying to parse a file with extension with vmd (Vocaloid Motion Data 0002). I do not know what encoding it uses. I have attempted using UTF-8, UTF-16, CS_ASCII and Windows-31j (Shift JIS), but none of them worked (but based on what I know, most of UTF-8 should resolve since the byte is 2 for most of characters).

String testFile = rawFilePath+"/test.vmd";
BufferedWriter bw = null;
FileWriter fw = null;
fw = new FileWriter(outputPath+"/newFile.txt");
bw = new BufferedWriter(fw);
BufferedReader fBr = new BufferedReader(new InputStreamReader(
    new FileInputStream(testFile), "UTF-8"));  //US-ASCII windows-31j
int count=0;
String line;
while ((line = fBr.readLine()) != null) {
    System.out.println(line);
    bw.write(line);
    bw.write("\r\n");
    count++;
    if(count > 3) { //print small portion of a larger file for testing
        break;
    }
    ...
}

Both print and the output file writes something like this:

???~?N ??????????P ?Z???^?[    ??kkkkkkkk

I was wondering if this is an encoding issue, or some other issue?  How do I parse readable data from this?


问:
Dynamically change CSS flex order via JavaScript based on user event order
I have an application that has a  selection list of items that will dynamically open in an
 area.  Each item is defined as a
 in the
 area with display:none, until each is activated by a JavaScript function as the user clicks selections in the .  As they appear in the
 area, they show up in the sequence they are defined in the
.  The salient and somewhat pseudo parts of the code are shown below.

I would like each div to show up in the sequence that the user clicks, and not in the sequence the divs are laid out.  So if the user selects item002 then item001, the respective divs would show in the sequence item002, item001.

I've been trying to find a way to do this with flex column layout by dynamically changing the order of the article divs, something like:

```<code>document.getElementById(shID).order = myOrdervar;
</code>```

So far nothing I've tried has worked, and I can't find documentation on flex telling me if this is even possible.  Does anyone have a technique for changing the display sequence of the article divs, with or without flex?

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <style>
        body {
            font: 1em Helvetica;
            background: #999999;
        }
        #main {
            min-height: 500px;
            margin: 0;
            padding: 0;
            display: flex;
            flex-flow: column;
        }
        #main > article {
            margin: 4px;
            padding: 5px;
            border: 1px solid #cccc33;
            border-radius: 7pt;
            background: #dddd88;
            height: 600px;
            flex: 3 1 60%;
            order: 2;
            flex-flow: column;
        }
        #main > nav {
            margin: 4px;
            padding: 5px;
            border: 1px solid #8888bb;
            border-radius: 7pt;
            background: #ccccff;
            height: 600px;
            flex: 1 6 20%;
            order: 1;
            overflow: auto;
        }
        header, footer {
            display: block;
            margin: 4px;
            padding: 5px;
            min-height: 100px;
            border: 1px solid #eebb55;
            border-radius: 7pt;
            background: #ffeebb;
            display: -webkit-flex;
            display: flex;
            -webkit-align-items: center;
            align-items: center;
            -webkit-justify-content: center;
            justify-content: center;
        }
        /* Too narrow to support three columns */
        @media all and (max-width: 640px) {
            #main, #page {
                flex-direction: column;
            }
            #main > article, #main > nav, #main > aside {
                /* Return them to document order */
                order: 0;
                flex-direction: column;
            }
            #main > nav, #main > aside, header, footer {
                min-height: 50px;
                max-height: 50px;
            }
        }
    </style>
    <script language="javascript" type="text/javascript">
        var globalOrder = 1;
        function showHide(shID) {
            if (document.getElementById(shID)) {
                if (document.getElementById(shID + '-show').style.display != 'none') {
                    document.getElementById(shID + '-show').style.display = 'none';
                    document.getElementById(shID).style.display = 'flex';
                    document.getElementById(shID).style.order = globalOrder;
                    globalOrder++;
                }
                else {
                    document.getElementById(shID + '-show').style.display = 'inline';
                    document.getElementById(shID).style.display = 'none';
                }
            }
        }
    </script>
    <style type="text/css">
        /* This CSS is used for the Show/Hide functionality. */
        .more {
            display: none;
            border-top: 0px solid #666;
            border-bottom: 0px solid #666;
        }
        .showSquid {
            display: block;
            border-top: 0px solid #666;
            border-bottom: 0px solid #666;
        }
        a.showLink, a.hideLink {
            text-decoration: none;
            font-size: 1.0em;
            font-family: 'MergeLight', Arial, Verdana, Helvetica, sans-serif;
            font-weight: bold;
            padding-left: 0px;
            border-top: 0px solid #666;
            border-bottom: 0px dotted #36f;
        }
        a.hideLink {
            background: transparent url(up.gif) no-repeat left;
        }
        a.showLink:hover, a.hideLink:hover {
            color: white;
        }
    </style>
</head>
<body>
    <header>
        Sources
    </header>
    <div id='main'>
        <nav>
            <a href='#' id='Wilmington Wind-show' class='showLink' onclick='showHide("Wilmington Wind");return false;'>
                Wilmington Wind
            </a><br>
            <a href='#' id='ArtMachine.mp3-show' class='showLink' onclick='showHide("ArtMachine.mp3");return false;'>
                Art Machine
            </a><br>
            <a href='#' id='Breathing-original.mp3-show' class='showLink' onclick='showHide("Breathing-original.mp3");return false;'>
                Breathing
            </a><br>
            <a href='#' id='ToroidMachine-show' class='showLink' onclick='showHide("ToroidMachine");return false;'>
            </a>
        </nav>
        <article>
            <div id='Wilmington Wind' class='more' style="flex-direction: column;">
                Wilmington Wind<br>
            </div>
            <div id='ArtMachine.mp3' class='more' style="flex-direction: column;">
                Art Machine<br>
            </div>
            <div id='Breathing-original.mp3' class='more' style="flex-direction: column;">
                Breathing
            </div> <!-- Breathing-original.mp3 -->
        </article>
        <footer>© 2017</footer>
    </div>
</body>
</html>
</code>```

答:
The parent element needs display: flex; — in your case, that's the
 element.

Add this in your

Body:
I have an application that has a  selection list of items that will dynamically open in an
 area.  Each item is defined as a
 in the
 area with display:none, until each is activated by a JavaScript function as the user clicks selections in the .  As they appear in the
 area, they show up in the sequence they are defined in the
.  The salient and somewhat pseudo parts of the code are shown below.

I would like each div to show up in the sequence that the user clicks, and not in the sequence the divs are laid out.  So if the user selects item002 then item001, the respective divs would show in the sequence item002, item001.

I've been trying to find a way to do this with flex column layout by dynamically changing the order of the article divs, something like:

document.getElementById(shID).order = myOrdervar;

So far nothing I've tried has worked, and I can't find documentation on flex telling me if this is even possible.  Does anyone have a technique for changing the display sequence of the article divs, with or without flex?

<!DOCTYPE html>

        Sources

                Wilmington Wind

                Art Machine

                Breathing

                Wilmington Wind

                Art Machine

                Breathing

        © 2017

Body:
The parent element needs display: flex; — in your case, that's the <article> element.

Add this in your <style> element:

article {
    display: flex;
}


问:
What is the value type of the Map?
I have following code snippet:

```<code>  private def buildProps(host: => String)(config: => List[KafkaConfig]) =
    (config.map {
      case ClientId(value: String) =>
        (ProducerConfig.CLIENT_ID_CONFIG, value)
      case Acks(value: String) =>
        (ProducerConfig.ACKS_CONFIG, value)
      case Retries(value) =>
        (ProducerConfig.RETRIES_CONFIG, value)
      case BatchSize(value) =>
        (ProducerConfig.BATCH_SIZE_CONFIG, value)
      case LingerMs(value) =>
        (ProducerConfig.LINGER_MS_CONFIG, value)
      case BufferMemory(value) =>
        (ProducerConfig.BUFFER_MEMORY_CONFIG, value)
    } ++ List(
      (ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, host),
      (ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"),
      (ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"))
      ).toMap
</code>```

What is the type of the value from Map(String, ????)?
The type value of the case is very mixed:

```<code>final case class ClientId(value: String) extends KafkaConfig

final case class Acks(value: String) extends KafkaConfig

final case class Retries(value: java.lang.Integer) extends KafkaConfig

final case class BatchSize(value: java.lang.Integer) extends KafkaConfig

final case class LingerMs(value: java.lang.Integer) extends KafkaConfig

final case class BufferMemory(value: java.lang.Integer) extends KafkaConfig
</code>```

Some are Strings and another are Integers.

答:
An easy way to check for yourself is to give a clearly incorrect type:

```<code>private def buildProps(host: => String)(config: => List[KafkaConfig]): Int = ...
</code>```

You'll see an error like the following:

```<code>Error:(*line*, *column*) type mismatch;
 found   : *the type you are interested in*
 required: Int
</code>```

Title: What is the value type of the Map?

Body:
I have following code snippet:

  private def buildProps(host: => String)(config: => List[KafkaConfig]) =
    (config.map {
      case ClientId(value: String) =>
        (ProducerConfig.CLIENT_ID_CONFIG, value)
      case Acks(value: String) =>
        (ProducerConfig.ACKS_CONFIG, value)
      case Retries(value) =>
        (ProducerConfig.RETRIES_CONFIG, value)
      case BatchSize(value) =>
        (ProducerConfig.BATCH_SIZE_CONFIG, value)
      case LingerMs(value) =>
        (ProducerConfig.LINGER_MS_CONFIG, value)
      case BufferMemory(value) =>
        (ProducerConfig.BUFFER_MEMORY_CONFIG, value)
    } ++ List(
      (ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, host),
      (ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"),
      (ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"))
      ).toMap

What is the type of the value from Map(String, ????)?
The type value of the case is very mixed:

final case class ClientId(value: String) extends KafkaConfig

final case class Acks(value: String) extends KafkaConfig

final case class Retries(value: java.lang.Integer) extends KafkaConfig

final case class BatchSize(value: java.lang.Integer) extends KafkaConfig

final case class LingerMs(value: java.lang.Integer) extends KafkaConfig

final case class BufferMemory(value: java.lang.Integer) extends KafkaConfig

Some are Strings and another are Integers.

Body:
An easy way to check for yourself is to give a clearly incorrect type:

private def buildProps(host: => String)(config: => List[KafkaConfig]): Int = ...

You'll see an error like the following:

Error:(*line*, *column*) type mismatch;
 found   : *the type you are interested in*
 required: Int


问:
How can I make .goto non-blocking?
I'm writing a rails app which fetches text from an HTML page using Watir and Chrome Headless. All good so far!

The problem starts when I request a page which has a long load time to completely load all elements despite the fact that I don't need them.

Current code I use:

```<code>browser = Watir::Browser.new :chrome, headless: true

browser.goto(url)
</code>```

The .goto function call, however, blocks until ALL elements have loaded. That's not really what I need - what I need is for goto to just start fetching the page, then continue running code since I really just want to wait until the text I need is present, then fetch it.

Any ideas?

答:
With the new w3c webdriver specification, you can set the page load strategy to 'none.' https://w3c.github.io/webdriver/webdriver-spec.html#navigation

Only Firefox and IE might have this implemented already.

Title: How can I make .goto non-blocking?

Body:
I'm writing a rails app which fetches text from an HTML page using Watir and Chrome Headless. All good so far!

The problem starts when I request a page which has a long load time to completely load all elements despite the fact that I don't need them.

Current code I use:

browser = Watir::Browser.new :chrome, headless: true

browser.goto(url)

The .goto function call, however, blocks until ALL elements have loaded. That's not really what I need - what I need is for goto to just start fetching the page, then continue running code since I really just want to wait until the text I need is present, then fetch it.

Any ideas?


问:
Why is move necessary with emplace_back in this example?
The following minimal working example compiles when the code under option 1 or option 2 is used, but does not compile when the code under option 3 is used. I was under the assumption that emplace_back() implicitly uses/calls a move constructor, so why is an explicit move() necessary? Does it have something to do with r-value vs. l-value? Or does this have to do with std::unique_ptr needing to transfer ownership? (I am still new to these concepts, particularly in this context.)

For completeness, option 4 with push_back() does not compile, either, unless move() is called.

```<code>#include <iostream>
#include <vector>
#include <memory>

class Beta {
public:
    Beta(int x, int y, int z): mX(x), mY(y), mZ(z) { };
    int mX; int mY; int mZ;

};

class Alpha {
public:
    std::vector<std::unique_ptr<Beta>> betaVec;
    void addBeta(int x, int y, int z) {
        // only choose one of the following options:
        // option 1 (compiles)
        std::unique_ptr<Beta> pBeta = std::make_unique<Beta>(x, y, z);
        betaVec.emplace_back(move(pBeta));

        // option 2 (compiles)
        betaVec.emplace_back(std::make_unique<Beta>(x, y, z));

        // option 3 (does not compile)
        std::unique_ptr<Beta> pBeta = std::make_unique<Beta>(x, y, z);
        betaVec.emplace_back(pBeta);

        // option 4 (does not compile)
        std::unique_ptr<Beta> pBeta = std::make_unique<Beta>(x, y, z);
        betaVec.push_back(pBeta);

        // option 5 (compiles)
        std::unique_ptr<Beta> pBeta = std::make_unique<Beta>(x, y, z);
        betaVec.push_back(move(pBeta));
    }
};

int main() {

    return 0;
}
</code>```

Note: I do not believe that this is a duplicate of this question about passing unique_ptr parameters to functions, even though the answers to the linked question are useful, as this is asking about defining a unique_ptr within a function and then moving it to a member vector so that it is not destroyed at the end of the function and, furthermore, is asking specifically about emplace_back() in this context.

Additionally, I think that it would be useful to have explanations given in this context, as it is sometimes difficult to translate explanations from one context to another. Thank you!

答:
I was under the assumption that emplace_back() implicitly uses/calls a move constructor

Sorry, but you're assumption is wrong. emplace_back constructs the object in the vector in-place, i.e. instead of copying/moving the object from its parameters, it constructs the element directly which avoids the copy/move constructor.

Now, if you construct the object with the same (but another) object, then of course either the copy or the move constructor will get used instead, which is what is happening in your case.

so why is an explicit move() necessary

Because you can't copy a std::unique_ptr. Basically, emplace_back does something akin to this:

```<code>new (place) T(std::forward<Ts>(args)...);
</code>```

It's like if you did: T a(std::forward<Ts>(args)...) (for construction only, it doesn't actually do the same thing).

Now it might be a bit more obvious:

```<code>T option1(std::move(pBeta)); // ok, move
T option3(pBeta); // error, copy
</code>```

Does it have something to do with r-value vs. l-value? Or does this have to do with std::unique_ptr needing to transfer ownership?

Well, in a way, yes. std::unique_ptr requires explicit transfer of ownership, that's why the copy is disabled and the move is not (you still want to transfer ownership! And a copy can happen everywhere - why std::auto_ptr was deprecated, then removed). An rvalue uses move semantics by default, while an lvalue does not. By using std::move, you are doing a conversion from an lvalue to a prvalue, effectively "hiding" the fact that you have an lvalue, and the compiler will happily move from it.

Body:
The following minimal working example compiles when the code under option 1 or option 2 is used, but does not compile when the code under option 3 is used. I was under the assumption that emplace_back() implicitly uses/calls a move constructor, so why is an explicit move() necessary? Does it have something to do with r-value vs. l-value? Or does this have to do with std::unique_ptr needing to transfer ownership? (I am still new to these concepts, particularly in this context.)

For completeness, option 4 with push_back() does not compile, either, unless move() is called.

#include <iostream>
#include <vector>
#include <memory>

class Beta {
public:
    Beta(int x, int y, int z): mX(x), mY(y), mZ(z) { };
    int mX; int mY; int mZ;

};

class Alpha {
public:
    std::vector<std::unique_ptr<Beta>> betaVec;
    void addBeta(int x, int y, int z) {
        // only choose one of the following options:
        // option 1 (compiles)
        std::unique_ptr<Beta> pBeta = std::make_unique<Beta>(x, y, z);
        betaVec.emplace_back(move(pBeta));

        // option 2 (compiles)
        betaVec.emplace_back(std::make_unique<Beta>(x, y, z));

        // option 3 (does not compile)
        std::unique_ptr<Beta> pBeta = std::make_unique<Beta>(x, y, z);
        betaVec.emplace_back(pBeta);

        // option 4 (does not compile)
        std::unique_ptr<Beta> pBeta = std::make_unique<Beta>(x, y, z);
        betaVec.push_back(pBeta);

        // option 5 (compiles)
        std::unique_ptr<Beta> pBeta = std::make_unique<Beta>(x, y, z);
        betaVec.push_back(move(pBeta));
    }
};

int main() {

    return 0;
}

Note: I do not believe that this is a duplicate of this question about passing unique_ptr parameters to functions, even though the answers to the linked question are useful, as this is asking about defining a unique_ptr within a function and then moving it to a member vector so that it is not destroyed at the end of the function and, furthermore, is asking specifically about emplace_back() in this context.

Additionally, I think that it would be useful to have explanations given in this context, as it is sometimes difficult to translate explanations from one context to another. Thank you!

Body:
I was under the assumption that emplace_back() implicitly uses/calls a move constructor

Sorry, but you're assumption is wrong. emplace_back constructs the object in the vector in-place, i.e. instead of copying/moving the object from its parameters, it constructs the element directly which avoids the copy/move constructor.

Now, if you construct the object with the same (but another) object, then of course either the copy or the move constructor will get used instead, which is what is happening in your case.

so why is an explicit move() necessary

Because you can't copy a std::unique_ptr. Basically, emplace_back does something akin to this:

new (place) T(std::forward<Ts>(args)...);

It's like if you did: T a(std::forward<Ts>(args)...) (for construction only, it doesn't actually do the same thing).

Now it might be a bit more obvious:

T option1(std::move(pBeta)); // ok, move
T option3(pBeta); // error, copy

Does it have something to do with r-value vs. l-value? Or does this have to do with std::unique_ptr needing to transfer ownership?

Well, in a way, yes. std::unique_ptr requires explicit transfer of ownership, that's why the copy is disabled and the move is not (you still want to transfer ownership! And a copy can happen everywhere - why std::auto_ptr was deprecated, then removed). An rvalue uses move semantics by default, while an lvalue does not. By using std::move, you are doing a conversion from an lvalue to a prvalue, effectively "hiding" the fact that you have an lvalue, and the compiler will happily move from it.


问:
how to define the Console.WriteLine behavior for a class in C#?
I have a class:

```<code>class Rect{
    int x;
    int y;
    public Rect(int x, int y){
        this.x = x;
        this.y = y;
    }

}
</code>```

I want this happen:

```<code>Console.WriteLine(new Rect(12,12));
>>> <Rect with x=12, y=12>
</code>```

How could I do it?

答:
You can override ToString() method:

```<code>class Rect{
    int x;
    int y;
    public Rect(int x, int y){
        this.x = x;
        this.y = y;
    }

    public override string ToString()
    {
        return "("+x.ToString()+","+y.ToString()+")";
    }

}
</code>```

Body:
I have a class:

class Rect{
    int x;
    int y;
    public Rect(int x, int y){
        this.x = x;
        this.y = y;
    }

}

I want this happen:

Console.WriteLine(new Rect(12,12));
>>> <Rect with x=12, y=12>

How could I do it?

Body:
You can override ToString() method:

class Rect{
    int x;
    int y;
    public Rect(int x, int y){
        this.x = x;
        this.y = y;
    }

    public override string ToString()
    {
        return "("+x.ToString()+","+y.ToString()+")";
    }

}


问:
How to obtain document vectors in doc2vec in gensim
I know to obtain a document vector for a given tag in doc2vec using print(model.docvecs['recipe__11']).

My document vectors are either recipes (tags start with recipe__), newspapers (tags start with news__) or ingredients (tags start with ingre__)

Now I want to retrieve all the document vectors of recipes. The pattern of my recipe documents is recipe__<some number> (e.g., recipe__23, recipe__34). I am interested in knowing if it possible to obtain multiple document vectors using a pattern (e.g., tags starting with recipe__)

Please help me!

答:
There's no pattern-retrieval, but you can access the list of all known (string) doc-tags in model.docvecs.offset2doctag. You could then loop over that list to find all matches, and retrieve each individually.

Also, all the doc-vectors are in a large array model.docvecs.doctag_syn0 And, if you've used exclusively string doc-tags, then the position of a tag in offset2doctag will be exactly the index of the corresponding vector in doctag_syn0. That would allow you to use numpy 'mask indexing' to grab a subset of vectors as a new array, like:

```<code>recipes_mask = [tag.startswith('recipe_') for tag in model.dacvecs.offset2doctag]
recipes_vectors = model.docvecs.doctag_syn0[recipes_mask]
</code>```

Of course, this array-of-vectors no longer has the recipes in the same positions as the original, so you'd need extra steps to know where (for example) the 'recipe__11' vector is in recipes_vectors.

Body:
There's no pattern-retrieval, but you can access the list of all known (string) doc-tags in model.docvecs.offset2doctag. You could then loop over that list to find all matches, and retrieve each individually.

Also, all the doc-vectors are in a large array model.docvecs.doctag_syn0 And, if you've used exclusively string doc-tags, then the position of a tag in offset2doctag will be exactly the index of the corresponding vector in doctag_syn0. That would allow you to use numpy 'mask indexing' to grab a subset of vectors as a new array, like:

recipes_mask = [tag.startswith('recipe_') for tag in model.dacvecs.offset2doctag]
recipes_vectors = model.docvecs.doctag_syn0[recipes_mask]

Of course, this array-of-vectors no longer has the recipes in the same positions as the original, so you'd need extra steps to know where (for example) the 'recipe__11' vector is in recipes_vectors.


问:
Is there any way to check if a class is within another class?
So say I wanted to check if square[6] is in row[2]. How would I do this? I want to be able to tell if two squares are within the same row.</p>

```<code><!--Row 1-->
<div class = "row">
    <!--Square 1-->
    <div class = "square" onclick="clicked(0,0)"></div>
    <!--Square 2-->
    <div class = "square" onclick="clicked(1,0)"></div>
    <!--Square 3-->
    <div class = "square" onclick="clicked(2,0)"></div>
    <!--Square 4-->
    <div class = "square" onclick="clicked(3,0)"></div>
</div>
<!--Row 2-->
<div class = "row">
    <!--Square 5-->
    <div class = "square" onclick="clicked(4,1)"></div>
    <!--Square 6-->
    <div class = "square" onclick="clicked(5,1)"></div>
    <!--Square 7-->
    <div class = "square" onclick="clicked(6,1)"></div>
    <!--Square 8-->
    <div class = "square" onclick="clicked(7,1)"></div>
</div>
</code>```

答:
```<code>const byClass = document.getElementsByClassName.bind(document);

if( byClass("row")[1] === byClass("square")[5].parentElement )
  alert("square[6] is in row[1]");
</code>```

<p>Just check if one is the parent of the other </p>

Body:
const byClass = document.getElementsByClassName.bind(document);

if( byClass("row")[1] === byClass("square")[5].parentElement )
  alert("square[6] is in row[1]");

Just check if one is the parent of the other


问:
Ranking MarkLogic search results
I am trying figure out a way to rank search results according to a field that is not part of the search criteria. i.e. relevance of the search not only depend on the matches but documents also have a default relevance rank among themselves.

My searches so far has failed and could not confirm if it is even a supported feature; most cts:search documentation is about ranking matches.

So, is there a built-in marklogic feature that allow us to assign a value multiplier to documents; based on element values for example.

thanks a lot,
K.

PS: I use marklogic 9.

答:
You can alter the score based on the distance of a value in the document from a target value.  See:

```<code>http://docs.marklogic.com/guide/search-dev/relevance#id_45452
</code>```

You can also set the quality on the document to influence scoring.  See:

```<code>http://docs.marklogic.com/guide/search-dev/relevance#id_68032
</code>```

Hoping that helps.

Title: Ranking MarkLogic search results

Body:
You can alter the score based on the distance of a value in the document from a target value.  See:

http://docs.marklogic.com/guide/search-dev/relevance#id_45452

You can also set the quality on the document to influence scoring.  See:

http://docs.marklogic.com/guide/search-dev/relevance#id_68032

Hoping that helps.


问:
SQL file executes in MySQL workbench but not in python
I'm writing a python script to migrate data from one MySQL database to another. The script loads a sql file dumped by mysqldump and splits the commands similarly to this SO question. When I execute the script in python 2.7 using the python-mysql library, python outputs the following error:

```<code>_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'\'\\"><script>alert(1)\' at line 1')
</code>```

Checking the associated file, I see that python fails when it tries to execute a massive insert statement that includes 6 records like this:

```<code>('58cd48g5158b8','2015-12-02 16:05:25','\"><script>alert(1);</script>','12.16.98.253')
</code>```

But, if I were to execute the same file in MySQL Workbench, it completes without an error.

1. Why does MySQL server execute the file without problems, but mysql-python errors out?

2. Why does python treat the string as a a SQL syntax error?

Note: this table is the 13th to be processed in the script and the insert command is the 18th command for that table; so, I doubt it's an issue with my code.

Relevant Python Code

```<code>def loadMigrationScriptForTable(self, tableName, schemaName='obfuscated'):
    fileName = 'obfuscated' + schemaName + '.' + tableName + '.sql'
    fileDir = self.conf.get('obfuscated', 'obfuscated')
    workfile = os.path.join(fileDir, fileName)
    try:
        file = open(workfile, 'r')
        contents = file.read()
        return contents
    except IOError:
        return Exception('File does not exist: '+workfile)

# Migrate tables whose table definition has not been altered but row counts has changed.
def migrateTablesWithUnmodifiedDefinition(self):
    tables = self.conf.get('obfuscated', 'obfuscated').split(', ')
    responses = []
    for table in tables:
        # Load SQL file (as string)
        MySQLScript = self.loadMigrationScriptForTable(table)
        if(isinstance(MySQLScript, Exception)):
            print table, MySQLScript
            continue # Skip remaining code if file couldn't load.

        # Split commands
        sqlCommands = MySQLScript.split(';')
        for sqlCommand in sqlCommands:
            # Execute SQL file.
            print table, sqlCommand[0:99]
            response = self.db.executeScript(sqlCommand)
            print "        ", response
            responses.append(response)

def executeScript(self, script):
    self._DB.connection.execute(script)
</code>```

答:
As Daniel Roseman hinted, it was an issue with my code. When parsing and splitting sql files generated by mysqldump you should split it based on the semicolon and newline character, otherwise string.split will split on semicolons inside strings.

Erroneous Code

# Split commands
sqlCommands = MySQLScript.split(';')
```

<h3>Fixed Code</h3>

<pre class="lang-py prettyprint-override"><code># Split commands
sqlCommands = MySQLScript.split(';\n')
</code>```

OS  Note

Note: This works on windows; but, I have not tested it yet on *nix yet. If running on *nix, it may be more prudent to use string.splitlines.

```<code># Split commands
sqlCommands = MySQLScript.splitlines()
</code>```

Body:
I'm writing a python script to migrate data from one MySQL database to another. The script loads a sql file dumped by mysqldump and splits the commands similarly to this SO question. When I execute the script in python 2.7 using the python-mysql library, python outputs the following error:

_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'\'\\">','12.16.98.253')

But, if I were to execute the same file in MySQL Workbench, it completes without an error.

1. Why does MySQL server execute the file without problems, but mysql-python errors out?

2. Why does python treat the string as a a SQL syntax error?

Note: this table is the 13th to be processed in the script and the insert command is the 18th command for that table; so, I doubt it's an issue with my code.

Relevant Python Code

def loadMigrationScriptForTable(self, tableName, schemaName='obfuscated'):
    fileName = 'obfuscated' + schemaName + '.' + tableName + '.sql'
    fileDir = self.conf.get('obfuscated', 'obfuscated')
    workfile = os.path.join(fileDir, fileName)
    try:
        file = open(workfile, 'r')
        contents = file.read()
        return contents
    except IOError:
        return Exception('File does not exist: '+workfile)

# Migrate tables whose table definition has not been altered but row counts has changed.
def migrateTablesWithUnmodifiedDefinition(self):
    tables = self.conf.get('obfuscated', 'obfuscated').split(', ')
    responses = []
    for table in tables:
        # Load SQL file (as string)
        MySQLScript = self.loadMigrationScriptForTable(table)
        if(isinstance(MySQLScript, Exception)):
            print table, MySQLScript
            continue # Skip remaining code if file couldn't load.

        # Split commands
        sqlCommands = MySQLScript.split(';')
        for sqlCommand in sqlCommands:
            # Execute SQL file.
            print table, sqlCommand[0:99]
            response = self.db.executeScript(sqlCommand)
            print "        ", response
            responses.append(response)

def executeScript(self, script):
    self._DB.connection.execute(script)

Body:
As Daniel Roseman hinted, it was an issue with my code. When parsing and splitting sql files generated by mysqldump you should split it based on the semicolon and newline character, otherwise string.split will split on semicolons inside strings.

Erroneous Code

# Split commands
sqlCommands = MySQLScript.split(';')

Fixed Code

# Split commands
sqlCommands = MySQLScript.split(';\n')

OS  Note

Note: This works on windows; but, I have not tested it yet on *nix yet. If running on *nix, it may be more prudent to use string.splitlines.

# Split commands
sqlCommands = MySQLScript.splitlines()


问:
Spinnaker with Kubernetes: Not able to connect the docker hub repository
I'm trying to configure the spinnaker to deploy applications in kubernetes environment.

I followed a documentation,
at step-3 the containers are not showing up as shown in the screenshot. Then I moved to next step(Pipeline creation), when I select type: Docker in the Automated Trigger, again the Repo name is not showing up as shown in screenshot.

So, I'm suspecting there is problem with spinnaker and docker hub repo(Authentication/Misconfiguration?)

I have copied the Kubernetes Authentication config file to ~/.kube/config. I think there is no problem with spinnaker and kubernetes. When I create a Load Balancer in spinnaker I can see Kube Services are creating (test-dev & test-prod)

```<code>root@veeru:~# kubectl get services
NAME                CLUSTER-IP      EXTERNAL-IP   PORT(S)                      AGE
kubernetes          192.168.3.1     <none>        443/TCP                      91d
test-dev            192.168.3.113   <none>        80/TCP                       6h
test-prod           192.168.3.185                 80/TCP                       6h
</code>```

My spinnaker-local.yml

```<code><Content removed for brevity>

  kubernetes:
    # For more information on configuring Kubernetes clusters (kubernetes), see
    # http://www.spinnaker.io/v1.0/docs/target-deployment-setup#section-kubernetes-cluster-setup

    # NOTE: enabling kubernetes also requires enabling dockerRegistry.
    enabled: true
    primaryCredentials:
      # These credentials use authentication information at ~/.kube/config
      # by default.
      name: veerendrav2
      namespace: default
      dockerRegistryAccount: veerendrav2

  dockerRegistry:
    # If you want to deploy containers to a container management solution,
    # you must specifiy where these container images exist first.

    # NOTE: Enabling dockerRegistry is independent of other providers.
    # However, for convienience, we tie docker and kubernetes together
    # since kubernetes (and only kubernetes) depends on this docker provider
    # configuration.
    enabled: true

    primaryCredentials:
      name: veerendrav2
      address: https://hub.docker.com
      repository: veerendrav2/spin-kub-demo

<Content removed for brevity>
</code>```

My /opt/spinnaker/config/clouddriver-local.yml

```<code>dockerRegistry:
  enabled: true
  accounts:
    - name: veerendrav2
      address: https://hub.docker.com/ # Point to registry of choice
      username: veerendrav2
      password: password
      repositories:
        - veerendrav2/spin-kub-demo
</code>```

My Sample application github repo and docker hub repo

Thanks

答:
The recommended way to configure the docker registry address, or any other configs, is using Halyard. Modifying the config files directly could result in them getting overwritten.

You can add an account, or edit an existing one this way.

```<code># Add a docker registry account
hal config provider docker-registry account add <ACCOUNT_NAME> --address https://index.docker.io

# Edit the account(i.e. add a repo)
hal config provider docker-registry account edit grizzthedj --add-repository <ACCOUNT_NAME>/<REPO>

# Deploy the changes
hal deploy apply
</code>```

Body:
I'm trying to configure the spinnaker to deploy applications in kubernetes environment.

I followed a documentation,
at step-3 the containers are not showing up as shown in the screenshot. Then I moved to next step(Pipeline creation), when I select type: Docker in the Automated Trigger, again the Repo name is not showing up as shown in screenshot.

So, I'm suspecting there is problem with spinnaker and docker hub repo(Authentication/Misconfiguration?)

I have copied the Kubernetes Authentication config file to ~/.kube/config. I think there is no problem with spinnaker and kubernetes. When I create a Load Balancer in spinnaker I can see Kube Services are creating (test-dev & test-prod)

root@veeru:~# kubectl get services
NAME                CLUSTER-IP      EXTERNAL-IP   PORT(S)                      AGE
kubernetes          192.168.3.1     <none>        443/TCP                      91d
test-dev            192.168.3.113   <none>        80/TCP                       6h
test-prod           192.168.3.185                 80/TCP                       6h

My spinnaker-local.yml

<Content removed for brevity>

  kubernetes:
    # For more information on configuring Kubernetes clusters (kubernetes), see
    # http://www.spinnaker.io/v1.0/docs/target-deployment-setup#section-kubernetes-cluster-setup

    # NOTE: enabling kubernetes also requires enabling dockerRegistry.
    enabled: true
    primaryCredentials:
      # These credentials use authentication information at ~/.kube/config
      # by default.
      name: veerendrav2
      namespace: default
      dockerRegistryAccount: veerendrav2

  dockerRegistry:
    # If you want to deploy containers to a container management solution,
    # you must specifiy where these container images exist first.

    # NOTE: Enabling dockerRegistry is independent of other providers.
    # However, for convienience, we tie docker and kubernetes together
    # since kubernetes (and only kubernetes) depends on this docker provider
    # configuration.
    enabled: true

    primaryCredentials:
      name: veerendrav2
      address: https://hub.docker.com
      repository: veerendrav2/spin-kub-demo

<Content removed for brevity>

My /opt/spinnaker/config/clouddriver-local.yml

dockerRegistry:
  enabled: true
  accounts:
    - name: veerendrav2
      address: https://hub.docker.com/ # Point to registry of choice
      username: veerendrav2
      password: password
      repositories:
        - veerendrav2/spin-kub-demo

My Sample application github repo and docker hub repo

Thanks

Body:
The recommended way to configure the docker registry address, or any other configs, is using Halyard. Modifying the config files directly could result in them getting overwritten.

You can add an account, or edit an existing one this way.

# Add a docker registry account
hal config provider docker-registry account add <ACCOUNT_NAME> --address https://index.docker.io

# Edit the account(i.e. add a repo)
hal config provider docker-registry account edit grizzthedj --add-repository <ACCOUNT_NAME>/<REPO>

# Deploy the changes
hal deploy apply


问:
How to provide code for tkinter toplevel before data can be accessed
I am trying to have my tkinter toplevel have an access key before the content can be printed.It doesn't output any error but when I provide the access key it doesn't print the content to my terminal.I changed the access key but still I am not able to print the data.

from tkinter import *

```<code>def qw():
    global en1
    if en1.get() == 2e2c2v:
        print("You have visa to Paris")
        tp.destroy()  # after printing should close the toplevel window
    else:
        print("you dont have access to print the data")

def login_toplevel():
    global en1
    tp = Toplevel()
    tp.geometry("300x300")
    en1 = Entry(tp)
    en1.pack()
    b = Button(tp, text="provide key to print", command=qw)
    b.pack()

root = Tk()
root.geometry("400x400")

b = Button(root, text= "print", command=login_toplevel).pack()

root.mainloop()
</code>```

答:
Changed your access key to string "2e2c2v" then declare global variable for Toplevel window as well global en1, tp and parse it for your both functions

```<code>from tkinter import *

def qw():
    global en1, tp
    if en1.get() == "2e2c2v":
        print("You have visa to Paris")
        tp.destroy()  # after printing should close the toplevel window
    else:
        print("you dont have access to print the data")

def login_toplevel():
    global en1, tp
    tp = Toplevel()
    tp.geometry("300x300")
    en1 = Entry(tp)
    en1.pack()
    b = Button(tp, text="provide key to print", command=qw)
    b.pack()

root = Tk()
root.geometry("400x400")

b = Button(root, text= "print", command=login_toplevel).pack()

root.mainloop()
</code>```

Body:
I am trying to have my tkinter toplevel have an access key before the content can be printed.It doesn't output any error but when I provide the access key it doesn't print the content to my terminal.I changed the access key but still I am not able to print the data.

from tkinter import *

def qw():
    global en1
    if en1.get() == 2e2c2v:
        print("You have visa to Paris")
        tp.destroy()  # after printing should close the toplevel window
    else:
        print("you dont have access to print the data")

def login_toplevel():
    global en1
    tp = Toplevel()
    tp.geometry("300x300")
    en1 = Entry(tp)
    en1.pack()
    b = Button(tp, text="provide key to print", command=qw)
    b.pack()

root = Tk()
root.geometry("400x400")

b = Button(root, text= "print", command=login_toplevel).pack()

root.mainloop()

Body:
Changed your access key to string "2e2c2v" then declare global variable for Toplevel window as well global en1, tp and parse it for your both functions

from tkinter import *

def qw():
    global en1, tp
    if en1.get() == "2e2c2v":
        print("You have visa to Paris")
        tp.destroy()  # after printing should close the toplevel window
    else:
        print("you dont have access to print the data")

def login_toplevel():
    global en1, tp
    tp = Toplevel()
    tp.geometry("300x300")
    en1 = Entry(tp)
    en1.pack()
    b = Button(tp, text="provide key to print", command=qw)
    b.pack()

root = Tk()
root.geometry("400x400")

b = Button(root, text= "print", command=login_toplevel).pack()

root.mainloop()


问:
python multiple stacked plots along y axis
I have a binned data of an x-axis n-length vector and 3 y-axis n-length vector for 3 different histograms on the same x-axis.

Now I want this kind of stacked bar plot or any thing similar as below.

The nearest I have found is Qtiplot (which is not python). It can generate exactly this kind of histogram plots. But it computes the histogram by itself and requires the actual data samples which are not present in my case (I only have the histogram itself).

Please note that I don't know python very well. So I don't have a clue from where I shall start, neither I am really in a mood to learn programming in python. I need this only to make a nice vector-graphics plot for my research thesis.

I have tagged python as I think python is the most obvious language. In case someone knows any better solution other than in python (but not Matlab, I cannot install that huge pile), I will thankfully add the proper tag.

Thanks in advance for any help.

答:
```<code>import matplotlib.pyplot as plt

apple_weight=[3,3,3,10,10,1,1,1,4,4,4,4,7,7,7]
banana_weight=[3,3,3,10,10,1,1,1,4,4,4,4,7,7,7]
mango_weight=[3,3,3,10,10,1,1,1,4,4,4,4,7,7,7]

fig=plt.figure()
ax1=fig.add_subplot(111)
ax2=ax1.twinx()
#only two y axes so the third list just add to either

ax1.hist(apple_weight)
ax2.hist(banana_weight)
ax1.hist(mango_weight)
plt.show()
</code>```

ContentLicense: CC BY-SA 4.0


问:
Prevent Child component from taking style from Parent
I have a component inside another which I'd like to style completely independently from the parent.  Current example being the text alignment;  I've set text-align:center in the parent but I don't want that to trickle down to the child.  I've tried the three different types of ViewEncapsulation (Native, None and Emulated) but in all cases the style is fed down to the child and the text is centrally aligned.   Any ideas how to deal with this?

Parent Component:

```<code><div class="Home__Banner">
  <div class="container">
    <div class="mt-5 mb-5">
    <app-mh-search-form></app-mh-search-form>
  </div>
</div>
</code>```

Parent Style :

```<code>.Home {
  &__Banner {
     background: url('/assets/images/homepage/mainImg.jpg') no-repeat center
         center fixed;
     background-size: cover;
     text-align: center;
  }
}
</code>```

Child Component:

```<code><div class="MhSearchForm">
  <div class="container">
    <div class="row">
      <div class="MhSearchForm__Nav">
        <div class="MhSearchForm__NavLink" (click)="setActiveState('buy')">
          BUY
        </div>
        <div class="MhSearchForm__NavLink" (click)="setActiveState('rent')">
          RENT
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

The 'Buy' and 'Rent' text is center aligned, despite it being in a separate component

答: That is because your "Buy" and "Rent" text are inside the div with the .Home__Banner class, even if that class is for parent in CSS you are telling everything contained in the class Home_Banner should have its text align. To avoid this you have to set a style to your "MhSearchForm__NavLink" to set the text align to the left.</p>

Body:
I have a component inside another which I'd like to style completely independently from the parent.  Current example being the text alignment;  I've set text-align:center in the parent but I don't want that to trickle down to the child.  I've tried the three different types of ViewEncapsulation (Native, None and Emulated) but in all cases the style is fed down to the child and the text is centrally aligned.   Any ideas how to deal with this?

Parent Component:

    <app-mh-search-form></app-mh-search-form>

Parent Style :

.Home {
  &__Banner {
     background: url('/assets/images/homepage/mainImg.jpg') no-repeat center
         center fixed;
     background-size: cover;
     text-align: center;
  }
}

Child Component:

          BUY

          RENT

The 'Buy' and 'Rent' text is center aligned, despite it being in a separate component


问:
TYPO3 CKEditor – configuration not working
I have an TYPO3 8.7.7 installation and I am using rte_ckeditor. I am trying to configure the editor – but it seems not to work.
When I set RTE.default.preset = full or anything else nothing changes in my backend form.

But I need to configure some individual options. So I set the default preset to my own YAML file (RTE.default.preset = mytemplate) which is also registered in my extension ext_localconf.php with

```<code>$GLOBALS['TYPO3_CONF_VARS']['RTE']['Presets']['mytemplate'] = 'EXT:mytemplate/Configuration/RTE/rte.yaml';
</code>```

I have cleared typo3temp Folder, system caches via backend, all caches via install tool, deactivated and reactivated my template extension.

I also do not change anything in my backend form at the RTE.

The only thing it did sometimes, when I clear the system cache in backend and save the backend form TYPO3 shows me syntax error in my YAML file – which are all solved now, but it also do not show anything again. Just the default RTE...

My YAML file has nothing special... just come classes and the format tags "pre" relaced with "h6"

```<code>imports:
    - { resource: "EXT:rte_ckeditor/Configuration/RTE/Processing.yaml" }
    - { resource: "EXT:rte_ckeditor/Configuration/RTE/Editor/Base.yaml" }
    - { resource: "EXT:rte_ckeditor/Configuration/RTE/Editor/Plugins.yaml" }

editor:
  config:

    contentsCss: ["EXT:mytemplate/Resources/Public/css/rte/rte.css"]

    format_tags: "p;h1;h2;h3;h4;h5;h6"

    stylesSet:
      - { name: "align-left", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6', 'p', 'td', 'th'], attributes: { 'class': 'align-left' }}
      - { name: "align-center", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6', 'p', 'td', 'th'], attributes: { 'class': 'align-center' }}
      - { name: "align-right", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6', 'p', 'td', 'th'], attributes: { 'class': 'align-right' }}
      - { name: "align-justify", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6', 'p', 'td', 'th'], attributes: { 'class': 'align-justify' }}
      - { name: "Headline Stil 1", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6'], attributes: { 'class': 'headline-style-1' }}
      - { name: "Headline Stil 2", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6'], attributes: { 'class': 'headline-style-2' }}
      - { name: "Headline Stil 3", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6'], attributes: { 'class': 'headline-style-3' }}
      - { name: "Headline Stil 4", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6'], attributes: { 'class': 'headline-style-4' }}
      - { name: "Button-Link Primär", element: ['a'], attributes: { 'class': 'rte-btn-primary' }}
      - { name: "Button-Link Sekundär", element: ['a'], attributes: { 'class': 'rte-btn-secondary' }}
      - { name: "Button-Link Tertiär", element: ['a'], attributes: { 'class': 'rte-btn-tertiary' }}

    toolbarGroups:
      - { name: styles, groups: [ styles, format ] }
      - { name: basicstyles, groups: [ basicstyles ] }
      - { name: paragraph, groups: [ list, indent, blocks, align ] }
      - { name: links, groups: [ links ] }
      - { name: clipboard, groups: [ clipboard, cleanup, undo ] }
      - { name: editing, groups: [ spellchecker ] }
      - { name: insert, groups: [ insert ] }
      - { name: tools, groups: [ table, specialchar ] }
      - { name: document, groups: [ mode ] }

    justifyClasses:
      - align-left
      - align-center
      - align-right
      - align-justify

    extraPlugins:
      - justify

    removePlugins:
      - image

    removeButtons:
      - Anchor
      - Underline
      - Strike
      - Styles
</code>```

What is the trick to get my config working?!

答:
In my case I was using DCE Extension – an the preset got ignored. To use any preset use this DCE field Config:

```<code><config>
    <type>text</type>
    <rows>5</rows>
    <cols>30</cols>
    <eval>trim,required</eval>
    <enableRichtext>1</enableRichtext>
    <richtextConfiguration>mypreset</richtextConfiguration>
</config>
</code>```

I informed the Ext developer of DCE Ext and he updated the RTE Config "preset" already.

Body:
I have an TYPO3 8.7.7 installation and I am using rte_ckeditor. I am trying to configure the editor – but it seems not to work.
When I set RTE.default.preset = full or anything else nothing changes in my backend form.

But I need to configure some individual options. So I set the default preset to my own YAML file (RTE.default.preset = mytemplate) which is also registered in my extension ext_localconf.php with

$GLOBALS['TYPO3_CONF_VARS']['RTE']['Presets']['mytemplate'] = 'EXT:mytemplate/Configuration/RTE/rte.yaml';

I have cleared typo3temp Folder, system caches via backend, all caches via install tool, deactivated and reactivated my template extension.

I also do not change anything in my backend form at the RTE.

The only thing it did sometimes, when I clear the system cache in backend and save the backend form TYPO3 shows me syntax error in my YAML file – which are all solved now, but it also do not show anything again. Just the default RTE...

My YAML file has nothing special... just come classes and the format tags "pre" relaced with "h6"

imports:
    - { resource: "EXT:rte_ckeditor/Configuration/RTE/Processing.yaml" }
    - { resource: "EXT:rte_ckeditor/Configuration/RTE/Editor/Base.yaml" }
    - { resource: "EXT:rte_ckeditor/Configuration/RTE/Editor/Plugins.yaml" }

editor:
  config:

    contentsCss: ["EXT:mytemplate/Resources/Public/css/rte/rte.css"]

    format_tags: "p;h1;h2;h3;h4;h5;h6"

    stylesSet:
      - { name: "align-left", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6', 'p', 'td', 'th'], attributes: { 'class': 'align-left' }}
      - { name: "align-center", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6', 'p', 'td', 'th'], attributes: { 'class': 'align-center' }}
      - { name: "align-right", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6', 'p', 'td', 'th'], attributes: { 'class': 'align-right' }}
      - { name: "align-justify", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6', 'p', 'td', 'th'], attributes: { 'class': 'align-justify' }}
      - { name: "Headline Stil 1", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6'], attributes: { 'class': 'headline-style-1' }}
      - { name: "Headline Stil 2", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6'], attributes: { 'class': 'headline-style-2' }}
      - { name: "Headline Stil 3", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6'], attributes: { 'class': 'headline-style-3' }}
      - { name: "Headline Stil 4", element: ['h1', 'h2', 'h3', 'h4','h5', 'h6'], attributes: { 'class': 'headline-style-4' }}
      - { name: "Button-Link Primär", element: ['a'], attributes: { 'class': 'rte-btn-primary' }}
      - { name: "Button-Link Sekundär", element: ['a'], attributes: { 'class': 'rte-btn-secondary' }}
      - { name: "Button-Link Tertiär", element: ['a'], attributes: { 'class': 'rte-btn-tertiary' }}

    toolbarGroups:
      - { name: styles, groups: [ styles, format ] }
      - { name: basicstyles, groups: [ basicstyles ] }
      - { name: paragraph, groups: [ list, indent, blocks, align ] }
      - { name: links, groups: [ links ] }
      - { name: clipboard, groups: [ clipboard, cleanup, undo ] }
      - { name: editing, groups: [ spellchecker ] }
      - { name: insert, groups: [ insert ] }
      - { name: tools, groups: [ table, specialchar ] }
      - { name: document, groups: [ mode ] }

    justifyClasses:
      - align-left
      - align-center
      - align-right
      - align-justify

    extraPlugins:
      - justify

    removePlugins:
      - image

    removeButtons:
      - Anchor
      - Underline
      - Strike
      - Styles

What is the trick to get my config working?!

Body:
In my case I was using DCE Extension – an the preset got ignored. To use any preset use this DCE field Config:

<config>
    <type>text</type>
    <rows>5</rows>
    <cols>30</cols>
    <eval>trim,required</eval>
    <enableRichtext>1</enableRichtext>
    <richtextConfiguration>mypreset</richtextConfiguration>
</config>

I informed the Ext developer of DCE Ext and he updated the RTE Config "preset" already.