问:
Why does max behave differently if I pass a lambda as key compared to applying it directly to a map of the original iterable with the same lambda?
I'm trying to understand how the key argument works in the max function, coming from a problem of finding the closest integer to 0 from a list, and using the positive value in case of having the same positive and negative value in the list.

I have found this to be an efficient solution online, given a list of integers x:

```<code>print(max(a, key=lambda x: (-abs(x), x), default=0))
</code>```

This returns a single integer, where I would expect to return a tuple, given that the lambda will transform every element of x into a tuple, then I did this:

```<code>b = list(map(lambda x: (-abs(x), x), a))
max(b)
</code>```

And this second example returns a tuple. Why does the first one return a single elements when it is comparing tuples generated by the lambda?

答:
You are comparing two different things.

For your first case, if we look at the docs: https://docs.python.org/3/library/functions.html#max

max(arg1, arg2, *args[, key])

  Return the largest item in an iterable or the largest of two or more arguments. The key argument specifies a one-argument ordering function like that used for list.sort().

Which means that the key lambda x: (-abs(x), x) is a ordering function, which means that for every x in iterable a, (-abs(x), x) is evaluated and is used to order the items for finding out the maximum element of the iterator, and according to that ordering, 1 is the maximum element

```<code>In [24]: a = [1,4,6,-8,-10]

In [40]: print(max(a, key=lambda x: (-abs(x), x), default=0))
1
</code>```

For the second case, if we look at the docs: https://docs.python.org/3/library/functions.html#map

map(function, iterable, ...)

  Return an iterator that applies function to every item of iterable, yielding the results

Which means that the function lambda x: (-abs(x), x) is applied to every element x of a, so we get back (-abs(x), x) for every x, and the max is applied on the updated iterator, which is the largest tuple (-1,1)

```<code>In [25]: b = list(map(lambda x: (-abs(x), x), a))

In [26]: b
Out[26]: [(-1, 1), (-4, 4), (-6, 6), (-8, -8), (-10, -10)]

In [27]: max(b)
Out[27]: (-1, 1)
</code>```

Body:
I'm trying to understand how the key argument works in the max function, coming from a problem of finding the closest integer to 0 from a list, and using the positive value in case of having the same positive and negative value in the list.

I have found this to be an efficient solution online, given a list of integers x:

print(max(a, key=lambda x: (-abs(x), x), default=0))

This returns a single integer, where I would expect to return a tuple, given that the lambda will transform every element of x into a tuple, then I did this:

b = list(map(lambda x: (-abs(x), x), a))
max(b)

And this second example returns a tuple. Why does the first one return a single elements when it is comparing tuples generated by the lambda?

Body:
You are comparing two different things.

For your first case, if we look at the docs: https://docs.python.org/3/library/functions.html#max

max(arg1, arg2, *args[, key])

  Return the largest item in an iterable or the largest of two or more arguments. The key argument specifies a one-argument ordering function like that used for list.sort().

Which means that the key lambda x: (-abs(x), x) is a ordering function, which means that for every x in iterable a, (-abs(x), x) is evaluated and is used to order the items for finding out the maximum element of the iterator, and according to that ordering, 1 is the maximum element

In [24]: a = [1,4,6,-8,-10]

In [40]: print(max(a, key=lambda x: (-abs(x), x), default=0))
1

For the second case, if we look at the docs: https://docs.python.org/3/library/functions.html#map

map(function, iterable, ...)

  Return an iterator that applies function to every item of iterable, yielding the results

Which means that the function lambda x: (-abs(x), x) is applied to every element x of a, so we get back (-abs(x), x) for every x, and the max is applied on the updated iterator, which is the largest tuple (-1,1)

In [25]: b = list(map(lambda x: (-abs(x), x), a))

In [26]: b
Out[26]: [(-1, 1), (-4, 4), (-6, 6), (-8, -8), (-10, -10)]

In [27]: max(b)
Out[27]: (-1, 1)


来源: stackexchange

问:
The Drawer is transparent
The drawer's background is transparent. I have tried to hot reload the entire code which i wrote from scratch again, yet it didn't work.

```<code>drawer: ListView(
        children: <Widget>[
          DrawerHeader(
            padding:
                EdgeInsets.symmetric(vertical: 20.0, horizontal: 100.0),
            child: Text('Hi!'),
            curve: Curves.easeInCubic,
          ),
          ListTile(
            contentPadding: EdgeInsets.all(100.0),
            leading: Icon(Icons.home),
            trailing: Icon(Icons.donut_small),
            title: Text(
              'Home',
              style: TextStyle(color: Colors.white),
            ),
          )
        ],
      ),
</code>```

Reference Image

答:
You are using DrawerHeader incorrectly. DrawerHeader is only the top portion of the Drawer that you want to open. You should use it to set a title for that Drawer and probably a different background color.
Try this instead:

```<code>         Drawer(
          child: ListView(
            children: <Widget>[
              DrawerHeader(
                padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 100.0),
                child: Text('Hi!'),
                curve: Curves.easeInCubic,
              ),
              ListTile(
                contentPadding: EdgeInsets.all(100.0),
                leading: Icon(Icons.home),
                trailing: Icon(Icons.donut_small),
                title: Text(
                  'Home',
                  style: TextStyle(color: Colors.white),
                ),
              )
            ],
          ),
        ),
</code>```

ContentLicense: CC BY-SA 4.0

Title: The Drawer is transparent

Body:
The drawer's background is transparent. I have tried to hot reload the entire code which i wrote from scratch again, yet it didn't work.

drawer: ListView(
        children: <Widget>[
          DrawerHeader(
            padding:
                EdgeInsets.symmetric(vertical: 20.0, horizontal: 100.0),
            child: Text('Hi!'),
            curve: Curves.easeInCubic,
          ),
          ListTile(
            contentPadding: EdgeInsets.all(100.0),
            leading: Icon(Icons.home),
            trailing: Icon(Icons.donut_small),
            title: Text(
              'Home',
              style: TextStyle(color: Colors.white),
            ),
          )
        ],
      ),

Reference Image

Body:
You are using DrawerHeader incorrectly. DrawerHeader is only the top portion of the Drawer that you want to open. You should use it to set a title for that Drawer and probably a different background color.
Try this instead:

         Drawer(
          child: ListView(
            children: <Widget>[
              DrawerHeader(
                padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 100.0),
                child: Text('Hi!'),
                curve: Curves.easeInCubic,
              ),
              ListTile(
                contentPadding: EdgeInsets.all(100.0),
                leading: Icon(Icons.home),
                trailing: Icon(Icons.donut_small),
                title: Text(
                  'Home',
                  style: TextStyle(color: Colors.white),
                ),
              )
            ],
          ),
        ),


问:
Open new form in dialogbox from view
I have a form called PCBatchInfo. In this form, there only have 4 field which is BatchNo, Inspector, Start date, and End Date. I will then open this form and insert the information.

On other side, I have Computer form with many field which is use to show all document in view.

PCBatchInfo and Computer form have same field which is PBatchNo. So, what I will do is, I insert BatchNo in PCBatchInfo. Then when I save it, it will also change BatchNo for all Computer document.

I want to open new PCBatchInfo form in dialogbox in view. As I do some research, dialogbox only can open existing document using Queryopendocument.

Let's say, I click button in view then it will show dialogbox with PCBatchInfo form. I insert all information required, then save. Can I open this form using dialogbox from view using a button?

UPDATE

I have found a way to use dialogbox but couldn't get to save the form. Code is as below.

```<code>varResult = ws.DialogBox("PCBatchInfo", True, True, False, False, True, False, "Please insert all information below", dialogDoc, False, False, True)
    If varResult Then
        batchValue = dialogDoc.BBatchNo(0)
        inspectorValue = dialogDoc.BInspector(0)
        dateValue1 = dialogDoc.BStart(0)
        dateValue2 = dialogDoc.Bend(0)
    End If
</code>```

Can anyone help me how can I save form from dialogBox? Thanks in advance!

答:
In order to use the dialogBox you need to have a document. This document needs to only in memory.
Before and after the call to DialogBox you can do what every you like with that document. You can also set a Form field. The form is only used to display the data. The document contains the data, and can be changed or just simply saved.

If you want to show the dialogbox from the selected document in the view then look at NotesUIView.caretNoteId which returns the NoteID of the current selected document.

Title: Open new form in dialogbox from view

Body:
I have a form called PCBatchInfo. In this form, there only have 4 field which is BatchNo, Inspector, Start date, and End Date. I will then open this form and insert the information.

On other side, I have Computer form with many field which is use to show all document in view.

PCBatchInfo and Computer form have same field which is PBatchNo. So, what I will do is, I insert BatchNo in PCBatchInfo. Then when I save it, it will also change BatchNo for all Computer document.

I want to open new PCBatchInfo form in dialogbox in view. As I do some research, dialogbox only can open existing document using Queryopendocument.

Let's say, I click button in view then it will show dialogbox with PCBatchInfo form. I insert all information required, then save. Can I open this form using dialogbox from view using a button?

UPDATE

I have found a way to use dialogbox but couldn't get to save the form. Code is as below.

varResult = ws.DialogBox("PCBatchInfo", True, True, False, False, True, False, "Please insert all information below", dialogDoc, False, False, True)
    If varResult Then
        batchValue = dialogDoc.BBatchNo(0)
        inspectorValue = dialogDoc.BInspector(0)
        dateValue1 = dialogDoc.BStart(0)
        dateValue2 = dialogDoc.Bend(0)
    End If

Can anyone help me how can I save form from dialogBox? Thanks in advance!


问:
Bootstrap carousel for dynamic content in Wordpress
So I've created a bootstrap carousel in WordPress and it works fine. My only problem is that when I click on the image it doesn't take me to the specific article. How Can I solve this? Here is my Code:

