问:
Is it possible to create a category of the "Block" object in Objective-C
I would like to add functions by creating a category for Objective-C Blocks.

```<code>__block int (^aBlock)(int) = ^int( int n ){
    if( n <= 1 ) return n;
    return aBlock( n - 1 ) + aBlock( n - 2 );
};
</code>```

Instead of just allowing the normal [aBlock copy], [aBlock retain], [aBlock release], [aBlock autorelease]. I could do thing like:

```<code>[aBlock mapTo:anArray];
</code>```

Possible Category

```<code>@interface UnknownBlockClass (map)

- (NSArray *)mapTo:(NSArray *)array_;

@end
</code>```

答:
The simple answer is no. A __block variable is a C level object not an Objective C object. You can call [aBlock copy] but this invokes a C function block_copy() not the nsobject copy method. So the __block type is a C type and therefore you can't add categories.

correction:__block is an identifier in the C compiler not a typedef.

I'm not sure if this will achieve what you think it will, infact I'm not even quite sure what it does:

```<code>__block int (^aBlock)(int) = ^int( int n ){
if( n <= 1 ) return n;
return fib( n - 1 ) + fib( n - 2 );
};
</code>```

the __block identifier tells the complier that the variable should be mutable in referencing blocks and should be preserved if any referencing block is copied to the heap. what confuses me about your code is that __block is usually used to wrap a variable, not a block itself.

Body:
I would like to add functions by creating a category for Objective-C Blocks.

__block int (^aBlock)(int) = ^int( int n ){
    if( n <= 1 ) return n;
    return aBlock( n - 1 ) + aBlock( n - 2 );
};

Instead of just allowing the normal [aBlock copy], [aBlock retain], [aBlock release], [aBlock autorelease]. I could do thing like:

[aBlock mapTo:anArray];

Possible Category

@interface UnknownBlockClass (map)

- (NSArray *)mapTo:(NSArray *)array_;

@end

Body:
The simple answer is no. A __block variable is a C level object not an Objective C object. You can call [aBlock copy] but this invokes a C function block_copy() not the nsobject copy method. So the __block type is a C type and therefore you can't add categories.

correction:__block is an identifier in the C compiler not a typedef.

I'm not sure if this will achieve what you think it will, infact I'm not even quite sure what it does:

__block int (^aBlock)(int) = ^int( int n ){
if( n <= 1 ) return n;
return fib( n - 1 ) + fib( n - 2 );
};

the __block identifier tells the complier that the variable should be mutable in referencing blocks and should be preserved if any referencing block is copied to the heap. what confuses me about your code is that __block is usually used to wrap a variable, not a block itself.


来源: stackexchange

问:
How to query based on child dictionary in firebase? Objective C

Okay so I have this User data. This is just one of the many users in my database. I want to be able to get all users that have a certain key in the "friends" dictionary. How would I do that?

I've tried

```<code>[[[[ref child:@"Users"]queryOrderedByChild:@"friends"] queryEqualToValue:[my uid]] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
</code>```

答:
You are querying equal to value with a uid but you have ordered by child with friends; the value of the snapshots inside friends is a number but you want to query equal to the key.

You can do this by adjusting your queryOrderedByChild to contain the uid you would like to check for, and query equal to 1 instead. The query child path can be made by interpolating the uid into a string already containing friends/ like so [NSString stringWithFormat:@"friends/%@", uid].

ContentLicense: CC BY-SA 3.0

Body:
Okay so I have this User data. This is just one of the many users in my database. I want to be able to get all users that have a certain key in the "friends" dictionary. How would I do that?

I've tried

[[[[ref child:@"Users"]queryOrderedByChild:@"friends"] queryEqualToValue:[my uid]] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {


问:
Iterating over flat array and building json in PHP
I have a flat array of files that's dynamically built from a directory structure, a sample of such output can be seen here;

```<code>Array (
    [0] => filename-in-root.png
    [1] => another-filename-in-root.png
    [directory.subdirectory.0] => logo-of-some-sort.jpeg
    [directory.subdirectory.1] => image-of-queen.jpg
    [anotherdirectory.0] => a-screenshot-png
    [anotherdir.0] => a-lovely-picture.png
    [nextdirectory.0] => me-giving-the-bird.png
)
</code>```

Then what im doing is feeding this output into another function to produce json output i can plug into my javascript component.

It works great for files in the root, and also if there is only 1 file in a directory / subdirectory ... BUT when adding multiple files to directories and subdirectories, it causes the directory structure to be output again as seen below;

```<code>[
    [0,"/","/",false,1],
    [1,"/filename-in-root.png","filename-in-root.png",true,1],
    [2,"/another-filename-in-root.png","another-filename-in-root.png",true,1],
    [3,"/directory","Directory",false,1],
    [4,"/directory/subdirectory","Subdirectory",false,2],
    [5,"/directory/subdirectory/logo-of-some-sort.jpeg","logo-of-some-sort.jpeg",true,3],
    [6,"/directory","Directory",false,1],
    [7,"/directory/subdirectory","Subdirectory",false,2],
    [8,"/directory/subdirectory/image-of-queen.jpg","image-of-queen.jpg",true,3],
    and so on.........
]
</code>```

As you can see, item 6 and 7 shouldnt be there as item 8 is already marked in the right directory, the number at the end indicates how many indents it should have.

The code im using to generate this is as follows;

```<code>function generateJson($flatArray)
{
    $arrayId = 1;
    $final_array = [[0, '/', '/', false, 1]];
    ksort($flatArray, SORT_STRING);

    foreach ($flatArray as $key => $val) {
        $exploded_key = explode('.', $key);
        foreach ($exploded_key as $k => $v) {
            if ($k == sizeof($exploded_key)-1) {
                $count = 1;
                for ($i = 0; $i < count(array_slice($exploded_key, 0, $k)); $i++) {
                    $count++;
                }
                $final_array[] = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k)) . '/' . $val, $val, true, $count];
                $arrayId++;
            } else {
                $count = 1;
                for ($i = 0; $i < count(array_slice($exploded_key, 0, $k)); $i++) {
                    $count++;
                }
                $final_array[] = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k + 1)), ucfirst($v), false, $count];
                $arrayId++;
            }
        }
    }

    return json_encode($final_array);
}
</code>```

Im so stuck on this ... any help would be greatly appreciated.

答:
Before appending any element to the $final_array (which is json_encoded), we can check if it already exists to avoid duplication.

Also we can decrease the duplication in the code:

```<code>function generateJson($flatArray)
{
    $arrayId = 1;
    $final_array = [[0, '/', '/', false, 1]];
    $final_paths = []; // New array to store paths
    ksort($flatArray, SORT_STRING);
    foreach ($flatArray as $key => $val) {
        $exploded_key = explode('.', $key);
        foreach ($exploded_key as $k => $v) {
            $count = 1;
            // Changes start from here (in addition to initializing $final_paths array above)
            $end = count(array_slice($exploded_key, 0, $k));
            for ($i = 0; $i < $end; $i++) {
                $count++;
            }
            // The only statement changed is wrapped with the if-statement
            if ($k == sizeof($exploded_key)-1) {
                $new_element = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k)) . '/' . $val, $val, true, $count];
            } else {
                $new_element = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k + 1)), ucfirst($v), false, $count];
            }
            // *This is it*: append the element ONLY IF it is not in the array
            if(!in_array($new_element[1], $final_paths)) {
                $final_paths[] = $new_element[1];
                $final_array[] = $new_element;
                $arrayId++;
            }
        }
    }
    return json_encode($final_array);
}
</code>```

Maybe not the best solution (from running-time perspective), but it should work.

Body:
I have a flat array of files that's dynamically built from a directory structure, a sample of such output can be seen here;

Array (
    [0] => filename-in-root.png
    [1] => another-filename-in-root.png
    [directory.subdirectory.0] => logo-of-some-sort.jpeg
    [directory.subdirectory.1] => image-of-queen.jpg
    [anotherdirectory.0] => a-screenshot-png
    [anotherdir.0] => a-lovely-picture.png
    [nextdirectory.0] => me-giving-the-bird.png
)

Then what im doing is feeding this output into another function to produce json output i can plug into my javascript component.

It works great for files in the root, and also if there is only 1 file in a directory / subdirectory ... BUT when adding multiple files to directories and subdirectories, it causes the directory structure to be output again as seen below;

[
    [0,"/","/",false,1],
    [1,"/filename-in-root.png","filename-in-root.png",true,1],
    [2,"/another-filename-in-root.png","another-filename-in-root.png",true,1],
    [3,"/directory","Directory",false,1],
    [4,"/directory/subdirectory","Subdirectory",false,2],
    [5,"/directory/subdirectory/logo-of-some-sort.jpeg","logo-of-some-sort.jpeg",true,3],
    [6,"/directory","Directory",false,1],
    [7,"/directory/subdirectory","Subdirectory",false,2],
    [8,"/directory/subdirectory/image-of-queen.jpg","image-of-queen.jpg",true,3],
    and so on.........
]

As you can see, item 6 and 7 shouldnt be there as item 8 is already marked in the right directory, the number at the end indicates how many indents it should have.

The code im using to generate this is as follows;

function generateJson($flatArray)
{
    $arrayId = 1;
    $final_array = [[0, '/', '/', false, 1]];
    ksort($flatArray, SORT_STRING);

    foreach ($flatArray as $key => $val) {
        $exploded_key = explode('.', $key);
        foreach ($exploded_key as $k => $v) {
            if ($k == sizeof($exploded_key)-1) {
                $count = 1;
                for ($i = 0; $i < count(array_slice($exploded_key, 0, $k)); $i++) {
                    $count++;
                }
                $final_array[] = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k)) . '/' . $val, $val, true, $count];
                $arrayId++;
            } else {
                $count = 1;
                for ($i = 0; $i < count(array_slice($exploded_key, 0, $k)); $i++) {
                    $count++;
                }
                $final_array[] = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k + 1)), ucfirst($v), false, $count];
                $arrayId++;
            }
        }
    }

    return json_encode($final_array);
}

Im so stuck on this ... any help would be greatly appreciated.

Body:
Before appending any element to the $final_array (which is json_encoded), we can check if it already exists to avoid duplication.

Also we can decrease the duplication in the code:

function generateJson($flatArray)
{
    $arrayId = 1;
    $final_array = [[0, '/', '/', false, 1]];
    $final_paths = []; // New array to store paths
    ksort($flatArray, SORT_STRING);
    foreach ($flatArray as $key => $val) {
        $exploded_key = explode('.', $key);
        foreach ($exploded_key as $k => $v) {
            $count = 1;
            // Changes start from here (in addition to initializing $final_paths array above)
            $end = count(array_slice($exploded_key, 0, $k));
            for ($i = 0; $i < $end; $i++) {
                $count++;
            }
            // The only statement changed is wrapped with the if-statement
            if ($k == sizeof($exploded_key)-1) {
                $new_element = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k)) . '/' . $val, $val, true, $count];
            } else {
                $new_element = [$arrayId, '/' . join('/', array_slice($exploded_key, 0, $k + 1)), ucfirst($v), false, $count];
            }
            // *This is it*: append the element ONLY IF it is not in the array
            if(!in_array($new_element[1], $final_paths)) {
                $final_paths[] = $new_element[1];
                $final_array[] = $new_element;
                $arrayId++;
            }
        }
    }
    return json_encode($final_array);
}

