问:
Can you increase specifity by nesting class inside of another class?
Would this

```<code>.class{
 .subclass{ }
}
</code>```

be same as

```<code>.class{}
.subclass{}
</code>```

are there any diffrences apart from visual ones?

答:
It does increase specificity.

```<code>.class {
    .subclass{}
}
</code>```

after being compiled into regular css is:

```<code>.class .subclass {
}
</code>```

While your second example stays exactly the same after compiling.

Of course this only works if you are using SASS / LESS.

Body:
Would this

.class{
 .subclass{ }
}

be same as

.class{}
.subclass{}

are there any diffrences apart from visual ones?

Body:
It does increase specificity.

.class {
    .subclass{}
}

after being compiled into regular css is:

.class .subclass {
}

While your second example stays exactly the same after compiling.

Of course this only works if you are using SASS / LESS.


来源: stackexchange

问:
R Question: ifelse producing unexpected results
I am new to R and am getting unexpected results while using the ifelse() function. Here is an example. Below is a subset of the data frame I am working with. After the last command, why does the example$Points column contain 12 instead of 2? I have tried this for many different values of example$Value and the result is always 10 more than what I expect.

Example:

```<code>example
     Question StudentID SchoolID Value Worth Answer Points
2926       18    101290    84386     2     2     Co      0
2927       18    100878    84386     2     2     Co      0
2928       18    100895    84386     1     5     Co      0
2929       18    100913    84386     2     2     Co      0
2930       18    100884    84386     2     2     Co      0
example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
example
     Question StudentID SchoolID Value Worth Answer Points
2926       18    101290    84386     2     2     Co     12
2927       18    100878    84386     2     2     Co     12
2928       18    100895    84386     1     5     Co     11
2929       18    100913    84386     2     2     Co     12
2930       18    100884    84386     2     2     Co     12
</code>```

I've been using the work-around of just then subtracting 10 from the column, but I would like to avoid this and get to the bottom of what is going on here.

Any help would be greatly appreciated. Thank you!

答: My guess is that example$Value is a factor and you're getting the underlying codes instead of the labels.  I recommend taking a look at your data as soon as it's read into R to see what's causing your input method to treat those values as factors instead of integer / numeric.

ContentLicense: CC BY-SA 2.5

Body:
I am new to R and am getting unexpected results while using the ifelse() function. Here is an example. Below is a subset of the data frame I am working with. After the last command, why does the example$Points column contain 12 instead of 2? I have tried this for many different values of example$Value and the result is always 10 more than what I expect.

Example:

example
     Question StudentID SchoolID Value Worth Answer Points
2926       18    101290    84386     2     2     Co      0
2927       18    100878    84386     2     2     Co      0
2928       18    100895    84386     1     5     Co      0
2929       18    100913    84386     2     2     Co      0
2930       18    100884    84386     2     2     Co      0
example$Points <- ifelse(example$Answer == "Co", example$Value, example$Points)
example
     Question StudentID SchoolID Value Worth Answer Points
2926       18    101290    84386     2     2     Co     12
2927       18    100878    84386     2     2     Co     12
2928       18    100895    84386     1     5     Co     11
2929       18    100913    84386     2     2     Co     12
2930       18    100884    84386     2     2     Co     12

I've been using the work-around of just then subtracting 10 from the column, but I would like to avoid this and get to the bottom of what is going on here.

Any help would be greatly appreciated. Thank you!


答:
Nesting in SASS does exactly that. It increases specificity of the selector.

Play with this gist on SassMeister.

```<code>.class {
  .subclass {
    color: red;
  }
}
</code>```

compiles to:

```<code>.class .subclass {
  color: red;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Can you increase specifity by nesting class inside of another class?

Body:
Nesting in SASS does exactly that. It increases specificity of the selector.

Play with this gist on SassMeister.

.class {
  .subclass {
    color: red;
  }
}

compiles to:

.class .subclass {
  color: red;
}


问:
How to set the Caret on the position of RightClick?
I have a RichTextBox with a SpellCheck implemented. I want to place the cursor/caret exactly where the rightclick is positioned. For example, if i have two misspelled words such as :

I belive this is wroking

and I right click on "belive", the context menu that opens is based on Wroking, because my cursor was last positioned there. To open the list of suggested words of "belive", I have to first Left click on the word, to position the caret and then RightClick.

So to make it clear, I want to automatically position the caret where my cursor is on RightClick. Is it possible to do that? Thanks in advance.

答:
I Found a way to solve the problem, by getting the mouseposition on MouseRightButtonUp event and attributing it to a TextPointer. From there, I can select the exact Range of the current word, and then do something with it.

Point mousePoint = Mouse.GetPosition(textBox);

TextPointer current = textBox.GetPositionFromPoint(mousePoint, true);


问:
Calculate numbers inside view
I am trying to add numbers from a loop inside MVC view and display the total value of those numbers. But the code bellow is just adding numbers one beside another not getting calculated. Can you plz tell me how can i make it to calculate all number and display? </p>

```<code>@{ var TotalWatch = ""; }
@foreach(var item in ViewBag.tableItems)
{
 if (item.NumberOfWatch != "")
 {
     TotalWatch += item.NumberOfWatch;
 }
}
@TotalWatch
</code>```

答:
Assuming item.NumberOfWatch is a string, the following should work, but is a bad approach.

```<code>@{ var TotalWatch = 0; }
@foreach(var item in ViewBag.tableItems)
{
 if (item.NumberOfWatch != "")
 {
     TotalWatch += int.Parse(item.NumberOfWatch);
 }
}
@TotalWatch
</code>```

Instead, you should have a strongly-typed view model, which should be passed to the View, rather than passing data through ViewBag.

e.g.

Your model:

```<code>class YourViewModel
  int TotalWatch // sum it here
</code>```

Your view:

```<code>@Model.TotalWatch
</code>```

Title: Calculate numbers inside view

Body:
I am trying to add numbers from a loop inside MVC view and display the total value of those numbers. But the code bellow is just adding numbers one beside another not getting calculated. Can you plz tell me how can i make it to calculate all number and display?

@{ var TotalWatch = ""; }
@foreach(var item in ViewBag.tableItems)
{
 if (item.NumberOfWatch != "")
 {
     TotalWatch += item.NumberOfWatch;
 }
}
@TotalWatch

Body:
Assuming item.NumberOfWatch is a string, the following should work, but is a bad approach.

@{ var TotalWatch = 0; }
@foreach(var item in ViewBag.tableItems)
{
 if (item.NumberOfWatch != "")
 {
     TotalWatch += int.Parse(item.NumberOfWatch);
 }
}
@TotalWatch

Instead, you should have a strongly-typed view model, which should be passed to the View, rather than passing data through ViewBag.

e.g.

Your model:

class YourViewModel
  int TotalWatch // sum it here

Your view:

@Model.TotalWatch


问:
Why are sum types called sum types?
In the course of learning Haskell I read about Algebraic Data Types, sum types and product types. While product types are analogous to the Cartesian product and "product" immediately made sense to me I don't understand why sum types (aka variant types aka tagged union aka discriminated union aka disjoint union) are called sum types.

Wikipedia says:

The sum type corresponds to intuitionistic logical disjunction under
  the Curry–Howard correspondence.

OK, I get it: Disjunction is analogous to OR in boolean algebra and this kind of looks like sums because

```<code> OR |   | +
-----------
0 0 | 0 | 0
0 1 | 1 | 1
1 0 | 1 | 1
1 1 | 1 | 0 (mismatch here)
</code>```

But it does not really fit because of 1 + 1.

I found various explanations on what product and sum types are and I think I get it. The sum type is either one thing OR the other thing.

But why exactly is it called sum type? Just because it is a convention to use the symbol + for the OR operator? Or because "Sum types are the dual of product types."?

(Again, unless I missed something big, please don't explain sum/product type. I think I get the concept. I only want to know why it is called sum type.)

答: It's called a sum type because the number of values of A + B is the sum of the number of values of A and B.

Title: Why are sum types called sum types?

Body:
In the course of learning Haskell I read about Algebraic Data Types, sum types and product types. While product types are analogous to the Cartesian product and "product" immediately made sense to me I don't understand why sum types (aka variant types aka tagged union aka discriminated union aka disjoint union) are called sum types.

Wikipedia says:

The sum type corresponds to intuitionistic logical disjunction under
  the Curry–Howard correspondence.

OK, I get it: Disjunction is analogous to OR in boolean algebra and this kind of looks like sums because

 OR |   | +
-----------
0 0 | 0 | 0
0 1 | 1 | 1
1 0 | 1 | 1
1 1 | 1 | 0 (mismatch here)

But it does not really fit because of 1 + 1.

I found various explanations on what product and sum types are and I think I get it. The sum type is either one thing OR the other thing.

But why exactly is it called sum type? Just because it is a convention to use the symbol + for the OR operator? Or because "Sum types are the dual of product types."?

(Again, unless I missed something big, please don't explain sum/product type. I think I get the concept. I only want to know why it is called sum type.)


问:
SSIS transformation (almost like a pivot)
I have the following data coming in to SSIS

```<code>Set   Value
---   -------
1     One
1     Two
1     Three
2     Four
2     Five
2     Six
</code>```

I want to transform it to read

```<code>Set   ValueList
---   -------
1     One, Two, Three
2     Four, Five, Six
</code>```

How do I do this in SSIS?

答:
I used the Script Component to do the string concatenation across rows</p>

```<code>string TagId = "-1";
string TagList = "";
bool IsFirstRow = true;

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    if (Row.TAGSId.ToString() == TagId)
    {
        TagList += Row.TAG + ",";
    }
    else
    {
        if (IsFirstRow)
        {
            Output0Buffer.AddRow();
            IsFirstRow = false;
        }

        TagId = Row.TAGSId.ToString();
        TagList = Row.TAG.ToString() + ",";
    }

    Output0Buffer.TagId = int.Parse(TagId);
    Output0Buffer.TagList = TagList;
    Output0Buffer.TagLength = TagList.Length;

    //variable used in subsequent queries
    this.Variables.TagList = TagList;
}
</code>```

Body:
I have the following data coming in to SSIS

Set   Value
---   -------
1     One
1     Two
1     Three
2     Four
2     Five
2     Six

I want to transform it to read

Set   ValueList
---   -------
1     One, Two, Three
2     Four, Five, Six

How do I do this in SSIS?

Body:
I used the Script Component to do the string concatenation across rows

string TagId = "-1";
string TagList = "";
bool IsFirstRow = true;

public override void Input0_ProcessInputRow(Input0Buffer Row)
{
    if (Row.TAGSId.ToString() == TagId)
    {
        TagList += Row.TAG + ",";
    }
    else
    {
        if (IsFirstRow)
        {
            Output0Buffer.AddRow();
            IsFirstRow = false;
        }

        TagId = Row.TAGSId.ToString();
        TagList = Row.TAG.ToString() + ",";
    }

    Output0Buffer.TagId = int.Parse(TagId);
    Output0Buffer.TagList = TagList;
    Output0Buffer.TagLength = TagList.Length;

    //variable used in subsequent queries
    this.Variables.TagList = TagList;
}


问:
Find the pushdown automata of this language L={A^i B^j C^k | 2k <= i <= 3k OR j != (i+k) } with one stack
I can't find the automata because I can only imagine it with multiple stacks or with intersections of set theory.</p>

答:
The language: L = { A^i B^j C^k | 2k <= i <= 3k OR j != (i+k) }

This language is the union of two languages L' and L'':

```<code>L'  = { A^i B^j C^k | 2k <= i <= 3k }
L'' = { A^i B^j C^k | j != (i+k) }
</code>```

If we figure out NPDAs for each of these languages, we can write down a new NPDA for the union of these two languages by:

introducing a new start state, q*

adding transitions f(q*,e,Z) = (q0',Z) and f(q*,e,Z) = (q0'',Z) where e is epsilon/lambda, Z is the bottom of stack symbol and q0' and q0'' are the start states of NPDAs for L' and L'', respectively.

We have decomposed the harder problem into two simpler problems, and figured out how to put the answers to the easier problems together to answer the harder problem. This is the most important skill you can possibly develop when it comes to formal sciences such as computer science, mathematics and, to a large extent, computer programming.

What should a NPDA for L' look like? It can read any number of Bs at all, provided they come in between As and Cs. We need to keep track of how many As we see, say by pushing an A onto the stack each time we see one; and we need to pop As off the stack once we start seeing Cs. Assuming we want to accept by empty stack, we need to remove all the As; but how do we know how many to remove? If we had 2k = i, we would remove two As for every C we see. If we had i = 3k, we would remove three As for every C we see. As it is, we are somewhere in between. This is conceptually difficulty. The notion of nondeterminism - the N in NPDA - is crucial here. We don't need to know exactly how the string will get accepted; we just need a process that can accept a string in the language, and can't accept one not in the language. We can guess whether we need to remove two or three As from the stack at any particular juncture; this will guarantee we don't exceed the 2k and 3k bounds, and it will also allow us to get any result in between. To make this work, we can simply crash or reject all failed executions of valid strings, provided one of the possible executions passes.

Here is a NPDA based on this description, assuming acceptance by empty stack and accepting state:

```<code>Q    s    S    Q'    S'
------------------------
// read A's and push onto stack
q0   A    Z    q0    AZ
q0   A    A    q0    AA