```<code><div class="container slider-container">
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
  <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
    </ol>

<!-- Wrapper for slides -->
 <div class="carousel-inner" role="listbox">
<?php $slider = get_posts(array('post_type' => 'post', 'posts_per_page' => 3)); ?>
  <?php $count = 0; ?>
  <?php foreach($slider as $slide): ?>
  <div class="item <?php echo ($count == 0) ? 'active' : ''; ?>">
      <a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
        <img src="<?php echo wp_get_attachment_url( get_post_thumbnail_id($slide->ID)) ?>" class="img-responsive"/>
    </a>
  </div>
  <?php $count++; ?>
<?php endforeach; ?>
</code>```

```<code><!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next">
       <span class="glyphicon glyphicon-chevron-right"></span>
       <span class="sr-only">Next</span>
    </a>
  </div>
</div>
</code>```

答:
here is my purposition, i used it on my websites, hope to help you !</p>

```<code>`<?php
     $args = array(
     'post_type' => 'slide',
     'posts_per_page' => -1,
     'order' => 'ASC',
   );
$slide = new WP_Query($args);?>
<?php if ($slide->have_posts()): ?>
<div id="slider">
        <div class="bd-example">
            <div id="carouselExampleCaptions" class="carousel slide carousel-fade" data-ride="carousel" data-interval=10000>
                <div class="">
                    <ol class="carousel-indicators">
                        <?php $i = 0;while ($slide->have_posts()): $publicity->the_post();?>
                            <li data-target="#carousel-example-generic" data-slide-to="<?php echo $i ?>" class="<?php if ($i === 0): ?>active<?php endif;?>"></li>
                        <?php $i++; endwhile;?>
                    </ol>
                    <div class="carousel-inner">
                        <?php $i = 0;while ($slide->have_posts()): $slide->the_post();?
                                <div class="carousel-item <?php if (0 == $i) {echo ' active';}?>" style="background:url('<?php the_post_thumbnail_url('full');?>') center center no-repeat; background-size: cover; min-height: 100vh;">
                                    <div class="carousel-caption d-none d-md-block">
                                        <div class="row align-items-center ">
                                            <div class="col-lg-4 title">
                                                <span><?php the_title();?></span>
                                                <h2><?php the_content();?></h2>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                        <?php $i++;endwhile;?>
                    </div>
                </div>
            </div>
        </div>
    </div>
   <?php wp_reset_postdata();endif;?>
`
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I've created a bootstrap carousel in WordPress and it works fine. My only problem is that when I click on the image it doesn't take me to the specific article. How Can I solve this? Here is my Code:

<?php $slider = get_posts(array('post_type' => 'post', 'posts_per_page' => 3)); ?>
  <?php $count = 0; ?>
  <?php foreach($slider as $slide): ?>
  <div class="item <?php echo ($count == 0) ? 'active' : ''; ?>">
      <a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
        <img src="<?php echo wp_get_attachment_url( get_post_thumbnail_id($slide->ID)) ?>" class="img-responsive"/>

  <?php $count++; ?>
<?php endforeach; ?>

      Previous

       Next

Body:
here is my purposition, i used it on my websites, hope to help you !

`<?php
     $args = array(
     'post_type' => 'slide',
     'posts_per_page' => -1,
     'order' => 'ASC',
   );
$slide = new WP_Query($args);?>
<?php if ($slide->have_posts()): ?>
<div id="slider">
        <div class="bd-example">
            <div id="carouselExampleCaptions" class="carousel slide carousel-fade" data-ride="carousel" data-interval=10000>
                <div class="">
                    <ol class="carousel-indicators">
                        <?php $i = 0;while ($slide->have_posts()): $publicity->the_post();?>
                            <li data-target="#carousel-example-generic" data-slide-to="<?php echo $i ?>" class="<?php if ($i === 0): ?>active<?php endif;?>"></li>
                        <?php $i++; endwhile;?>
                    </ol>
                    <div class="carousel-inner">
                        <?php $i = 0;while ($slide->have_posts()): $slide->the_post();?
                                <div class="carousel-item <?php if (0 == $i) {echo ' active';}?>" style="background:url('<?php the_post_thumbnail_url('full');?>') center center no-repeat; background-size: cover; min-height: 100vh;">
                                    <div class="carousel-caption d-none d-md-block">
                                        <div class="row align-items-center ">
                                            <div class="col-lg-4 title">
                                                <span><?php the_title();?></span>
                                                <h2><?php the_content();?></h2>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                        <?php $i++;endwhile;?>
                    </div>
                </div>
            </div>
        </div>
    </div>
   <?php wp_reset_postdata();endif;?>
`


问:
Subject.subscribe not firing in ngOnInit
I have defined the subject in my service.ts
The onEditItem() in detail.component.ts passes the value of id in .next() and the Subject is subscribed in new.component.ts
But the subscription is not working. Subscription is done in ngOnInit  in new.component.ts

The value of id is successfully passed in onEditItem() but subscription is not working. I've tried doing console.log check inside subscription. But nothing is printed in console.

in details.component.html

```<code><a class="btn btn-primary" (click)="onEditItem()" routerLink="/new">Edit</a>
</code>```

in details.component.ts

```<code>  onEditItem(){this.contactService.startedEditing.next(this.id);}
</code>```

in contactService.ts

```<code>export class ContactService {
  startedEditing =new Subject<number>();
}
</code>```

in new.component.ts

```<code>ngOnInit() {
  this.subscription = this.contactService.startedEditing.subscribe(
    (index: number) => {
      console.log(index);

      this.editedItemIndex = index;
      console.log(this.editedItemIndex);
      this.editMode = true;
      this.editedItem = this.contactService.getContacts(index);

      this.editForm.setValue({
        name: this.editedItem.name,
        address: this.editedItem.address
      })
    }
  );
}
</code>```

I expected that the form which is defined in new.component.html should be initialized with the value from details component but the subscription is not working in ngOnInit.

答:
The subject is a hybrid version of observable and observer. So it will show both behaviors and it is not necessary to create separate observable.

I have created a simple stackbitz for your question. Please check  (https://stackblitz.com/edit/angular-ypeadt) hope this helps. Cheers!

Body:
I have defined the subject in my service.ts
The onEditItem() in detail.component.ts passes the value of id in .next() and the Subject is subscribed in new.component.ts
But the subscription is not working. Subscription is done in ngOnInit  in new.component.ts

The value of id is successfully passed in onEditItem() but subscription is not working. I've tried doing console.log check inside subscription. But nothing is printed in console.

in details.component.html

Edit

in details.component.ts

  onEditItem(){this.contactService.startedEditing.next(this.id);}

in contactService.ts

export class ContactService {
  startedEditing =new Subject<number>();
}

in new.component.ts

ngOnInit() {
  this.subscription = this.contactService.startedEditing.subscribe(
    (index: number) => {
      console.log(index);

      this.editedItemIndex = index;
      console.log(this.editedItemIndex);
      this.editMode = true;
      this.editedItem = this.contactService.getContacts(index);

      this.editForm.setValue({
        name: this.editedItem.name,
        address: this.editedItem.address
      })
    }
  );
}

I expected that the form which is defined in new.component.html should be initialized with the value from details component but the subscription is not working in ngOnInit.


问:
Property displayed as undefined in React Component - Retrieve props.match and additional property in component
I have an index.js from which i am calling a Component like this

```<code>const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" component={MyComponent} prop1={prop1}/>
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);
</code>```

But in MyComponent.js, this.props.prop1 is displayed as undefined. Any idea why ?
I need to able to get this.props.match.params and prop1

答:
if you need to pass a prop to a component being rendered by React Router, instead of using Routes component prop, use its render prop passing it an inline function then pass along the arguments to the element you’re creating.

```<code><Route
  path='/pathname'
  render={(prop1) => <MyComponent props={prop1} />}
/>
</code>```

please try this, should work.

Body:
I have an index.js from which i am calling a Component like this

const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" component={MyComponent} prop1={prop1}/>
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);

But in MyComponent.js, this.props.prop1 is displayed as undefined. Any idea why ?
I need to able to get this.props.match.params and prop1

Body:
if you need to pass a prop to a component being rendered by React Router, instead of using Routes component prop, use its render prop passing it an inline function then pass along the arguments to the element you’re creating.

<Route
  path='/pathname'
  render={(prop1) => <MyComponent props={prop1} />}
/>

please try this, should work.


问:
What is php's performance on directly accessing array's row with key specified
I have a question regarding array's performance.... how does php handle array keys? I mean if I do something like $my_city = $cities[15]; .... does php directly access the exact row item in $cities array or does php iterate trough array until it finds the matched row?

and if it access the row directly... is there a difference in performance between an array with 100 rows and array with 100,000 rows?

like in this example
$my_city = $cities[15];

答: It access it directly. Behind the scene everything is memory pointers arithmetic. I can hardly believe that array concept or implementation in PHP somehow differs from  other languages like C, Java or C#.</p>


问:
Checking whether a sequence of integers is increasing
I'm stuck only partially passing the below problem.

Given a sequence of integers, check whether it is possible to obtain a strictly increasing sequence by erasing no more than one element from it.

Example

```<code>sequence = [1, 3, 2, 1]
almostIncreasingSequence(sequence) = false

sequence = [1, 3, 2]
almostIncreasingSequence(sequence) = true
</code>```

My code that is only passing some examples:

```<code>bool almostIncreasingSequence(int[] sequence) {
   int seqIncreasing = 0;
    if (sequence.Length == 1) return true;
    for (int i = 0;i < sequence.Length-2;i++)
    {
        if ((sequence[i] == sequence[++i]+1)||(sequence[i] == sequence[++i]))
        {
            seqIncreasing++;
        }
    }
    return ((seqIncreasing == sequence.Length) || (--seqIncreasing == sequence.Length));
}
</code>```

Failed Examples:

```<code>Input:
    sequence: [1, 3, 2]
Output:
    false
Expected Output:
    true

Input:
    sequence: [10, 1, 2, 3, 4, 5]
Output:
    false
Expected Output:
    true

Input:
    sequence: [0, -2, 5, 6]
Output:
    false
Expected Output:
    true

Input:
    sequence: [1, 1]