Maybe not the best solution (from running-time perspective), but it should work.


问:
VBA - Export excel charts to power point on same slide
```<code>Sub Export_Allcahrts_ppt()

Dim mypowerpoint As PowerPoint.Application

Set mypowerpoint = New PowerPoint.Application

mypowerpoint.Visible = msoTrue

Dim mypowerpoint_pres  As PowerPoint.Presentation

Set mypowerpoint_pres = mypowerpoint.Presentations.Add

Dim myslide  As PowerPoint.Slide

Set myslide = mypowerpoint_pres.Slides.Add(1, ppLayoutBlank)

Dim mychart  As ChartObject

Dim j As Long
j = 0
For Each mychart In Sheet1.ChartObjects
j = j + 1
Next

For Each mychart In Sheet1.ChartObjects

mychart.Copy

myslide.Shapes.PasteSpecial ppPasteBitmap

myslide.Shapes(1).Top = 100

myslide.Shapes(1).Height = 200

myslide.Shapes(1).Left = 30

If mypowerpoint_pres.Slides.Count < j Then

Set myslide = mypowerpoint_pres.Slides.Add(mypowerpoint_pres.Slides.Count + 1, ppLayoutBlank)

Else

Exit Sub

End If

Next

End Sub
</code>```

答:
First, you don't need to loop to get j; just use

```<code>j = Sheet1.ChartObjects.Count
</code>```

But you also don't need j at all. What your code does is insert a new slide for each new chart if the number of slides does not yet equal the number of charts copied so far.

So try this slightly rearranged and streamlined code. I haven't tested it, but I don't think I've changed the syntax.

```<code>Sub Export_Allcahrts_ppt()
  Dim mypowerpoint As PowerPoint.Application
  Dim mypowerpoint_pres As PowerPoint.Presentation
  Dim myslide As PowerPoint.Slide
  Dim mychart As ChartObject
  Dim j As Long

  Set mypowerpoint = New PowerPoint.Application
  mypowerpoint.Visible = msoTrue

  Set mypowerpoint_pres = mypowerpoint.Presentations.Add

  Set myslide = mypowerpoint_pres.Slides.Add(1, ppLayoutBlank)

  j = Sheet1.ChartObjects.Count

  For Each mychart In Sheet1.ChartObjects
    mychart.Copy
    myslide.Shapes.PasteSpecial ppPasteBitmap

    With myslide.Shapes(myslide.Shapes.Count)
      .Top = 100
      .Height = 200
      .Left = 30
    End With
  Next

End Sub
</code>```

Body:
First, you don't need to loop to get j; just use

j = Sheet1.ChartObjects.Count

But you also don't need j at all. What your code does is insert a new slide for each new chart if the number of slides does not yet equal the number of charts copied so far.

So try this slightly rearranged and streamlined code. I haven't tested it, but I don't think I've changed the syntax.

Sub Export_Allcahrts_ppt()
  Dim mypowerpoint As PowerPoint.Application
  Dim mypowerpoint_pres As PowerPoint.Presentation
  Dim myslide As PowerPoint.Slide
  Dim mychart As ChartObject
  Dim j As Long

  Set mypowerpoint = New PowerPoint.Application
  mypowerpoint.Visible = msoTrue

  Set mypowerpoint_pres = mypowerpoint.Presentations.Add

  Set myslide = mypowerpoint_pres.Slides.Add(1, ppLayoutBlank)

  j = Sheet1.ChartObjects.Count

  For Each mychart In Sheet1.ChartObjects
    mychart.Copy
    myslide.Shapes.PasteSpecial ppPasteBitmap

    With myslide.Shapes(myslide.Shapes.Count)
      .Top = 100
      .Height = 200
      .Left = 30
    End With
  Next

End Sub


问:
How to deliver data to other page in Framework7?
How to deliver the data to the detail page ?

You see the below demo I write, I am studying Framework7, but I am puzzle about to deliver data to the detail page.

Such as I click the first item, I want to deliver the index = 0 to the detail page, if I click the second item, I want to deliver index = 1 to the detail page.

My code is below:

```<code><ul>
  <li class="item-content">
     <div class="item-media"><a href="about.html"><img src="http://up.qqjia.com/z/25/tu32695_9.jpg" width="44"></a></div>
     <div class="item-inner">
     <div class="item-title-row">
          <div class="item-title">Daniel</div>
     </div>
     <div class="item-subtitle">CEO</div>
     </div>

  </li>
  ...
</ul>
</code>```

You see,I goto the about page is use  label, so, How can I deliver the index number, and so I can dynamic set the about page's data.

If there get a demo, maybe that explain more detail.

答:
I opted for an easier way.

Set the data attribute on the 'a' tag:

```<code><a href="#nextpage" data-myfieldname="myfieldvalue">
</code>```

Then retrieve the data from the Javascript's click event handler:

```<code>mydata = $(this).data('myfieldname');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to deliver the data to the detail page ?

You see the below demo I write, I am studying Framework7, but I am puzzle about to deliver data to the detail page.

Such as I click the first item, I want to deliver the index = 0 to the detail page, if I click the second item, I want to deliver index = 1 to the detail page.

My code is below:

Daniel

CEO

  ...

You see,I goto the about page is use  label, so, How can I deliver the index number, and so I can dynamic set the about page's data.

If there get a demo, maybe that explain more detail.

Body:
I opted for an easier way.

Set the data attribute on the 'a' tag:

<a href="#nextpage" data-myfieldname="myfieldvalue">

Then retrieve the data from the Javascript's click event handler:

mydata = $(this).data('myfieldname');


问:
Cannot add object of type T to List<T> in java
I have been learning generics in Java. Although I understand the concepts regarding type inference, parameterized classes and methods, I came across a strange scenario while experimenting.

I have implemented a Box class which can be used to hold items of type T. I am using List as an internal data structure for this abstraction. Following is my code:

```<code>public class Box<T> {

    private List<T> items;

    public Box(){
        items = new ArrayList<>();
    }

    public <T> void addItemToBox(T t){
        items.add(t);
    }
}
</code>```

I am getting a compile time error at items.add(t) saying add(T) in List cannot be applied to (T). I am unable to figure out the cause of this error. Also, I don't understand why I can't add an item of type T to a list which is parameterized by T.

答:
You've made a local redeclaration of generic type variable <T> on your method addItemToBox that shadows the one on class Box<T>.

The <T> on your method is not the same  on List<T> items;

Your current code is 100% equivalent to:

```<code>public class Box<T> {

    private List<T> items;

    public Box(){
        items = new ArrayList<>();
    }

    public <T2> void addItemToBox(T2 t){
        items.add(t);
    }
}
</code>```

If you see it that way, it should be clear why your code fails to compile.

Solution: remove the <T> in front of the method declaration

```<code>public void addItemToBox(T t)
</code>```

Body:
I have been learning generics in Java. Although I understand the concepts regarding type inference, parameterized classes and methods, I came across a strange scenario while experimenting.

I have implemented a Box class which can be used to hold items of type T. I am using List as an internal data structure for this abstraction. Following is my code:

public class Box<T> {

    private List<T> items;

    public Box(){
        items = new ArrayList<>();
    }

    public <T> void addItemToBox(T t){
        items.add(t);
    }
}

I am getting a compile time error at items.add(t) saying add(T) in List cannot be applied to (T). I am unable to figure out the cause of this error. Also, I don't understand why I can't add an item of type T to a list which is parameterized by T.

Body:
You've made a local redeclaration of generic type variable <T> on your method addItemToBox that shadows the one on class Box<T>.

The <T> on your method is not the same  on List<T> items;

Your current code is 100% equivalent to:

public class Box<T> {

    private List<T> items;

    public Box(){
        items = new ArrayList<>();
    }

    public <T2> void addItemToBox(T2 t){
        items.add(t);
    }
}

If you see it that way, it should be clear why your code fails to compile.

Solution: remove the <T> in front of the method declaration

public void addItemToBox(T t)


问:
How to not specify an optional parameter?
The img function for the canvas context has parameters like this:

img, sx (optional), sy (optional), swidth (optional), sheight (optional), x, y

As you can see, there are optional parameters in between img and x. How would I specify that I don't want to use sx sy swidth or sheight and skip to x?

答:
If you're talking about the CanvasRenderingContext2D.drawImage() method, then it actually allows you to just pass those three arguments:

```<code>ctx.drawImage(img, x, y);
</code>```

For more information, see MDN.

Body:
If you're talking about the CanvasRenderingContext2D.drawImage() method, then it actually allows you to just pass those three arguments:

ctx.drawImage(img, x, y);

For more information, see MDN.


问:
Functors () overloading for classes
I do not think this is possible and curious if it is or why it is not:

```<code>class A
{

}
</code>```

I would like to treat instances of A as functions such as

```<code>A a = new A();

a();
or
a(3);
etc...
</code>```

This is to treat classes as functions for special cases when it is useful to do so. For example, I'm essentially wrapping a Func object but would love to treat an instance of such a class to act as the Func object itself. This way I don't have to have a "dummy" function to call in the class.

```<code>    public class Condition
    {
        protected Func<bool> Eval { get; set; }
        protected bool Or = false;

        protected Condition() { }
        public Condition(Func<bool> f, bool Or = false) { Eval = f; this.Or = Or; }
        protected Func<bool> GetEval(Condition c) { return c.Eval; }
        protected bool GetOr(Condition c) { return c.Or; }

    }

    public class ConditionBlock : Condition
    {
        List<Condition> Conditions;

        public ConditionBlock() { Eval = _Eval; }

        public ConditionBlock(List<Condition> Conditions) : this() { this.Conditions = Conditions; }
        public ConditionBlock(Condition[] Conditions) : this() { this.Conditions = new List<Condition>(Conditions); }
        public void Add(Condition c) { if (Conditions == null) Conditions = new List<Condition>(); Conditions.Add(c); }

        private bool _Eval()
        {
            if (Conditions == null || Conditions.Count == 0) return true;

            bool ans = !GetOr(Conditions[0]);
            for (int i = 0; i < Conditions.Count; i++)
                ans = GetOr(Conditions[i]) ? ans | GetEval(Conditions[i])() : ans & GetEval(Conditions[i])();

            return ans;
        }

        public bool _()
        {
            return Eval();
        }
    }