// begin reading B's
q0   B    Z    q1    Z
q0   B    A    q1    Z

// begin reading C's if no B's
q0   C    A    q2    -
q0   C    A    q3    -

// read B's
q1   B    Z    q1    Z
q1   B    A    q1    A

// begin reading C's if B's
q1   C    A    q2    -
q1   C    A    q3    -

// pop the final A for the last C read
q2   -    A    q4    -

// if popping three A's, pop the middle A
q3   -    A    q2    -

// pop the first A for each C read after the first C
q4   C    A    q2    -
q4   C    A    q3    -

// transition to separate accepting state if stack empty
q4   -    Z    qA    -
</code>```

In the above NPDA, transitions that would lead to a "dead" state are not shown. If you want to show it, add those transitions and call the state qR. In the absence of those explicit transitions, the NPDA is customarily understood to "crash" and reject the input. For any string in L', there will be a way through this NPDA that ends in state qA with an empty stack.

For the other language, we can break it down further. L'' is the union of two languages R' and R'':

```<code>R'  = { A^i B^j C^k | j < i + k }
R'' = { A^i B^j C^k | j > i + k }
</code>```

Using the same construction outlined above, we can create a NPDA for L'' by finding NPDAs for R' and R'' and putting those answers together.

For R', we can push As into the stack when we read As; we can pop As, if any, or push Bs otherwise, when reading Bs; and, finally, we can pop Bs, if any, or push Cs otherwise, when reading Cs. We will have j < i + k if and only if there is either an A or C on top of the stack when we're done. Then, we can move to the accepting state and pop As and Cs from the stack to get an empty stack.

For R'', we can do the same thing and look for a B on top of the stack. We can move to an accepting state and pop Bs to clear the stack.

```<code>    R'                             R''

Q    s    S    Q'    S'        Q    s    S    Q'    S'
-----------------------        -----------------------
// count A's, first B/C        // count A's, first B/C
q0'  A    Z    q0'   AZ        q0'' A    Z    q0''  AZ
q0'  A    A    q0'   AA        q0'' A    A    q0''  AA
q0'  B    Z    q1'   BZ        q0'' B    Z    q1''  BZ
q0'  B    A    q1'   -         q0'' B    A    q1''  -
q1'  C    Z    q2'   CZ        q0'' C    A    q2''  CZ
q1'  C    A    q2'   CA        q0'' C    Z    q2''  CA

// count B's, first C          // count B's, first C
q1'  B    Z    q1'   BZ        q1'' B    Z    q1''  BZ
q1'  B    A    q1'   -         q1'' B    A    q1''  -
q1'  B    B    q1'   BB        q1'' B    B    q1''  BB
q1'  C    Z    q2'   CZ        q1'' C    Z    q2''  CZ
q1'  C    A    q2'   CA        q1'' C    A    q2''  CA
q1'  C    B    q2'   CB        q1'' C    B    q2''  CB

// count C's                   // count C's
q2'  C    Z    q2'   CZ        q2'' C    Z    q2''  CZ
q2'  C    A    q2'   CA        q2'' C    A    q2''  CA
q2'  C    B    q2'   -         q2'' C    B    q2''  -
q2'  C    C    q2'   CC        q2'' C    C    q2''  CC

// accept if A's or C's        // accept if B's
q2'  -    A    qA'   -         q2'' -    B    qA'-  -
q2'  -    C    qA'   -

// accept if A's or C's        // accept if B's
qA'  -    A    qA'   -         qA'' -    B    qA''  -
qA'  -    C    qA'   -
</code>```

A NPDA for your original language is therefore the following:

```<code>Q    s    S    Q'    S'
-----------------------
q*   -    Z    q0    Z
q*   -    Z    q0'   Z
q*   -    Z    q0''  Z
</code>```

Add to this all the other transitions given earlier and define acceptance to be by empty stack in any of the three accepting states qA, qA' or qA''.

Body:
The language: L = { A^i B^j C^k | 2k <= i <= 3k OR j != (i+k) }

This language is the union of two languages L' and L'':

L'  = { A^i B^j C^k | 2k <= i <= 3k }
L'' = { A^i B^j C^k | j != (i+k) }

If we figure out NPDAs for each of these languages, we can write down a new NPDA for the union of these two languages by:

introducing a new start state, q*

adding transitions f(q*,e,Z) = (q0',Z) and f(q*,e,Z) = (q0'',Z) where e is epsilon/lambda, Z is the bottom of stack symbol and q0' and q0'' are the start states of NPDAs for L' and L'', respectively.

We have decomposed the harder problem into two simpler problems, and figured out how to put the answers to the easier problems together to answer the harder problem. This is the most important skill you can possibly develop when it comes to formal sciences such as computer science, mathematics and, to a large extent, computer programming.

What should a NPDA for L' look like? It can read any number of Bs at all, provided they come in between As and Cs. We need to keep track of how many As we see, say by pushing an A onto the stack each time we see one; and we need to pop As off the stack once we start seeing Cs. Assuming we want to accept by empty stack, we need to remove all the As; but how do we know how many to remove? If we had 2k = i, we would remove two As for every C we see. If we had i = 3k, we would remove three As for every C we see. As it is, we are somewhere in between. This is conceptually difficulty. The notion of nondeterminism - the N in NPDA - is crucial here. We don't need to know exactly how the string will get accepted; we just need a process that can accept a string in the language, and can't accept one not in the language. We can guess whether we need to remove two or three As from the stack at any particular juncture; this will guarantee we don't exceed the 2k and 3k bounds, and it will also allow us to get any result in between. To make this work, we can simply crash or reject all failed executions of valid strings, provided one of the possible executions passes.

Here is a NPDA based on this description, assuming acceptance by empty stack and accepting state:

Q    s    S    Q'    S'
------------------------
// read A's and push onto stack
q0   A    Z    q0    AZ
q0   A    A    q0    AA

// begin reading B's
q0   B    Z    q1    Z
q0   B    A    q1    Z

// begin reading C's if no B's
q0   C    A    q2    -
q0   C    A    q3    -

// read B's
q1   B    Z    q1    Z
q1   B    A    q1    A

// begin reading C's if B's
q1   C    A    q2    -
q1   C    A    q3    -

// pop the final A for the last C read
q2   -    A    q4    -

// if popping three A's, pop the middle A
q3   -    A    q2    -

// pop the first A for each C read after the first C
q4   C    A    q2    -
q4   C    A    q3    -

// transition to separate accepting state if stack empty
q4   -    Z    qA    -

In the above NPDA, transitions that would lead to a "dead" state are not shown. If you want to show it, add those transitions and call the state qR. In the absence of those explicit transitions, the NPDA is customarily understood to "crash" and reject the input. For any string in L', there will be a way through this NPDA that ends in state qA with an empty stack.

For the other language, we can break it down further. L'' is the union of two languages R' and R'':

R'  = { A^i B^j C^k | j < i + k }
R'' = { A^i B^j C^k | j > i + k }

Using the same construction outlined above, we can create a NPDA for L'' by finding NPDAs for R' and R'' and putting those answers together.

For R', we can push As into the stack when we read As; we can pop As, if any, or push Bs otherwise, when reading Bs; and, finally, we can pop Bs, if any, or push Cs otherwise, when reading Cs. We will have j < i + k if and only if there is either an A or C on top of the stack when we're done. Then, we can move to the accepting state and pop As and Cs from the stack to get an empty stack.

For R'', we can do the same thing and look for a B on top of the stack. We can move to an accepting state and pop Bs to clear the stack.

    R'                             R''

Q    s    S    Q'    S'        Q    s    S    Q'    S'
-----------------------        -----------------------
// count A's, first B/C        // count A's, first B/C
q0'  A    Z    q0'   AZ        q0'' A    Z    q0''  AZ
q0'  A    A    q0'   AA        q0'' A    A    q0''  AA
q0'  B    Z    q1'   BZ        q0'' B    Z    q1''  BZ
q0'  B    A    q1'   -         q0'' B    A    q1''  -
q1'  C    Z    q2'   CZ        q0'' C    A    q2''  CZ
q1'  C    A    q2'   CA        q0'' C    Z    q2''  CA

// count B's, first C          // count B's, first C
q1'  B    Z    q1'   BZ        q1'' B    Z    q1''  BZ
q1'  B    A    q1'   -         q1'' B    A    q1''  -
q1'  B    B    q1'   BB        q1'' B    B    q1''  BB
q1'  C    Z    q2'   CZ        q1'' C    Z    q2''  CZ
q1'  C    A    q2'   CA        q1'' C    A    q2''  CA
q1'  C    B    q2'   CB        q1'' C    B    q2''  CB

// count C's                   // count C's
q2'  C    Z    q2'   CZ        q2'' C    Z    q2''  CZ
q2'  C    A    q2'   CA        q2'' C    A    q2''  CA
q2'  C    B    q2'   -         q2'' C    B    q2''  -
q2'  C    C    q2'   CC        q2'' C    C    q2''  CC

// accept if A's or C's        // accept if B's
q2'  -    A    qA'   -         q2'' -    B    qA'-  -
q2'  -    C    qA'   -

// accept if A's or C's        // accept if B's
qA'  -    A    qA'   -         qA'' -    B    qA''  -
qA'  -    C    qA'   -

A NPDA for your original language is therefore the following:

Q    s    S    Q'    S'
-----------------------
q*   -    Z    q0    Z
q*   -    Z    q0'   Z
q*   -    Z    q0''  Z

Add to this all the other transitions given earlier and define acceptance to be by empty stack in any of the three accepting states qA, qA' or qA''.


问:
laravel eloquent with sum multiple rows from linked table
I have a table Quotes that has a one-to-many relationship with the QuoteDetails table.

The table structure looks like this:

```<code>return $this->quotes->with('quotedetails')
    ->orderBy('created_at', 'DESC')->paginate(10);