Output:
    false
Expected Output:
    true
</code>```

答:
Having solved that CodeSignal challenge using C# myself, I can tell you how I approached it.

First, a helper method to handle the logic of deciding when to remove an element from a sequence:

private static bool removeElement(IEnumerable<int> sequence, int i) {
    // This method handles the logic for determining whether to remove an element from a sequence of integers.
    // Initialize the return variable and declare some useful element aliases.
    bool removeElement = false;
    int c = sequence.ElementAt(i), p = sequence.ElementAtOrDefault(i - 1), n = sequence.ElementAtOrDefault(i + 1);

    // Remove the first element if and only if it is greater than or equal to the next element.
    if      (i == 0)                      removeElement = (c >= n);
    // Remove the last element if and only if it is less than or equal to the previous element.
    else if (i == (sequence.Count() - 1)) removeElement = (c <= p);
    // Removal logic for an element somewhere in the middle of the sequence:
    else {
        // If the current element is greater than the previous element...
        // ...and the current element is less than the next element, then do not remove the current element.
        if (c > p && c < n) removeElement = false;
        // If the current element is greater than or equal to the next element, then it might need to be removed.
        else if (c > p && c >= n) {
            removeElement = true;

            // Handle edge case for test 19.
            // If the current element is the next-to-last element...
            // ...and the only reason it's being considered for removal is because it is less than the last element...
            // ...then skip it and remove the last element instead.
            if (i == (sequence.Count() - 2)) removeElement = false;

            // Handle edge case for test 16.
            // If the current element occurs before the next-to-last element...
            if (i < (sequence.Count() - 2))
                // ...and both the current and next elements are less than the following element...
                // ...then skip the current element and remove the next one instead.
                if (n < sequence.ElementAt(i + 2) && c < sequence.ElementAt(i + 2)) removeElement = false;
        // Otherwise, remove the current element.
        } else removeElement = true;
    }

    return removeElement;
}
```

<p>Then I wrote two versions of the main method: one using LINQ, and one without.</p>

<p>LINQ version:</p>

<pre class="lang-cs prettyprint-override"><code>bool almostIncreasingSequence(int[] sequence) {
    // Eliminate the most trivial cases first.
    if      (sequence.Length <= 2)                                        return true;
    else if (sequence.SequenceEqual(sequence.Distinct().OrderBy(x => x))) return true;
    else {
        // Get the index of the first element that should be removed from the sequence.
        int index = Enumerable.Range(0, sequence.Length).First(x => removeElement(sequence, x));
        // Remove that element from the sequence.
        sequence = sequence.Where((x, i) => i != index).ToArray();
    }

    // Return whether or not the remaining sequence is strictly increasing.
    return sequence.SequenceEqual(sequence.Distinct().OrderBy(x => x));
}
</code>```

Non-LINQ version:

bool almostIncreasingSequence(int[] sequence) {
    // Eliminate the most trivial cases.
    if (sequence.Length <= 2) return true;
    // Make a copy of the input array in the form of a List collection.
    var initSequence = new List<int>(sequence);
    // Iterate through the List.
    for (int i = 0; i < initSequence.Count; i++) {
        // If the current element needs to be removed from the List, remove it.
        if (removeElement(initSequence, i)) {
            initSequence.RemoveAt(i);
            // Now the entire sequence after the first removal must be strictly increasing.
            // If this is not the case, return false.
            for (int j = i; j < initSequence.Count; j++) {
                if (removeElement(initSequence, j)) return false;
            }

            break;
        }
    }

    return true;
}
```

<p>Both variations pass all of the provided test cases:</p>

```38/38 tests passed.
Sample tests: 19/19
Hidden tests: 19/19
Score: 300/300
```

Body:
I'm stuck only partially passing the below problem.

Given a sequence of integers, check whether it is possible to obtain a strictly increasing sequence by erasing no more than one element from it.

Example

sequence = [1, 3, 2, 1]
almostIncreasingSequence(sequence) = false

sequence = [1, 3, 2]
almostIncreasingSequence(sequence) = true

My code that is only passing some examples:

bool almostIncreasingSequence(int[] sequence) {
   int seqIncreasing = 0;
    if (sequence.Length == 1) return true;
    for (int i = 0;i < sequence.Length-2;i++)
    {
        if ((sequence[i] == sequence[++i]+1)||(sequence[i] == sequence[++i]))
        {
            seqIncreasing++;
        }
    }
    return ((seqIncreasing == sequence.Length) || (--seqIncreasing == sequence.Length));
}

Failed Examples:

Input:
    sequence: [1, 3, 2]
Output:
    false
Expected Output:
    true

Input:
    sequence: [10, 1, 2, 3, 4, 5]
Output:
    false
Expected Output:
    true

Input:
    sequence: [0, -2, 5, 6]
Output:
    false
Expected Output:
    true

Input:
    sequence: [1, 1]
Output:
    false
Expected Output:
    true

Body:
Having solved that CodeSignal challenge using C# myself, I can tell you how I approached it.

First, a helper method to handle the logic of deciding when to remove an element from a sequence:

private static bool removeElement(IEnumerable<int> sequence, int i) {
    // This method handles the logic for determining whether to remove an element from a sequence of integers.
    // Initialize the return variable and declare some useful element aliases.
    bool removeElement = false;
    int c = sequence.ElementAt(i), p = sequence.ElementAtOrDefault(i - 1), n = sequence.ElementAtOrDefault(i + 1);

    // Remove the first element if and only if it is greater than or equal to the next element.
    if      (i == 0)                      removeElement = (c >= n);
    // Remove the last element if and only if it is less than or equal to the previous element.
    else if (i == (sequence.Count() - 1)) removeElement = (c <= p);
    // Removal logic for an element somewhere in the middle of the sequence:
    else {
        // If the current element is greater than the previous element...
        // ...and the current element is less than the next element, then do not remove the current element.
        if (c > p && c < n) removeElement = false;
        // If the current element is greater than or equal to the next element, then it might need to be removed.
        else if (c > p && c >= n) {
            removeElement = true;

            // Handle edge case for test 19.
            // If the current element is the next-to-last element...
            // ...and the only reason it's being considered for removal is because it is less than the last element...
            // ...then skip it and remove the last element instead.
            if (i == (sequence.Count() - 2)) removeElement = false;

            // Handle edge case for test 16.
            // If the current element occurs before the next-to-last element...
            if (i < (sequence.Count() - 2))
                // ...and both the current and next elements are less than the following element...
                // ...then skip the current element and remove the next one instead.
                if (n < sequence.ElementAt(i + 2) && c < sequence.ElementAt(i + 2)) removeElement = false;
        // Otherwise, remove the current element.
        } else removeElement = true;
    }

    return removeElement;
}

Then I wrote two versions of the main method: one using LINQ, and one without.

LINQ version:

bool almostIncreasingSequence(int[] sequence) {
    // Eliminate the most trivial cases first.
    if      (sequence.Length <= 2)                                        return true;
    else if (sequence.SequenceEqual(sequence.Distinct().OrderBy(x => x))) return true;
    else {
        // Get the index of the first element that should be removed from the sequence.
        int index = Enumerable.Range(0, sequence.Length).First(x => removeElement(sequence, x));
        // Remove that element from the sequence.
        sequence = sequence.Where((x, i) => i != index).ToArray();
    }

    // Return whether or not the remaining sequence is strictly increasing.
    return sequence.SequenceEqual(sequence.Distinct().OrderBy(x => x));
}

Non-LINQ version:

bool almostIncreasingSequence(int[] sequence) {
    // Eliminate the most trivial cases.
    if (sequence.Length <= 2) return true;
    // Make a copy of the input array in the form of a List collection.
    var initSequence = new List<int>(sequence);
    // Iterate through the List.
    for (int i = 0; i < initSequence.Count; i++) {
        // If the current element needs to be removed from the List, remove it.
        if (removeElement(initSequence, i)) {
            initSequence.RemoveAt(i);
            // Now the entire sequence after the first removal must be strictly increasing.
            // If this is not the case, return false.
            for (int j = i; j < initSequence.Count; j++) {
                if (removeElement(initSequence, j)) return false;
            }

            break;
        }
    }

    return true;
}

Both variations pass all of the provided test cases:

38/38 tests passed.
Sample tests: 19/19
Hidden tests: 19/19
Score: 300/300


问:
Oracle months_between function unexpected result
Oracle's months_between function returns unexpected results.

For example, the difference between 20191001 and 20190916 is 15 days, so the return value of the function is expected to be (1/31) * 15 = 0.4838 ....

```<code>SELECT months_between('20191001','20190916')
from dual
</code>```

.5161290322580645161290322580645161290323

Is this a specification? Or is it a bug?

答:
The function MONTHS_BETWEEN works with 31 day months when the day-of-the-month is not the last day of the month.

```<code>SELECT MONTHS_BETWEEN
  (TO_DATE('20190201','YYYYMMDD'),
   TO_DATE('20190131','YYYYMMDD') ) "Months"
FROM DUAL;
</code>```

will return 0.032 (rounded) but

```<code>SELECT MONTHS_BETWEEN
 (TO_DATE('20190301','YYYYMMDD'),
  TO_DATE('20190228','YYYYMMDD') ) "Months"
FROM DUAL;
</code>```

will return 0.129

For a more complete description of MONTHS_BETWEN see the documentation

Body:
Oracle's months_between function returns unexpected results.

For example, the difference between 20191001 and 20190916 is 15 days, so the return value of the function is expected to be (1/31) * 15 = 0.4838 ....

SELECT months_between('20191001','20190916')
from dual

.5161290322580645161290322580645161290323

Is this a specification? Or is it a bug?

Body:
The function MONTHS_BETWEEN works with 31 day months when the day-of-the-month is not the last day of the month.

SELECT MONTHS_BETWEEN
  (TO_DATE('20190201','YYYYMMDD'),
   TO_DATE('20190131','YYYYMMDD') ) "Months"
FROM DUAL;

will return 0.032 (rounded) but