</code>```

To initiate the Computation I call the member (), e.g., cblock.(). It would look much nicer if I could call it as cblock(). Effectively a ConditionBlock is a compound function. Would be nice to be able to treat it as such. Using _() is quite ugly as is renaming it to anything else such as cblock.fire(), cblock.eval(), etc...

答:
You can't overload the () operator in C#, but that's what delegates are for; they do what you describe, e.g.:

```<code>class AccumulateToString
{
    private int sum;
    public string ToString(int val)
    { this.sum += val; return this.sum.ToString(); }
}
var fn = new Converter<int, string>(new AccumulateToString().ToString);
Console.WriteLine(fn(2)); // <-- called like a function but is an object w/ state
</code>```

ContentLicense: CC BY-SA 2.5

Title: Functors () overloading for classes

Body:
I do not think this is possible and curious if it is or why it is not:

class A
{

}

I would like to treat instances of A as functions such as

A a = new A();

a();
or
a(3);
etc...

This is to treat classes as functions for special cases when it is useful to do so. For example, I'm essentially wrapping a Func object but would love to treat an instance of such a class to act as the Func object itself. This way I don't have to have a "dummy" function to call in the class.

    public class Condition
    {
        protected Func<bool> Eval { get; set; }
        protected bool Or = false;

        protected Condition() { }
        public Condition(Func<bool> f, bool Or = false) { Eval = f; this.Or = Or; }
        protected Func<bool> GetEval(Condition c) { return c.Eval; }
        protected bool GetOr(Condition c) { return c.Or; }

    }

    public class ConditionBlock : Condition
    {
        List<Condition> Conditions;

        public ConditionBlock() { Eval = _Eval; }

        public ConditionBlock(List<Condition> Conditions) : this() { this.Conditions = Conditions; }
        public ConditionBlock(Condition[] Conditions) : this() { this.Conditions = new List<Condition>(Conditions); }
        public void Add(Condition c) { if (Conditions == null) Conditions = new List<Condition>(); Conditions.Add(c); }

        private bool _Eval()
        {
            if (Conditions == null || Conditions.Count == 0) return true;

            bool ans = !GetOr(Conditions[0]);
            for (int i = 0; i < Conditions.Count; i++)
                ans = GetOr(Conditions[i]) ? ans | GetEval(Conditions[i])() : ans & GetEval(Conditions[i])();

            return ans;
        }

        public bool _()
        {
            return Eval();
        }
    }

To initiate the Computation I call the member (), e.g., cblock.(). It would look much nicer if I could call it as cblock(). Effectively a ConditionBlock is a compound function. Would be nice to be able to treat it as such. Using _() is quite ugly as is renaming it to anything else such as cblock.fire(), cblock.eval(), etc...

Body:
You can't overload the () operator in C#, but that's what delegates are for; they do what you describe, e.g.:

class AccumulateToString
{
    private int sum;
    public string ToString(int val)
    { this.sum += val; return this.sum.ToString(); }
}
var fn = new Converter<int, string>(new AccumulateToString().ToString);
Console.WriteLine(fn(2)); // <-- called like a function but is an object w/ state


问:
Remove specific parameter from URL while preserving other parameters
I want remove a parameter from a URL:

```<code>$linkExample1='https://stackoverflow.com/?name=alaa&counter=1';
$linkExample2='https://stackoverflow.com/?counter=4&star=5';
</code>```

I am trying to get this result:

https://stackoverflow.com/?name=alaa&

https://stackoverflow.com/?&star=5

I am trying to do it using preg_replace, but I've no idea how it can be done.

答:
This is working for me:</p>

```<code>function removeParameterFromUrl($url, $key)
{
    $parsed = parse_url($url);
    $path = $parsed['path'];
    unset($_GET[$key]);
    if(!empty(http_build_query($_GET))){
      return $path .'?'. http_build_query($_GET);
    } else return $path;
}
</code>```

Body:
I want remove a parameter from a URL:

$linkExample1='https://stackoverflow.com/?name=alaa&counter=1';
$linkExample2='https://stackoverflow.com/?counter=4&star=5';

I am trying to get this result:

https://stackoverflow.com/?name=alaa&

https://stackoverflow.com/?&star=5

I am trying to do it using preg_replace, but I've no idea how it can be done.

Body:
This is working for me:

function removeParameterFromUrl($url, $key)
{
    $parsed = parse_url($url);
    $path = $parsed['path'];
    unset($_GET[$key]);
    if(!empty(http_build_query($_GET))){
      return $path .'?'. http_build_query($_GET);
    } else return $path;
}


问:
form semantic-ui dropdown selection in angular 2
When I select an item in my dropdown, the empty falues in my form won't change. The formcontrol didn't get the data. Here is my html. I am using data-value in getting the selected value of the field

    <input name="category" type="hidden" formControlName="category">

Select Category...

{{item.name}}

```

答:
I already solved this. I just used <select> instead of
 and used [attr.value]="item._id" in the <option> to get the selected item's id or value.

Body: I already solved this. I just used <select> instead of <div> and used [attr.value]="item._id" in the <option> to get the selected item's id or value.


问:
All possible 0 and 1 matrices of a normal graph
To better explain what I need, here is my first code:

```<code>function allpos = f1(x)
allpos=reshape(permute((dec2base(0:power(2,x*x)-1,2)-'0'),[3 2 1]),x,x,[]);
</code>```

This code does exactly what I need it to. If the users inputs f1(2), it returns every matrix from [0 0; 0 0] to [1 1; 1 1]. However, it also gives me a lot of useless matrices. I only want matrices that are mirrored across the diagonal, with only zeros on the diagonal.

To put more simply, for f1(3), I only want
[0 0 0; 0 0 0; 0 0 0] to [0 1 1; 1 0 1; 1 1 0]. That means that if I run the new f1(3); it will return 8 matrices, not 512.

How do I rewrite the function to do this? I know that it will require some sort of addition of a triangular matrix and its transposed self, but I cant piece it together. Thanks!

答:
It can probably be made more concise but the following does what you ask.</p>

```<code>function allpos = f1(x)
N = (x-1)*x / 2;
z = permute(dec2base(0:power(2,N)-1,2)-'0',[3 2 1]);
allpos = zeros(x,x,power(2,N));
idx = repmat(logical(tril(ones(x),-1)),[1,1,power(2,N)]);
allpos(idx) = z(:);
allpos = permute(allpos,[2 1 3]);
allpos(idx) = z(:);
</code>```

Body:
To better explain what I need, here is my first code:

function allpos = f1(x)
allpos=reshape(permute((dec2base(0:power(2,x*x)-1,2)-'0'),[3 2 1]),x,x,[]);

This code does exactly what I need it to. If the users inputs f1(2), it returns every matrix from [0 0; 0 0] to [1 1; 1 1]. However, it also gives me a lot of useless matrices. I only want matrices that are mirrored across the diagonal, with only zeros on the diagonal.

To put more simply, for f1(3), I only want
[0 0 0; 0 0 0; 0 0 0] to [0 1 1; 1 0 1; 1 1 0]. That means that if I run the new f1(3); it will return 8 matrices, not 512.

How do I rewrite the function to do this? I know that it will require some sort of addition of a triangular matrix and its transposed self, but I cant piece it together. Thanks!

Body:
It can probably be made more concise but the following does what you ask.

function allpos = f1(x)
N = (x-1)*x / 2;
z = permute(dec2base(0:power(2,N)-1,2)-'0',[3 2 1]);
allpos = zeros(x,x,power(2,N));
idx = repmat(logical(tril(ones(x),-1)),[1,1,power(2,N)]);
allpos(idx) = z(:);
allpos = permute(allpos,[2 1 3]);
allpos(idx) = z(:);


问:
HTML5/JavaScript Windows Store App packaged using VS2013 vs VS2017
I have a HTML5/JavaScript Store project built on VS2013 using WinJS2.0 and AngularJS. The app is pretty matured at this stage and runs fine both Windows 8.1 and Windows 10. However, when I try to built the same project using VS2017 I am running into issues with following objects

MSPointerEvent

execUnsafeLocalFunction

From what I understand is Windows Store App built using HTML/JavaScript using Edge underneath to execute. So why does it matter if I am using a different IDE to build the package. IDE is not performing any compilation.
Please advice

答:
You've changed from a Windows Store app (W8.1, backed by IE) to a UWP app (W10, backed by Edge). VS2013 can't create UWP apps and VS2017 can't create Windows Store apps, so you must have ported.

In particular, pointer events are now a w3c standard, and the MS-prefixed versions are removed from EdgeHtml in favor of standardized pointer events. See Pointer Event Updates

The execUnsafeLocalFunction has been removed in favor of a new security model. See Keep your app secure – Setting Application Content URI Rules (ACURs)


问:
What's the defference between "-Dorg.gradle.project.env=demo" and "-Denv=demo" in gradle?
Today I'm trying to use the system property in my code .When I enter ./gradlew -Dorg.gradle.project.env=demo test ,the NullPointExcepetion happens,though I println env in script successfully!Then I try another way , entering ./gradlew -Denv=demo test and my code get the env set in command line successfully .So my question is What's the defference between "-Dorg.gradle.project.env=demo" and "-Denv=demo" in gradle?P.s. This link(12.2. Gradle properties and system properties in https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_properties_and_system_properties) told me to use org.gradle.project to set system property.I guess when you use org.gradle.project, you should use another method to get system property ,not using
    System.getProperty("env")

答:
I guess when you use org.gradle.project, you should use another method to get system property, not using System.getProperty("env")

You're right. This two syntaxes are different and serve different purposes.

The latter one, -Denv is a standard way of passing system properties in Java world. If you run java -help you'll see:

-D<name>=<value> set a system property

So, when you use it, env system property becomes available via System.getProperty("env") and it's value will be demo.

The first one -Dorg.gradle.project.env is actually a system property too! It's obvious after reading the lines above. However, it sets a system property named org.gradle.project.env, not just env. So, unless your test expect this name, it won't work. And your tests must no expect this name, because they should, generally, be unaware of the build tool.

What Gradle docs says is:

Gradle offers a variety of ways to add properties to your build. With the -D command line option you can pass a system property to the JVM which runs Gradle. The -D option of the gradle command has the same effect as the -D option of the java command.

Gradle can also set project properties when it sees specially-named system properties or environment variables. This feature is very useful when you don’t have admin rights to a continuous integration server and you need to set property values that should not be easily visible, typically for security reasons. In that situation, you can’t use the -P option, and you can’t change the system-level configuration files. The correct strategy is to change the configuration of your continuous integration build job, adding an environment variable setting that matches an expected pattern. This won’t be visible to normal users on the system.

If the environment variable name looks like ORG_GRADLE_PROJECT_prop=somevalue, then Gradle will set a prop property on your project object, with the value of somevalue. Gradle also supports this for system properties, but with a different naming pattern, which looks like org.gradle.project.prop.