</code>```

Results in:

```<code>{
   "current_page":1,
   "data":[
      {
         "id":2,
         "subject":"demo",
         "quotedetails":[
            {
               "id":2,
               "quotes_id":2,
               "description":"testing data",
               "total":1080
            },
            {
               "id":3,
               "quotes_id":2,
               "description":"testing",
               "total":180
            }
         ]
      },
      {
         "id":1,
         "subject":"demo",
         "quotedetails":[
            {
               "id":1,
               "quotes_id":1,
               "description":"data",
               "total":360
            }
         ]
      }
   ],
   "per_page":10,
   "prev_page_url":null,
   "to":2,
   "total":2
}
</code>```

I want to include the sum of quotedetails.total rather than the full list of QuoteDetails rows. I am not sure how this should be done.

Here is how I am querying in my model (Quotes)

```<code>public function quotedetails(){
        return $this->hasMany('App\Models\QuotesDetail', 'quotes_id', 'id');
    }
</code>```

How can i get the total sum.

Here is how i expect the output

```<code>{
   "current_page":1,
   "data":[
      {
         "id":2,
         "subject":"demo link data",
         "quotesum": 1260
      },
      {
         "id":1,
         "subject":"demo",
         "quotesum": 360
      }
   ],
   "per_page":10,
   "prev_page_url":null,
   "to":2,
   "total":2
}
</code>```

答:
I understand that you want to do it by query, But taking this without even query you'll be able to transform the paginated data this way, giving this example:

```<code>$quotes = Quotes::whereNotNull('id')->with('quotedetails')
    ->orderBy('created_at', 'DESC')->paginate();

//transform the data in the Paginate instance
$quotes->getCollection()->transform(function($quote){
     $quote->quotesum = $quote->quotedetails->sum('total');
     unset($quote['quotedetails']);
     return $quote;
});
</code>```

The data in the paginated result is transformed and you have what you requested.

Pro: More possibilities to do more with your response without adding any query.

Con: More data in the result mean more work on the collection especially in case of large data.

ContentLicense: CC BY-SA 4.0

Body:
I have a table Quotes that has a one-to-many relationship with the QuoteDetails table.

The table structure looks like this:

return $this->quotes->with('quotedetails')
    ->orderBy('created_at', 'DESC')->paginate(10);

Results in:

{
   "current_page":1,
   "data":[
      {
         "id":2,
         "subject":"demo",
         "quotedetails":[
            {
               "id":2,
               "quotes_id":2,
               "description":"testing data",
               "total":1080
            },
            {
               "id":3,
               "quotes_id":2,
               "description":"testing",
               "total":180
            }
         ]
      },
      {
         "id":1,
         "subject":"demo",
         "quotedetails":[
            {
               "id":1,
               "quotes_id":1,
               "description":"data",
               "total":360
            }
         ]
      }
   ],
   "per_page":10,
   "prev_page_url":null,
   "to":2,
   "total":2
}

I want to include the sum of quotedetails.total rather than the full list of QuoteDetails rows. I am not sure how this should be done.

Here is how I am querying in my model (Quotes)

public function quotedetails(){
        return $this->hasMany('App\Models\QuotesDetail', 'quotes_id', 'id');
    }

How can i get the total sum.

Here is how i expect the output

{
   "current_page":1,
   "data":[
      {
         "id":2,
         "subject":"demo link data",
         "quotesum": 1260
      },
      {
         "id":1,
         "subject":"demo",
         "quotesum": 360
      }
   ],
   "per_page":10,
   "prev_page_url":null,
   "to":2,
   "total":2
}

Body:
I understand that you want to do it by query, But taking this without even query you'll be able to transform the paginated data this way, giving this example:

$quotes = Quotes::whereNotNull('id')->with('quotedetails')
    ->orderBy('created_at', 'DESC')->paginate();

//transform the data in the Paginate instance
$quotes->getCollection()->transform(function($quote){
     $quote->quotesum = $quote->quotedetails->sum('total');
     unset($quote['quotedetails']);
     return $quote;
});

The data in the paginated result is transformed and you have what you requested.

Pro: More possibilities to do more with your response without adding any query.

Con: More data in the result mean more work on the collection especially in case of large data.


问:
NSBundleResourceRequest beginAccessingResources never completes
I am trying to utilize ODR in my application, but the beginAccessingResources never completes. Below is a simplified version of my code:

```<code>let bundleResourceRequest = NSBundleResourceRequest(tags: tags)

bundleResourceRequest.beginAccessingResources { error in

    DispatchQueue.main.async {
        if let error = error {
            bundleResourceRequest.endAccessingResources()

            // Handle error

        } else {
            // Successful
        }
    }
}
</code>```

I have started simple by tagging a .sks file with the tag Level1 and another .sks with the tag Home. When I begin access resources for the tag Home, I get a successful completion with no problem. However, when I try with the Level1 tag, the completion block never fires. I don't receive an error or success. When I look in Disk Report, it shows Home is In Use and Level1 is Downloading with a progress bar that never moves. Level1 is a total of 16 KB so it isn't too large, and I have let it sit for ~10 minutes with no success.

What could be causing this function to never complete?

答: I was able to fix this by going to Build Settings and changing Embed Asset Packs in Product Bundle to Yes for Debug.

Body:
I am trying to utilize ODR in my application, but the beginAccessingResources never completes. Below is a simplified version of my code:

let bundleResourceRequest = NSBundleResourceRequest(tags: tags)

bundleResourceRequest.beginAccessingResources { error in

    DispatchQueue.main.async {
        if let error = error {
            bundleResourceRequest.endAccessingResources()

            // Handle error

        } else {
            // Successful
        }
    }
}

I have started simple by tagging a .sks file with the tag Level1 and another .sks with the tag Home. When I begin access resources for the tag Home, I get a successful completion with no problem. However, when I try with the Level1 tag, the completion block never fires. I don't receive an error or success. When I look in Disk Report, it shows Home is In Use and Level1 is Downloading with a progress bar that never moves. Level1 is a total of 16 KB so it isn't too large, and I have let it sit for ~10 minutes with no success.

What could be causing this function to never complete?


问:
implementation of scala function name.exists(_.isUpper) in Java (Programming in scala)
```<code>// scala code
    val nameHasUpperCase = name.exists(_.isUpperCase)
</code>```

In principle, such control abstractions are possible in Java as well.
  You’d need to define an interface that contains a method with the
  abstracted functionality. For instance, if you wanted to support
  querying over strings, you might invent an interface, named
  CharacterProperty, which has just one method, hasProperty: // this is
  Java

interface CharacterProperty { boolean hasProperty(char ch); }

With that interface you could formulate a method exists in Java: It
  takes a string and CharacterProperty and returns true if there’s a
  character in the string that satisfies the property. You could then
  invoke exists as follows:

```<code>//this is Java
 exists(name, new CharacterProperty() {
    public boolean hasProperty(char ch) {
      return Character.isUpperCase(ch); }
 });
</code>```

I can not get this case runnable. How to interpret the author's words and implement this in Java language with interface? Any help will be appreciated, Thanks.

答:
Basically, in Java 8 you can almost do it as nicely as in Scala:

name.chars().anyMatch(Character::isUpperCase)

Before Java 8, there was no way to do method abstraction (introduced by lambdas and method references), so you had to write wrapper classes for single-function tests, making it awkward and cumbersome. Hence the remark that nobody really does it.

The code would probably go like this:

```<code>public boolean exists(String str, CharacterProperty prop) {
    return str.chars().anyMatch(prop::hasProperty);
}
</code>```

Body:
// scala code
    val nameHasUpperCase = name.exists(_.isUpperCase)

In principle, such control abstractions are possible in Java as well.
  You’d need to define an interface that contains a method with the
  abstracted functionality. For instance, if you wanted to support
  querying over strings, you might invent an interface, named
  CharacterProperty, which has just one method, hasProperty: // this is
  Java

interface CharacterProperty { boolean hasProperty(char ch); }

With that interface you could formulate a method exists in Java: It
  takes a string and CharacterProperty and returns true if there’s a
  character in the string that satisfies the property. You could then
  invoke exists as follows:

//this is Java
 exists(name, new CharacterProperty() {
    public boolean hasProperty(char ch) {
      return Character.isUpperCase(ch); }
 });

I can not get this case runnable. How to interpret the author's words and implement this in Java language with interface? Any help will be appreciated, Thanks.

Body:
Basically, in Java 8 you can almost do it as nicely as in Scala:

name.chars().anyMatch(Character::isUpperCase)

Before Java 8, there was no way to do method abstraction (introduced by lambdas and method references), so you had to write wrapper classes for single-function tests, making it awkward and cumbersome. Hence the remark that nobody really does it.

The code would probably go like this:

public boolean exists(String str, CharacterProperty prop) {
    return str.chars().anyMatch(prop::hasProperty);
}


问:
How to 'queue' piece of code in javascript
I've made a class that, when initialized, starts to download a JSON file.

However, the downloading runs asynchronously.
So after I declare it I start working with it, but it fails because it hasn't loaded the file yet.

I could turn async off, but is there another way without freezing the browser?

I'm currently working around it with a setTimeout option, but that seems like an ugly hack.

```<code>  var d;
  $(document).ready(function() {
      d = new Duk('element');
      d.getBlueprint('hud.json');
      setTimeout(start, '2000');
  });

  function start(){
      test = new d.Dialog(d.blueprint.screens.test);
      test.draw();
  }
</code>```

答:
You want your getBlueprint() method to be able to accept a callback which is run when the file is finished downloading.</p>

```<code>function getBlueprint(file, callback)
{
    // do whatever to get the file
    // ...
    // trigger the callback
    callback();
}