SELECT MONTHS_BETWEEN
 (TO_DATE('20190301','YYYYMMDD'),
  TO_DATE('20190228','YYYYMMDD') ) "Months"
FROM DUAL;

will return 0.129

For a more complete description of MONTHS_BETWEN see the documentation


问:
How to Append Arrray List Data Into Text File
Below is the code.

I want to add the Array List Data into Text File.At this time it Inserts the data but when i add new data it overwrites the previous data and just add new one so i want that it will ask that you want that the data already exists you want to overwrite or append if data do not exist it simply append to the file.

```<code>using (TextWriter writer = File.CreateText(@"C:\Users\Precision\Desktop\testing\data.txt"))
{
    foreach (var obj in dirList)
    {
        writer.WriteLine(obj);
    }
}

Console.WriteLine("Record Saved Successfully...");
</code>```

答: Change your File.CreateText to File.AppendText

Body:
Below is the code.

I want to add the Array List Data into Text File.At this time it Inserts the data but when i add new data it overwrites the previous data and just add new one so i want that it will ask that you want that the data already exists you want to overwrite or append if data do not exist it simply append to the file.

using (TextWriter writer = File.CreateText(@"C:\Users\Precision\Desktop\testing\data.txt"))
{
    foreach (var obj in dirList)
    {
        writer.WriteLine(obj);
    }
}

Console.WriteLine("Record Saved Successfully...");


问:
Getting null data on response body using retrofit2?
I am new to retrofit 2 and i am trying to get json array data but getting null, this is the url for getting the data.

But the funny thing is when i try to debug inside onResponse i am getting success message as well as response.body data. What is the problem here?

https://xenzet.com/GameCheat/viewgamesjson.php

this is json data

```<code>[
    {
        "gameid":"2",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/counter strike 1.6.png",
        "Games_Name":"1"
    },
    {
        "gameid":"3",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/gta.ico",
        "Games_Name":"vice city sucjlfsdrgefdsrhag"
    },
    {
        "gameid":"4",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/pubg.png",
        "Games_Name":"pubg"
    },
    {
    "gameid":"5",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/doom.png",
    "Games_Name":"Doom Enternal"
    },
    {
    "gameid":"6",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/for.png",
    "Games_Name":"Fornite"
    },
    {
    "gameid":"9",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/dota2.png",
    "Games_Name":"dota2"
    }
]
</code>```

this is the method which is trying to get data

```<code> public void fetch_information() {

        ApiInterface = ApiClient.getApiClient().create(Api.class);

        Call<List<Games>> call = ApiInterface.GetGames();

        call.enqueue(new Callback<List<Games>>() {
            @Override
            public void onResponse(Call<List<Games>> call, Response<List<Games>> response) {
                if(response.isSuccessful()) {

                    gameslist = response.body();
                    gamescounter = gameslist.size();
                    adapter = new GameRecyclerViewAdapter(GamesActivity.this, gameslist);
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<List<Games>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }
</code>```

this is ApiClient

```<code>public class ApiClient {

    public static  String Base_URL ;

    public static Retrofit retrofit;

    public static Retrofit getApiClient()
    {
        if (retrofit == null)
        {
            Base_URL ="https://xenzet.com/GameCheat/";
            retrofit = new Retrofit.Builder().baseUrl(Base_URL)
                    .addConverterFactory(GsonConverterFactory.create()).build();

        }
        return retrofit;
    }
}
</code>```

and Api

```<code>public interface Api {

    @GET("viewgamesjson.php")
    Call<List<Games>> GetGames();
}
</code>```

and in OnCreate i am calling fetch information method.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_games);
    gameslist = new ArrayList<Games>();
    RecyclerView recyclerView = findViewById(R.id.recyclerview_gameslist);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
     fetch_information();

    Toast.makeText(getApplicationContext(),"" +gamescounter, Toast.LENGTH_SHORT).show();

    adapter = new GameRecyclerViewAdapter(this, gameslist);

   recyclerView.setAdapter(adapter);
    adapter.setClickListener((GameRecyclerViewAdapter.ItemClickListener) this);
}
</code>```

trying to fill data of game list in recycler view but fails as it null.

this is logcat

```<code>2019-05-27 14:03:43.261 1261-1261/com.example.quizgames E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quizgames, PID: 1261
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
    at com.example.quizgames.GamesActivity$1.onResponse(GamesActivity.java:109)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:836)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6251)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