Differently saying, Gradle allows you to set project proprties by providing system properties with special names, and that is what you did. You've set a Project's property named env to a value demo by providing a system property with a name org.gradle.project.env. This property is available in you build script via project.env and can be used to tweak builds in various ways.


问:
z-index not working on side nav
I am trying to have the hamburger menu "on top" of the side nav, to later toggle the sidenav with this hamburger (instead of having to close it with the x).

Problem is that the z-index seems to be ignored. Why is that and how can I resolve that to bring the hamburger to the front even when the sidenav comes in?

function openNav() {
    document.getElementById("myNav").style.width = "100%";
}

function closeNav() {
    document.getElementById("myNav").style.width = "0%";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: blue;
    overflow-x: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.overlay a:hover, .overlay a:focus {
    color: #f1f1f1;
}

.overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
}

.front {
    z-index: 1050;
}</code>```

  ×

    About
    Services
    Clients
    Contact

Fullscreen Overlay Nav Example

☰ open```

答: Z-index only only works for positioned elements and that too only inside its own stacking context. ☰ open is not positioned. You can read this article to learn more. Possible duplicate: Why does z-index not work?.

Title: z-index not working on side nav

Body:
I am trying to have the hamburger menu "on top" of the side nav, to later toggle the sidenav with this hamburger (instead of having to close it with the x).

Problem is that the z-index seems to be ignored. Why is that and how can I resolve that to bring the hamburger to the front even when the sidenav comes in?

function openNav() {
    document.getElementById("myNav").style.width = "100%";
}

function closeNav() {
    document.getElementById("myNav").style.width = "0%";
}

.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: blue;
    overflow-x: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.overlay a:hover, .overlay a:focus {
    color: #f1f1f1;
}

.overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
}

.front {
    z-index: 1050;
}

  ×

    About
    Services
    Clients
    Contact

Fullscreen Overlay Nav Example

☰ open

Body: Z-index only only works for positioned elements and that too only inside its own stacking context. <span class="front" ...">&#9776; open</span> is not positioned. You can read this article to learn more. Possible duplicate: Why does z-index not work?.


问:
Installing a wildcard SSL certificate in Red Hat 6 hosted on Azure
Short version: I have a wildcard certificate for a domain.  We presently have 2 Apache servers, using Red Hat 6.8, running on the Azure cloud.

My question is: How do I install the wildcard certificate, and have it work properly, since the URL is (for example) http://mysite-prod01.centralus.cloudapp.azure.com -- but the certificate is for *.mydomain.com?

We're using Traffic Manager for www.mydomain.com, as the 'front' for the 2 web servers.  Any ideas?  I've searched and found installing SSL certificates on Red Hat, which isn't an issue, or installing certificates on Windows Azure.

There have to be a fair number of folks hosting their Red Hat servers on Azure, so this must have been solved before ... thanks in advance for your time.

答:
Nothing to do with Azure. Install the certs as you would normally do and CNAME your domain to the traffic manager endpoint.

```<code>www.example.com   IN  CNAME   something.trafficmanager.net
</code>```

Traffic Manager works at the DNS level, so you don't handshake TLS with it, you do it with one of the VMs, depending which endpoint you get.

Body:
Nothing to do with Azure. Install the certs as you would normally do and CNAME your domain to the traffic manager endpoint.

www.example.com   IN  CNAME   something.trafficmanager.net

Traffic Manager works at the DNS level, so you don't handshake TLS with it, you do it with one of the VMs, depending which endpoint you get.


问:
How Do I Use Python To Add Images To An HTML File?
so I have some images I am attempting to have pop up on an html page when my for loop iterates over a word. Like a hieroglyph translation.

I have gone to my AIs for help but they did not succeed in clearing up my confusion.

Unfortunately, I am unsure on how it is that I write these images into an html page. To clarify, I understand that I need to use the .write() function, but I don't know what HTML to write.

Would it be something like this?

```<code>f.write("<html>")

f.write("<body>")

f.write(<img src=hierpglypha.png, "alt="MyHiero" width="500" height="377">)

f.write("</body>")

f.write("/html>")
</code>```

BREAK

```<code>import webbrowser

mydict = {
    'a': 'eglypha.jpg',
    'b': 'eglyphb.jpg',
    'c': 'eglyphc.jpg',
    'd': 'eglyphd.jpg',
    'g': 'eglyph.jpg',
    'h': 'eglyphh.jpg',
    'i': 'eglyphi.jpg',
    'j': 'eglyphj.jpg',
    'k': 'eglyphk.jpg',
    'l': 'eglyphl.jpg',
    'm': 'eglyphm.jpg',
    'n': 'eglyphn.jpg',
    'o': 'eglypho.jpg',
    'p': 'eglypgp.jpg',
    'q': 'eglyphq.jpg',
    'r': 'eglyphr.jpg',
    's': 'eglyphs.jpg',
    't': 'eglypht.jpg',
    'u': 'eglyphu.jpg',
    'v': 'eglyphv.jpg',
    'w': 'eglyphw.jpg',
    'x': 'eglyphx.jpg',
    'y': 'eglyphy.jpg',
    'z': 'eglyphz.jpg',
    '1': 'eglyphTOP.jpg',
    '2': 'eglyphBOTTOM.jpg'
}

def egypt(x):
    #X is your name.
    myWord = "1"
    s = "" #HTML string to return
    for i in x: #saw this way of writing for loops in a lab. looked pretty nifty, so Im gonna use it
        if(x[i] != 'e' or x[i] != 'f'):
            myWord += x[i]
    myWord += "2"

    f.write("<html>")
    f.write("<body>")

    for i in myWord:
        f.write("<img src="+ mydict[myWord[i]])

    #TODO

    return s

#ask user for location of file to be created
plocation = input("Enter location: ")
#Create file
f = open(plocation, 'w')

name = input("Name: ")

#Write the HTML to the file
f.write(egypt(name))

#Close
f.close()

#Display it from within Python
webbrowser.open_new_tab(plocation)
</code>```

答:
Well, depends on your server type.

If serve as a web service server:

Just add below(make sure the image path is available)

```<code><img src=hierpglypha.png, "alt="MyHiero" width="500" height="377">
</code>```

If just wanna write the image data into file.

Use base64, code snippet below:

```<code><img class="icon" src="data:image/png;base64,iVBORw0KGgoAAAANSUhE....>
</code>```

data after the base64, is the image base64 encode data.

Regarding the base64, there are many ways, you could get from some online site or python base64 package .etc

Body:
so I have some images I am attempting to have pop up on an html page when my for loop iterates over a word. Like a hieroglyph translation.

I have gone to my AIs for help but they did not succeed in clearing up my confusion.

Unfortunately, I am unsure on how it is that I write these images into an html page. To clarify, I understand that I need to use the .write() function, but I don't know what HTML to write.

Would it be something like this?

f.write("")

f.write("")

f.write()

f.write("")

f.write("/html>")

BREAK

import webbrowser

mydict = {
    'a': 'eglypha.jpg',
    'b': 'eglyphb.jpg',
    'c': 'eglyphc.jpg',
    'd': 'eglyphd.jpg',
    'g': 'eglyph.jpg',
    'h': 'eglyphh.jpg',
    'i': 'eglyphi.jpg',
    'j': 'eglyphj.jpg',
    'k': 'eglyphk.jpg',
    'l': 'eglyphl.jpg',
    'm': 'eglyphm.jpg',
    'n': 'eglyphn.jpg',
    'o': 'eglypho.jpg',
    'p': 'eglypgp.jpg',
    'q': 'eglyphq.jpg',
    'r': 'eglyphr.jpg',
    's': 'eglyphs.jpg',
    't': 'eglypht.jpg',
    'u': 'eglyphu.jpg',
    'v': 'eglyphv.jpg',
    'w': 'eglyphw.jpg',
    'x': 'eglyphx.jpg',
    'y': 'eglyphy.jpg',
    'z': 'eglyphz.jpg',
    '1': 'eglyphTOP.jpg',
    '2': 'eglyphBOTTOM.jpg'
}

def egypt(x):
    #X is your name.
    myWord = "1"
    s = "" #HTML string to return
    for i in x: #saw this way of writing for loops in a lab. looked pretty nifty, so Im gonna use it
        if(x[i] != 'e' or x[i] != 'f'):
            myWord += x[i]
    myWord += "2"

    f.write("")
    f.write("")

    for i in myWord:
        f.write("<img src="+ mydict[myWord[i]])

    #TODO

    return s

#ask user for location of file to be created
plocation = input("Enter location: ")
#Create file
f = open(plocation, 'w')

name = input("Name: ")

#Write the HTML to the file
f.write(egypt(name))

#Close
f.close()

#Display it from within Python
webbrowser.open_new_tab(plocation)

Body:
Well, depends on your server type.

If serve as a web service server:

Just add below(make sure the image path is available)

<img src=hierpglypha.png, "alt="MyHiero" width="500" height="377">

If just wanna write the image data into file.

Use base64, code snippet below:

<img class="icon" src="data:image/png;base64,iVBORw0KGgoAAAANSUhE....>

data after the base64, is the image base64 encode data.

Regarding the base64, there are many ways, you could get from some online site or python base64 package .etc


问:
Uniform Interface for Math functions for custom and standard type
I have some custom types a::Vector in a namespace a for which I have defined some math functions a::abs, a::pow and a::isnan among others. I want to be able to call abs(T t) without having to worry about whether the argument T is a double or a a::Vector. Using just abs everywhere correctly uses a::abs for a::Vector using ADL, however defaults to using C-style abs(int t) function even for double arguments while I want it to use std::abs or fabs.

I do not want to use using std::abs declarations since this are considered bad in general. What are my options to have a uniform interface abs(T t) for all the different types?

答:
If template<class T> abs(T x) were defined in std, then you could specialize that template, but there is no such generic template for std::abs. Adding overloads to namespace std is undefined behavior. https://stackoverflow.com/a/14403772

I would recommend using std::abs;. There is generally nothing wrong with using specific functions; it's only using namespace that's bad.


问:
Adding a list of managed libraryDependencies (of an arbitrary length) within an SBT Build
In a nutshell, I have written a tool in scala that generates a list of jars from those stored in a directory locally, that parses a given repo identifying the groupID that matches each local jar and outputs all the necessary information to use in sbt. I want to be able to resolve a list of dependencies identified at runtime (otherwise this is useless) to essentially automate the update process when building more complicated applications for hadoop as well as to test program compatibility for different builds and conditions.

Bottom Line: I have not found a solution which allows me to pass librarydependencies discovered within the build, to the build.

Some Things I Have Tried:

1) Using keywords within for loops

I generated the jarList with a Dependencies.scala code in the /project directory and added this to my build.sbt

```<code>jarList.foreach(x =>
libraryDependencies += x.GroupID % x.ArtifactID % x.Revision
)
</code>```