$(document).ready(function() {
    var d;
    function start(){
        test = new d.Dialog(d.blueprint.screens.test);
        test.draw();
    }
    d = new Duk('element');
    d.getBlueprint('hud.json', start);
    setTimeout(start, '2000');
});
</code>```

Body:
I've made a class that, when initialized, starts to download a JSON file.

However, the downloading runs asynchronously.
So after I declare it I start working with it, but it fails because it hasn't loaded the file yet.

I could turn async off, but is there another way without freezing the browser?

I'm currently working around it with a setTimeout option, but that seems like an ugly hack.

  var d;
  $(document).ready(function() {
      d = new Duk('element');
      d.getBlueprint('hud.json');
      setTimeout(start, '2000');
  });

  function start(){
      test = new d.Dialog(d.blueprint.screens.test);
      test.draw();
  }

Body:
You want your getBlueprint() method to be able to accept a callback which is run when the file is finished downloading.

function getBlueprint(file, callback)
{
    // do whatever to get the file
    // ...
    // trigger the callback
    callback();
}

$(document).ready(function() {
    var d;
    function start(){
        test = new d.Dialog(d.blueprint.screens.test);
        test.draw();
    }
    d = new Duk('element');
    d.getBlueprint('hud.json', start);
    setTimeout(start, '2000');
});


问:
How do I run terraform init from a different folder?
I want to script terraform for CI/CD purpose and I don't like CDing in scripts, I rather have specific paths.

I tried terraform init c:\my\folder\containing\tf-file

But running that puts the .terraform folder in my cwd.

答:
The [DIR] option in terraform init command tells terraform where to process tf files from, but doesn't tell it where to store state files. If you want to change what local path state files are stored at, add a section to your main.tf to configure backend path.

```<code>terraform {
  backend "local" {
    path = "relative/path/to/terraform.tfstate"
  }
}
</code>```

I haven't actually tried this out, but you may be able to pass the path from command line as:

```<code>-backend-config="path=/foo"
</code>```

Body:
The [DIR] option in terraform init command tells terraform where to process tf files from, but doesn't tell it where to store state files. If you want to change what local path state files are stored at, add a section to your main.tf to configure backend path.

terraform {
  backend "local" {
    path = "relative/path/to/terraform.tfstate"
  }
}

I haven't actually tried this out, but you may be able to pass the path from command line as:

-backend-config="path=/foo"


问:
Ruby 1.8.6 Array#uniq not removing duplicate hashes
I have this array, in a ruby 1.8.6 console:

```<code>arr = [{:foo => "bar"}, {:foo => "bar"}]
</code>```

both elements are equal to each other:

```<code>arr[0] == arr[1]
=> true
#just in case there's some "==" vs "===" oddness...
arr[0] === arr[1]
=> true
</code>```

But, arr.uniq doesn't remove the duplicates:

```<code>arr.uniq
=> [{:foo=>"bar"}, {:foo=>"bar"}]
</code>```

Can anyone tell me what's going on here?

EDIT:  I can write a not very clever uniqifier which uses include? as follows:

```<code>uniqed = []
arr.each do |hash|
  unless uniqed.include?(hash)
    uniqed << hash
  end
end;false
uniqed
=> [{:foo=>"bar"}]
</code>```

This produces the correct result, which makes the failure of uniq even more mysterious.

EDIT 2:  Some notes on what's going on, possibly just for my own clarity.  As @Ajedi32 points out in the comments, the failure to uniqify comes from the fact that the two elements are different objects.  Some classes define eql? and hash methods, used for comparison, to mean "are these effectively the same thing, even if they're not the same object in memory".  String does this for example, which is why you can define two variables to be "foo" and they are said to be equal to one another, even though they're not the same object.

The Hash class doesn't do this, in Ruby 1.8.6, and so when .eql? and .hash are called on a hash object (the .hash method has nothing to do with the Hash data type - it's like the checksum kind of hash) it falls back to using the methods defined in the Object base class, which simply say "Is it the same object in memory".

The == and === operators, for hash objects, already do what I want, ie to say that two hashes are the same if their contents are the same.  I've overriden Hash#eql? to use these, like so:

```<code>class Hash
  def eql?(other_hash)
    self == other_hash
  end
end
</code>```

But, I'm not sure how to handle Hash#hash: that is, I don't know how to generate a checksum which will be the same for two hashes whose contents are the same and always different for two hashes with different contents.

@Ajedi32 suggested I have a look at Rubinius' implentation of the Hash#hash method here https://github.com/rubinius/rubinius/blob/master/core/hash.rb#L589 , and my version of Rubinius' implementation looks like this:

```<code>class Hash
  def hash
    result = self.size
    self.each do |key,value|
      result ^= key.hash
      result ^= value.hash
    end
    return result
  end
end
</code>```

and this does seem to work, although I don't know what the "^=" operator does, which makes me a bit nervous.  Also, it's very slow - about 50x as slow based on some primitive benchmarking.  This might make it too slow to use.

EDIT 3: A bit of research has revealed that "^" is the Bitwise Exclusive OR operator.  When we have two inputs, an XOR returns 1 if the inputs are different (ie it returns 0 for 0,0 and 1,1 and 1 for 0,1 and 1,0).

So, at first I thought that means that

```<code>result ^= key.hash
</code>```

is shorthand for

```<code>result = result ^ key.hash
</code>```

In other words, do an XOR between the current value of result and the other thing, and then save that in result. I still don't quite get the logic of this though.  I thought that perhaps the ^ operator was something to do with pointers, because calling it on variables works while calling it on the value of the variable doesn't work:  eg

```<code>var = 1
=> 1
var ^= :foo
=> 14904
1 ^= :foo
SyntaxError: compile error
(irb):11: syntax error, unexpected tOP_ASGN, expecting $end
</code>```

So, it's fine with calling ^= on a variable but not the value of the variable, which made me think it's something to do with referencing/dereferencing.

Later implementations of Ruby also have C code for the Hash#hash method, and Rubinius' implementaion seems too slow.  Bit stuck...

答:
How about using JSON stringify and Parsing it back like in Javascript?

```<code>require 'json'
arr.map { |x| x.to_json}.uniq.map { |x| JSON.parse(x) }
</code>```

The json methods might not be supported in 1.8.6 please use which ever is supported.

Body:
I have this array, in a ruby 1.8.6 console:

arr = [{:foo => "bar"}, {:foo => "bar"}]

both elements are equal to each other:

arr[0] == arr[1]
=> true
#just in case there's some "==" vs "===" oddness...
arr[0] === arr[1]
=> true

But, arr.uniq doesn't remove the duplicates:

arr.uniq
=> [{:foo=>"bar"}, {:foo=>"bar"}]

Can anyone tell me what's going on here?

EDIT:  I can write a not very clever uniqifier which uses include? as follows:

uniqed = []
arr.each do |hash|
  unless uniqed.include?(hash)
    uniqed << hash
  end
end;false
uniqed
=> [{:foo=>"bar"}]

This produces the correct result, which makes the failure of uniq even more mysterious.

EDIT 2:  Some notes on what's going on, possibly just for my own clarity.  As @Ajedi32 points out in the comments, the failure to uniqify comes from the fact that the two elements are different objects.  Some classes define eql? and hash methods, used for comparison, to mean "are these effectively the same thing, even if they're not the same object in memory".  String does this for example, which is why you can define two variables to be "foo" and they are said to be equal to one another, even though they're not the same object.

The Hash class doesn't do this, in Ruby 1.8.6, and so when .eql? and .hash are called on a hash object (the .hash method has nothing to do with the Hash data type - it's like the checksum kind of hash) it falls back to using the methods defined in the Object base class, which simply say "Is it the same object in memory".

The == and === operators, for hash objects, already do what I want, ie to say that two hashes are the same if their contents are the same.  I've overriden Hash#eql? to use these, like so:

class Hash
  def eql?(other_hash)
    self == other_hash
  end
end

But, I'm not sure how to handle Hash#hash: that is, I don't know how to generate a checksum which will be the same for two hashes whose contents are the same and always different for two hashes with different contents.

@Ajedi32 suggested I have a look at Rubinius' implentation of the Hash#hash method here https://github.com/rubinius/rubinius/blob/master/core/hash.rb#L589 , and my version of Rubinius' implementation looks like this:

class Hash
  def hash
    result = self.size
    self.each do |key,value|
      result ^= key.hash
      result ^= value.hash
    end
    return result
  end
end

and this does seem to work, although I don't know what the "^=" operator does, which makes me a bit nervous.  Also, it's very slow - about 50x as slow based on some primitive benchmarking.  This might make it too slow to use.

EDIT 3: A bit of research has revealed that "^" is the Bitwise Exclusive OR operator.  When we have two inputs, an XOR returns 1 if the inputs are different (ie it returns 0 for 0,0 and 1,1 and 1 for 0,1 and 1,0).

So, at first I thought that means that

result ^= key.hash

is shorthand for

result = result ^ key.hash

In other words, do an XOR between the current value of result and the other thing, and then save that in result. I still don't quite get the logic of this though.  I thought that perhaps the ^ operator was something to do with pointers, because calling it on variables works while calling it on the value of the variable doesn't work:  eg

var = 1
=> 1
var ^= :foo
=> 14904
1 ^= :foo
SyntaxError: compile error
(irb):11: syntax error, unexpected tOP_ASGN, expecting $end

So, it's fine with calling ^= on a variable but not the value of the variable, which made me think it's something to do with referencing/dereferencing.

Later implementations of Ruby also have C code for the Hash#hash method, and Rubinius' implementaion seems too slow.  Bit stuck...

Body:
How about using JSON stringify and Parsing it back like in Javascript?

require 'json'
arr.map { |x| x.to_json}.uniq.map { |x| JSON.parse(x) }

The json methods might not be supported in 1.8.6 please use which ever is supported.


问:
Vue-js Vue-i18n dictionnay seem not loaded
I try to intertionalise my app, i use vue-i18n...

in my app.js i have this :

import Vue from 'vue';
import VueI18n from 'vue-i18n';

import App from './App';

Vue.use(VueI18n);

const messages = {
  en: {
    message: {
      hello: 'hello world',
    },
    hello: 'hello world',
  },
};

const i18n = new VueI18n({
  local: 'en',
  messages,
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  i18n,
  router,
  template: '<App/>',
  components: { App },
  render: h => h(App),
});```
</div>
</div>
</p>

<p>and in child of child of ... component i try to do a simple :   </p>

````this.$t('hello');`
```

But always have : [vue-i18n] Cannot translate the value of keypath 'hello'. Use the value of keypath as default.

So i think i missconfig some thing but i can't found why !!

答:
You have a typo in local, it should be locale (you forgot the e)

So, do this:

```<code>const i18n = new VueI18n({
  locale: 'en',
  messages,
});
</code>```

Body:
I try to intertionalise my app, i use vue-i18n...

in my app.js i have this :

import Vue from 'vue';
import VueI18n from 'vue-i18n';

import App from './App';

Vue.use(VueI18n);