</code>```

This is class Games

```<code>public class Games {

    @SerializedName("gameid")
    @Expose
    private String gameid;
    @SerializedName("gameIcon")
    @Expose
    private String gameIcon;
    @SerializedName("Games_Name")
    @Expose
    private String gamesName;

    public String getGameid() {
        return gameid;
    }

    public void setGameid(String gameid) {
        this.gameid = gameid;
    }

    public String getGameIcon() {
        return gameIcon;
    }

    public void setGameIcon(String gameIcon) {
        this.gameIcon = gameIcon;
    }

    public String getGamesName() {
        return gamesName;
    }

    public void setGamesName(String gamesName) {
        this.gamesName = gamesName;
    }

//    public Games(String Gameid,String Gameicon,String GameName)
//    {
//      this.gameid = Gameid;
//      this.gameIcon = Gameicon;
//      this.gamesName = GameName;
//
//    }

}
</code>```

This is recycler view

```<code>class GameRecyclerViewAdapter extends RecyclerView.Adapter<GameRecyclerViewAdapter.ViewHolder> {

    private List<Games> mGames;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    GameRecyclerViewAdapter(Context context, List<Games> games) {
        this.mInflater = LayoutInflater.from(context);
        this.mGames = games;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.gameitem, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Games Game = mGames.get(position);
        String Gameid = Game.getGameid();
        String Gameicon = Game.getGameIcon();
        String Gamename = Game.getGamesName();
        holder.GameNameTxt.setText(Gamename);
        Glide.with(holder.GameIconImage.getContext()).load(Game.getGameIcon()).thumbnail(0.1f).
                placeholder(R.color.colorPrimary).diskCacheStrategy(DiskCacheStrategy.NONE).into(holder.GameIconImage);

    }

    // total number of rows
    @Override
    public int getItemCount() {

        return mGames == null ? 0 : mGames.size();

    }

    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView GameNameTxt;
        ImageView GameIconImage;
        ViewHolder(View itemView) {
            super(itemView);
            GameNameTxt = itemView.findViewById(R.id.gamename);
            GameIconImage = itemView.findViewById(R.id.imageView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);

    }
}
</code>```

答:
The problem is, that you set up your list adapter in onCreate(), where gameslist is still null.

```<code>adapter = new GameRecyclerViewAdapter(this, gameslist);
recyclerView.setAdapter(adapter);
</code>```

When you call the setAdapter() method, the recyclerView will ask the adapter for the number of items; and in getItemCount() I suppose, you have something like return gameslist.count(). Since gameslist is still null, this causes the NPE.

To fix it, change getItemCount() to something like this:

```<code>return gameslist == null ? 0 : gameslist.size()
</code>```

EDIT

I checked your URL (with Postman), and it appears that the content-type of the response is text/html and not application/json as it should be. I suppose that therefore the response isn't converted using Gson and thus you end up with null.

Body:
I am new to retrofit 2 and i am trying to get json array data but getting null, this is the url for getting the data.

But the funny thing is when i try to debug inside onResponse i am getting success message as well as response.body data. What is the problem here?

https://xenzet.com/GameCheat/viewgamesjson.php

this is json data

[
    {
        "gameid":"2",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/counter strike 1.6.png",
        "Games_Name":"1"
    },
    {
        "gameid":"3",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/gta.ico",
        "Games_Name":"vice city sucjlfsdrgefdsrhag"
    },
    {
        "gameid":"4",
        "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/pubg.png",
        "Games_Name":"pubg"
    },
    {
    "gameid":"5",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/doom.png",
    "Games_Name":"Doom Enternal"
    },
    {
    "gameid":"6",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/for.png",
    "Games_Name":"Fornite"
    },
    {
    "gameid":"9",
    "gameIcon":"https:\/\/xenzet.com\/GameCheat\/uploads\/dota2.png",
    "Games_Name":"dota2"
    }
]

this is the method which is trying to get data

 public void fetch_information() {

        ApiInterface = ApiClient.getApiClient().create(Api.class);

        Call<List<Games>> call = ApiInterface.GetGames();

        call.enqueue(new Callback<List<Games>>() {
            @Override
            public void onResponse(Call<List<Games>> call, Response<List<Games>> response) {
                if(response.isSuccessful()) {

                    gameslist = response.body();
                    gamescounter = gameslist.size();
                    adapter = new GameRecyclerViewAdapter(GamesActivity.this, gameslist);
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<List<Games>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

this is ApiClient

public class ApiClient {

    public static  String Base_URL ;

    public static Retrofit retrofit;

    public static Retrofit getApiClient()
    {
        if (retrofit == null)
        {
            Base_URL ="https://xenzet.com/GameCheat/";
            retrofit = new Retrofit.Builder().baseUrl(Base_URL)
                    .addConverterFactory(GsonConverterFactory.create()).build();

        }
        return retrofit;
    }
}

and Api

public interface Api {

    @GET("viewgamesjson.php")
    Call<List<Games>> GetGames();
}

and in OnCreate i am calling fetch information method.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_games);
    gameslist = new ArrayList<Games>();
    RecyclerView recyclerView = findViewById(R.id.recyclerview_gameslist);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
     fetch_information();

    Toast.makeText(getApplicationContext(),"" +gamescounter, Toast.LENGTH_SHORT).show();

    adapter = new GameRecyclerViewAdapter(this, gameslist);

   recyclerView.setAdapter(adapter);
    adapter.setClickListener((GameRecyclerViewAdapter.ItemClickListener) this);
}

trying to fill data of game list in recycler view but fails as it null.

this is logcat

2019-05-27 14:03:43.261 1261-1261/com.example.quizgames E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quizgames, PID: 1261
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
    at com.example.quizgames.GamesActivity$1.onResponse(GamesActivity.java:109)
    at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
    at android.os.Handler.handleCallback(Handler.java:836)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6251)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

This is class Games

public class Games {

    @SerializedName("gameid")
    @Expose
    private String gameid;
    @SerializedName("gameIcon")
    @Expose
    private String gameIcon;
    @SerializedName("Games_Name")
    @Expose
    private String gamesName;

    public String getGameid() {
        return gameid;
    }

    public void setGameid(String gameid) {
        this.gameid = gameid;
    }

    public String getGameIcon() {
        return gameIcon;
    }

    public void setGameIcon(String gameIcon) {
        this.gameIcon = gameIcon;
    }

    public String getGamesName() {
        return gamesName;
    }

    public void setGamesName(String gamesName) {
        this.gamesName = gamesName;
    }

//    public Games(String Gameid,String Gameicon,String GameName)
//    {
//      this.gameid = Gameid;
//      this.gameIcon = Gameicon;
//      this.gamesName = GameName;
//
//    }

}

This is recycler view

class GameRecyclerViewAdapter extends RecyclerView.Adapter<GameRecyclerViewAdapter.ViewHolder> {

    private List<Games> mGames;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    GameRecyclerViewAdapter(Context context, List<Games> games) {
        this.mInflater = LayoutInflater.from(context);
        this.mGames = games;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.gameitem, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Games Game = mGames.get(position);
        String Gameid = Game.getGameid();
        String Gameicon = Game.getGameIcon();
        String Gamename = Game.getGamesName();
        holder.GameNameTxt.setText(Gamename);
        Glide.with(holder.GameIconImage.getContext()).load(Game.getGameIcon()).thumbnail(0.1f).
                placeholder(R.color.colorPrimary).diskCacheStrategy(DiskCacheStrategy.NONE).into(holder.GameIconImage);

    }

    // total number of rows
    @Override
    public int getItemCount() {

        return mGames == null ? 0 : mGames.size();

    }

    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView GameNameTxt;
        ImageView GameIconImage;
        ViewHolder(View itemView) {
            super(itemView);
            GameNameTxt = itemView.findViewById(R.id.gamename);
            GameIconImage = itemView.findViewById(R.id.imageView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);

    }
}

Body:
The problem is, that you set up your list adapter in onCreate(), where gameslist is still null.

adapter = new GameRecyclerViewAdapter(this, gameslist);
recyclerView.setAdapter(adapter);

When you call the setAdapter() method, the recyclerView will ask the adapter for the number of items; and in getItemCount() I suppose, you have something like return gameslist.count(). Since gameslist is still null, this causes the NPE.

To fix it, change getItemCount() to something like this:

return gameslist == null ? 0 : gameslist.size()

EDIT

I checked your URL (with Postman), and it appears that the content-type of the response is text/html and not application/json as it should be. I suppose that therefore the response isn't converted using Gson and thus you end up with null.


问:
URL encoding a string in bash script
I am writing a bash script in where I am trying to submit a post variable, however wget is treating it as multiple URLS I believe because it is not URLENCODED... here is my basic thought

```<code>MESSAGE='I am trying to post this information'
wget -O test.txt http://xxxxxxxxx.com/alert.php --post-data 'key=xxxx&message='$MESSAGE''
</code>```

I am getting errors and the alert.php is not getting the post variable plus it pretty mush is saying

can't resolve I
can't resolve am
can't resolve trying
.. and so on.

My example above is a simple kinda sudo example but I believe if I can url encode it, it would pass, I even tried php like:

```<code>MESSAGE='I am trying to post this information'
MESSAGE=$(php -r 'echo urlencode("'$MESSAGE'");')
</code>```

but php errors out.. any ideas? How can i pass the variable in $MESSAGE without php executing it?

答:
Extending Rockallite's very helpful answer for Python 3 and multiline input from a file (this time on Ubuntu, but that shouldn't matter):

```<code>cat any.txt | python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.stdin.read()))"
</code>```

This will result in all lines from the file concatenated into a single URL, the newlines being replaced by %0A.

Title: URL encoding a string in bash script

Body:
I am writing a bash script in where I am trying to submit a post variable, however wget is treating it as multiple URLS I believe because it is not URLENCODED... here is my basic thought

MESSAGE='I am trying to post this information'
wget -O test.txt http://xxxxxxxxx.com/alert.php --post-data 'key=xxxx&message='$MESSAGE''

I am getting errors and the alert.php is not getting the post variable plus it pretty mush is saying

can't resolve I
can't resolve am
can't resolve trying
.. and so on.

My example above is a simple kinda sudo example but I believe if I can url encode it, it would pass, I even tried php like:

MESSAGE='I am trying to post this information'
MESSAGE=$(php -r 'echo urlencode("'$MESSAGE'");')

but php errors out.. any ideas? How can i pass the variable in $MESSAGE without php executing it?

Body:
Extending Rockallite's very helpful answer for Python 3 and multiline input from a file (this time on Ubuntu, but that shouldn't matter):

cat any.txt | python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.stdin.read()))"

This will result in all lines from the file concatenated into a single URL, the newlines being replaced by %0A.


问:
face-api.js - Why is browser's faceapi.detectAllFaces() is faster than server's?
I want to use face detection on my server-side. Therefore, I found face-api.js for this task.
I discovered that each call of faceapi.detectAllFaces() lasts for ~10 seconds.
But when I start the browser-example, only the first function lasts 10 seconds and all the next lasts less than one second.

My server-side code (you can see a similar code in ageAndGenderRecognition.ts):

```<code>import * as faceapi from 'face-api.js';
import { canvas, faceDetectionNet, faceDetectionOptions, saveFile } from './commons';
await faceDetectionNet.loadFromDisk('../../weights')
await faceapi.nets.faceLandmark68Net.loadFromDisk('../../weights')
await faceapi.nets.ageGenderNet.loadFromDisk('../../weights')

const img = await canvas.loadImage('../images/bbt1.jpg')

console.time();
const results = await faceapi.detectAllFaces(img, faceDetectionOptions);
// ~10 seconds.
console.timeEnd();

console.time();
const results2 = await faceapi.detectAllFaces(img, faceDetectionOptions);
// ~10 seconds again.
console.timeEnd();
</code>```

Why faceapi.detectAllFaces() (except first call) is faster in browser-example than in ageAndGenderRecognition.ts? And which similar thing I can to do to my faceapi.detectAllFaces()-function has the same speed?

答:
There might be some reasons why your nodejs sample code runs for 10s:

You are not importing @tensorflow/tfjs-node at all, in this case tfjs does not use the native Tensorflow CPU backend and operations will take much longer on the CPU.

You are importing @tensorflow/tfjs-node but there is a version mismatch between the tfjs-core version that face-api.js and the version of @tensorflow/tfjs-node your have installed via npm. In this case tfjs will display a warning message.

Everything is set up correctly, but your CPU is just tremendously slow. In this case you can either try to use @tensorflow/tfjs-node-gpu (if you have a CUDA compatible nvidia GPU) or you can change the faceDetectionOptions to new faceapi.TinyFaceDetectorOptions(), which will run the TinyFaceDetector instead of the default SSD Mobilenet v1 model, which is much faster.

The reason why the first call in the browser takes that long is not due to the actual prediction time. It is because using the WebGL backend of tfjs, on the first run (warm up run) all the shader programs are compiled, which takes so long. Afterwards these are cached. The prediction in the browser takes only a few miliseconds because the WebGL backend is GPU accelerated. The 10s warm up time in the browser and the prediction time you are seeing in nodejs are not related at all.

Body:
I want to use face detection on my server-side. Therefore, I found face-api.js for this task.
I discovered that each call of faceapi.detectAllFaces() lasts for ~10 seconds.
But when I start the browser-example, only the first function lasts 10 seconds and all the next lasts less than one second.

My server-side code (you can see a similar code in ageAndGenderRecognition.ts):

import * as faceapi from 'face-api.js';
import { canvas, faceDetectionNet, faceDetectionOptions, saveFile } from './commons';
await faceDetectionNet.loadFromDisk('../../weights')
await faceapi.nets.faceLandmark68Net.loadFromDisk('../../weights')
await faceapi.nets.ageGenderNet.loadFromDisk('../../weights')

const img = await canvas.loadImage('../images/bbt1.jpg')

console.time();
const results = await faceapi.detectAllFaces(img, faceDetectionOptions);
// ~10 seconds.
console.timeEnd();

console.time();
const results2 = await faceapi.detectAllFaces(img, faceDetectionOptions);
// ~10 seconds again.
console.timeEnd();

Why faceapi.detectAllFaces() (except first call) is faster in browser-example than in ageAndGenderRecognition.ts? And which similar thing I can to do to my faceapi.detectAllFaces()-function has the same speed?


问:
ThisAddin.Ribbon (Excel) is always null since installing VS2010 SP1
I recently installed VS2010 SP1 and now the ThisAddIn.Ribbon value is always null (Excel VStO application addin, using Excel 2010).  No code changes (only change besides VS2010 SP1 was adding the 'TargetFramework' to the GenerateOfficeAddInManifest class -- I guess a new addition in SP1).

When I run my addin and look in the debugger I see that AddIn.Ribbon is null and never gets initialized.  Of course this worked perfectly fine yesterday, prior to my SP1 upgrade.

Did SP1 break Excel application addins that use the ribbon?  Does anyone else have a repro also or a scenario where ThisAddIn.Ribbon is getting initialized?

Thanks!

答:
Looks like there may have been an (inadvertent) breaking change in Visual Studio 2010 SP1. It seems that the config file is not loaded properly.

You might be able to work around the issue using the tip here:
http://social.msdn.microsoft.com/Forums/en-SG/vsto/thread/0005ca8d-979d-4393-82ff-13a41e788166

ContentLicense: CC BY-SA 2.5


问:
Pure javascript solution to fix headlines hierarchy
In order to fix accessibility problems with headline hierarchy required for section 508 (Requirement 1194.22 (d)), I need to rewrite headlines hierarchy with JS.

Problem is that HTML is already built and that back-end technologies cannot be used to reorder those headlines. We have a situation that some headlines are of lower order than they are supposed to be, so they appear in this order, for example:

```<code>H1
  H2
    H4
    H4
    H4