2) Manually editing the build.sbt by appending each libraryDependency found to a line at the bottom of the build.sbt file by running something like this in my /project/Dependencies.scala file

```<code>import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;

try{
  val file =new File(new
File(".").getAbsolutePath().toString.replaceAll("^(.*)\\.(.*)$","$1$2")++"build.sbt")
  if(!file.exists()){
    file.createNewFile()
                    }
  val fw = new FileWriter(file,true)
  val bw = new BufferedWriter(fw)
  val pw = new PrintWriter(bw)
  pw.println(s"""libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.7.3" """.stripMargin)
  pw.close();

  println("Data successfully appended at the end of file")
}catch {
  case ioe: IOException => println("Exception occurred:")
  ioe.printStackTrace()
}
</code>```

This option sort of works (if I completely stop and restart the build)

3) Loading/running one sbt build before another build, the problem is that it seems like SBT always loads information from each build.sbt file resulting in the same problem as that above.

Has anyone else ever tried to do anything like this? Or does anyone have any ideas/ advice on doing this?

Thanks

答:
I think you can go with the first option, changing it a little bit.
In your build.sbt file declare a list of module ids produced from your jarList:

```<code>lazy val jarDependencies: Seq[ModuleID] = jarList.map(x => x.GroupID % x.ArtifactID % x.Revision)
</code>```

Then add it to libraryDependencies:

```<code>libraryDependencies ++= jarDependencies
</code>```

Remember that build.sbt contains pure Scala code, maybe with just few limitations (like having statements that result in Unit, e.g. calling foreach, is not allowed). So knowing the types of certain declarations (libraryDependencies has type SettingKey[Seq[ModuleID]]) should help with adding more magic.

Body:
In a nutshell, I have written a tool in scala that generates a list of jars from those stored in a directory locally, that parses a given repo identifying the groupID that matches each local jar and outputs all the necessary information to use in sbt. I want to be able to resolve a list of dependencies identified at runtime (otherwise this is useless) to essentially automate the update process when building more complicated applications for hadoop as well as to test program compatibility for different builds and conditions.

Bottom Line: I have not found a solution which allows me to pass librarydependencies discovered within the build, to the build.

Some Things I Have Tried:

1) Using keywords within for loops

I generated the jarList with a Dependencies.scala code in the /project directory and added this to my build.sbt

jarList.foreach(x =>
libraryDependencies += x.GroupID % x.ArtifactID % x.Revision
)

2) Manually editing the build.sbt by appending each libraryDependency found to a line at the bottom of the build.sbt file by running something like this in my /project/Dependencies.scala file

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;

try{
  val file =new File(new
File(".").getAbsolutePath().toString.replaceAll("^(.*)\\.(.*)$","$1$2")++"build.sbt")
  if(!file.exists()){
    file.createNewFile()
                    }
  val fw = new FileWriter(file,true)
  val bw = new BufferedWriter(fw)
  val pw = new PrintWriter(bw)
  pw.println(s"""libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "2.7.3" """.stripMargin)
  pw.close();

  println("Data successfully appended at the end of file")
}catch {
  case ioe: IOException => println("Exception occurred:")
  ioe.printStackTrace()
}

This option sort of works (if I completely stop and restart the build)

3) Loading/running one sbt build before another build, the problem is that it seems like SBT always loads information from each build.sbt file resulting in the same problem as that above.

Has anyone else ever tried to do anything like this? Or does anyone have any ideas/ advice on doing this?

Thanks

Body:
I think you can go with the first option, changing it a little bit.
In your build.sbt file declare a list of module ids produced from your jarList:

lazy val jarDependencies: Seq[ModuleID] = jarList.map(x => x.GroupID % x.ArtifactID % x.Revision)

Then add it to libraryDependencies:

libraryDependencies ++= jarDependencies

Remember that build.sbt contains pure Scala code, maybe with just few limitations (like having statements that result in Unit, e.g. calling foreach, is not allowed). So knowing the types of certain declarations (libraryDependencies has type SettingKey[Seq[ModuleID]]) should help with adding more magic.


问:
Creating a pandas column conditional to another columns values
I'm trying to create a class column in a pandas dataframe conditional another columns values. The value will be 1 if the other column's i+1 value is greater than the i value and 0 otherwise.

For example:

```<code>column1 column2
   5       1
   6       0
   3       0
   2       1
   4       0
</code>```

How do create column2 by iterating through column1?

答:
You can use the diff method on the first column with a period of -1, then check if it is less than zero to create the second column.

```<code>import pandas as pd

df = pd.DataFrame({'c1': [5,6,3,2,4]})
df['c2'] = (df.c1.diff(-1) < 0).astype(int)

df
# returns:
   c1  c2
0   5   1
1   6   0
2   3   0
3   2   1
4   4   0
</code>```

Body:
I'm trying to create a class column in a pandas dataframe conditional another columns values. The value will be 1 if the other column's i+1 value is greater than the i value and 0 otherwise.

For example:

column1 column2
   5       1
   6       0
   3       0
   2       1
   4       0

How do create column2 by iterating through column1?

Body:
You can use the diff method on the first column with a period of -1, then check if it is less than zero to create the second column.

import pandas as pd

df = pd.DataFrame({'c1': [5,6,3,2,4]})
df['c2'] = (df.c1.diff(-1) < 0).astype(int)

df
# returns:
   c1  c2
0   5   1
1   6   0
2   3   0
3   2   1
4   4   0


问:
create or update python dictionary entry
Perhaps I've been spoiled by Brand X programming languages, but is there a better pythonic idiom for the following?

```<code>thing_dict = {}

def find_or_create_thing(key):
    if (thing_dict.has_key(key)):
        thing = thing_dict[key]
    else:
        thing = create_new_thing(key)
        thing_dict[key] = thing
    return thing
</code>```

It seems like something like this could be done in one or two lines.  I considered using a Conditional Expression, but Python's odd syntax simply didn't lend itself to legibility.

I also considered a try: ... except KeyError:, but that was just about as much text and probably considerably more execution overhead.

P.S. I know that asking programming style questions on S.O. is problematic, but I'll take my chances...

答:
Not much shorter but maybe "prettier" (depending on the use case):</p>

```<code>class ThingDict(dict):
    def __missing__(self, key):
        self[key] = create_new_thing(key)
        return self[key]

thing_dict = ThingDict()

def find_or_create_thing(key):
    return thing_dict[key]
</code>```

Body:
Perhaps I've been spoiled by Brand X programming languages, but is there a better pythonic idiom for the following?

thing_dict = {}

def find_or_create_thing(key):
    if (thing_dict.has_key(key)):
        thing = thing_dict[key]
    else:
        thing = create_new_thing(key)
        thing_dict[key] = thing
    return thing

It seems like something like this could be done in one or two lines.  I considered using a Conditional Expression, but Python's odd syntax simply didn't lend itself to legibility.

I also considered a try: ... except KeyError:, but that was just about as much text and probably considerably more execution overhead.

P.S. I know that asking programming style questions on S.O. is problematic, but I'll take my chances...

Body:
Not much shorter but maybe "prettier" (depending on the use case):

class ThingDict(dict):
    def __missing__(self, key):
        self[key] = create_new_thing(key)
        return self[key]

thing_dict = ThingDict()

def find_or_create_thing(key):
    return thing_dict[key]


答:
Add front class to your h2 element and add position: relative to front style:

function openNav() {
    document.getElementById("myNav").style.width = "100%";
}

function closeNav() {
    document.getElementById("myNav").style.width = "0%";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: blue;
    overflow-x: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.overlay a:hover, .overlay a:focus {
    color: #f1f1f1;
}

.overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
}

.front {
    z-index: 1050;
    position: relative;
}</code>```

  ×

    About
    Services
    Clients
    Contact

Fullscreen Overlay Nav Example

☰ open```

Title: z-index not working on side nav

Body:
Add front class to your h2 element and add position: relative to front style:

function openNav() {
    document.getElementById("myNav").style.width = "100%";
}

function closeNav() {
    document.getElementById("myNav").style.width = "0%";
}

.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: blue;
    overflow-x: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.overlay a:hover, .overlay a:focus {
    color: #f1f1f1;
}

.overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
}

.front {
    z-index: 1050;
    position: relative;
}

<div id="myNav" class="overlay">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <div class="overlay-content">
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Clients</a>
    <a href="#">Contact</a>
  </div>
</div>

<h2 class="front">Fullscreen Overlay Nav Example</h2>
<span class="front" style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>


问:
image processing in client side
I need to fetch an image from a web site knowing it's URL and then edit it (cropping and resizing) in client side.

What the best way to do this using JavaScript, Jquery, HTML5?

can you provide some links or tutorials,...?

Thanks in advance.

答:
You can use a Javascript Image Processing Framework like MarvinJ. The example below demonstrates how to resize and crop an image in js in the client side.

var canvas1 = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");
var canvas3 = document.getElementById("canvas3");

image = new MarvinImage();
image.load("https://i.imgur.com/gaW8OeL.jpg", imageLoaded);