const messages = {
  en: {
    message: {
      hello: 'hello world',
    },
    hello: 'hello world',
  },
};

const i18n = new VueI18n({
  local: 'en',
  messages,
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  i18n,
  router,
  template: '<App/>',
  components: { App },
  render: h => h(App),
});

and in child of child of ... component i try to do a simple :

`this.$t('hello');`

But always have : [vue-i18n] Cannot translate the value of keypath 'hello'. Use the value of keypath as default.

So i think i missconfig some thing but i can't found why !!

Body:
You have a typo in local, it should be locale (you forgot the e)

So, do this:

const i18n = new VueI18n({
  locale: 'en',
  messages,
});


问:
Trying to use Shuffle.js but getting Uncaught TypeError: Shuffle is not a constructor
This ought to be a simple enough question for those in the know- why am I getting this error in my console? I have tried following along with the code that appears under "usage" on the Shuffle homepage but I think the page is neglecting to include all of the steps for getting started with the library.

Here is my code on my index file located within the shufflejs folder created when the library was installed.

```<code><!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Shuffle Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
</head>

<body>
<div id="grid" class="row my-shuffle-container">
<figure class="col-4@sm picture-item" data-groups='["photography"]' data-date-created="2010-09-14" data-title="Baseball">
<div class="aspect aspect--16x9">
  <div class="aspect__inner">
    <img src="/img/baseball.png" alt="" height="145" width="230">
  </div>
</div>
<figcaption>Baseball</figcaption>
</figure>
<figure class="col-4@sm picture-item" data-groups='["wallpaper","3d"]' data-date-created="2011-08-14" data-title="Tennis">
<div class="aspect aspect--16x9">
  <div class="aspect__inner">
    <img src="/img/tennis-ball.png" alt="" height="145" width="230">
  </div>
</div>
<figcaption>Tennis</figcaption>
</figure>
<figure class="col-4@sm picture-item" data-groups='["wallpaper","3d"]' data-date-created="2009-05-27" data-title="iMac">
<div class="aspect aspect--16x9">
  <div class="aspect__inner">
    <img src="/img/imac.png" alt="" height="145" width="230">
  </div>
</div>
<figcaption>iMac</figcaption>
</figure>
<div class="col-1@sm my-sizer-element"></div>
</div>

<script>
var Shuffle = window.shuffle;
var element = document.getElementById('grid');
var sizer = element.querySelector('.my-sizer-element');

var shuffle = new Shuffle(element, {
itemSelector: '.picture-item',
sizer: sizer // could also be a selector: '.my-sizer-element'
});
// Overrideable options
Shuffle.options = {
group: Shuffle.ALL_ITEMS, // Initial filter group.
speed: 250, // Transition/animation speed (milliseconds).
easing: 'ease', // CSS easing function to use.
itemSelector: '*', // e.g. '.picture-item'.
sizer: null, // Element or selector string. Use an element to determine     the size of columns and gutters.
gutterWidth: 0, // A static number or function that tells the plugin how wide the gutters between columns are (in pixels).
columnWidth: 0, // A static number or function that returns a number which tells the plugin how wide the columns are (in pixels).
delimeter: null, // If your group is not json, and is comma delimeted, you could set delimeter to ','.
buffer: 0, // Useful for percentage based heights when they might not always be exactly the same (in pixels).
columnThreshold: 0.01, // Reading the width of elements isn't precise enough and can cause columns to jump between values.
initialSort: null, // Shuffle can be initialized with a sort object. It is the same object given to the sort method.
throttle: throttle, // By default, shuffle will throttle resize events. This can be changed or removed.
throttleTime: 300, // How often shuffle can be called on resize (in milliseconds).
staggerAmount: 15, // Transition delay offset for each item in milliseconds.
staggerAmountMax: 250, // Maximum stagger delay in milliseconds.
useTransforms: true, // Whether to use transforms or absolute positioning.
};
</script>
</body>
</html>
</code>```

答:
I had the same problem and fixed it by adding shuffle.min.js to my files instead of using a CDN. It worked using just:

```<code>var Shuffle = window.Shuffle;
var el = document.querySelector('#shuffle');
var shuffleInstance = new Shuffle(el,{
    itemSelector: '.item'
});
</code>```

I hope this helps.

Body:
This ought to be a simple enough question for those in the know- why am I getting this error in my console? I have tried following along with the code that appears under "usage" on the Shuffle homepage but I think the page is neglecting to include all of the steps for getting started with the library.

Here is my code on my index file located within the shufflejs folder created when the library was installed.

<!doctype html>

<meta charset="UTF-8">
<title>Shuffle Test</title>

Baseball

Tennis

iMac

Body:
I had the same problem and fixed it by adding shuffle.min.js to my files instead of using a CDN. It worked using just:

var Shuffle = window.Shuffle;
var el = document.querySelector('#shuffle');
var shuffleInstance = new Shuffle(el,{
    itemSelector: '.item'
});

I hope this helps.


问:
menu parent-child hover - stop animation - jquery
I have this example here: http://jsfiddle.net/QRChv/

Im trying to set it up so that when you hover over a child list item, its animation will start, but the parent doesnt invoke its .hover() function.

I dont know if this can be done, but is there a way to stop the parent from actually going through with its animation. So it wont actually do anything when its child list item is being hovered over.

I have a bunch of if statements setup for each list item, tried to keep it simple.

答:
I've updated your code:

http://jsfiddle.net/QRChv/4/

You need to stop event propagation, i.e. by returning false from the handler.

You could also call .stopPropagation() yourself on the event object


问:
Regex to test for restricted word in email address not working correctly
I have a regular expression that is giving me some trouble.    I want to restrict domains that have a certain word in them, such as 'foobar'.    I have a regex to test for a certain domain, such as foobar.com, but I also want to cover:

internal.foobar.com

foobarcorp.com

randomdomainwithfoobarinit.co.uk

foobar.net

Etc

So far my regex, covers almost everything correctly, except if there are characters before foobar   so myfoobar.com would not be caught, but foobarcorp.com would.    I have tried a mix of w+ and . and * after the @ sign with no luck finding the right combo.   Any ideas?   I tried to search around stack overflow, but most of the similar questions cover restricting a certain, already known domain where I am trying to cover domains I don't necessarily know about ahead of time.

Code:

```<code>var regex = /\w+@((?!foobar).)*\../i;
ngModel.$setValidity('restrict-email', regex.test(value));
</code>```

答:
Maybe something like:

/.*(foobar).*/i

I tested it on RegExr and it matched all the cases you mentioned.

Body:
I have a regular expression that is giving me some trouble.    I want to restrict domains that have a certain word in them, such as 'foobar'.    I have a regex to test for a certain domain, such as foobar.com, but I also want to cover:

internal.foobar.com

foobarcorp.com

randomdomainwithfoobarinit.co.uk

foobar.net

Etc

So far my regex, covers almost everything correctly, except if there are characters before foobar   so myfoobar.com would not be caught, but foobarcorp.com would.    I have tried a mix of w+ and . and * after the @ sign with no luck finding the right combo.   Any ideas?   I tried to search around stack overflow, but most of the similar questions cover restricting a certain, already known domain where I am trying to cover domains I don't necessarily know about ahead of time.

Code:

var regex = /\w+@((?!foobar).)*\../i;
ngModel.$setValidity('restrict-email', regex.test(value));


问:
What is the best practice for naming kafka topics?
We are new to kafka and we have a few teams working on a few applications that publish/subscribe events to/from each other. Since the kafka topic names are going to be shared across teams, is there any best practice for naming?

Basically we don't want to see team A naming a topic companyname-appname-events while team B naming another topic productname_functionB in totally different styles.

Any suggestions are appreciated !

Note this probably sounds more like the following asked question:
What should be naming convention of topic and partition of Kafka?
However, the author there was asking something more specific.

答:
https://cnr.sh/essays/how-paint-bike-shed-kafka-topic-naming-conventions helped us answering that same question.

As a summary this article suggest to follow similar best practices to naming databases and tables, and it provides these additional points of advice:

Avoid topic names based on things that change

Avoid topic names based on information that would be stored in other places

Avoid topic names based on their planned consumers/producers. This is essentially a special case of the first advice :D.

Decide casing early on, and consider enforcing it or at least check/monitor it. This way you catch offenders early on.


问:
MySQL ERROR 1241 (21000): Operand should contain 1 column(s) on returning entries before update
I need to SELECT all the unsent emails in tbl_emails table, while also updating their status to 'sent'. I select them into @temp first. Then update statuses. Finally, I select @temp.

```<code> CREATE DEFINER = root@localhost PROCEDURE get_unsent_emails ()
         SET @temp = (SELECT * FROM tbl_emails WHERE email_sent = 0);
         UPDATE tbl_emails
         SET email_sent = 1
         WHERE email_sent = 0;
         SELECT @temp;
</code>```

I get the following error:

MySQL ERROR 1241 (21000): Operand should contain 1 column(s)

~

答:
Why not using a TEMPORARY TABLE in the stored procedure.

```<code> CREATE DEFINER = root@localhost PROCEDURE get_unsent_emails ()
         CREATE TEMPORARY TABLE temp AS (SELECT * FROM tbl_emails WHERE email_sent = 0);
         UPDATE tbl_emails
         SET email_sent = 1
         WHERE email_sent = 0;
         SELECT * FROM temp;
         DROP TEMPORARY TABLE temp;
</code>```

Edit prevent race condition

Because off spencer7593's comment.

I assume there is a id column in the table tbl_emails what is the PRIMARY KEY.

```<code> CREATE DEFINER = root@localhost PROCEDURE get_unsent_emails ()
         CREATE TEMPORARY TABLE temp AS (SELECT * FROM tbl_emails WHERE email_sent = 0);
         UPDATE tbl_emails
         SET email_sent = 1
         WHERE email_sent = 0 AND id IN(SELECT id FROM temp);
         SELECT * FROM temp;
         DROP TEMPORARY TABLE temp;
</code>```

Body:
I need to SELECT all the unsent emails in tbl_emails table, while also updating their status to 'sent'. I select them into @temp first. Then update statuses. Finally, I select @temp.

 CREATE DEFINER = root@localhost PROCEDURE get_unsent_emails ()
         SET @temp = (SELECT * FROM tbl_emails WHERE email_sent = 0);
         UPDATE tbl_emails
         SET email_sent = 1
         WHERE email_sent = 0;
         SELECT @temp;

I get the following error:

MySQL ERROR 1241 (21000): Operand should contain 1 column(s)

~

Body:
Why not using a TEMPORARY TABLE in the stored procedure.

 CREATE DEFINER = root@localhost PROCEDURE get_unsent_emails ()
         CREATE TEMPORARY TABLE temp AS (SELECT * FROM tbl_emails WHERE email_sent = 0);
         UPDATE tbl_emails
         SET email_sent = 1
         WHERE email_sent = 0;
         SELECT * FROM temp;
         DROP TEMPORARY TABLE temp;