H1
  H3
    H4
    H4
      H5
  H2
    H4
</code>```

This should be converted to

```<code>H1
  H2
    H3
    H3
    H3
H1
  H2
    H3
    H3
      H4
  H2
    H3
</code>```

How do I accomplish this?

答:
When incorporating third party libraries, having bad heading hierarchy is a quite common problem, but in fact the main problem is that in many cases those heading should not exist. Getting rid of them should be considered before applying the following script which does the intended job.

This javascript uses jQuery but can be adapted in vanilla-javascript. It parses the page for standard headings (h1 to h6) and changes the level to the appropriate expected level at the rank considering its parent one.

The difficulty of this kind of scripts is that in your example, fixing the heading hierarchy just by changing the first h4 to a h3 for instance might work on paper but is not a reliable solution.

```<code>$(document).ready(function() {
  var level=0, plevel=[0];
  $("h1,h2,h3,h4,h5,h5").each(function() {
    var c_level=$(this)[0].tagName.substr(1);
    var p_level=plevel[plevel.length-1];

    while (c_level<p_level) {
      plevel.pop();
      level--;
      p_level=plevel[plevel.length-1];
    }

    if (c_level>p_level) {
      level++;
      plevel.push(c_level);
    }

    if (c_level!=level) {
      $(this).replaceWith("<h"+(level)+">"+$(this).html()+"</h"+(level)+">");
    }

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

Body:
In order to fix accessibility problems with headline hierarchy required for section 508 (Requirement 1194.22 (d)), I need to rewrite headlines hierarchy with JS.

Problem is that HTML is already built and that back-end technologies cannot be used to reorder those headlines. We have a situation that some headlines are of lower order than they are supposed to be, so they appear in this order, for example:

H1
  H2
    H4
    H4
    H4
H1
  H3
    H4
    H4
      H5
  H2
    H4

This should be converted to

H1
  H2
    H3
    H3
    H3
H1
  H2
    H3
    H3
      H4
  H2
    H3

How do I accomplish this?

Body:
When incorporating third party libraries, having bad heading hierarchy is a quite common problem, but in fact the main problem is that in many cases those heading should not exist. Getting rid of them should be considered before applying the following script which does the intended job.

This javascript uses jQuery but can be adapted in vanilla-javascript. It parses the page for standard headings (h1 to h6) and changes the level to the appropriate expected level at the rank considering its parent one.

The difficulty of this kind of scripts is that in your example, fixing the heading hierarchy just by changing the first h4 to a h3 for instance might work on paper but is not a reliable solution.

$(document).ready(function() {
  var level=0, plevel=[0];
  $("h1,h2,h3,h4,h5,h5").each(function() {
    var c_level=$(this)[0].tagName.substr(1);
    var p_level=plevel[plevel.length-1];

    while (c_level<p_level) {
      plevel.pop();
      level--;
      p_level=plevel[plevel.length-1];
    }

    if (c_level>p_level) {
      level++;
      plevel.push(c_level);
    }

    if (c_level!=level) {
      $(this).replaceWith("<h"+(level)+">"+$(this).html()+"</h"+(level)+">");
    }

  });
});


问:
How to open file in new Pycharm window from the command line
How do I open a file in a new (detached) window using the command line?

I am currently able to open files in the pycharm editor (on ubuntu) using

```<code>xdg-open /path/to/file
</code>```

These files are not opened in new windows in pycharm. Instead they are opened in the docked editor.

Selecting a file in a project window and hitting shift enter lets you open a file in a new window. So this functionality is built into pycharm.

How would I invoke this command using a terminal command?

答:
You can read more about it here, but in short, you need to pass line number along with path to script.

Example:

```<code>pycharm --line 3 ~/MyProject/scripts/numbers.js

pycharm ~/MyProject/scripts/numbers.js:3
</code>```

Body:
How do I open a file in a new (detached) window using the command line?

I am currently able to open files in the pycharm editor (on ubuntu) using

xdg-open /path/to/file

These files are not opened in new windows in pycharm. Instead they are opened in the docked editor.

Selecting a file in a project window and hitting shift enter lets you open a file in a new window. So this functionality is built into pycharm.

How would I invoke this command using a terminal command?

Body:
You can read more about it here, but in short, you need to pass line number along with path to script.

Example:

pycharm --line 3 ~/MyProject/scripts/numbers.js

pycharm ~/MyProject/scripts/numbers.js:3


问:
Python JSON Google Translator extraction problem
I am trying to extract the JSON object in python using Simplejson. But I am getting the following error.

```<code>Traceback (most recent call last):
  File "Translator.py", line 42, in <module>
    main()
  File "Translator.py", line 38, in main
    parse_json(trans_text)
  File "Translator.py", line 27, in parse_json
    result = json['translations']['translatedText']
TypeError: list indices must be integers, not str
</code>```

This is my JSON object looks like,

```<code>{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}
</code>```

and this is my python piece of code for it.

```<code>def parse_json(trans_text):
    json = simplejson.loads(str(trans_text).replace("'", '"'))
    result = json['translations']['translatedText']
    print result
</code>```

any idea on it?

答:
json['translations'] is a list of objects. To extract the 'translatedText' property, you could use itemgetter:

```<code>from operator import itemgetter

print map(itemgetter('translatedText'), json['translations'])
</code>```

See the implementation of detect_language_v2() for another usage example.

Body:
I am trying to extract the JSON object in python using Simplejson. But I am getting the following error.

Traceback (most recent call last):
  File "Translator.py", line 42, in <module>
    main()
  File "Translator.py", line 38, in main
    parse_json(trans_text)
  File "Translator.py", line 27, in parse_json
    result = json['translations']['translatedText']
TypeError: list indices must be integers, not str

This is my JSON object looks like,

{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}

and this is my python piece of code for it.

def parse_json(trans_text):
    json = simplejson.loads(str(trans_text).replace("'", '"'))
    result = json['translations']['translatedText']
    print result

any idea on it?

Body:
json['translations'] is a list of objects. To extract the 'translatedText' property, you could use itemgetter:

from operator import itemgetter

print map(itemgetter('translatedText'), json['translations'])

See the implementation of detect_language_v2() for another usage example.


问:
split string each x characters in dataframe
I know there are some answers here about splitting a string every nth character, such as this one and this one,  However these are pretty question specific and mostly related to a single string and not to a data frame of multiple strings.

Example data

```<code>df <- data.frame(id = 1:2, seq = c('ABCDEFGHI', 'ZABCDJHIA'))
</code>```

Looks like this:

```<code>  id       seq
1  1 ABCDEFGHI
2  2 ZABCDJHIA
</code>```

Splitting on every third character

I want to split the string in each row every thrid character, such that the resulting data frame looks like this:

```<code>id  1   2   3
1   ABC DEF GHI
2   ZAB CDJ HIA
</code>```

What I tried

I used the splitstackshape before to split a string on a single character, like so: df %>% cSplit('seq', sep = '', stripWhite = FALSE, type.convert = FALSE) I would love to have a similar function (or perhaps it is possbile with cSplit) to split on every third character.

答:
You can split a string each x characters in base also with read.fwf (Read Fixed Width Format Files), which needs either a file or a connection.

```<code>read.fwf(file=textConnection(as.character(df$seq)), widths=c(3,3,3))

   V1  V2  V3
1 ABC DEF GHI
2 ZAB CDJ HIA
</code>```

Body:
I know there are some answers here about splitting a string every nth character, such as this one and this one,  However these are pretty question specific and mostly related to a single string and not to a data frame of multiple strings.

Example data

df <- data.frame(id = 1:2, seq = c('ABCDEFGHI', 'ZABCDJHIA'))

Looks like this:

  id       seq
1  1 ABCDEFGHI
2  2 ZABCDJHIA

Splitting on every third character

I want to split the string in each row every thrid character, such that the resulting data frame looks like this:

id  1   2   3
1   ABC DEF GHI
2   ZAB CDJ HIA

What I tried

I used the splitstackshape before to split a string on a single character, like so: df %>% cSplit('seq', sep = '', stripWhite = FALSE, type.convert = FALSE) I would love to have a similar function (or perhaps it is possbile with cSplit) to split on every third character.

Body:
You can split a string each x characters in base also with read.fwf (Read Fixed Width Format Files), which needs either a file or a connection.

read.fwf(file=textConnection(as.character(df$seq)), widths=c(3,3,3))

   V1  V2  V3
1 ABC DEF GHI
2 ZAB CDJ HIA


问:
window.location.href doesn't redirect
I know this is a question much discussed but I can't figure out why it does not work for me.

This is my function:

```<code>function ShowComments(){

 alert("fired");
 var movieShareId = document.getElementById('movieId');
 //alert("found div" + movieShareId.textContent || movieShareId.innerText);
 //alert("redirect location: /comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/");
 window.location.href = "/comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/";
 var newLocation = window.location;
 //alert("full location: " + window.location);

}
</code>```

If I have the alerts uncommented or if I have Mozilla's bugzilla open it works fine, otherwise it does not redirect to the other page.

Any ideas why?

答:
You can't use window.location.replace or document.location.href or any of your favourite vanilla javascript methods to redirect a page to itself.

So if you're dynamically adding in the redirect path from the back end, or pulling it from a data tag, make sure you do check at some stage for redirects to the current page. It could be as simple as:

```<code>if(window.location.href == linkout)
{
    location.reload();
}
else
{
    window.location.href = linkout;
}
</code>```

Title: window.location.href doesn't redirect

Body:
I know this is a question much discussed but I can't figure out why it does not work for me.

This is my function:

function ShowComments(){

 alert("fired");
 var movieShareId = document.getElementById('movieId');
 //alert("found div" + movieShareId.textContent || movieShareId.innerText);
 //alert("redirect location: /comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/");
 window.location.href = "/comments.aspx?id=" + movieShareId.textContent || movieShareId.innerText + "/";
 var newLocation = window.location;
 //alert("full location: " + window.location);

}

If I have the alerts uncommented or if I have Mozilla's bugzilla open it works fine, otherwise it does not redirect to the other page.

Any ideas why?

Body:
You can't use window.location.replace or document.location.href or any of your favourite vanilla javascript methods to redirect a page to itself.

So if you're dynamically adding in the redirect path from the back end, or pulling it from a data tag, make sure you do check at some stage for redirects to the current page. It could be as simple as:

if(window.location.href == linkout)
{
    location.reload();
}
else
{
    window.location.href = linkout;
}


问:
How to create a 302 GET request with postman?
In postman I want to create a GET request that returns a 302 status code (along with a Location response header). I have been trying to replicate the original request from the browser inspector, but I always get a 200 response (and no Location response header).

How can I get the desired response with the Location response header?

答:
What is probably happening is that Postman receives a 302 status code, but is configured to redirect in this case, so it automatically redirects after which Postman receives a 200 status code, which is what you end up seeing.

Apparently turning off "automatically follow redirects" should offer you a solution.
https://learning.getpostman.com/docs/postman/launching_postman/settings/
View postman request when redirects


问:
How to push mat-list-items to the bottom without using absolute position in Angular Material?
I have just started using Angular Material and I wanted to implement the sidenav to have items that are at the bottom of the page. For now I am able to accomplish it with css.

```<code>position: absolute;
left: 0;
bottom: 0;
</code>```

Is there any way to put spaces between items? My issue comes when I resize the page, the bottom items overlap with the items which are above.

I've included screenshots and the code below. Thanks.

```<code><mat-sidenav-container class="h-screen w-screen">
<mat-sidenav #sidenav class="shadow border-0" fixedInViewport mode="side" opened>
    <mat-toolbar>
        <button mat-mini-fab color="warn" (click)="navigation.toggle()">
            <mat-icon inline=true fontSet="fa" fontIcon="fa-fire" aria-label="SLMC Logo"></mat-icon>
        </button>
    </mat-toolbar>
    <mat-nav-list>
        <a mat-list-item>
            <button mat-icon-button>
                <mat-icon inline=true fontSet="fa" fontIcon="fa-users-cog" aria-label="Administrator"></mat-icon>
            </button>
        </a>
        <a mat-list-item>
            <button mat-icon-button>
                <mat-icon inline=true fontSet="fa" fontIcon="fa-tachometer-alt" aria-label="Services"></mat-icon>
            </button>
        </a>
        <a mat-list-item>
            <button mat-icon-button>
                <mat-icon inline=true fontSet="fa" fontIcon="fa-chart-bar" aria-label="Analytics"></mat-icon>
            </button>
        </a>
        <a mat-list-item>
            <button mat-icon-button>
                <mat-icon inline=true fontSet="fa" fontIcon="fa-plus" aria-label="Compose"></mat-icon>
            </button>
        </a>

        <!-- This is where the bottom items reside.-->
        <div class="absolute bottom-0 left-0">
            <a mat-list-item>
                <button mat-icon-button>
                    <mat-icon inline=true fontSet="fa" fontIcon="fa-bell" aria-label="Notifications"></mat-icon>
                </button>
            </a>
            <a mat-list-item>
                <button mat-icon-button>
                    <mat-icon inline=true fontSet="fa" fontIcon="fa-user" aria-label="User Account"></mat-icon>
                </button>
            </a>
            <a mat-list-item>
                <button mat-icon-button>
                    <mat-icon inline=true fontSet="fa" fontIcon="fa-cog" aria-label="Settings"></mat-icon>
                </button>
            </a>
        </div>
    </mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
    <mat-sidenav-container>
        <mat-sidenav #navigation class="shadow border-0" fixedInViewport mode="side" opened>
            <app-navigation (toggleNavigation)="navigation.toggle()"></app-navigation>
        </mat-sidenav>
        <mat-sidenav-content class="page-wrap">
            <app-header></app-header>
            <main class="flex-1">
                <router-outlet></router-outlet>
            </main>
            <app-footer></app-footer>
        </mat-sidenav-content>
    </mat-sidenav-container>
</mat-sidenav-content>
</code>```

答:
Very interesting and logical question... getting the bottom 3 icons to stick to the bottom requires position:absolute, which causes the over-riding effect (which is exactly the effect which is expected with absolute positioning).

To get our ideal scenario, we gotta toggle the position:relative between position:absolute based on the breakpoint where the over-riding starts to take effect. This is where we needed JavaScript/TypeScript as CSS can't do this alone...

You can check complete working stackblitz here

this is the relevant TS file:

```<code>import {Component} from '@angular/core';
import {HostListener} from '@angular/core';

/** @title Sidenav open & close behavior */
@Component({
  selector: 'sidenav-open-close-example',
  templateUrl: 'sidenav-open-close-example.html',
  styleUrls: ['sidenav-open-close-example.css'],
})
export class SidenavOpenCloseExample {
  events: string[] = [];
  opened: boolean;
  appropriateClass:string = '';

  @HostListener('window:resize', ['$event'])
  getScreenHeight(event?){
    //console.log(window.innerHeight);
    if(window.innerHeight<=412){
      this.appropriateClass = 'bottomRelative';
    }else{
      this.appropriateClass = 'bottomStick';
    }
  }
  constructor(){
    this.getScreenHeight();
  }

  shouldRun = [/(^|\.)plnkr\.co$/, /(^|\.)stackblitz\.io$/].some(h => h.test(window.location.host));
}
</code>```

note the ngClass in the relevant HTML below:

```<code>  <mat-nav-list>
        <div class="">
          <a mat-list-item>
              <button mat-icon-button>
                  <mat-icon inline=true fontSet="fa" fontIcon="fa-users-cog" aria-label="Administrator"></mat-icon>
              </button>
          </a>
          <a mat-list-item>
              <button mat-icon-button>
                  <mat-icon inline=true fontSet="fa" fontIcon="fa-tachometer-alt" aria-label="Services"></mat-icon>
              </button>
          </a>
          <a mat-list-item>
              <button mat-icon-button>
                  <mat-icon inline=true fontSet="fa" fontIcon="fa-chart-bar" aria-label="Analytics"></mat-icon>
              </button>
          </a>
          <a mat-list-item>
              <button mat-icon-button>
                  <mat-icon inline=true fontSet="fa" fontIcon="fa-plus" aria-label="Compose"></mat-icon>
              </button>
          </a>
        </div>
        <!-- This is where the bottom items reside.-->
          <div [ngClass]='appropriateClass'>
              <a mat-list-item>
                  <button mat-icon-button>
                      <mat-icon inline=true fontSet="fa" fontIcon="fa-bell" aria-label="Notifications"></mat-icon>
                  </button>
              </a>
              <a mat-list-item>
                  <button mat-icon-button>
                      <mat-icon inline=true fontSet="fa" fontIcon="fa-user" aria-label="User Account"></mat-icon>
                  </button>
              </a>
              <a mat-list-item>
                  <button mat-icon-button>
                      <mat-icon inline=true fontSet="fa" fontIcon="fa-cog" aria-label="Settings"></mat-icon>
                  </button>
              </a>
          </div>

    </mat-nav-list>
</code>```

relevant CSS:

```<code>button {border:1px solid red}
.bottomStick{/*border-top:1px solid green;border-bottom:1px solid green;*/position:absolute; bottom:0}
.bottomRelative{position:relative;}
</code>```

Body:
I have just started using Angular Material and I wanted to implement the sidenav to have items that are at the bottom of the page. For now I am able to accomplish it with css.

position: absolute;
left: 0;
bottom: 0;

Is there any way to put spaces between items? My issue comes when I resize the page, the bottom items overlap with the items which are above.

I've included screenshots and the code below. Thanks.

<mat-sidenav-container class="h-screen w-screen">
<mat-sidenav #sidenav class="shadow border-0" fixedInViewport mode="side" opened>
    <mat-toolbar>
        <button mat-mini-fab color="warn" (click)="navigation.toggle()">
            <mat-icon inline=true fontSet="fa" fontIcon="fa-fire" aria-label="SLMC Logo"></mat-icon>
        </button>
    </mat-toolbar>
    <mat-nav-list>

            <button mat-icon-button>
                <mat-icon inline=true fontSet="fa" fontIcon="fa-users-cog" aria-label="Administrator"></mat-icon>
            </button>

            <button mat-icon-button>
                <mat-icon inline=true fontSet="fa" fontIcon="fa-tachometer-alt" aria-label="Services"></mat-icon>
            </button>

            <button mat-icon-button>
                <mat-icon inline=true fontSet="fa" fontIcon="fa-chart-bar" aria-label="Analytics"></mat-icon>
            </button>

            <button mat-icon-button>
                <mat-icon inline=true fontSet="fa" fontIcon="fa-plus" aria-label="Compose"></mat-icon>
            </button>

                <button mat-icon-button>
                    <mat-icon inline=true fontSet="fa" fontIcon="fa-bell" aria-label="Notifications"></mat-icon>
                </button>

                <button mat-icon-button>
                    <mat-icon inline=true fontSet="fa" fontIcon="fa-user" aria-label="User Account"></mat-icon>
                </button>

                <button mat-icon-button>
                    <mat-icon inline=true fontSet="fa" fontIcon="fa-cog" aria-label="Settings"></mat-icon>
                </button>

    </mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
    <mat-sidenav-container>
        <mat-sidenav #navigation class="shadow border-0" fixedInViewport mode="side" opened>
            <app-navigation (toggleNavigation)="navigation.toggle()"></app-navigation>
        </mat-sidenav>
        <mat-sidenav-content class="page-wrap">
            <app-header></app-header>

                <router-outlet></router-outlet>

            <app-footer></app-footer>
        </mat-sidenav-content>
    </mat-sidenav-container>
</mat-sidenav-content>

Body:
Very interesting and logical question... getting the bottom 3 icons to stick to the bottom requires position:absolute, which causes the over-riding effect (which is exactly the effect which is expected with absolute positioning).

To get our ideal scenario, we gotta toggle the position:relative between position:absolute based on the breakpoint where the over-riding starts to take effect. This is where we needed JavaScript/TypeScript as CSS can't do this alone...

You can check complete working stackblitz here

this is the relevant TS file:

import {Component} from '@angular/core';
import {HostListener} from '@angular/core';

/** @title Sidenav open & close behavior */
@Component({
  selector: 'sidenav-open-close-example',
  templateUrl: 'sidenav-open-close-example.html',
  styleUrls: ['sidenav-open-close-example.css'],
})
export class SidenavOpenCloseExample {
  events: string[] = [];
  opened: boolean;
  appropriateClass:string = '';

  @HostListener('window:resize', ['$event'])
  getScreenHeight(event?){
    //console.log(window.innerHeight);
    if(window.innerHeight<=412){
      this.appropriateClass = 'bottomRelative';
    }else{
      this.appropriateClass = 'bottomStick';
    }
  }
  constructor(){
    this.getScreenHeight();
  }

  shouldRun = [/(^|\.)plnkr\.co$/, /(^|\.)stackblitz\.io$/].some(h => h.test(window.location.host));
}

note the ngClass in the relevant HTML below:

  <mat-nav-list>
        <div class="">
          <a mat-list-item>
              <button mat-icon-button>
                  <mat-icon inline=true fontSet="fa" fontIcon="fa-users-cog" aria-label="Administrator"></mat-icon>
              </button>
          </a>
          <a mat-list-item>
              <button mat-icon-button>
                  <mat-icon inline=true fontSet="fa" fontIcon="fa-tachometer-alt" aria-label="Services"></mat-icon>
              </button>
          </a>
          <a mat-list-item>
              <button mat-icon-button>
                  <mat-icon inline=true fontSet="fa" fontIcon="fa-chart-bar" aria-label="Analytics"></mat-icon>
              </button>
          </a>
          <a mat-list-item>
              <button mat-icon-button>
                  <mat-icon inline=true fontSet="fa" fontIcon="fa-plus" aria-label="Compose"></mat-icon>
              </button>
          </a>
        </div>
        <!-- This is where the bottom items reside.-->
          <div [ngClass]='appropriateClass'>
              <a mat-list-item>
                  <button mat-icon-button>
                      <mat-icon inline=true fontSet="fa" fontIcon="fa-bell" aria-label="Notifications"></mat-icon>
                  </button>
              </a>
              <a mat-list-item>
                  <button mat-icon-button>
                      <mat-icon inline=true fontSet="fa" fontIcon="fa-user" aria-label="User Account"></mat-icon>
                  </button>
              </a>
              <a mat-list-item>
                  <button mat-icon-button>
                      <mat-icon inline=true fontSet="fa" fontIcon="fa-cog" aria-label="Settings"></mat-icon>
                  </button>
              </a>
          </div>

    </mat-nav-list>

relevant CSS:

button {border:1px solid red}
.bottomStick{/*border-top:1px solid green;border-bottom:1px solid green;*/position:absolute; bottom:0}
.bottomRelative{position:relative;}


问:
Segmentation fault when passing big integers as values in vector
Getting segmentation fault(Core Dumped) when big integers are passed. It works fine for smaller inputs.

Replaced int with long int and also tried to declare the variables globally, but still the same error. This function is used to perform a number of right circular rotations and return the value of the element at a given index. Here is the function:

```<code>    vector<long long int> circularArrayRotation(vector<long long int> a, long long int k, vector<long long int> queries) {
        vector <long long int> b;
        std::vector<long long int> result(queries.size());

        b=a;
        for(long long int j=0;j<k;j++)
        {
            for(long long int i=0;i<a.size();i++)
                a[i]=b[(a.size()+i-1)%a.size()];
            b=a;
        }

        for(long long int k=0;k<queries.size();k++)
            result[k]=a[queries[k]];
        for(long long int i=0;i<result.size();i++)
                cout<<result[i]<<endl;

        return result;

    }
</code>```

The remaining code can be found here link

答:
The problem can be queries[k] > a.size() at line
result[k]=a[queries[k]];
As we don't know actual inputs, it is really hard to pinpoint the reason.

Body:
Getting segmentation fault(Core Dumped) when big integers are passed. It works fine for smaller inputs.

Replaced int with long int and also tried to declare the variables globally, but still the same error. This function is used to perform a number of right circular rotations and return the value of the element at a given index. Here is the function:

    vector<long long int> circularArrayRotation(vector<long long int> a, long long int k, vector<long long int> queries) {
        vector <long long int> b;
        std::vector<long long int> result(queries.size());

        b=a;
        for(long long int j=0;j<k;j++)
        {
            for(long long int i=0;i<a.size();i++)
                a[i]=b[(a.size()+i-1)%a.size()];
            b=a;
        }

        for(long long int k=0;k<queries.size();k++)
            result[k]=a[queries[k]];
        for(long long int i=0;i<result.size();i++)
                cout<<result[i]<<endl;

        return result;

    }

The remaining code can be found here link


问:
How to build every project in a solution by using msbuild.exe
Is there a possibility to build every project within a solution by using msbuild in the command line? I'm using Visual Studio 2008</p>

答:
Have you tried:</p>

```<code>msbuild mySolution.sln /p:Configuration=Debug
</code>```

Body:
Have you tried:

msbuild mySolution.sln /p:Configuration=Debug


问:
Flow with redux - passing union type gives error
I have this type:

```<code>export type Action<P> = {
  type: string,
  payload: P
}
</code>```

I now need to pass a return type to Dispatch, which I want to be an Action<number> or an Action<boolean>

Why can I not do this?

```<code>const mapDispatchToProps = (dispatch: Dispatch<Action<number | boolean>>) => {
  return bindActionCreators(
    {
      updateAlertModalHeight: updateAlertModalHeight,
      updateAlertModalIsOpen: updateAlertModalIsOpen,
      updateHasYesNo: updateAlertModalHasYesNo
    },
    dispatch
  )
}
</code>```

It doesn't let me do Action<number> | Action<boolean> either.

The error is:

Cannot call bindActionCreators because number [1] is incompatible
  with boolean [2] in type argument P [3] of type argument A [4] of
  property updateAlertModalHeight of type argument C. (References:
  [1] [2] [3] [4])flow

Where am I going wrong?

Here is updateAlertModalHeight from the error message:

```<code>export const updateAlertModalHeight: ActionCreator<Action<number>, number> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_HEIGHT,
  payload
})
</code>```

and:

```<code>export const updateAlertModalIsOpen: ActionCreator<Action<boolean>, boolean> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_IS_OPEN,
  payload
})
</code>```

the two action creators have a different type and Flow is not allowing them to be used in the same bindActionCreators call. How do I get flow to allow it?

It all seems to work when I make everything this type:

```<code>export type ActionT = Action<boolean | string | number>

export const updateAlertModalIsOpen: ActionCreator<ActionT, boolean> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_IS_OPEN,
  payload
})
</code>```

and:

```<code>const mapDispatchToProps = (dispatch: Dispatch<ActionT>) => {
</code>```

But that is less specific typing which sucks because it doesn't describe which type of action is being returned.

I would like to edit the redux type definitions to allow multiple Action types but it is difficult to understand what change to make.

答:
The generic type argument of dispatch is invariant, which means that it cannot be anything else than exactly what you specified — in particular, it cannot be specialized to number from boolean|number.  Intuitively,  the type information number is more specific than boolean|number.

The actual problem is the type of bindActionCreators, which enforces the same type argument as you give to dispatch to both updateAlertModalHeight, and updateAlertModalIsOpen. But these functions take different types of arguments! One takes a number, and one a Boolean, hence the type checker can't infer the types correctly. It works when you change the type argument of updateAlertModalHeight and updateAlertModalIsOpen to allow for being called with either type, i.e. saying "it's OK if you pass a number, I'll ignore it, and only act if you pass me a boolean." The type system sees it can pass both a number and boolean to the functions and therefore everything type checks.

The real solution here that does not rely on changing the argument types, would be to do two calls to  bindActionCreators, once with a number-dispatch and once with boolean-dispatch.

Body:
I have this type:

export type Action
 = {
  type: string,
  payload: P
}

I now need to pass a return type to Dispatch, which I want to be an Action<number> or an Action<boolean>

Why can I not do this?

const mapDispatchToProps = (dispatch: Dispatch<Action<number | boolean>>) => {
  return bindActionCreators(
    {
      updateAlertModalHeight: updateAlertModalHeight,
      updateAlertModalIsOpen: updateAlertModalIsOpen,
      updateHasYesNo: updateAlertModalHasYesNo
    },
    dispatch
  )
}

It doesn't let me do Action<number> | Action<boolean> either.

The error is:

Cannot call bindActionCreators because number [1] is incompatible
  with boolean [2] in type argument P [3] of type argument A [4] of
  property updateAlertModalHeight of type argument C. (References:
  [1] [2] [3] [4])flow

Where am I going wrong?

Here is updateAlertModalHeight from the error message:

export const updateAlertModalHeight: ActionCreator<Action<number>, number> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_HEIGHT,
  payload
})

and:

export const updateAlertModalIsOpen: ActionCreator<Action<boolean>, boolean> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_IS_OPEN,
  payload
})

the two action creators have a different type and Flow is not allowing them to be used in the same bindActionCreators call. How do I get flow to allow it?

It all seems to work when I make everything this type:

export type ActionT = Action<boolean | string | number>

export const updateAlertModalIsOpen: ActionCreator<ActionT, boolean> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_IS_OPEN,
  payload
})

and:

const mapDispatchToProps = (dispatch: Dispatch<ActionT>) => {

But that is less specific typing which sucks because it doesn't describe which type of action is being returned.

I would like to edit the redux type definitions to allow multiple Action types but it is difficult to understand what change to make.