function imageLoaded(){
 imageOut = image.clone()
 image.draw(canvas1)

  // Crop
  Marvin.crop(image, imageOut, 50, 50, 100, 100);
  imageOut.draw(canvas2);

  // Scale
  Marvin.scale(image, imageOut, 100);
 imageOut.draw(canvas3);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<canvas id="canvas1" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="200"></canvas><br/>
<canvas id="canvas3" width="200" height="200"></canvas></code>```

Title: image processing in client side

Body:
You can use a Javascript Image Processing Framework like MarvinJ. The example below demonstrates how to resize and crop an image in js in the client side.

var canvas1 = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");
var canvas3 = document.getElementById("canvas3");

image = new MarvinImage();
image.load("https://i.imgur.com/gaW8OeL.jpg", imageLoaded);

function imageLoaded(){
 imageOut = image.clone()
 image.draw(canvas1)

  // Crop
  Marvin.crop(image, imageOut, 50, 50, 100, 100);
  imageOut.draw(canvas2);

  // Scale
  Marvin.scale(image, imageOut, 100);
 imageOut.draw(canvas3);
}

<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<canvas id="canvas1" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="200"></canvas><br/>
<canvas id="canvas3" width="200" height="200"></canvas>


问:
How to design stateful conversation with Dialogflow
I'm trying to make an app to reserve meeting rooms in my office by Google Home and Dialogflow.
Here's my plan:

```<code>Me: "OK Google, is there any available room now?"
Google Home: "Room 1 is available until 16:00."
Me:  "Book it."
Google Home: "Booked Room 1."
</code>```

The current problem is how to make Google Home's response stateful. In my plan, when I say "Book it", Google Home has to remember Room 1. But I don't know how to make it happen.

I read documents of conversation API, but I haven't understand it's possible to preserve variables or states within the same conversation Id.
https://developers.google.com/actions/reference/v1/conversation

Does anyone know about that?

答:
It is absolutely possible, and even fairly easy, to preserve state as part of the conversation your users have with your Action. Dialogflow makes it particularly easy with what they call context, and it uses this in a few ways:

As part of your fulfillment, you can set a Context, the lifetime (number of steps in the conversation) that context will be good for, and any parameter/value pairs for this context. Using your example, when you have the Action replying with the room number and time, you might set a "pending_request" context with the pair {"room": "1"} and {"time": "2017-11-15T16:00Z"} and a lifetime of 5.

You can indicate as part of the Intent what Contexts must be set for that Intent to be selected in the conversation. So asking "Who is available?" while the "pending_request" context is active might trigger an Intent that looks who is available at that time that can meet at that room (perhaps because they're in the same building). But if the context is not active, it might trigger an Intent to see who is available right now that you can call (even if they're in a different building).

The parameters that you set in the Context are available to you in the Intent that is called. So you'll be able to find out what room and time have been set in the fulfillment of the Intent.

If you don't renew the Context, it will vanish after the selected number of exchanges. This means that after you inquire about the room, you could inquire if you have any appointments today (a question unrelated to the room or the time) and the phrase "Book it" would still have the context available to it.

If you're using the node.js client library from Google, you can use app.getContext() and app.setContext(). If you're doing it in JSON, you need to provide the Context information directly in the response.

Google also provides a more general app.data object that you can set properties on with the node.js client library, and these properties are retained during a conversation (although not between conversations). It uses Contexts behind the scenes, although it isn't quite as powerful as Contexts are since you can't use it as part of Intent matching.

(As an aside - the link you provided was to version 1 of the API. That version has been deprecated and will be turned off in May 2018. It was also for the Actions API rather than Dialogflow. The equivalent documentation is at https://developers.google.com/actions/reference/rest/conversation-webhook, but that probably isn't what you want if you're using Dialogflow.)

Body:
I'm trying to make an app to reserve meeting rooms in my office by Google Home and Dialogflow.
Here's my plan:

Me: "OK Google, is there any available room now?"
Google Home: "Room 1 is available until 16:00."
Me:  "Book it."
Google Home: "Booked Room 1."

The current problem is how to make Google Home's response stateful. In my plan, when I say "Book it", Google Home has to remember Room 1. But I don't know how to make it happen.

I read documents of conversation API, but I haven't understand it's possible to preserve variables or states within the same conversation Id.
https://developers.google.com/actions/reference/v1/conversation

Does anyone know about that?


问:
Scrolling to top of page on refresh
I am attempting to create some animations for when an element is scrolled into place in my ecmascript-6 react application. I have tried using several react scroll packages, but am not getting the results I need because I want to apply the animation to child components that are all mapped from the same parent component (and thus, all child components animate at the same time when the first child component is scrolled into place).

To work around this, I was thinking of just getting the current scroll position and the individual positions in for each component but am quite stuck and unclear on how to do this properly. For my child component, should I just call a function when the onScroll event is called? Or should I instead use something like jsx to get the these various window positions and run some evaluations and functions when the DOM is updated to the proper place I want?

Thanks, any help would be appreciated! I spent a couple days now searching for answers but think I'm just more stuck on how to call different window and element events and properties and how to compare them, and don't even know if this is neccessary and if there is instead an easier solution for scrolling animations, ideally, in just plain reactjs, without any packages.

答:
Easy! Just do it with the scrollTop method on DOM ready:

```<code>$(document).ready(function(){
   $(this).scrollTop(0);
});
</code>```

You can also just do it like this:

```<code>$(document).scrollTop(0);
</code>```

Title: Scrolling to top of page on refresh

Body:
Easy! Just do it with the scrollTop method on DOM ready:

$(document).ready(function(){
   $(this).scrollTop(0);
});

You can also just do it like this:

$(document).scrollTop(0);


问:
For loop with conditional if statements
I can't figure out what is wrong with this code. I have a dataframe called Fish. I want to add a column called CombineMe that is default 0. The value would change to  501 if it meets the two criteria (either the data source = A & sample method = visual then it would equal 501 and also if the data source = B & taxon code is the three EJ, EL or RV). I can't quite figure out where I'm going wrong. I've tried adjusting where the [i] are and adding commas...

```<code>for(i in 1:length(Fish)) {
Fish$CombineMe <- 0
if (Fish$data_source == "A" & Fish$sample_method == "visual") {
  Fish$CombineMe [i] <- 501
} else if (Fish$data_source == "B" & Fish$taxon_name == c("EJ", "EL", "RV")){
  Fish$CombineMe [i] <- 501
}}
</code>```

Here's a condensed example of what Fish looks like:

```<code>Fish <- data.frame ("data_source"=c("A", "A", "B", "C", "C", "D", "D"), "sample_method"= c("visualfish", "fish", "fish", "fish", "fish", "fish", "fish"),
                  "taxon_name"=c("EJ", "EJ", "RV", "EJ", "RV", "EL", "HR"))
</code>```

答:
The problem you are having is because everytime you loop you define Fish$CombineMe <- 0 so you are reseting the hole column to cero each time. To fix this:

```<code>Fish$CombineMe[i] <- 0
</code>```

Title: For loop with conditional if statements

Body:
I can't figure out what is wrong with this code. I have a dataframe called Fish. I want to add a column called CombineMe that is default 0. The value would change to  501 if it meets the two criteria (either the data source = A & sample method = visual then it would equal 501 and also if the data source = B & taxon code is the three EJ, EL or RV). I can't quite figure out where I'm going wrong. I've tried adjusting where the [i] are and adding commas...

for(i in 1:length(Fish)) {
Fish$CombineMe <- 0
if (Fish$data_source == "A" & Fish$sample_method == "visual") {
  Fish$CombineMe [i] <- 501
} else if (Fish$data_source == "B" & Fish$taxon_name == c("EJ", "EL", "RV")){
  Fish$CombineMe [i] <- 501
}}

Here's a condensed example of what Fish looks like:

Fish <- data.frame ("data_source"=c("A", "A", "B", "C", "C", "D", "D"), "sample_method"= c("visualfish", "fish", "fish", "fish", "fish", "fish", "fish"),
                  "taxon_name"=c("EJ", "EJ", "RV", "EJ", "RV", "EL", "HR"))

Body:
The problem you are having is because everytime you loop you define Fish$CombineMe <- 0 so you are reseting the hole column to cero each time. To fix this:

Fish$CombineMe[i] <- 0


问:
C Sorting records from a file
Hi Everyone I am working on a project to sort a file with a large quantity of records based on the given criteria (name or age or gender or hometown) and write to the output file in the format of the original file. However I am debating what is the fastest approach to do so. The file contains records such as:

```<code>Name Age gender hometown
Adam 28  Male   New york
Kevin 42 Male   Boston
...
</code>```

My thought is to read the file and create a linked-list of struct:

```<code>struct record
{
char * SortCriteriaString;
int SortCriteriaInt;
char * Name;
int Age;
char * Gender;
char * Hometown;};
</code>```

and then mersort the linked list based on the criteria I read from command line and store in the SortCriteriaInt or SortCriteriaString members of the struct.

Here is what I plan to do with this project. But I was asked to come up with the fastest sorter possible, so my question is: What are the fastest data structure and sorting algorithm for this task if not the one I described above?

答:
Sorting an array of pointers to structures would be faster than sorting a linked list of structures. If the structures aren't too big, then directly sorting an array of structures would be faster than sorting an array of pointers to structures, but this means using O(n) space (a temporary array) if using merge sort.

Since your structures have pointers to strings, merge sort should be faster than quick sort. Merge sort does more moves, but fewer compares than quick sort, and in this case, it's mostly moving pointers, but having to compare strings.

It may be faster to have fixed sized structures with maximum length allocated for the strings, so that the strings are moved during the sort. If the strings aren't too big, this will help with cache locality during the sort.

Title: C Sorting records from a file

Body:
Hi Everyone I am working on a project to sort a file with a large quantity of records based on the given criteria (name or age or gender or hometown) and write to the output file in the format of the original file. However I am debating what is the fastest approach to do so. The file contains records such as:

Name Age gender hometown
Adam 28  Male   New york
Kevin 42 Male   Boston
...

My thought is to read the file and create a linked-list of struct:

struct record
{
char * SortCriteriaString;
int SortCriteriaInt;
char * Name;
int Age;
char * Gender;
char * Hometown;};

and then mersort the linked list based on the criteria I read from command line and store in the SortCriteriaInt or SortCriteriaString members of the struct.

Here is what I plan to do with this project. But I was asked to come up with the fastest sorter possible, so my question is: What are the fastest data structure and sorting algorithm for this task if not the one I described above?


问:
Cronjob update permission
I want to create a cronjob to update and upgrade a pi once every day. My only issue is that at some points it asks permission to use or free up disk space. Is there an option to a command to continue with the coronjob?

What I am trying to run:

```<code>30 2 * * * sudo apt-get update && sudo apt-get upgrade
</code>```

答:
Actually you can use the root crontab. You can access it here:

```<code>sudo crontab -e
</code>```

then add your program:

```<code>30 2 * * * apt-get update && apt-get upgrade
</code>```

And it will be run with root permissions.

Title: Cronjob update permission

Body:
I want to create a cronjob to update and upgrade a pi once every day. My only issue is that at some points it asks permission to use or free up disk space. Is there an option to a command to continue with the coronjob?

What I am trying to run:

30 2 * * * sudo apt-get update && sudo apt-get upgrade

Body:
Actually you can use the root crontab. You can access it here:

sudo crontab -e

then add your program:

30 2 * * * apt-get update && apt-get upgrade

And it will be run with root permissions.


问:
Azure Function works fine in visual studio but is not being triggered once published
I have Created an azure function that connects to an exchange server and is triggered by a blob storage trigger. Testing this in visual studio, everything works fine; uploading a blob triggers the function and the connection is attempted.

When I publish the function to Azure however, it is no longer triggered by the blob storage when a file is uploaded.

The application and the function are both visible on the azure portal and the application is running. But the invocation log states that the function is never called. The function is also listed as read-only due to being developed in Visual Studio.

Is there a step I am missing after testing my function in visual studio and publishing the application to Azure?

Absolutely any help would be appreciated, I’m sure I am just doing something incredibly stupid.

Thanks.

Additional Information:
I'm publishing from Visual studio 2017 Enterprise

Here's the Function

```<code>using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Exchange.WebServices.Data;
using System;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Security;
using System.Net;

namespace ExchangeSimplifiedTestFunction
{
    public static class SimplifiedFunction
    {
        [FunctionName("SimplifiedFunction")]
        public static void Run([BlobTrigger("exchangestorage/{name}", Connection = "StorageConnection")]CloudBlockBlob myBlob, string name, TraceWriter log)
        {

            log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size:  Bytes");
            log.Info(myBlob.ToString());
            ExchangeService service = new ExchangeService();
            String customer = myBlob.DownloadText();

            string emailAddress = "email@email-test.local";

            //yuck yuck yuck yuck yuck
            var password = new SecureString(); foreach (char c in "password") password.AppendChar(c);

            NetworkCredential userCredentials = new NetworkCredential(emailAddress, password);
            service.Credentials = userCredentials;

            bool success;
            try
            {
                service.AutodiscoverUrl(emailAddress, RedirectionUrlValidationCallback);
                success = true;
            }
            catch (Microsoft.Exchange.WebServices.Data.AutodiscoverLocalException e)
            {
                log.Info($"loginFailed - expected during testing");
                success = false;
            }

            if (success) { log.Info($"Successfully connected to exchange server"); }

        }

        private static bool RedirectionUrlValidationCallback(string redirectionUrl)
        {
            bool result = false;
            Uri redirectionUri = new Uri(redirectionUrl);

            if (redirectionUri.Scheme == "https")
            {
                result = true;
            }
            return result;
        }

    }
}
</code>```

And Here's the local.settings.json

```<code>{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=exchangclientestorage;AccountKey=[accountKey];EndpointSuffix=core.windows.net",
    "AzureWebJobsDashboard": "",
    "StorageConnection": "DefaultEndpointsProtocol=https;AccountName=exchangclientestorage;AccountKey=[accountKey];EndpointSuffix=core.windows.net"

  }
}
</code>```

And Here are the results from testing locally

```<code>                %%%%%%
            @   %%%%%%    @
          @@   %%%%%%      @@
       @@@    %%%%%%%%%%%    @@@
     @@      %%%%%%%%%%        @@
       @@         %%%%       @@
         @@      %%%       @@
           @@    %%      @@
                %%
                %