Edit prevent race condition

Because off spencer7593's comment.

I assume there is a id column in the table tbl_emails what is the PRIMARY KEY.

 CREATE DEFINER = root@localhost PROCEDURE get_unsent_emails ()
         CREATE TEMPORARY TABLE temp AS (SELECT * FROM tbl_emails WHERE email_sent = 0);
         UPDATE tbl_emails
         SET email_sent = 1
         WHERE email_sent = 0 AND id IN(SELECT id FROM temp);
         SELECT * FROM temp;
         DROP TEMPORARY TABLE temp;


问:
How to use ZeroBrane Studio IDE debugger when lua is compiled as c++
I have compiled Lua 5.3 as a 32 bit c++ DLL and exe. The DLL contains all the lua code except for lua.cpp and luac.cpp. The exe compiles lua.cpp and uses the DLL to run the lua interpreter. This works fine when running on its own from the command line. I wish to be able to run from the IDE using this DLL and exe.

If I replace /ZeroBraneStudio/bin/lua53.dll and lua53.exe with my own versions, I can run scripts (clicking the two green arrows). However, debugging does not work, giving the following error:

The procedure entry point luaL_addlstring could not be located in the dynamic link library lua53.dll.

I can see that this is happening because the debugger is making use of luasocket. \ZeroBraneStudio\bin\clibs53\socket\core.dll is dependent on lua53.dll, and is expecting it to contain lua compiled as c.

So, what is the correct solution to this - is it to compile luasocket as c++ as well?

(And, if so, does anybody have instructions/guidance for doing so? I have been unable to find anything on this.)

Thanks.

答:
I'm not sure how exactly the DLL was compiled, but the error message likely indicates that the luaL_addlstring and other functions are not exported by it. If the symbols are exported correctly, you should be able to load luasocket and get the debugging working. See this thread for the related discussion.

Also, you don't need to replace lua53 library and executable, as you can configure the IDE to use your own copy of it using path.lua53 configuration setting as described in the documentation.


问:
I need some help here with SQL Sum function group by dates and group
I have a table called Table1

```
CaseNumber | Year  | Month | Group    | HoursAttended
1          | 2010  |   1   |   16-20  |  8
2          | 2010  |   1   |   16-20  |  1
3          | 2010  |   2   |    0-5   |  2
4          | 2009  |   4   |    0-5   |  2
4          | 2009  |   4   |  16-20   |  5
```

If I wanted to have a result like this

```
Year | Month |GroupHours| GroupHourTotal
2010 | 1     |16-20     | 9
2010 | 3     |2         | 2
2009 | 4     |0-5       | 2
2009 | 4     |16-20     | 5
```

I tried this but I am getting incorrect results when the dates are not in the same month.
Any ideas?

```select Year,Month,group,hourattended,sum(hourattended)
from Table1
groupby Year,Month,hourattended,sum(hourattended)
order by year desc
```

答:
```<code>
select Year,Month,group,sum(hourattended)
from Table1
groupby Year,Monthorder by year desc
</code>```

Body:
I have a table called Table1

CaseNumber | Year  | Month | Group    | HoursAttended
1          | 2010  |   1   |   16-20  |  8
2          | 2010  |   1   |   16-20  |  1
3          | 2010  |   2   |    0-5   |  2
4          | 2009  |   4   |    0-5   |  2
4          | 2009  |   4   |  16-20   |  5

If I wanted to have a result like this

Year | Month |GroupHours| GroupHourTotal
2010 | 1     |16-20     | 9
2010 | 3     |2         | 2
2009 | 4     |0-5       | 2
2009 | 4     |16-20     | 5

I tried this but I am getting incorrect results when the dates are not in the same month.
Any ideas?

select Year,Month,group,hourattended,sum(hourattended)
from Table1
groupby Year,Month,hourattended,sum(hourattended)
order by year desc


问:
Using recode and case_when together
Table1$subject contains the variables "Biology", "Chemistry", and "Physics".
For Table 2, I want to recode this, to replace all instances of Biology/Chemistry with 1 and all instances of Physics with 0.

I tried the following code, since I believe this is achievable using the recode and case_when commands:

```<code>    Table2 <- recode(Table1, case_when(
    .$subject <= "biology" ~ 1,
    .$subject <= "chemistry" ~ 1,
    .$subject <= "physics" ~ 0))
</code>```

Currently, I get an error message saying "case_when must be a two-sided formula, not a logical". I'm new to R so I'm not quite sure what I'm doing wrong. Really grateful if anyone has any ideas!

答:
Both recode and case_when operate on vectors, not data frames. So to create a new data frame you need to first call mutate, and then within mutate use either recode or case_when to create a new column (or overwrite an existing one).

(Also, as of the latest dplyr release you no longer need to use the .$ when using case_when)

library(tibble)
library(dplyr)

df <- tribble(
  ~subject,
  "chemistry",
  "biology",
  "physics"
)

df %>%
  mutate(subject2 = case_when(
    subject == "chemistry" ~ 1,
    subject == "biology" ~ 1,
    subject == "physics" ~ 2,
  ))

#> # A tibble: 3 x 2
#>     subject subject2
#>       <chr>    <dbl>
#> 1 chemistry        1
#> 2   biology        1
#> 3   physics        2

df %>%
  mutate(subject2 = recode(
    subject,
    "chemistry" = 1,
    "biology" = 1,
    "physics" = 2,
  ))

#> # A tibble: 3 x 2
#>     subject subject2
#>       <chr>    <dbl>
#> 1 chemistry        1
#> 2   biology        1
#> 3   physics        2
```

Title: Using recode and case_when together

Body:
Table1$subject contains the variables "Biology", "Chemistry", and "Physics".
For Table 2, I want to recode this, to replace all instances of Biology/Chemistry with 1 and all instances of Physics with 0.

I tried the following code, since I believe this is achievable using the recode and case_when commands:

    Table2 <- recode(Table1, case_when(
    .$subject <= "biology" ~ 1,
    .$subject <= "chemistry" ~ 1,
    .$subject <= "physics" ~ 0))

Currently, I get an error message saying "case_when must be a two-sided formula, not a logical". I'm new to R so I'm not quite sure what I'm doing wrong. Really grateful if anyone has any ideas!


问:
In D3, how does one place text inside shapes that already have text attached to them?
I am currently working on the following d3 example where I'd like to place text inside of the arcs, similar to this example. However, whenever I try to append text to anything, the text just doesn't display. I've looked at the developer console, and it appears to be there, but it won't visually display on the screen. I used all the code provided in the first example, except I tried to add the following the the arc elements:

```<code>("the d3 element").enter().append("svg:text").text("???")

("the d3 element").enter().append("text").text("???")

("the d3 element").append("svg:text").text("???")

("the d3 element").append("text").text("???")
</code>```

Aside from cutting off some of the styling changes, it seems like no matter where I put any of this code, it just doesn't want to work for me. I would appreciate and help!

答:
"whenever I try to append text to anything, the text just doesn't display": Text cannot be appended to most svg elements. You can append text to the svg itself or a g, but you cannot append it to a path, rect, circle, etc.

One of the most common methods of dealing with this is to use g elements to place a shape and text while binding data to the g. Using a transform on theg will translate shape and text - great for things like circles and rectangles.

There are several other approaches you can use to overlay text on svg elements:

Use the positioning attributes of an element to set the x and y attributes of text so that you can place text over top of an element.

Use a path as a text path to place text (as in your example)

Use utility methods such as centroid (for arcs or geopaths for example)

Find the bounding box of elements and place elements using this information.

These options help place, but won't make sure that the text falls within the bounds of a shape - that is different complication.

For arcs, one option is to use a circular path as a text-path where the circle has a radius between that of the inner and outer radius of your arc - then place the text using a text offset that reflects the start angle - or make an arc for each piece of text. The general mechanism is shown below (note it can't use a circle element as svg textPaths must follow paths):

var svg=d3.select("body")
  .append("svg")
  .attr("height",400)
  .attr("width",400)
  .attr("transform","translate(200,200)")

var arc = d3.arc()
  .innerRadius(50)
  .outerRadius(100)
  .startAngle(0)
  .endAngle(2);

var arcText = d3.arc()
  .innerRadius(75)
  .outerRadius(75)
  .startAngle(0)
  .endAngle(2);

var arc = svg.append("path")
  .attr("d",arc)
  .attr("fill","steelblue")

var textPath = svg.append("path")
  .attr("d",arcText)
  .attr("id","textpath")
  .attr("fill","none")
  .attr("stroke","black");

var text = svg.append("text")
  .append("textPath")
  .attr("xlink:href","#textpath")
  .text("title")
  .attr("startOffset", "25%")  // the bottom of the arc is from 50%-100%, the top from 0 to 50%
  .style("text-anchor","middle")```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script></code>```

The above mechanism is very similar to the example you link to - it appends text using the arcs as text paths. The example you reference uses text paths of the visible arc(donut) segments themselves - and offsets the x,y positions to move the text into the arc itself (as opposed to on the arc).

Note that I've used v4, as opposed to v3 as in the linked example.

Body:
I am currently working on the following d3 example where I'd like to place text inside of the arcs, similar to this example. However, whenever I try to append text to anything, the text just doesn't display. I've looked at the developer console, and it appears to be there, but it won't visually display on the screen. I used all the code provided in the first example, except I tried to add the following the the arc elements:

("the d3 element").enter().append("svg:text").text("???")

("the d3 element").enter().append("text").text("???")

("the d3 element").append("svg:text").text("???")

("the d3 element").append("text").text("???")

Aside from cutting off some of the styling changes, it seems like no matter where I put any of this code, it just doesn't want to work for me. I would appreciate and help!

Body:
"whenever I try to append text to anything, the text just doesn't display": Text cannot be appended to most svg elements. You can append text to the svg itself or a g, but you cannot append it to a path, rect, circle, etc.

One of the most common methods of dealing with this is to use g elements to place a shape and text while binding data to the g. Using a transform on theg will translate shape and text - great for things like circles and rectangles.

There are several other approaches you can use to overlay text on svg elements:

Use the positioning attributes of an element to set the x and y attributes of text so that you can place text over top of an element.

Use a path as a text path to place text (as in your example)

Use utility methods such as centroid (for arcs or geopaths for example)

Find the bounding box of elements and place elements using this information.

These options help place, but won't make sure that the text falls within the bounds of a shape - that is different complication.

For arcs, one option is to use a circular path as a text-path where the circle has a radius between that of the inner and outer radius of your arc - then place the text using a text offset that reflects the start angle - or make an arc for each piece of text. The general mechanism is shown below (note it can't use a circle element as svg textPaths must follow paths):

var svg=d3.select("body")
  .append("svg")
  .attr("height",400)
  .attr("width",400)
  .attr("transform","translate(200,200)")

var arc = d3.arc()
  .innerRadius(50)
  .outerRadius(100)
  .startAngle(0)
  .endAngle(2);

var arcText = d3.arc()
  .innerRadius(75)
  .outerRadius(75)
  .startAngle(0)
  .endAngle(2);

var arc = svg.append("path")
  .attr("d",arc)
  .attr("fill","steelblue")

var textPath = svg.append("path")
  .attr("d",arcText)
  .attr("id","textpath")
  .attr("fill","none")
  .attr("stroke","black");

var text = svg.append("text")
  .append("textPath")
  .attr("xlink:href","#textpath")
  .text("title")
  .attr("startOffset", "25%")  // the bottom of the arc is from 50%-100%, the top from 0 to 50%
  .style("text-anchor","middle")

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

The above mechanism is very similar to the example you link to - it appends text using the arcs as text paths. The example you reference uses text paths of the visible arc(donut) segments themselves - and offsets the x,y positions to move the text into the arc itself (as opposed to on the arc).

Note that I've used v4, as opposed to v3 as in the linked example.


问:
what is the purpose of '&' in insert statement while entering multiple records
Example :

```<code> INSERT into values(&id,'&name',&age);
</code>```

While executing the statement , it's showing a popup like 'please enter the substitution variable'

So my question :
what does substitution variable means ? And what is inner process happening with '&' symbol?

答:
& is a Bitwise AND operator, take a look here for more details.

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-and-transact-sql

Body:
Example :

 INSERT into values(&id,'&name',&age);

While executing the statement , it's showing a popup like 'please enter the substitution variable'

So my question :
what does substitution variable means ? And what is inner process happening with '&' symbol?


问:
@monthly cron job is not reliable
Our customer wants us to create a report every month.

In the past, we used a @monthly cron job for this task.

But this is not reliable:

The server could be down in this minute. Cron does not re-run those jobs

If the server is up, the database could be unreachable in this moment.

If the server is up and DB is up, there could be a third party system which is not reachable

There could be a software bug.

What can I do, to be sure that the report gets created monthly?

It is a Django based web application

答:
You should write some script that will test conditions and perform all required operations.

```<code>if is_work_finished_less_then_month_ago():
    return