[14/11/2017 11:46:05] Reading host configuration file 'C:\Users\davel\source\repos\ExchangeSimplifiedTestFunction\ExchangeSimplifiedTestFunction\bin\Debug\net461\host.json'
[14/11/2017 11:46:05] Host configuration file read:
[14/11/2017 11:46:05] {
}
Listening on http://localhost:7071/
Hit CTRL-C to exit...
[14/11/2017 11:46:05] Generating 1 job function(s)
[14/11/2017 11:46:05] Starting Host (HostId=dlopcdi101-792492740, Version=1.0.11075.0, ProcessId=14848, Debug=False, Attempt=0)
[14/11/2017 11:46:06] Found the following functions:
[14/11/2017 11:46:06] ExchangeSimplifiedTestFunction.SimplifiedFunction.Run
[14/11/2017 11:46:06]
[14/11/2017 11:46:06] Host lock lease acquired by instance ID '000000000000000000000000860DF48B'.
[14/11/2017 11:46:06] Job host started
[14/11/2017 11:46:06] Executing HTTP request: {
[14/11/2017 11:46:06]   "requestId": "ae39ae2c-8e64-4b22-bbd9-26215f558b4a",
[14/11/2017 11:46:06]   "method": "GET",
[14/11/2017 11:46:06]   "uri": "/"
[14/11/2017 11:46:06] }
[14/11/2017 11:46:06] Executed HTTP request: {
[14/11/2017 11:46:06]   "requestId": "ae39ae2c-8e64-4b22-bbd9-26215f558b4a",
[14/11/2017 11:46:06]   "method": "GET",
[14/11/2017 11:46:06]   "uri": "/",
[14/11/2017 11:46:06]   "authorizationLevel": "Anonymous"
[14/11/2017 11:46:06] }
[14/11/2017 11:46:06] Response details: {
[14/11/2017 11:46:06]   "requestId": "ae39ae2c-8e64-4b22-bbd9-26215f558b4a",
[14/11/2017 11:46:06]   "status": "OK"
[14/11/2017 11:46:06] }
[14/11/2017 11:46:06] Function started (Id=85129700-5403-42b3-9368-3f185503e73a)
[14/11/2017 11:46:06] Executing 'SimplifiedFunction' (Reason='New blob detected: exchangestorage/customer3.txt', Id=85129700-5403-42b3-9368-3f185503e73a)
[14/11/2017 11:46:07] C# Blob trigger function Processed blob
 Name:customer3.txt
 Size:  Bytes
[14/11/2017 11:46:07] Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob
Debugger listening on [::]:5858
[14/11/2017 11:46:09] loginFailed - expected during testing
[14/11/2017 11:46:09] Function completed (Success, Id=85129700-5403-42b3-9368-3f185503e73a, Duration=3135ms)
[14/11/2017 11:46:09] Executed 'SimplifiedFunction' (Succeeded, Id=85129700-5403-42b3-9368-3f185503e73a)
</code>```

And Finally the generated function.json

```<code>{
  "generatedBy": "Microsoft.NET.Sdk.Functions-1.0.0.0",
  "configurationSource": "attributes",
  "bindings": [
    {
      "type": "blobTrigger",
      "connection": "StorageConnection",
      "path": "exchangestorage/{name}",
      "name": "myBlob"
    }
  ],
  "disabled": false,
  "scriptFile": "..\\bin\\ExchangeSimplifiedTestFunction.dll",
  "entryPoint": "ExchangeSimplifiedTestFunction.SimplifiedFunction.Run"
}
</code>```

答: Just like Mikhail' comment, you should add the storage connection string into your Azure function's application settings. The file local.settings.json only works in your local develop environment, which does not work in azure function.

Body:
I have Created an azure function that connects to an exchange server and is triggered by a blob storage trigger. Testing this in visual studio, everything works fine; uploading a blob triggers the function and the connection is attempted.

When I publish the function to Azure however, it is no longer triggered by the blob storage when a file is uploaded.

The application and the function are both visible on the azure portal and the application is running. But the invocation log states that the function is never called. The function is also listed as read-only due to being developed in Visual Studio.

Is there a step I am missing after testing my function in visual studio and publishing the application to Azure?

Absolutely any help would be appreciated, I’m sure I am just doing something incredibly stupid.

Thanks.

Additional Information:
I'm publishing from Visual studio 2017 Enterprise

Here's the Function

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Exchange.WebServices.Data;
using System;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Security;
using System.Net;

namespace ExchangeSimplifiedTestFunction
{
    public static class SimplifiedFunction
    {
        [FunctionName("SimplifiedFunction")]
        public static void Run([BlobTrigger("exchangestorage/{name}", Connection = "StorageConnection")]CloudBlockBlob myBlob, string name, TraceWriter log)
        {

            log.Info($"C# Blob trigger function Processed blob\n Name:{name} \n Size:  Bytes");
            log.Info(myBlob.ToString());
            ExchangeService service = new ExchangeService();
            String customer = myBlob.DownloadText();

            string emailAddress = "email@email-test.local";

            //yuck yuck yuck yuck yuck
            var password = new SecureString(); foreach (char c in "password") password.AppendChar(c);

            NetworkCredential userCredentials = new NetworkCredential(emailAddress, password);
            service.Credentials = userCredentials;

            bool success;
            try
            {
                service.AutodiscoverUrl(emailAddress, RedirectionUrlValidationCallback);
                success = true;
            }
            catch (Microsoft.Exchange.WebServices.Data.AutodiscoverLocalException e)
            {
                log.Info($"loginFailed - expected during testing");
                success = false;
            }

            if (success) { log.Info($"Successfully connected to exchange server"); }

        }

        private static bool RedirectionUrlValidationCallback(string redirectionUrl)
        {
            bool result = false;
            Uri redirectionUri = new Uri(redirectionUrl);

            if (redirectionUri.Scheme == "https")
            {
                result = true;
            }
            return result;
        }

    }
}

And Here's the local.settings.json

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=exchangclientestorage;AccountKey=[accountKey];EndpointSuffix=core.windows.net",
    "AzureWebJobsDashboard": "",
    "StorageConnection": "DefaultEndpointsProtocol=https;AccountName=exchangclientestorage;AccountKey=[accountKey];EndpointSuffix=core.windows.net"

  }
}

And Here are the results from testing locally

                %%%%%%
            @   %%%%%%    @
          @@   %%%%%%      @@
       @@@    %%%%%%%%%%%    @@@
     @@      %%%%%%%%%%        @@
       @@         %%%%       @@
         @@      %%%       @@
           @@    %%      @@
                %%
                %

[14/11/2017 11:46:05] Reading host configuration file 'C:\Users\davel\source\repos\ExchangeSimplifiedTestFunction\ExchangeSimplifiedTestFunction\bin\Debug\net461\host.json'
[14/11/2017 11:46:05] Host configuration file read:
[14/11/2017 11:46:05] {
}
Listening on http://localhost:7071/
Hit CTRL-C to exit...
[14/11/2017 11:46:05] Generating 1 job function(s)
[14/11/2017 11:46:05] Starting Host (HostId=dlopcdi101-792492740, Version=1.0.11075.0, ProcessId=14848, Debug=False, Attempt=0)
[14/11/2017 11:46:06] Found the following functions:
[14/11/2017 11:46:06] ExchangeSimplifiedTestFunction.SimplifiedFunction.Run
[14/11/2017 11:46:06]
[14/11/2017 11:46:06] Host lock lease acquired by instance ID '000000000000000000000000860DF48B'.
[14/11/2017 11:46:06] Job host started
[14/11/2017 11:46:06] Executing HTTP request: {
[14/11/2017 11:46:06]   "requestId": "ae39ae2c-8e64-4b22-bbd9-26215f558b4a",
[14/11/2017 11:46:06]   "method": "GET",
[14/11/2017 11:46:06]   "uri": "/"
[14/11/2017 11:46:06] }
[14/11/2017 11:46:06] Executed HTTP request: {
[14/11/2017 11:46:06]   "requestId": "ae39ae2c-8e64-4b22-bbd9-26215f558b4a",
[14/11/2017 11:46:06]   "method": "GET",
[14/11/2017 11:46:06]   "uri": "/",
[14/11/2017 11:46:06]   "authorizationLevel": "Anonymous"
[14/11/2017 11:46:06] }
[14/11/2017 11:46:06] Response details: {
[14/11/2017 11:46:06]   "requestId": "ae39ae2c-8e64-4b22-bbd9-26215f558b4a",
[14/11/2017 11:46:06]   "status": "OK"
[14/11/2017 11:46:06] }
[14/11/2017 11:46:06] Function started (Id=85129700-5403-42b3-9368-3f185503e73a)
[14/11/2017 11:46:06] Executing 'SimplifiedFunction' (Reason='New blob detected: exchangestorage/customer3.txt', Id=85129700-5403-42b3-9368-3f185503e73a)
[14/11/2017 11:46:07] C# Blob trigger function Processed blob
 Name:customer3.txt
 Size:  Bytes
[14/11/2017 11:46:07] Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob
Debugger listening on [::]:5858
[14/11/2017 11:46:09] loginFailed - expected during testing
[14/11/2017 11:46:09] Function completed (Success, Id=85129700-5403-42b3-9368-3f185503e73a, Duration=3135ms)
[14/11/2017 11:46:09] Executed 'SimplifiedFunction' (Succeeded, Id=85129700-5403-42b3-9368-3f185503e73a)

And Finally the generated function.json

{
  "generatedBy": "Microsoft.NET.Sdk.Functions-1.0.0.0",
  "configurationSource": "attributes",
  "bindings": [
    {
      "type": "blobTrigger",
      "connection": "StorageConnection",
      "path": "exchangestorage/{name}",
      "name": "myBlob"
    }
  ],
  "disabled": false,
  "scriptFile": "..\\bin\\ExchangeSimplifiedTestFunction.dll",
  "entryPoint": "ExchangeSimplifiedTestFunction.SimplifiedFunction.Run"
}


答:
Normally you need to provide how Fish dataframe looks like. I try to guess based on your given code:

```<code>Fish$CombineMe <- 0
for(i in 1:nrow(Fish)) {

if (Fish$data_source[i] == "A" & Fish$sample_method[i] == "visual") {
  Fish$CombineMe[i] <- 501
} else if (Fish$data_source[i] == "B" & Fish$taxon_name[i] %in% c("EJ", "EL", "RV")){
  Fish$CombineMe [i] <- 501
}}
</code>```

I don't think you need a loop, though. Here is the alternative method using ifelse.

```<code>Fish$CombineMe <- 0
Fish$CombineMe <- ifelse(Fish$data_source == "A" & Fish$sample_method == "visual", 501, Fish$CombineMe)
Fish$CombineMe <- ifelse(Fish$data_source == "B" & Fish$taxon_name %in% c("EJ", "EL", "RV"), 501, Fish$CombineMe)
</code>```

Title: For loop with conditional if statements

Body:
Normally you need to provide how Fish dataframe looks like. I try to guess based on your given code:

Fish$CombineMe <- 0
for(i in 1:nrow(Fish)) {

if (Fish$data_source[i] == "A" & Fish$sample_method[i] == "visual") {
  Fish$CombineMe[i] <- 501
} else if (Fish$data_source[i] == "B" & Fish$taxon_name[i] %in% c("EJ", "EL", "RV")){
  Fish$CombineMe [i] <- 501
}}

I don't think you need a loop, though. Here is the alternative method using ifelse.

Fish$CombineMe <- 0
Fish$CombineMe <- ifelse(Fish$data_source == "A" & Fish$sample_method == "visual", 501, Fish$CombineMe)
Fish$CombineMe <- ifelse(Fish$data_source == "B" & Fish$taxon_name %in% c("EJ", "EL", "RV"), 501, Fish$CombineMe)


问:
Why "C:\Program Files" used as default. Is there any violations or degradation in performance if we change it?
Why does Microsoft recommend "C:\Program Files" for default installation destination? Are there any specific reason for that? And if I change the location is that going to effect the performance of the system and the application?</p>

答:
It makes computer management easier.

Support staff knows exactly where applications are located.

By separating the rarely changing applications ("C:\program Files") from the rapidly change user data ("C:\Documents and Settings") more efficient backup strategies can be implemented.

It allows the C:\Program Files directory tree to be set as "Everyone readable; Admin-writable", to prevent virus installs and accidental deletion.

OwnerDisplayName: Maharajan

LastEditorDisplayName: bdukes

OwnerDisplayName: James Curran


答:
This is the offending line of code:

```<code>Fish$CombineMe <- 0
</code>```

You are zeroing out the entire column, for each iteration of the loop.  Move this outside and before the loop and it should work.

But R is a vectorized language, and a much better way of making your assignment would not even use a loop at all:

```<code>cond1 <- Fish$data_source == 'A' & Fish$sample_method == 'visual'
cond2 <- Fish$data_source == "B" & Fish$taxon_name %in% c('EJ', 'EL', 'RV')
Fish$CombineMe <- ifelse(cond1 | cond2, 501, 0)
</code>```

Title: For loop with conditional if statements

Body:
This is the offending line of code:

Fish$CombineMe <- 0

You are zeroing out the entire column, for each iteration of the loop.  Move this outside and before the loop and it should work.

But R is a vectorized language, and a much better way of making your assignment would not even use a loop at all:

cond1 <- Fish$data_source == 'A' & Fish$sample_method == 'visual'
cond2 <- Fish$data_source == "B" & Fish$taxon_name %in% c('EJ', 'EL', 'RV')
Fish$CombineMe <- ifelse(cond1 | cond2, 501, 0)


问:
How to Access a list of titles(elements) from an array by inputting a single word?
I wrote a program that reads in a file. The name of the file was passed into my program as a command-line parameter. Each line of the file contained 3 fields, separated by a vertical bar, or pipe ("|").
The file contained information about books so each line contains a title(ex. Les Miserables), an author, and a genre which I put into three arrays:

```<code>title = []
author = []
genre = []
</code>```

I am trying to input a word like "Les" and get the specific elements from the arrays and print it like "(Fiction), Les Miserables by Victor Hugo".

This is my code so far:

```<code>for word in myArray:
fields = word.split(|)
title.append(fields[0])
author.append(fields[1])
genre.append(fields[2])
entry = raw_input()
if entry == T or t:

titlEntry = raw_input("Please enter title:")
n = len(title)
for i in range(0,n):
if titlEntry == i:
print "(" + genre[i] + ") " + title[i] + " by " + author[i]
</code>```

Please help

答:
First of all, this is not the way to do it; a dictionary would be better and I would ask you look into other structures as well. Also, think about sanitizing the input you read from the command line.  However, to get you going, you are close.  Try:</p>

```<code>titlEntry = raw_input("Please enter title:")
n = len(title)
for i in range(0,n):
    if titlEntry == title[i]:
        print "(" + genre[i] + ") " + title[i] + " by " + author[i]
</code>```

Body:
I wrote a program that reads in a file. The name of the file was passed into my program as a command-line parameter. Each line of the file contained 3 fields, separated by a vertical bar, or pipe ("|").
The file contained information about books so each line contains a title(ex. Les Miserables), an author, and a genre which I put into three arrays:

title = []
author = []
genre = []

I am trying to input a word like "Les" and get the specific elements from the arrays and print it like "(Fiction), Les Miserables by Victor Hugo".

This is my code so far:

for word in myArray:
fields = word.split(|)
title.append(fields[0])
author.append(fields[1])
genre.append(fields[2])
entry = raw_input()
if entry == T or t:

titlEntry = raw_input("Please enter title:")
n = len(title)
for i in range(0,n):
if titlEntry == i:
print "(" + genre[i] + ") " + title[i] + " by " + author[i]

Please help

Body:
First of all, this is not the way to do it; a dictionary would be better and I would ask you look into other structures as well. Also, think about sanitizing the input you read from the command line.  However, to get you going, you are close.  Try:

titlEntry = raw_input("Please enter title:")
n = len(title)
for i in range(0,n):
    if titlEntry == title[i]:
        print "(" + genre[i] + ") " + title[i] + " by " + author[i]


问:
jQuery .data() doesn't persist in jQuery created elements
In the following example, I've added some html elements with jQuery, then assigned some data to them (again with jQuery).  I can't figure out why $("#p1").data(); returns an empty object after the assignment of $("p2").data("intID", "b");.

```<code>$(document).ready(function () {

    //Create a new <p> elment and use jQuery to assign some data to it
    $("body").html($("body").html() + "<p id='p1'>TestOne</p>");
    $("#p1").data("intID", "a");

    //confirm data assignment was successful
    console.log($("#p1").data());

    //Create new <p> element and assign different data to it
    $("body").html($("body").html() + "<p id='p2'>TestTwo</p>");
    $("#p2").data("intID", "b");

    //Check that all data still exists (spoiler alert: it doesn't)
    console.log($("#p1").data());
    console.log($("#p2").data());
});
</code>```

Resulting console output:

```<code>{intID: "a"}
{}
{intID: "b"}
</code>```

I've already verified that this works the way I want with pre-existing HTML elements (i.e. those defined in the HTML source). I've combed over https://api.jquery.com/data/ and can't figure it out from there.

I understand that there are other ways of doing what I want to accomplish, so I'm more interested in a theoretical explanation of why this happens than I am in an alternative solution.  I would think it's a bug, but that degree of coding hubris died in me long ago.  Thanks!

答:
There is nothing wrong with .data() and it persists the values. However, the issue is the way you're creating the
 elements. Use .append() instead, like this:

$(document).ready(function () {

    //Create a new
 elment and use jQuery to assign some data to it
    $("body").append("
TestOne
");
    $("#p1").data("intID", "a");

    //confirm data assignment was successful
    console.log($("#p1").data());

    //Create new
 element and assign different data to it
    $("body").append("
TestTwo
");
    $("#p2").data("intID", "b");

    //Check that all data still exists (spoiler alert: it doesn't)
    console.log($("#p1").data());
    console.log($("#p2").data());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='p1'>TestOne</p>
<p id='p2'>TestTwo</p></code>```

Body:
In the following example, I've added some html elements with jQuery, then assigned some data to them (again with jQuery).  I can't figure out why $("#p1").data(); returns an empty object after the assignment of $("p2").data("intID", "b");.

$(document).ready(function () {

    //Create a new
 elment and use jQuery to assign some data to it
    $("body").html($("body").html() + "
TestOne
");
    $("#p1").data("intID", "a");

    //confirm data assignment was successful
    console.log($("#p1").data());

    //Create new
 element and assign different data to it
    $("body").html($("body").html() + "
TestTwo
");
    $("#p2").data("intID", "b");

    //Check that all data still exists (spoiler alert: it doesn't)
    console.log($("#p1").data());
    console.log($("#p2").data());
});

Resulting console output:

{intID: "a"}
{}
{intID: "b"}

I've already verified that this works the way I want with pre-existing HTML elements (i.e. those defined in the HTML source). I've combed over https://api.jquery.com/data/ and can't figure it out from there.

I understand that there are other ways of doing what I want to accomplish, so I'm more interested in a theoretical explanation of why this happens than I am in an alternative solution.  I would think it's a bug, but that degree of coding hubris died in me long ago.  Thanks!

Body:
There is nothing wrong with .data() and it persists the values. However, the issue is the way you're creating the <p> elements. Use .append() instead, like this:

$(document).ready(function () {

    //Create a new <p> elment and use jQuery to assign some data to it
    $("body").append("<p id='p1'>TestOne</p>");
    $("#p1").data("intID", "a");

    //confirm data assignment was successful
    console.log($("#p1").data());

    //Create new <p> element and assign different data to it
    $("body").append("<p id='p2'>TestTwo</p>");
    $("#p2").data("intID", "b");

    //Check that all data still exists (spoiler alert: it doesn't)
    console.log($("#p1").data());
    console.log($("#p2").data());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='p1'>TestOne</p>
<p id='p2'>TestTwo</p>