else:
    try:
        generate_normal_report()
    except some_error as e:
        report_about_error(e)
</code>```

Then run it every hour or day.

If you afraid of too many error_reports then do the same thing in report_about_error() method: check last time you sent report and do not send it if it's too often.

Title: @monthly cron job is not reliable

Body:
You should write some script that will test conditions and perform all required operations.

if is_work_finished_less_then_month_ago():
    return
else:
    try:
        generate_normal_report()
    except some_error as e:
        report_about_error(e)

Then run it every hour or day.

If you afraid of too many error_reports then do the same thing in report_about_error() method: check last time you sent report and do not send it if it's too often.


问:
Javascript assign only intersection of source to target object
I have two object, and I want to update the target object values from source, but only the values which exists in the target already.

```<code>const target = {
    a: 1,
    b: 2,
    c: {
        c_a: 3,
        c_b: 4,
    }
}

const source = {
    a: 10,
    c: {
        c_a: 30,
        c_d: 50,
    },
    d: 60
}

const result = assignOnlyIntersection(target, source);

JSON.stringify(result)

// {
//    a: 10,
//    b: 2,
//    c: {
//        c_a: 30,
//        c_b: 4
//    }
// }
</code>```

Is there a good way in ES6 for this? If not, does lodash has a feature for this? If not how can it be solved in a nice way?

答:
another ES6 approach

non-mutative:

```<code>const intersector = (target = {}, source = {}) => {
  return Object.keys(source).reduce((acc, prop) => {
    if (target.hasOwnProperty(prop)) {
      if (typeof source[prop] === 'object' && source[prop] !== null) {
        acc[prop] = intersector(target[prop], source[prop]);
      }
      else {
        acc[prop] = source[prop];
      }
    }
    return acc;
  }, {});
}
</code>```

mutative:

```<code>const intersector = (target = {}, source = {}) => {
  return Object.keys(source).reduce((acc, prop) => {
    if (target.hasOwnProperty(prop)) {
      if (typeof source[prop] === 'object' && source[prop] !== null) {
        acc[prop] = intersector(target[prop], source[prop]);
      }
      else {
        acc[prop] = source[prop];
      }
      target[prop] = acc[prop];
    }
    return acc;
  }, target);
};
</code>```

Body:
I have two object, and I want to update the target object values from source, but only the values which exists in the target already.

const target = {
    a: 1,
    b: 2,
    c: {
        c_a: 3,
        c_b: 4,
    }
}

const source = {
    a: 10,
    c: {
        c_a: 30,
        c_d: 50,
    },
    d: 60
}

const result = assignOnlyIntersection(target, source);

JSON.stringify(result)

// {
//    a: 10,
//    b: 2,
//    c: {
//        c_a: 30,
//        c_b: 4
//    }
// }

Is there a good way in ES6 for this? If not, does lodash has a feature for this? If not how can it be solved in a nice way?

Body:
another ES6 approach

non-mutative:

const intersector = (target = {}, source = {}) => {
  return Object.keys(source).reduce((acc, prop) => {
    if (target.hasOwnProperty(prop)) {
      if (typeof source[prop] === 'object' && source[prop] !== null) {
        acc[prop] = intersector(target[prop], source[prop]);
      }
      else {
        acc[prop] = source[prop];
      }
    }
    return acc;
  }, {});
}

mutative:

const intersector = (target = {}, source = {}) => {
  return Object.keys(source).reduce((acc, prop) => {
    if (target.hasOwnProperty(prop)) {
      if (typeof source[prop] === 'object' && source[prop] !== null) {
        acc[prop] = intersector(target[prop], source[prop]);
      }
      else {
        acc[prop] = source[prop];
      }
      target[prop] = acc[prop];
    }
    return acc;
  }, target);
};


问:
How can I hide button before printing and show it when printind process has been completed?
I have a print button with id="print_req". I wrote some Javascript code for printing a page, which is triggered by clicking on this button, and I also want to hide this button before printing, and show it after whole printing process.i mean not to print button in my printed document. Here is my code:

```<code>$(document).ready(function(){
    $("#print_req").click(function(){
        $("#print_req").css("display","none");
        window.print();
    });

    $("#print_req").css("display","block");
    return false;
});
</code>```

This correctly hide that button, but when the printing process get done, the button won't show again! What is the problem?

答:
Simply Do this...

$(document).ready(function(){

```<code>$('#print').on('click',function(){
  $('#print').hide();
  window.print();
  $('#print').show();

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

Body:
I have a print button with id="print_req". I wrote some Javascript code for printing a page, which is triggered by clicking on this button, and I also want to hide this button before printing, and show it after whole printing process.i mean not to print button in my printed document. Here is my code:

$(document).ready(function(){
    $("#print_req").click(function(){
        $("#print_req").css("display","none");
        window.print();
    });

    $("#print_req").css("display","block");
    return false;
});

This correctly hide that button, but when the printing process get done, the button won't show again! What is the problem?

Body:
Simply Do this...

$(document).ready(function(){

$('#print').on('click',function(){
  $('#print').hide();
  window.print();
  $('#print').show();

     });
});


问:
MaxScript - Spline Smooth?
I tried to make this script in 3dsmax 2017 using listener but it does not record just that action for spline - smooth (like in the screenshot).

When I select subobject level - Vertex, and select all, then I right click and choose smooth, , I got result I need.
I need to make it using script because I have a number of splines that need to be smooth.
any help appreciated.

```<code>select $Line001
subobjectLevel = 1
modPanel.setCurrentObject $.baseObject
</code>```

I tried couple of script that I find online but they don't work in 3dsmax 2017.
So if you have solution example that work in 3dsmax 2017.screenshot

答:
See the SplineShape topic in the maxscript reference.</p>

```<code>for spline = 1 to numSplines $
    where (selectedKnots = getKnotSelection $ spline).count > 0 do
        for knot in selectedKnots do setKnotType $ spline knot #smooth

updateShape $
</code>```

Title: MaxScript - Spline Smooth?

Body:
I tried to make this script in 3dsmax 2017 using listener but it does not record just that action for spline - smooth (like in the screenshot).

When I select subobject level - Vertex, and select all, then I right click and choose smooth, , I got result I need.
I need to make it using script because I have a number of splines that need to be smooth.
any help appreciated.

select $Line001
subobjectLevel = 1
modPanel.setCurrentObject $.baseObject

I tried couple of script that I find online but they don't work in 3dsmax 2017.
So if you have solution example that work in 3dsmax 2017.screenshot

Body:
See the SplineShape topic in the maxscript reference.

for spline = 1 to numSplines $
    where (selectedKnots = getKnotSelection $ spline).count > 0 do
        for knot in selectedKnots do setKnotType $ spline knot #smooth

updateShape $


问:
Listing by alphabetical order not ignoring special characters like "Ó"
I got some search results listed alphabetically by groups like this:

A --
Andre, Amalia...

B --
Bart, Bruno,
etc...

The problem is, if some name starts with a special character like "Ólga"
i got another group like this:

Ó --
Olga

My question: How to list names starting with "Ó" inside the group "O"? Thanks.

My code:

```<code><?php
$previous = null;
foreach($rows as $row1) {
 $firstLetter = substr($row1->titolo, 0, 1);
  if($previous !== $firstLetter) echo $firstLetter."<br />";
$previous = $firstLetter;
  echo $row1->titolo;
}
?>
</code>```

答:
In PHP you can use the Collator class

Provides string comparison capability with support for appropriate locale-sensitive sort orderings

http://docs.php.net/manual/en/class.collator.php

Body:
I got some search results listed alphabetically by groups like this:

A --
Andre, Amalia...

B --
Bart, Bruno,
etc...

The problem is, if some name starts with a special character like "Ólga"
i got another group like this:

Ó --
Olga

My question: How to list names starting with "Ó" inside the group "O"? Thanks.

My code:

<?php
$previous = null;
foreach($rows as $row1) {
 $firstLetter = substr($row1->titolo, 0, 1);
  if($previous !== $firstLetter) echo $firstLetter."
";
$previous = $firstLetter;
  echo $row1->titolo;
}
?>


问:
Div take the height of another div even when the later is smaller
I'm developing a web page and in it I have a list of news, divs with 2 other divs inside, an image on the left, and the title, date and the first 30 words of the news on the right. I want the image div to take the height of the text div, no matter what the size of the image is. The images usually don't have the same size/aspect ratio. I prefer to avoid fixed dimensions, since I want it to be responsive. By the way I'm using Bootstrap 3.3.7.

Here an example of what I have so far.

This is my HTML

```<code><!-- First News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4 news-img-div">
    <img src="https://fakeimg.pl/412x112/" alt="img_1" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 1</h4>
    <p>Nov 6, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Second News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4  news-img-div">
    <img src="https://fakeimg.pl/350x232/" alt="img_2" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 2</h4>
    <p>Nov 5, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Third News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4 news-img-div">
    <img src="https://fakeimg.pl/243x242/" alt="img_curso" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 3</h4>
    <p>Nov 4, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
</code>```

And this is my CSS (for visualization purposes)

```<code>.news-img-div {
  background-color: red;
}
.news-text-div {
  background-color:aqua;
}
</code>```

I set a background color to the divs for better visualization. You might need to expand the result tab so the image and the text stay in the same row.

Is there a way to accomplish using only CSS? Otherwise I welcome solutions with js.

答:
I see you tagged the post with jQuery, so here's one option for you...

http://jsfiddle.net/yLyv9fyx/3/

Or see below (NOTE: I believe the Script Error reported is caused by cross-domain script sourcing for bootstrap, though someone can correct me if this is inaccurate).

$(".news-img-div").each(function() {
  var textDivHeight = $(this).parent().find("div.news-text-div").height();
  $(this).height(textDivHeight);
  var imgHeight = $(this).find("img.img-responsive").height();
  if (imgHeight > textDivHeight) $(this).find("img.img-responsive").height(textDivHeight);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.news-img-div {
  background-color: red;
}

.news-text-div {
  background-color: aqua;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

News Title 1

Nov 6, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

News Title 2

Nov 5, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

News Title 3

Nov 4, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

```
</div>
</div>
</p>

<p><strong>UPDATE:</strong></p>

<p>This should be an improvement, but it looks like you already have a solution: http://jsfiddle.net/yLyv9fyx/5/</p>

<p>Javascript changed to:</p>

```function updateImgDiv() {
    $(".news-img-cont").each(function() {
        var textDivHeight = $(this).parent().find("div.news-text-cont").height();
        $(this).height(textDivHeight);
        var imgHeight = $(this).find("img.img-responsive").height();
        if (imgHeight>textDivHeight) $(this).find("img.img-responsive").height(textDivHeight);
    });
}
updateImgDiv();
$( window ).resize(function() {
    updateImgDiv();
});
```

Body:
I'm developing a web page and in it I have a list of news, divs with 2 other divs inside, an image on the left, and the title, date and the first 30 words of the news on the right. I want the image div to take the height of the text div, no matter what the size of the image is. The images usually don't have the same size/aspect ratio. I prefer to avoid fixed dimensions, since I want it to be responsive. By the way I'm using Bootstrap 3.3.7.

Here an example of what I have so far.

This is my HTML

News Title 1

Nov 6, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

News Title 2

Nov 5, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

News Title 3

Nov 4, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.

    See More

And this is my CSS (for visualization purposes)

.news-img-div {
  background-color: red;
}
.news-text-div {
  background-color:aqua;
}

I set a background color to the divs for better visualization. You might need to expand the result tab so the image and the text stay in the same row.

Is there a way to accomplish using only CSS? Otherwise I welcome solutions with js.

Body:
I see you tagged the post with jQuery, so here's one option for you...

http://jsfiddle.net/yLyv9fyx/3/

Or see below (NOTE: I believe the Script Error reported is caused by cross-domain script sourcing for bootstrap, though someone can correct me if this is inaccurate).

$(".news-img-div").each(function() {
  var textDivHeight = $(this).parent().find("div.news-text-div").height();
  $(this).height(textDivHeight);
  var imgHeight = $(this).find("img.img-responsive").height();
  if (imgHeight > textDivHeight) $(this).find("img.img-responsive").height(textDivHeight);
});

.news-img-div {
  background-color: red;
}

.news-text-div {
  background-color: aqua;
}

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<!-- First News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4 news-img-div">
    <img src="https://fakeimg.pl/412x112/" alt="img_1" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 1</h4>
    <p>Nov 6, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Second News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4  news-img-div">
    <img src="https://fakeimg.pl/350x232/" alt="img_2" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 2</h4>
    <p>Nov 5, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>
<!-- Third News -->
<div class="container-fluid panel panel-default">
  <div class="col-xs-12 col-sm-4 news-img-div">
    <img src="https://fakeimg.pl/243x242/" alt="img_curso" class="img-responsive">
  </div>
  <div class="col-xs-12 col-sm-8 news-text-div">
    <h4>News Title 3</h4>
    <p>Nov 4, 2017</p>
    <p class="text-justify">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus eu vehicula turpis. Donec tristique consequat libero a dapibus. Quisque in dolor tellus. Suspendisse auctor in libero non porta. Aliquam eu.</p>
    <a href="" class="btn btn-primary" role="button">See More</a>
  </div>
</div>

UPDATE:

This should be an improvement, but it looks like you already have a solution: http://jsfiddle.net/yLyv9fyx/5/

Javascript changed to:

function updateImgDiv() {
    $(".news-img-cont").each(function() {
        var textDivHeight = $(this).parent().find("div.news-text-cont").height();
        $(this).height(textDivHeight);
        var imgHeight = $(this).find("img.img-responsive").height();
        if (imgHeight>textDivHeight) $(this).find("img.img-responsive").height(textDivHeight);
    });
}
updateImgDiv();
$( window ).resize(function() {
    updateImgDiv();
});


问:
How to use non-capturing groups in this example
The following regex:

```<code>(\d+\.?\d+?)px \/\* (\d+) \*\/
</code>```

matches 5.5px /* 1440 */ in:

```<code>position: relative;
padding: 5.5px /* 1440 */ 9px /* 1440 */;
border: 0;
</code>```

but not 9px /* 1440 */.

This regex does match both 5.5px /* 1440 */ and 9px /* 1440 */ but captures groups I do not wish to capture.

```<code>(\d+(\.)?(\d+)?)px \/\* (\d+) \*\/
</code>```

How can I write (\d+(\.)?(\d+)?)px \/\* (\d+) \*\/ without capturing (\.) and (\d+)?

答:
Brief

As per my original comment...

Your regex is saying:

\d+ Match any digit one or more times

\.? Match the dot character . literally zero or one time

\d+? Match one or more digits, but as few as possible (lazy quantifier).

Realistically, the error is on the last line and changing +? to * should fix your issue, however, the following approach is usually regarded as the better method to catching decimal point numbers as it doesn't allow your regex to catch numbers ending in decimal points without number following it (i.e. 10. - this will be matched by \d+\.?\d*, but it will not be matched by \d+(?:\.\d+)?)

Code

See regex in use here

```<code>(\d+(?:\.\d+)?)px \/\* (\d+) \*\/
</code>```

The regex above uses \d+(?:\.\d+)?

Explanation

\d+ Match one or more digits

(?:\.\d+)? Match the following zero or one time

\. Match the dot character . literally

\d+ Match one or more digits

Body:
The following regex:

(\d+\.?\d+?)px \/\* (\d+) \*\/

matches 5.5px /* 1440 */ in:

position: relative;
padding: 5.5px /* 1440 */ 9px /* 1440 */;
border: 0;

but not 9px /* 1440 */.

This regex does match both 5.5px /* 1440 */ and 9px /* 1440 */ but captures groups I do not wish to capture.

(\d+(\.)?(\d+)?)px \/\* (\d+) \*\/

How can I write (\d+(\.)?(\d+)?)px \/\* (\d+) \*\/ without capturing (\.) and (\d+)?

Body:
Brief

As per my original comment...

Your regex is saying:

\d+ Match any digit one or more times

\.? Match the dot character . literally zero or one time

\d+? Match one or more digits, but as few as possible (lazy quantifier).

Realistically, the error is on the last line and changing +? to * should fix your issue, however, the following approach is usually regarded as the better method to catching decimal point numbers as it doesn't allow your regex to catch numbers ending in decimal points without number following it (i.e. 10. - this will be matched by \d+\.?\d*, but it will not be matched by \d+(?:\.\d+)?)

Code

See regex in use here

(\d+(?:\.\d+)?)px \/\* (\d+) \*\/

The regex above uses \d+(?:\.\d+)?

Explanation

\d+ Match one or more digits

(?:\.\d+)? Match the following zero or one time

\. Match the dot character . literally

\d+ Match one or more digits


问:
Angular2: How to enable save button if any model value changed on edit page
I am new for angular 2. I have a page where we can edit details of customer profile. How to enable save button if any property of has been changed. I know it is possible in angular1 by using $watch.</p>

答:
you can use form control validation for it.
some thing like this in html template:

```<code> <form fxLayout="column" [formGroup]="form">
          <mat-form-field class="mb-1">
            <input matInput [(ngModel)]="userProfileChangeModel.firstName" placeholder="نام"
                   [formControl]="form1.controls['fname']">
            <small *ngIf="form1.controls['fname'].hasError('required') && form1.controls['fname'].touched"
                   class="mat-text-warn">لطفا نام را وارد نمایید.
            </small>
            <small *ngIf="form1.controls['fname'].hasError('minlength') && form1.controls['fname'].touched"
                   class="mat-text-warn">نام باید حداقل 2 کاراکتر باشد.
            </small>
            <small *ngIf="form1.controls['fname'].hasError('pattern') && form1.controls['fname'].touched"
                   class="mat-text-warn">لطفا از حروف فارسی استفاده نمائید.
            </small>

          </mat-form-field>
           <mat-card-actions>
            <button mat-raised-button (click)="editUser()" color="primary" [disabled]="!form1.valid" type="submit">
              ذخیره
            </button>
          </mat-card-actions>
        </form>
</code>```

and like this in ts file:

```<code>    this.form = this.bf.group({
  fname: [null, Validators.compose([
    Validators.required,
    Validators.minLength(2),
    Validators.maxLength(20),
    Validators.pattern('^[\u0600-\u06FF, \u0590-\u05FF]*$')])],
});
</code>```

if:

```<code>[disabled]="!form1.valid"
</code>```

is valid save button will be active

bast regards.

Body:
you can use form control validation for it.
some thing like this in html template:

 <form fxLayout="column" [formGroup]="form">
          <mat-form-field class="mb-1">
            <input matInput [(ngModel)]="userProfileChangeModel.firstName" placeholder="نام"
                   [formControl]="form1.controls['fname']">
            <small *ngIf="form1.controls['fname'].hasError('required') && form1.controls['fname'].touched"
                   class="mat-text-warn">لطفا نام را وارد نمایید.
            </small>
            <small *ngIf="form1.controls['fname'].hasError('minlength') && form1.controls['fname'].touched"
                   class="mat-text-warn">نام باید حداقل 2 کاراکتر باشد.
            </small>
            <small *ngIf="form1.controls['fname'].hasError('pattern') && form1.controls['fname'].touched"
                   class="mat-text-warn">لطفا از حروف فارسی استفاده نمائید.
            </small>

          </mat-form-field>
           <mat-card-actions>
            <button mat-raised-button (click)="editUser()" color="primary" [disabled]="!form1.valid" type="submit">
              ذخیره
            </button>
          </mat-card-actions>
        </form>

and like this in ts file:

    this.form = this.bf.group({
  fname: [null, Validators.compose([
    Validators.required,
    Validators.minLength(2),
    Validators.maxLength(20),
    Validators.pattern('^[\u0600-\u06FF, \u0590-\u05FF]*$')])],
});

if:

[disabled]="!form1.valid"

is valid save button will be active

bast regards.