问:
Filtering a SelectList based on a User's Role
When assigning a user to a certain project, I'd like to limit the list of available users to people with the role "Project Manager". I could use some help with the syntax because I can't seem to get the LINQ syntax right for the Where method.

Create Action (GET)

```<code>// This is the unfiltered version
ViewBag.AssignedToId = new SelectList(db.Users, "Id", "FullName");
// Attempt to filter
ViewBag.AssignedToId= new SelectList(db.Users.Where(c => c.Roles.Contains("Project Manager")), "Id", "FullName");
</code>```

Create View

```<code><div class="form-group">
     @Html.LabelFor(model => model.AssignedToId, "Choose a Project Manager", htmlAttributes: new { @class = "control-label col-md-2" })
         <div class="col-md-10">
             @Html.DropDownList("AssignedToId", null, htmlAttributes: new { @class = "form-control" })
             @Html.ValidationMessageFor(model => model.AssignedToId, "", new { @class = "text-danger" })
         </div>
</div>
</code>```

I'm getting an error on the DropDownList saying

cannot compare elements of type 'System.Collections.Generic.ICollection'. Only primitive types, enumeration types and entity types are supported.

答:
If Roles is a collection, then I would suggest creating the list of "Project Manager" outside of the LINQ to Entities query.  Furthermore, create a const string variable to hold the "Project Manager" magic string.  This will save you from having to change that string in every location you use it if that string were to ever change.

```<code>public const string roleProjectManager = "Project Manager";

var lstProjectManagers = db.Users.Where(x => x.Roles.Contains(roleProjectManager)).ToList();
</code>```

Then create your SelectList.

```<code>ViewBag.AssignedToId= new SelectList(lstProjectManagers, "Id", "FullName");
</code>```

Let me know if this helps!

Body:
When assigning a user to a certain project, I'd like to limit the list of available users to people with the role "Project Manager". I could use some help with the syntax because I can't seem to get the LINQ syntax right for the Where method.

Create Action (GET)

// This is the unfiltered version
ViewBag.AssignedToId = new SelectList(db.Users, "Id", "FullName");
// Attempt to filter
ViewBag.AssignedToId= new SelectList(db.Users.Where(c => c.Roles.Contains("Project Manager")), "Id", "FullName");

Create View

     @Html.LabelFor(model => model.AssignedToId, "Choose a Project Manager", htmlAttributes: new { @class = "control-label col-md-2" })

             @Html.DropDownList("AssignedToId", null, htmlAttributes: new { @class = "form-control" })
             @Html.ValidationMessageFor(model => model.AssignedToId, "", new { @class = "text-danger" })

I'm getting an error on the DropDownList saying

cannot compare elements of type 'System.Collections.Generic.ICollection'. Only primitive types, enumeration types and entity types are supported.

Body:
If Roles is a collection, then I would suggest creating the list of "Project Manager" outside of the LINQ to Entities query.  Furthermore, create a const string variable to hold the "Project Manager" magic string.  This will save you from having to change that string in every location you use it if that string were to ever change.

public const string roleProjectManager = "Project Manager";

var lstProjectManagers = db.Users.Where(x => x.Roles.Contains(roleProjectManager)).ToList();

Then create your SelectList.

ViewBag.AssignedToId= new SelectList(lstProjectManagers, "Id", "FullName");

Let me know if this helps!


来源: stackexchange

问:
How to refactor duplicity in code that calls super
I have two NSResponder methods (cut, copy) and they have basically the same code except they call their own super. How to create method with parameter _CMD as selector that calls super and I won't end up with recursion? </p>

```<code>- (void)copy:(id)sender
{
    [self notifyAndPerformSelector:_cmd withObject:sender];
}

- (void)cut:(id)sender
{
    [self notifyAndPerformSelector:_cmd withObject:sender];
}

- (void)notifyAndPerformSelector:(SEL)selector withObject:(id)sender
{
    [super performSelector:selector withObject:sender];
    //code...
}
</code>```

答:
As you have discovered your code doesn't call the superclass method as you want but the one in the current class, resulting in infinite recursion.

Your first option faced with this is to refactor your code, something along the lines of:

```<code>@implementation MyDerivedClass
{
   - (void)copy:(id)sender
   {
       [super copy:sender];
       [self commonCodeAfterSelector:_cmd withObject:sender];
   }

   - (void)cut:(id)sender
   {
       [super cut:sender];
       [self commonCodeAfterSelector:_cmd withObject:sender];
   }

   - (void)notifyAndPerformSelector:(SEL)selector withObject:(id)sender
   {
       //code...
   }
}
</code>```

If this approach suits your situation use it. If not...

A second option is to become the compiler...

Standard and super method calls

A standard method call of the form:

```<code>[object someMethodWithArg1:x andArg2:y]
</code>```

invokes a search for the method someMethodWithArg1:andArg2:. This search starts at the runtime class of object. The emphasis on runtime is important, the actual object referenced by object could be of the same class as the declared type of object or and of the subclasses of that type and the search must find the most derived implementation of the method.

A super method call of the form:

```<code>[super someMethodWithArg1:x andArg2:y]
</code>```

also invokes a search for the method someMethodWithArg1:andArg2:. However in this search starts at the compile time class of superclass of the class in which code occurs. For example if MyDerivedClass above is a subclass of MyBaseClass then the search for the method starts at MyBaseClass ignoring the runtime type of self – which could be MyDerivedClass or a subclass of it (say MyDerivedDerivedClass)

Why does your current code recurse?

Your call:

```<code>[super performSelector:selector withObject:sender];
</code>```

starts the search for the method performSelector:withObject: in the superclass, that search won't find the method until it reaches the NSObject class. Once found the method is invoked and starts a standard (not super) search for the method for selector, this search starts at the runtime type of self and so finds the method in MyDerivedClass... recursion.

What you need is something like:

```<code>[self performSuperSelector:selector withObject:sender];
</code>```

but unfortunately that does not exist. But you can make one...

Compiling method calls

The compiler takes a standard method call of the form:

```<code>[object someMethodWithArg1:x andArg2:y]
</code>```

and effectively (we're glossing over a few details, the need ones will get filled in below) compiles this to a call to the runtime function objc_msgSend():

```<code>objc_msgSend(object, @selector("someMethodWithArg1:andArg2:"), x, y)
</code>```

Notice that the selector is passed as a SEL value, this is where the value for _cmd comes from.

A super call of the form:

```<code>[super someMethodWithArg1:x andArg2:y]
</code>```

is effectively compiled to a call to objc_msgSendSuper() of the form:

```<code>objc_msgSendSuper(`struct` containing `self` and superclass,
                  @selector("someMethodWithArg1:andArg2:"), x, y)
</code>```

You can call these runtime functions directly in your own code. You must import the <objc/objc-runtime.h> to obtain the definitions, cast them to the appropriate type, etc.

Becoming the compiler and bypassing performSelector

Your code uses performSelector as it has a SEL value, but as shown above the runtime calls used for method calling take a SEL directly. If you "compile" the super call yourself you do not need to use performSelector, which in turn avoids the recursion problem.

Before calling objc_msgSendSuper() the function needs to be cast so its return and argument types match the actual return and argument types of the selector you are calling. This is so that the correct code is compiled to handle the arguments and return value, and that code is dependent on the types. The two selectors you are calling, copy: and cut:, have the same type which makes the code shorter. To make the casting easier we first define a shorthand for the type:

```<code>typedef void (*CutOrCopyRunner)(struct objc_super *super, SEL op, id sender);
</code>```

which defines CurOrCopyRunner as a function pointer type. Now your method:

```<code>- (void)notifyAndPerformSelector:(SEL)selector withObject:(id)sender
{
   // "compile" [super selector:sender];

   // first cast objc_msgSendSuper to the correct type by
   // casting a function pointer to it (a function name by
   // itself, e.g. objc_msgSendSuper, evaluates to a pointer
   // to the function)
   CutOrCopyRunner msgSender = (CutOrCopyRunner)objc_msgSendSuper;

   // now build the first argument struct
   struct objc_super superInfo;
   superInfo.receiver = self;
   superInfo.super_class = MyDerivedClass.class.superclass;

   // now execute the super call
   msgSender(&superInfo, selector, sender);

   // code...
}
</code>```

HTH

ContentLicense: CC BY-SA 3.0

Body:
I have two NSResponder methods (cut, copy) and they have basically the same code except they call their own super. How to create method with parameter _CMD as selector that calls super and I won't end up with recursion?

- (void)copy:(id)sender
{
    [self notifyAndPerformSelector:_cmd withObject:sender];
}

- (void)cut:(id)sender
{
    [self notifyAndPerformSelector:_cmd withObject:sender];
}

- (void)notifyAndPerformSelector:(SEL)selector withObject:(id)sender
{
    [super performSelector:selector withObject:sender];
    //code...
}

Body:
As you have discovered your code doesn't call the superclass method as you want but the one in the current class, resulting in infinite recursion.

Your first option faced with this is to refactor your code, something along the lines of:

@implementation MyDerivedClass
{
   - (void)copy:(id)sender
   {
       [super copy:sender];
       [self commonCodeAfterSelector:_cmd withObject:sender];
   }

   - (void)cut:(id)sender
   {
       [super cut:sender];
       [self commonCodeAfterSelector:_cmd withObject:sender];
   }

   - (void)notifyAndPerformSelector:(SEL)selector withObject:(id)sender
   {
       //code...
   }
}

If this approach suits your situation use it. If not...

A second option is to become the compiler...

Standard and super method calls

A standard method call of the form:

[object someMethodWithArg1:x andArg2:y]

invokes a search for the method someMethodWithArg1:andArg2:. This search starts at the runtime class of object. The emphasis on runtime is important, the actual object referenced by object could be of the same class as the declared type of object or and of the subclasses of that type and the search must find the most derived implementation of the method.

A super method call of the form:

[super someMethodWithArg1:x andArg2:y]

also invokes a search for the method someMethodWithArg1:andArg2:. However in this search starts at the compile time class of superclass of the class in which code occurs. For example if MyDerivedClass above is a subclass of MyBaseClass then the search for the method starts at MyBaseClass ignoring the runtime type of self – which could be MyDerivedClass or a subclass of it (say MyDerivedDerivedClass)

Why does your current code recurse?

Your call:

[super performSelector:selector withObject:sender];

starts the search for the method performSelector:withObject: in the superclass, that search won't find the method until it reaches the NSObject class. Once found the method is invoked and starts a standard (not super) search for the method for selector, this search starts at the runtime type of self and so finds the method in MyDerivedClass... recursion.

What you need is something like:

[self performSuperSelector:selector withObject:sender];

but unfortunately that does not exist. But you can make one...

Compiling method calls

The compiler takes a standard method call of the form:

[object someMethodWithArg1:x andArg2:y]

and effectively (we're glossing over a few details, the need ones will get filled in below) compiles this to a call to the runtime function objc_msgSend():

objc_msgSend(object, @selector("someMethodWithArg1:andArg2:"), x, y)

Notice that the selector is passed as a SEL value, this is where the value for _cmd comes from.

A super call of the form:

[super someMethodWithArg1:x andArg2:y]

is effectively compiled to a call to objc_msgSendSuper() of the form:

objc_msgSendSuper(`struct` containing `self` and superclass,
                  @selector("someMethodWithArg1:andArg2:"), x, y)

You can call these runtime functions directly in your own code. You must import the <objc/objc-runtime.h> to obtain the definitions, cast them to the appropriate type, etc.

Becoming the compiler and bypassing performSelector

Your code uses performSelector as it has a SEL value, but as shown above the runtime calls used for method calling take a SEL directly. If you "compile" the super call yourself you do not need to use performSelector, which in turn avoids the recursion problem.

Before calling objc_msgSendSuper() the function needs to be cast so its return and argument types match the actual return and argument types of the selector you are calling. This is so that the correct code is compiled to handle the arguments and return value, and that code is dependent on the types. The two selectors you are calling, copy: and cut:, have the same type which makes the code shorter. To make the casting easier we first define a shorthand for the type:

typedef void (*CutOrCopyRunner)(struct objc_super *super, SEL op, id sender);

which defines CurOrCopyRunner as a function pointer type. Now your method:

- (void)notifyAndPerformSelector:(SEL)selector withObject:(id)sender
{
   // "compile" [super selector:sender];

   // first cast objc_msgSendSuper to the correct type by
   // casting a function pointer to it (a function name by
   // itself, e.g. objc_msgSendSuper, evaluates to a pointer
   // to the function)
   CutOrCopyRunner msgSender = (CutOrCopyRunner)objc_msgSendSuper;

   // now build the first argument struct
   struct objc_super superInfo;
   superInfo.receiver = self;
   superInfo.super_class = MyDerivedClass.class.superclass;

   // now execute the super call
   msgSender(&superInfo, selector, sender);

   // code...
}

HTH


问:
How to get multiple lines in a variable in For loop from bacth file
I am trying to get All task scheduler name fetched from below query :

UPDATE : Adding the code I have tried so far:

```<code>@echo off
echo TaskName, NextRunTime, Status
setlocal enabledelayedexpansion
for /f "tokens=* delims="  %%a in ('schtasks /query /fo list^|findstr /b "TaskName*"') do (
set Task=%%~a
set Task=!Task: =!
set Task=!Task:"=!
set Task=!Task:TaskName:=!
)
for /f "tokens=*" %%b in ('schtasks /query /fo list^|findstr /b "Next Run Time*"') do (
set Run=%%~b
set Run=!Run: =!
set Run=!Run:"=!
set Run=!Run:NextRunTime:=!
 )
 for /f "tokens=*" %%c in ('schtasks /query /fo list^|findstr /b "Status*"') do (
set Sta=%%~c
set Sta=!Sta: =!
set Sta=!Sta:"=!
set Sta=!Sta:Status:=!
)
echo !Task!,!Run!,!Sta!
</code>```

But instead if all the task it returns only 1 task. I believe, it just read 1st line of the string and returned the same and skipped all the others.

How can I fetch all the task names with this?

答:
Squashman's comment shows you how to do it:

```<code>@echo off
setlocal enabledelayedexpansion
for /f "delims="  %%a in ('schtasks /query /fo csv^|findstr /vb "TaskName"') do (
  echo %%a
)
</code>```

or if you don't want the quotes:

```<code>...
for /f "tokens=1-3 delims=,"  %%a in ('schtasks /query /fo csv^|findstr /vb "TaskName"') do (
  echo %%~a,%%~b,%%~c
)
</code>```

Body:
I am trying to get All task scheduler name fetched from below query :

UPDATE : Adding the code I have tried so far:

@echo off
echo TaskName, NextRunTime, Status
setlocal enabledelayedexpansion
for /f "tokens=* delims="  %%a in ('schtasks /query /fo list^|findstr /b "TaskName*"') do (
set Task=%%~a
set Task=!Task: =!
set Task=!Task:"=!
set Task=!Task:TaskName:=!
)
for /f "tokens=*" %%b in ('schtasks /query /fo list^|findstr /b "Next Run Time*"') do (
set Run=%%~b
set Run=!Run: =!
set Run=!Run:"=!
set Run=!Run:NextRunTime:=!
 )
 for /f "tokens=*" %%c in ('schtasks /query /fo list^|findstr /b "Status*"') do (
set Sta=%%~c
set Sta=!Sta: =!
set Sta=!Sta:"=!
set Sta=!Sta:Status:=!
)
echo !Task!,!Run!,!Sta!

But instead if all the task it returns only 1 task. I believe, it just read 1st line of the string and returned the same and skipped all the others.

How can I fetch all the task names with this?

Body:
Squashman's comment shows you how to do it:

@echo off
setlocal enabledelayedexpansion
for /f "delims="  %%a in ('schtasks /query /fo csv^|findstr /vb "TaskName"') do (
  echo %%a
)

or if you don't want the quotes:

...
for /f "tokens=1-3 delims=,"  %%a in ('schtasks /query /fo csv^|findstr /vb "TaskName"') do (
  echo %%~a,%%~b,%%~c
)


问:
How to handle dynamically created item inside function without click event?
In a dropdown box which I'm trying to not close it by clicking inside it, I want to close it by clicking outside box.

The problem is the box is created dynamically, so I can't access it using this code:

```<code>$('body').on('click', function(e) {
  if (!$('#products .add-to-cart').is(e.target) &&
    $('#products .add-to-cart').has(e.target).length === 0 &&
    $('.open').has(e.target).length === 0
  ) {
    $('#products .add-to-cart').removeClass('open');
  }
});
</code>```

My HTML code:

```<code><div class="button-group dropup">
  <button type="button" class="add-to-cart dropdown-toggle" id="add-to-cart-{{ product.product_id }}"><i class="fa fa-cart-plus"></i></button>
  <div id="options-{{ product.product_id }}" class="options-popup dropdown-menu">
    <a class="cls" href="#" id="close-add-to-basket"><i class="fa fa-times-circle"></i></a>
</code>```

答:
You have to use document object in order to get the new created box element, Here is a working example:

```<code>$(document).on('click', '#close-add-to-basket', function(e) {
    e.preventDefault();
    $(document).find('#products .add-to-cart').removeClass('open');
});
</code>```

Body:
In a dropdown box which I'm trying to not close it by clicking inside it, I want to close it by clicking outside box.

The problem is the box is created dynamically, so I can't access it using this code:

$('body').on('click', function(e) {
  if (!$('#products .add-to-cart').is(e.target) &&
    $('#products .add-to-cart').has(e.target).length === 0 &&
    $('.open').has(e.target).length === 0
  ) {
    $('#products .add-to-cart').removeClass('open');
  }
});

My HTML code:

  <button type="button" class="add-to-cart dropdown-toggle" id="add-to-cart-{{ product.product_id }}"></button>

Body:
You have to use document object in order to get the new created box element, Here is a working example:

$(document).on('click', '#close-add-to-basket', function(e) {
    e.preventDefault();
    $(document).find('#products .add-to-cart').removeClass('open');
});


问:
Using Android Studio default search icon for searchView
Can't seem to find the right search icon for the searchView for my actionBar. Does Android Studio even offer a non-bad one or do I have to create my own?

Here's what's offered in Android Studio: ( I want to have all white icons)

```<code>android:icon="@android:drawable/ic_menu_search"
</code>```

This search icon doesn't work for me.

===============================================

Here's another Android Studio icon that won't work with my white icons:

```<code>android:icon="@android:drawable/ic_search_category_default"
</code>```

==============================================

```<code>android:icon="@drawable/ic_search_black_24dp"
</code>```

The final Android Studio available search icon from Image Asset Folder --> Clip Art. It's finally a white icon but it's positioned higher than the settings icon. Don't know why.

I need a white icon like the last one but to be in the same position as the settings Icon. Is there any way to lower icon without making it look odd on other phones? Do I have to create my own icon and if so, what sizes? Why does Android Studio put the white search Icon so high up compared to others?

答:
You can also access this list of icons in https://material.io/icons/
 from Android Studio

Body:
Can't seem to find the right search icon for the searchView for my actionBar. Does Android Studio even offer a non-bad one or do I have to create my own?

Here's what's offered in Android Studio: ( I want to have all white icons)

android:icon="@android:drawable/ic_menu_search"

This search icon doesn't work for me.

===============================================

Here's another Android Studio icon that won't work with my white icons:

android:icon="@android:drawable/ic_search_category_default"

==============================================

android:icon="@drawable/ic_search_black_24dp"

The final Android Studio available search icon from Image Asset Folder --> Clip Art. It's finally a white icon but it's positioned higher than the settings icon. Don't know why.

I need a white icon like the last one but to be in the same position as the settings Icon. Is there any way to lower icon without making it look odd on other phones? Do I have to create my own icon and if so, what sizes? Why does Android Studio put the white search Icon so high up compared to others?


问:
JavaFX: Determine Bounds of a node while being invisible?
is there any way to determine the bounds (especially height and width) of a node which is already attached to a scene but set to invisible?

I want to show a label on screen only if its width exceeds 100px... but it is always 0:

```<code>@Override
public void start(Stage primaryStage) {
    Group root = new Group();
    Scene scene = new Scene(root, 500, 500, Color.BLACK);
    primaryStage.setScene(scene);
    primaryStage.show();

    Label n = new Label();
    n.setVisible(false);
    n.setStyle("-fx-background-color: red;");
    root.getChildren()
        .addAll(n);
    n.textProperty()
        .addListener((v, ov, nv) -> {
            System.out.println(n.getBoundsInParent());
            n.setVisible(n.getWidth() > 100);
        });
    n.setText("TEST11111111111111111111111");
}
</code>```

The result of the sysout: (also n.getWidth() is no better)

BoundingBox [minX:0.0, minY:0.0, minZ:0.0, width:0.0, height:0.0, depth:0.0, maxX:0.0, maxY:0.0, maxZ:0.0]

Is there any trick ?

Thanks all!

答:
Your problem is that you are listening for changes to the text property and expecting the width of the node to be updated at that time - but it's not.  The width of nodes are only calculated and set during a render pass which consists of an applyCSS and layout routine (see: Get the height of a node in JavaFX (generate a layout pass)).  Your code incorrectly sets the node to invisible before the updated size of the node is calculated.

Instead of using a listener on the text property to determine visibility of the node, I suggest that you use a binding expression to create a direct binding on the visibility property to the desired width property.  An example of this approach is provided below.  You can see that the label only displays when the text to display is longer than the required width (in this case 100 pixels).

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class BoundSample extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        Pane root = new Pane();
        Scene scene = new Scene(root, 200, 100);
        primaryStage.setScene(scene);
        primaryStage.show();

        Label n = new Label();
        n.setVisible(false);
        n.visibleProperty().bind(n.widthProperty().greaterThan(100));

        TextField textField = new TextField("TEST11111111111111111111111");
        n.textProperty().bind(textField.textProperty());
        textField.relocate(0, 50);

        root.getChildren().addAll(n, textField);
    }
}
</code>```

Body:
is there any way to determine the bounds (especially height and width) of a node which is already attached to a scene but set to invisible?

I want to show a label on screen only if its width exceeds 100px... but it is always 0:

@Override
public void start(Stage primaryStage) {
    Group root = new Group();
    Scene scene = new Scene(root, 500, 500, Color.BLACK);
    primaryStage.setScene(scene);
    primaryStage.show();

    Label n = new Label();
    n.setVisible(false);
    n.setStyle("-fx-background-color: red;");
    root.getChildren()
        .addAll(n);
    n.textProperty()
        .addListener((v, ov, nv) -> {
            System.out.println(n.getBoundsInParent());
            n.setVisible(n.getWidth() > 100);
        });
    n.setText("TEST11111111111111111111111");
}

The result of the sysout: (also n.getWidth() is no better)

BoundingBox [minX:0.0, minY:0.0, minZ:0.0, width:0.0, height:0.0, depth:0.0, maxX:0.0, maxY:0.0, maxZ:0.0]

Is there any trick ?

Thanks all!

Body:
Your problem is that you are listening for changes to the text property and expecting the width of the node to be updated at that time - but it's not.  The width of nodes are only calculated and set during a render pass which consists of an applyCSS and layout routine (see: Get the height of a node in JavaFX (generate a layout pass)).  Your code incorrectly sets the node to invisible before the updated size of the node is calculated.

Instead of using a listener on the text property to determine visibility of the node, I suggest that you use a binding expression to create a direct binding on the visibility property to the desired width property.  An example of this approach is provided below.  You can see that the label only displays when the text to display is longer than the required width (in this case 100 pixels).

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class BoundSample extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        Pane root = new Pane();
        Scene scene = new Scene(root, 200, 100);
        primaryStage.setScene(scene);
        primaryStage.show();

        Label n = new Label();
        n.setVisible(false);
        n.visibleProperty().bind(n.widthProperty().greaterThan(100));

        TextField textField = new TextField("TEST11111111111111111111111");
        n.textProperty().bind(textField.textProperty());
        textField.relocate(0, 50);

        root.getChildren().addAll(n, textField);
    }
}


问:
How would I create a palindrome checker without if statements
I'm trying to create a programme like this previous one I've made;

It simply gives a boolean true/false on if a string backwards is still spelt the same way.

I've created this using if statements, but would like too know if it is possible too create using only methods and loops, and if so how? I have looked for duplicates, and there are similar posts that achieve what I have below, but everything I find uses if else statements

Any help appreciated as always; thanks.

```<code>import java.util.*;
public class testingthingsv24 {

private static Scanner in;

public static void main(String args[])
{
    in = new Scanner(System.in);
    System.out.println("Please Enter Your String: ");
    String n=in.nextLine();
    System.out.println("Your String Was: "+n);
    StringBuffer str=new StringBuffer(n);
    StringBuffer str2=new StringBuffer(str.reverse());
    String s2=new String(str2);
    System.out.println("Reversed Is: "+str2);
    if(n.equals(s2))
        System.out.println("ITS A PALINDROME");
    else
        System.out.println("ITS NOT A PALINDROME");
}
}
</code>```

Output:

```<code>Please Enter Your String:
dad
Your String Was: dad
Reversed Is: dad
ITS A PALINDROME
</code>```

答:
would like too know if it is possible too create using only methods and loops, and if so how?

Sure.  The if statement is redundant in Java.  There are plenty of other conditionals in the language, and there are multiple ways that you could implement the semantics of an if statement (including an else clause, if desired) without actually using an if statement.

For example, you can always replace

```<code>if (condition) {
    // statements when true ...
} else {
    // statements when false ...
}
</code>```

with

```<code>if_replacement: do {
    while (condition) {
        // statements when true ...
        break if_replacement;
    }
    // statements when false ...
} while (false);
</code>```

Note that that has no association whatever with any particular problem, and that it uses only looping constructs.  A somewhat simpler form is possible if you don't need the analog of an else block.  In principle you could replace every if in any program with a construct of this form.

Body:
I'm trying to create a programme like this previous one I've made;

It simply gives a boolean true/false on if a string backwards is still spelt the same way.

I've created this using if statements, but would like too know if it is possible too create using only methods and loops, and if so how? I have looked for duplicates, and there are similar posts that achieve what I have below, but everything I find uses if else statements

Any help appreciated as always; thanks.

import java.util.*;
public class testingthingsv24 {

private static Scanner in;

public static void main(String args[])
{
    in = new Scanner(System.in);
    System.out.println("Please Enter Your String: ");
    String n=in.nextLine();
    System.out.println("Your String Was: "+n);
    StringBuffer str=new StringBuffer(n);
    StringBuffer str2=new StringBuffer(str.reverse());
    String s2=new String(str2);
    System.out.println("Reversed Is: "+str2);
    if(n.equals(s2))
        System.out.println("ITS A PALINDROME");
    else
        System.out.println("ITS NOT A PALINDROME");
}
}

Output:

Please Enter Your String:
dad
Your String Was: dad
Reversed Is: dad
ITS A PALINDROME

Body:
would like too know if it is possible too create using only methods and loops, and if so how?

Sure.  The if statement is redundant in Java.  There are plenty of other conditionals in the language, and there are multiple ways that you could implement the semantics of an if statement (including an else clause, if desired) without actually using an if statement.

For example, you can always replace

if (condition) {
    // statements when true ...
} else {
    // statements when false ...
}

with

if_replacement: do {
    while (condition) {
        // statements when true ...
        break if_replacement;
    }
    // statements when false ...
} while (false);

Note that that has no association whatever with any particular problem, and that it uses only looping constructs.  A somewhat simpler form is possible if you don't need the analog of an else block.  In principle you could replace every if in any program with a construct of this form.


问:
SQL Query for Deserialized XML
I am trying to create a sql query in C# that will transfer my data from my xml file to the sql server.  I am successfully able to deserialize my XML into a "get, set" methods and output my xml into the console.  I have been searching Google for the past day to find how to create a insert query to add my xml into my sql table.  Here is what I have so far for both my classes.  Class1 is my "get, set" method class, and Program is my "main" method class.

Class1.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    public class Class1
    {
        public static object Item_ID { get; set; }
        public static object Invent_id { get; set; }
        public static object Itemsize { get; set; }
        public static object Color { get; set; }
        public static decimal Curr_price { get; set; }
        public static object Qoh { get; set; }
    }
    public class transactions
    {
        [XmlRoot(ElementName = "UPDATE")]
        public class UPDATE
        {
            [XmlAttribute(AttributeName = "qoh")]
            public string Qoh { get; set; }
            [XmlAttribute(AttributeName = "curr_price")]
            public string Curr_price { get; set; }
            [XmlAttribute(AttributeName = "color")]
            public string Color { get; set; }
            [XmlAttribute(AttributeName = "itemsize")]
            public string Itemsize { get; set; }
            [XmlAttribute(AttributeName = "invent_id")]
            public string Invent_id { get; set; }
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "ADD")]
        public class ADD
        {
            [XmlAttribute(AttributeName = "qoh")]
            public string Qoh { get; set; }
            [XmlAttribute(AttributeName = "curr_price")]
            public string Curr_price { get; set; }
            [XmlAttribute(AttributeName = "color")]
            public string Color { get; set; }
            [XmlAttribute(AttributeName = "itemsize")]
            public string Itemsize { get; set; }
            [XmlAttribute(AttributeName = "invent_id")]
            public string Invent_id { get; set; }
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "DELETE")]
        public class DELETE
        {
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "transactions")]
        public class Transactions
        {
            [XmlElement(ElementName = "UPDATE")]
            public UPDATE UPDATE { get; set; }
            [XmlElement(ElementName = "ADD")]
            public List<ADD> ADD { get; set; }
            [XmlElement(ElementName = "DELETE")]
            public DELETE DELETE { get; set; }
        }
    }
}
</code>```

Main Class

```<code>using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string conString = "Driver={MySQL ODBC 5.3 ANSI Driver};"
                + "Server=XXX;Port=YYY;"
                + "Database=inventory;"
                + "uid=ZZZ;pwd=XYZ";
            OdbcConnection connection = new OdbcConnection(conString);

            {
                XDocument theFile = XDocument.Load("C:\\Users\\Bob\\Documents\\Update.xml");

                foreach (XElement el in theFile.Root.Elements())
                {
                    if (el.Name == "ADD")
                    {
                       Console.WriteLine("{0}   {1}   {2}   {3}   {4}   {5}   {6}", el.Name, el.Attribute("qoh").Value, el.Attribute("curr_price").Value, el.Attribute("color").Value, el.Attribute("itemsize").Value, el.Attribute("invent_id").Value, el.Attribute("item_id").Value);
                       Console.ReadLine();

                        OdbcCommand Command1 = new OdbcCommand("INSERT INTO item (item_id, invent_id, itemsize, color, curr_price, qoh) VALUES( ?, ?, ?, ?, ?, ?) ", connection);
                        Command1.Parameters.Add("@SZ", OdbcType.VarChar).Value = Class1.Itemsize;
                        Command1.Parameters.Add("@COL", OdbcType.VarChar).Value = Class1.Color;
                        Command1.Parameters.Add("@PR", OdbcType.Double).Value = (double)Class1.Curr_price;
                        Command1.Parameters.Add("@QOH", OdbcType.Int).Value = Class1.Qoh;
                        Command1.Parameters.Add("@ID", OdbcType.Int).Value = Class1.Item_ID;

                        Console.ReadLine();
                    }
                    else if (el.Name == "UPDATE")
                    {
                        Console.WriteLine("{0}   {1}   {2}   {3}   {4}   {5}   {6}", el.Name, el.Attribute("qoh").Value, el.Attribute("curr_price").Value, el.Attribute("color").Value, el.Attribute("itemsize").Value, el.Attribute("invent_id").Value, el.Attribute("item_id").Value);
                        Console.ReadLine();
                    }
                    else if (el.Name == "DELETE")
                    {
                        Console.WriteLine("{0}   {1}", el.Name, el.Attribute("item_id").Value);
                        Console.ReadLine();
                    }
                }
            }
        }
    }
}
</code>```

Update:

In regards to using MySQL LOAD query, here is what I have but am not sure if it is correct.  After reading your link about Infile Loading, it seems I just point the query to the xml file location and it will copy the data into the fields in my SQL table.  I also changed the parameters in the correct order and still does not work.  It seems it is not seeing the values from my xml file or my parameter line is not correct.

```<code> OdbcCommand Command1 = new OdbcCommand("LOAD XML LOCAL INFILE 'C:\\Users\\Bob\\Documents\\Update.xml' INTO TABLE item ROWS IDENTIFIED BY '<ADD>'");
</code>```

答:
I figured out how to use Load XML with my query.  I noticed that the file path needed "/", not "\" as it could not read the file.  After making this change, it work.  Below is my edited code.</p>

```<code>if (el.Name == "ADD")
                    {
                       Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully added.");
                        Console.ReadLine();

                        OdbcCommand Command1 = new OdbcCommand("LOAD XML LOCAL INFILE 'C:/Users/Adam/Documents/Update.xml' INTO TABLE item ROWS IDENTIFIED BY '<ADD>'", connection);
                        connection.Open();
                        OdbcDataReader reader = Command1.ExecuteReader();
                        connection.Close();
                    }
</code>```

Title: SQL Query for Deserialized XML

Body:
I am trying to create a sql query in C# that will transfer my data from my xml file to the sql server.  I am successfully able to deserialize my XML into a "get, set" methods and output my xml into the console.  I have been searching Google for the past day to find how to create a insert query to add my xml into my sql table.  Here is what I have so far for both my classes.  Class1 is my "get, set" method class, and Program is my "main" method class.

Class1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    public class Class1
    {
        public static object Item_ID { get; set; }
        public static object Invent_id { get; set; }
        public static object Itemsize { get; set; }
        public static object Color { get; set; }
        public static decimal Curr_price { get; set; }
        public static object Qoh { get; set; }
    }
    public class transactions
    {
        [XmlRoot(ElementName = "UPDATE")]
        public class UPDATE
        {
            [XmlAttribute(AttributeName = "qoh")]
            public string Qoh { get; set; }
            [XmlAttribute(AttributeName = "curr_price")]
            public string Curr_price { get; set; }
            [XmlAttribute(AttributeName = "color")]
            public string Color { get; set; }
            [XmlAttribute(AttributeName = "itemsize")]
            public string Itemsize { get; set; }
            [XmlAttribute(AttributeName = "invent_id")]
            public string Invent_id { get; set; }
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "ADD")]
        public class ADD
        {
            [XmlAttribute(AttributeName = "qoh")]
            public string Qoh { get; set; }
            [XmlAttribute(AttributeName = "curr_price")]
            public string Curr_price { get; set; }
            [XmlAttribute(AttributeName = "color")]
            public string Color { get; set; }
            [XmlAttribute(AttributeName = "itemsize")]
            public string Itemsize { get; set; }
            [XmlAttribute(AttributeName = "invent_id")]
            public string Invent_id { get; set; }
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "DELETE")]
        public class DELETE
        {
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "transactions")]
        public class Transactions
        {
            [XmlElement(ElementName = "UPDATE")]
            public UPDATE UPDATE { get; set; }
            [XmlElement(ElementName = "ADD")]
            public List<ADD> ADD { get; set; }
            [XmlElement(ElementName = "DELETE")]
            public DELETE DELETE { get; set; }
        }
    }
}

Main Class

using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string conString = "Driver={MySQL ODBC 5.3 ANSI Driver};"
                + "Server=XXX;Port=YYY;"
                + "Database=inventory;"
                + "uid=ZZZ;pwd=XYZ";
            OdbcConnection connection = new OdbcConnection(conString);

            {
                XDocument theFile = XDocument.Load("C:\\Users\\Bob\\Documents\\Update.xml");

                foreach (XElement el in theFile.Root.Elements())
                {
                    if (el.Name == "ADD")
                    {
                       Console.WriteLine("{0}   {1}   {2}   {3}   {4}   {5}   {6}", el.Name, el.Attribute("qoh").Value, el.Attribute("curr_price").Value, el.Attribute("color").Value, el.Attribute("itemsize").Value, el.Attribute("invent_id").Value, el.Attribute("item_id").Value);
                       Console.ReadLine();

                        OdbcCommand Command1 = new OdbcCommand("INSERT INTO item (item_id, invent_id, itemsize, color, curr_price, qoh) VALUES( ?, ?, ?, ?, ?, ?) ", connection);
                        Command1.Parameters.Add("@SZ", OdbcType.VarChar).Value = Class1.Itemsize;
                        Command1.Parameters.Add("@COL", OdbcType.VarChar).Value = Class1.Color;
                        Command1.Parameters.Add("@PR", OdbcType.Double).Value = (double)Class1.Curr_price;
                        Command1.Parameters.Add("@QOH", OdbcType.Int).Value = Class1.Qoh;
                        Command1.Parameters.Add("@ID", OdbcType.Int).Value = Class1.Item_ID;

                        Console.ReadLine();
                    }
                    else if (el.Name == "UPDATE")
                    {
                        Console.WriteLine("{0}   {1}   {2}   {3}   {4}   {5}   {6}", el.Name, el.Attribute("qoh").Value, el.Attribute("curr_price").Value, el.Attribute("color").Value, el.Attribute("itemsize").Value, el.Attribute("invent_id").Value, el.Attribute("item_id").Value);
                        Console.ReadLine();
                    }
                    else if (el.Name == "DELETE")
                    {
                        Console.WriteLine("{0}   {1}", el.Name, el.Attribute("item_id").Value);
                        Console.ReadLine();
                    }
                }
            }
        }
    }
}

Update:

In regards to using MySQL LOAD query, here is what I have but am not sure if it is correct.  After reading your link about Infile Loading, it seems I just point the query to the xml file location and it will copy the data into the fields in my SQL table.  I also changed the parameters in the correct order and still does not work.  It seems it is not seeing the values from my xml file or my parameter line is not correct.

 OdbcCommand Command1 = new OdbcCommand("LOAD XML LOCAL INFILE 'C:\\Users\\Bob\\Documents\\Update.xml' INTO TABLE item ROWS IDENTIFIED BY '<ADD>'");

Body:
I figured out how to use Load XML with my query.  I noticed that the file path needed "/", not "\" as it could not read the file.  After making this change, it work.  Below is my edited code.

if (el.Name == "ADD")
                    {
                       Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully added.");
                        Console.ReadLine();

                        OdbcCommand Command1 = new OdbcCommand("LOAD XML LOCAL INFILE 'C:/Users/Adam/Documents/Update.xml' INTO TABLE item ROWS IDENTIFIED BY '<ADD>'", connection);
                        connection.Open();
                        OdbcDataReader reader = Command1.ExecuteReader();
                        connection.Close();
                    }


问:
Vim: reopen all previous files in a new session after restart
I usually have long lived vim session with dozens of files open. Once in a while, I need to restart vim, say to install a new plugin or apply some new config.

How can I reopen all the previous files after restart?

答:
Here is a basic setup of automatic session save / load extracted from my config:

```<code>let s:session_loaded = 1

augroup autosession
  " load last session on start
  " Note: without 'nested' filetypes are not restored.
  autocmd VimEnter * nested call s:session_vim_enter()
  autocmd VimLeavePre * call s:session_vim_leave()
augroup END

function! s:session_vim_enter()
    if bufnr('$') == 1 && bufname('%') == '' && !&mod && getline(1, '$') == ['']
        execute 'silent source ~/.vim/lastsession.vim'
    else
      let s:session_loaded = 0
    endif
endfunction

function! s:session_vim_leave()
  if s:session_loaded == 1
    let sessionoptions = &sessionoptions
    try
        set sessionoptions-=options
        set sessionoptions+=tabpages
        execute 'mksession! ~/.vim/lastsession.vim'
    finally
        let &sessionoptions = sessionoptions
    endtry
  endif
endfunction
</code>```

It will only restore the session if you run vim without arguments, so if you do vim somefile.txt to do the quick edit, it will not touch the last session.

Bonus (this will restore cursor position inside files too):

```<code>" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event
" handler.
autocmd MyAutoCmd BufReadPost *
    \ if line("'\"") > 0 |
    \   if line("'\"") <= line("$") |
    \     exe("norm '\"") |
    \   else |
    \     exe "norm $" |
    \   endif|
    \ endif
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is a basic setup of automatic session save / load extracted from my config:

let s:session_loaded = 1

augroup autosession
  " load last session on start
  " Note: without 'nested' filetypes are not restored.
  autocmd VimEnter * nested call s:session_vim_enter()
  autocmd VimLeavePre * call s:session_vim_leave()
augroup END

function! s:session_vim_enter()
    if bufnr('$') == 1 && bufname('%') == '' && !&mod && getline(1, '$') == ['']
        execute 'silent source ~/.vim/lastsession.vim'
    else
      let s:session_loaded = 0
    endif
endfunction

function! s:session_vim_leave()
  if s:session_loaded == 1
    let sessionoptions = &sessionoptions
    try
        set sessionoptions-=options
        set sessionoptions+=tabpages
        execute 'mksession! ~/.vim/lastsession.vim'
    finally
        let &sessionoptions = sessionoptions
    endtry
  endif
endfunction

It will only restore the session if you run vim without arguments, so if you do vim somefile.txt to do the quick edit, it will not touch the last session.

Bonus (this will restore cursor position inside files too):

" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event
" handler.
autocmd MyAutoCmd BufReadPost *
    \ if line("'\"") > 0 |
    \   if line("'\"") <= line("$") |
    \     exe("norm '\"") |
    \   else |
    \     exe "norm $" |
    \   endif|
    \ endif


问:
Integrating SMS service in Jenkins
Does anyone know how to implement SMS Plugin in Jenkins?!

I have searched in Jenkins and found the plugin (SMS Notification), however it involves cost.

I want to integrate SMS without bearing the cost.  Any help is appreciated!! :)

Thanks

答:
This is a legitimate question!

Make sure you are using Jenkins 2.x

Download the email-ext plugin from https://plugins.jenkins.io/email-ext

Install the plugin and restart Jenkins

Configure your job -- in the Post Build Actions, select Editable Email Notification and enter the emails for the cellular company being used in the Project Recipient List

T-mobile would be phonenumber@tmomail.net

Verizon would be phonenumber@vtext.com

AT&T would be phonenumber@txt.att.net ... etc

Make sure you avoid the problem I had: Your System Admin e-mail address must have a valid email address.

Title: Integrating SMS service in Jenkins


问:
iPhone - content won't scroll while image is loaded from URL
I'm trying to do something in my iPhone app where it downloads an image from a URL. The image downloads fine on the page, but I can't scroll through content or interact with it in any other way until the images download, making the app feels like it's frozen at first.

I've just used this code to load the image:

```<code>- (void)viewDidAppear:(BOOL)animated
{
    *photo1.image = [UIImage imageWithData:
        [NSData dataWithContentsOfURL:
            [NSURL URLWithString:@"http://www.ikipond.com/wp-includes/images/cosplayipn/will_1.png"]
         ]
    ];
}
</code>```

I'd really appreciate a suggestion of how to make it so users can interact with the page while the images are still downloading. Thanks a lot,

Chris

答:
do it on any thread but the main.

a place to start; Async image downloader

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to do something in my iPhone app where it downloads an image from a URL. The image downloads fine on the page, but I can't scroll through content or interact with it in any other way until the images download, making the app feels like it's frozen at first.

I've just used this code to load the image:

- (void)viewDidAppear:(BOOL)animated
{
    *photo1.image = [UIImage imageWithData:
        [NSData dataWithContentsOfURL:
            [NSURL URLWithString:@"http://www.ikipond.com/wp-includes/images/cosplayipn/will_1.png"]
         ]
    ];
}

I'd really appreciate a suggestion of how to make it so users can interact with the page while the images are still downloading. Thanks a lot,

Chris


问:
App widget crash during second configuration launch
I am developing an app widget which launches a configuration activity when the widget is moved to the screen. The first time I place the widget on the screen, the configuration launches and runs successfully. After I removed the widget, then placed it on the screen again, the activity crashes, with logcat showing the following:

```<code>E/AndroidRuntime(15830): FATAL EXCEPTION: main
E/AndroidRuntime(15830): Process: com.lge.launcher2, PID: 15830
E/AndroidRuntime(15830): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=-1, data=Intent { (has extras) }} to activity {com.lge.launcher2/com.lge.launcher2.Launcher}: java.lang.NullPointerException: Attempt to read from field 'android.content.ComponentName android.appwidget.AppWidgetProviderInfo.provider' on a null object reference
E/AndroidRuntime(15830):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3554)
E/AndroidRuntime(15830):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3597)
E/AndroidRuntime(15830):    at android.app.ActivityThread.access$1300(ActivityThread.java:148)
E/AndroidRuntime(15830):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1332)
E/AndroidRuntime(15830):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(15830):    at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime(15830):    at android.app.ActivityThread.main(ActivityThread.java:5272)
E/AndroidRuntime(15830):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(15830):    at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(15830):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
E/AndroidRuntime(15830):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
E/AndroidRuntime(15830): Caused by: java.lang.NullPointerException: Attempt to read from field 'android.content.ComponentName android.appwidget.AppWidgetProviderInfo.provider' on a null object reference
E/AndroidRuntime(15830):    at com.lge.launcher2.views.LauncherAppWidgetHostView.<init>(LauncherAppWidgetHostView.java:71)
E/AndroidRuntime(15830):    at com.lge.launcher2.application.LauncherAppWidgetHost.onCreateView(LauncherAppWidgetHost.java:56)
E/AndroidRuntime(15830):    at android.appwidget.AppWidgetHost.createView(AppWidgetHost.java:313)
E/AndroidRuntime(15830):    at com.lge.launcher2.application.WidgetManager.createView(WidgetManager.java:105)
E/AndroidRuntime(15830):    at com.lge.launcher2.Launcher.completeAddAppWidget(Launcher.java:1670)
E/AndroidRuntime(15830):    at com.lge.launcher2.Launcher.completeAdd(Launcher.java:649)
E/AndroidRuntime(15830):    at com.lge.launcher2.Launcher.onActivityResult(Launcher.java:685)
E/AndroidRuntime(15830):    at android.app.Activity.dispatchActivityResult(Activity.java:6179)
E/AndroidRuntime(15830):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3550)
E/AndroidRuntime(15830):    ... 10 more
W/ActivityManager( 1022):   Force finishing activity com.lge.launcher2/.Launcher
W/ResourcesManager(14274): Asset path '/system/framework/com.google.android.maps.jar' does not exist or contains no resources.
W/ResourcesManager(14274): Asset path '/system/framework/com.lge.mdm.jar' does not exist or contains no resources.
W/ResourcesManager(14274): Asset path '/system/framework/com.lge.telephony.sms.jar' does not exist or contains no resources.
W/ResourcesManager(14274): Asset path '/system/framework/lghiddenlibs.jar' does not exist or contains no resources.
W/ResourcesManager(14274): Asset path '/system/framework/qcrilhook.jar' does not exist or contains no resources.
W/PhoneWindowManagerEx( 1022): Call!!!getLGSystemUiVisibility. =0x0
D/StatusBarManagerServiceEx( 1022): setLGSystemUiVisibility(0x0)
D/StatusBarManagerServiceEx( 1022): manageNaviBtnDisableList userId=0 what=0x0 pkg=WindowManager.LayoutParams
</code>```

I toggled the "Don't keep activities" configuration as suggested in this question, but that didn't change anything.
My test system is an LG3 device running Lollipop. What causes the crash?

Additional points

If I wait at the first input screen for a while (TBD how long exactly) the same crash occurs.

I set the result in onCreate as follows:

Intent resultValue = new Intent();
 resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
 setResult(RESULT_CANCELED, resultValue);

and when the user completes the configuration process, as follows:

```<code> Intent resultValue = new Intent();
 resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
 setResult(RESULT_OK, resultValue);
 finish();
</code>```

My problem might be related to this question, which has not been answered.

答:
AppWidgetId is valid also does not only mean that it has been passed to the activity but also that it has been registered within Android's AppWidgetManager.
This happens by default before calling the configuration activity.

However, in my case, I deleted appWidgetIds manually from Android's AppWidgetManager whenever onUpdate was called an the preference was not known to my application. Lesson learned - don't change Android's appwidget state.

Body:
I am developing an app widget which launches a configuration activity when the widget is moved to the screen. The first time I place the widget on the screen, the configuration launches and runs successfully. After I removed the widget, then placed it on the screen again, the activity crashes, with logcat showing the following:

E/AndroidRuntime(15830): FATAL EXCEPTION: main
E/AndroidRuntime(15830): Process: com.lge.launcher2, PID: 15830
E/AndroidRuntime(15830): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=5, result=-1, data=Intent { (has extras) }} to activity {com.lge.launcher2/com.lge.launcher2.Launcher}: java.lang.NullPointerException: Attempt to read from field 'android.content.ComponentName android.appwidget.AppWidgetProviderInfo.provider' on a null object reference
E/AndroidRuntime(15830):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3554)
E/AndroidRuntime(15830):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3597)
E/AndroidRuntime(15830):    at android.app.ActivityThread.access$1300(ActivityThread.java:148)
E/AndroidRuntime(15830):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1332)
E/AndroidRuntime(15830):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(15830):    at android.os.Looper.loop(Looper.java:135)
E/AndroidRuntime(15830):    at android.app.ActivityThread.main(ActivityThread.java:5272)
E/AndroidRuntime(15830):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(15830):    at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(15830):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
E/AndroidRuntime(15830):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
E/AndroidRuntime(15830): Caused by: java.lang.NullPointerException: Attempt to read from field 'android.content.ComponentName android.appwidget.AppWidgetProviderInfo.provider' on a null object reference
E/AndroidRuntime(15830):    at com.lge.launcher2.views.LauncherAppWidgetHostView.<init>(LauncherAppWidgetHostView.java:71)
E/AndroidRuntime(15830):    at com.lge.launcher2.application.LauncherAppWidgetHost.onCreateView(LauncherAppWidgetHost.java:56)
E/AndroidRuntime(15830):    at android.appwidget.AppWidgetHost.createView(AppWidgetHost.java:313)
E/AndroidRuntime(15830):    at com.lge.launcher2.application.WidgetManager.createView(WidgetManager.java:105)
E/AndroidRuntime(15830):    at com.lge.launcher2.Launcher.completeAddAppWidget(Launcher.java:1670)
E/AndroidRuntime(15830):    at com.lge.launcher2.Launcher.completeAdd(Launcher.java:649)
E/AndroidRuntime(15830):    at com.lge.launcher2.Launcher.onActivityResult(Launcher.java:685)
E/AndroidRuntime(15830):    at android.app.Activity.dispatchActivityResult(Activity.java:6179)
E/AndroidRuntime(15830):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3550)
E/AndroidRuntime(15830):    ... 10 more
W/ActivityManager( 1022):   Force finishing activity com.lge.launcher2/.Launcher
W/ResourcesManager(14274): Asset path '/system/framework/com.google.android.maps.jar' does not exist or contains no resources.
W/ResourcesManager(14274): Asset path '/system/framework/com.lge.mdm.jar' does not exist or contains no resources.
W/ResourcesManager(14274): Asset path '/system/framework/com.lge.telephony.sms.jar' does not exist or contains no resources.
W/ResourcesManager(14274): Asset path '/system/framework/lghiddenlibs.jar' does not exist or contains no resources.
W/ResourcesManager(14274): Asset path '/system/framework/qcrilhook.jar' does not exist or contains no resources.
W/PhoneWindowManagerEx( 1022): Call!!!getLGSystemUiVisibility. =0x0
D/StatusBarManagerServiceEx( 1022): setLGSystemUiVisibility(0x0)
D/StatusBarManagerServiceEx( 1022): manageNaviBtnDisableList userId=0 what=0x0 pkg=WindowManager.LayoutParams

I toggled the "Don't keep activities" configuration as suggested in this question, but that didn't change anything.
My test system is an LG3 device running Lollipop. What causes the crash?

Additional points

If I wait at the first input screen for a while (TBD how long exactly) the same crash occurs.

I set the result in onCreate as follows:

Intent resultValue = new Intent();
 resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
 setResult(RESULT_CANCELED, resultValue);

and when the user completes the configuration process, as follows:

 Intent resultValue = new Intent();
 resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
 setResult(RESULT_OK, resultValue);
 finish();

My problem might be related to this question, which has not been answered.


问:
INotifyPropertyChanged not connecting inside WndProc Message
I am currently working on a Windows desktop application in WPF. It is build around the MVVM pattern, therefore the view is binded to the viewmodel via INotifyPropertyChanged with the help of the Telerik library. The application as a whole works well but one module requires messages from a hardware instrument. This instrument only sends information via WndMessage, meaning we implement the WndProc method.

The WndProc method works as expected except for the fact that any binding call is not received by the view. We tested the bindings outside the WndProc and they work well. Sadly, we tried to trigger the notification via invoke and manual refreshing but to no avail.

Is there a way for the notify message to reach the view during a WndProc? I provided snippet of the code but the code itself is really simple.

Databinding

```<code>public List<PlotCoordinate> PointsList
{
    get
    {
        return _pointsList;
    }
}
</code>```

WndProc message reception

```<code>private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    MainWindowViewModel viewModel = _dataContext;
    InstrumentViewModel instrument = viewModel.InstrumentViewModelReference as InstrumentViewModel;
    instrument?.ProcessMessage(hwnd, msg, wParam, lParam, ref handled);

    return IntPtr.Zero;
}
</code>```

Data manipulation inside the WndProc

```<code>public void DrawGraphFromInstrumentData()
{
    // Clear previous data and prepare new series
    _pointsList = new List<PlotCoordinate>();

    // ... fill the list with new data

    OnPropertyChanged("PointsList");
}
</code>```

Any insight would be greatly appreciated.

Edit

After some fooling around I think I managed to identify the problem. The problem is not the _dataContext but at this line :

```<code>InstrumentViewModel instrument = viewModel.InstrumentViewModelReference as InstrumentViewModel;
</code>```

Using the _dataContext directly activates the PropertyChanged but using the instrument does not. I'll keep looking into this.

答: Use an ObservableCollection<PlotCoordinate> instead of just your List<PlotCoordinate>. Be sure to be on the UI thread when adding to this list, and your View should recognize when new items are added rather than just when the List itself is changed.

Body:
I am currently working on a Windows desktop application in WPF. It is build around the MVVM pattern, therefore the view is binded to the viewmodel via INotifyPropertyChanged with the help of the Telerik library. The application as a whole works well but one module requires messages from a hardware instrument. This instrument only sends information via WndMessage, meaning we implement the WndProc method.

The WndProc method works as expected except for the fact that any binding call is not received by the view. We tested the bindings outside the WndProc and they work well. Sadly, we tried to trigger the notification via invoke and manual refreshing but to no avail.

Is there a way for the notify message to reach the view during a WndProc? I provided snippet of the code but the code itself is really simple.

Databinding

public List<PlotCoordinate> PointsList
{
    get
    {
        return _pointsList;
    }
}

WndProc message reception

private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    MainWindowViewModel viewModel = _dataContext;
    InstrumentViewModel instrument = viewModel.InstrumentViewModelReference as InstrumentViewModel;
    instrument?.ProcessMessage(hwnd, msg, wParam, lParam, ref handled);

    return IntPtr.Zero;
}

Data manipulation inside the WndProc

public void DrawGraphFromInstrumentData()
{
    // Clear previous data and prepare new series
    _pointsList = new List<PlotCoordinate>();

    // ... fill the list with new data

    OnPropertyChanged("PointsList");
}

Any insight would be greatly appreciated.

Edit

After some fooling around I think I managed to identify the problem. The problem is not the _dataContext but at this line :

InstrumentViewModel instrument = viewModel.InstrumentViewModelReference as InstrumentViewModel;

Using the _dataContext directly activates the PropertyChanged but using the instrument does not. I'll keep looking into this.


问:
How to properly make method async?
I have method for computing Levenshtein distance

```<code>public static LevenshteinMatches LevenshteinSingleThread(this string str, string expression, int maxDistance) {
        if (str.Length > expression.Length + 1) {
            int len = expression.Length;
            long strLen = str.Length - len + 1;
            int[] results = new int[strLen];
            int[][,] dimension = new int[strLen][,];
            for (int i = 0; i < strLen; i++) {
                dimension[i] = new int[len + 1, len + 1];
            }

            string source = str;
            source = source.ToUpper();
            expression = expression.ToUpper();

            for (int i = 0; i < strLen; i++) {
                results[i] = SqueareLevenshtein(ref dimension[i], str.Substring(i, len).ToUpper(), expression, len);
            }

            LevenshteinMatches matches = new LevenshteinMatches();

            for (int i = 0; i < strLen; i++) {
                if (results[i] <= maxDistance) {
                    matches.addMatch(str.Substring(i, len), Math.Round((1.0 - ((double)results[i] / len)) * 100.0, 2), i, len, results[i]);
                }
            }

            return matches;
        }
        else {
            LevenshteinMatch match = str.LevenshteinCPU(expression, maxDistance);
            if (match != null)
                return new LevenshteinMatches(match);
            else
                return new LevenshteinMatches();
        }
    }
</code>```

What should I do to make it async?

Or should i leave this method and just call it some different way?

Here is my attempt to make it async; Not sure what is wrong but I can't get any results - thread is inf working  but it should take only few ms.

```<code>public static async Task<LevenshteinMatches> LevenshteinSingleThread(this string str, string expression, int maxDistance) {
        return await Task.Factory.StartNew(() => {
            if (str.Length > expression.Length + 1) {
                int len = expression.Length;
                long strLen = str.Length - len + 1;
                int[] results = new int[strLen];
                int[][,] dimension = new int[strLen][,];
                for (int i = 0; i < strLen; i++) {
                    dimension[i] = new int[len + 1, len + 1];
                }

                string source = str;
                source = source.ToUpper();
                expression = expression.ToUpper();

                for (int i = 0; i < strLen; i++) {
                    results[i] = SqueareLevenshtein(ref dimension[i], str.Substring(i, len).ToUpper(), expression, len);
                }

                LevenshteinMatches matches = new LevenshteinMatches();

                for (int i = 0; i < strLen; i++) {
                    if (results[i] <= maxDistance) {
                        matches.addMatch(str.Substring(i, len), Math.Round((1.0 - ((double)results[i] / len)) * 100.0, 2), i, len, results[i]);
                    }
                }

                return matches;
            }
            else {
                LevenshteinMatch match = str.LevenshteinCPU(expression, maxDistance);
                if (match != null)
                    return new LevenshteinMatches(match);
                else
                    return new LevenshteinMatches();
            }
        });
    }
</code>```

rest of the code link

And that's how I call it:

```<code>string s = "xcjavxzcbvmrmummuuutmtumuumtryumtryumtrutryumtryumtrymutryumtyumtryumtrmutyumtrurtmutymurtmyutrymut";

        s = string.Concat(Enumerable.Repeat(s, 4000));

        var watch = System.Diagnostics.Stopwatch.StartNew();
        var ret = s.LevenshteinSingleThread("jas", 1);
        var res = ret.Result;
        watch.Stop();

        var elapsedMs = watch.ElapsedMilliseconds;
</code>```

答:
There is nothing async about your function, it is entirely CPU bound work. Changing the signature to async Task<LevenshteinMatches> and never using await in the function should have caused a warning in the compiler.

Instead of "making it async" if the thing you are really after is making it work in parallel then just call the code in parallel.

```<code>string s = "xcjavxzcbvmrmummuuutmtumuumtryumtryumtrutryumtryumtrymutryumtyumtryumtrmutyumtrurtmutymurtmyutrymut";
s = string.Concat(Enumerable.Repeat(s, 4000));

var expressions = new[] {"jas", "cbv"}

var tasks = new List<Task<LevenshteinMatches>>()
foreach(var expression in expressions)
{
   var task = new Task.Run(()=> message.LevenshteinSingleThread(expression, 1)); //Start multiple threads
   tasks.Add(task);
}
LevenshteinMatches[] results = Task.WaitAll(tasks); //Wait for all the threads to end.
</code>```

You could even make parts of the internal function multi-threaded by using Parallel.For( to make some of the for loops parallel, just be careful that any collections you call Add on are either synchronized inside a lock or are thread safe collections.

For example if SqueareLevenshtein is thread safe internally you could do

```<code>Parallel.For(0, strLen, i => {
                                   //Are you sure ref is needed here?
    results[i] = SqueareLevenshtein(ref dimension[i], str.Substring(i, len).ToUpper(), expression, len);
});

LevenshteinMatches matches = new LevenshteinMatches();

Parallel.For(0, strLen; i => {
    if (results[i] <= maxDistance) {
        lock(matches)
        {
            matches.addMatch(str.Substring(i, len), Math.Round((1.0 - ((double)results[i] / len)) * 100.0, 2), i, len, results[i]);
        }
    }
});

return matches;
</code>```

Title: How to properly make method async?

Body:
I have method for computing Levenshtein distance

public static LevenshteinMatches LevenshteinSingleThread(this string str, string expression, int maxDistance) {
        if (str.Length > expression.Length + 1) {
            int len = expression.Length;
            long strLen = str.Length - len + 1;
            int[] results = new int[strLen];
            int[][,] dimension = new int[strLen][,];
            for (int i = 0; i < strLen; i++) {
                dimension[i] = new int[len + 1, len + 1];
            }

            string source = str;
            source = source.ToUpper();
            expression = expression.ToUpper();

            for (int i = 0; i < strLen; i++) {
                results[i] = SqueareLevenshtein(ref dimension[i], str.Substring(i, len).ToUpper(), expression, len);
            }

            LevenshteinMatches matches = new LevenshteinMatches();

            for (int i = 0; i < strLen; i++) {
                if (results[i] <= maxDistance) {
                    matches.addMatch(str.Substring(i, len), Math.Round((1.0 - ((double)results[i] / len)) * 100.0, 2), i, len, results[i]);
                }
            }

            return matches;
        }
        else {
            LevenshteinMatch match = str.LevenshteinCPU(expression, maxDistance);
            if (match != null)
                return new LevenshteinMatches(match);
            else
                return new LevenshteinMatches();
        }
    }

What should I do to make it async?

Or should i leave this method and just call it some different way?

Here is my attempt to make it async; Not sure what is wrong but I can't get any results - thread is inf working  but it should take only few ms.

public static async Task<LevenshteinMatches> LevenshteinSingleThread(this string str, string expression, int maxDistance) {
        return await Task.Factory.StartNew(() => {
            if (str.Length > expression.Length + 1) {
                int len = expression.Length;
                long strLen = str.Length - len + 1;
                int[] results = new int[strLen];
                int[][,] dimension = new int[strLen][,];
                for (int i = 0; i < strLen; i++) {
                    dimension[i] = new int[len + 1, len + 1];
                }

                string source = str;
                source = source.ToUpper();
                expression = expression.ToUpper();

                for (int i = 0; i < strLen; i++) {
                    results[i] = SqueareLevenshtein(ref dimension[i], str.Substring(i, len).ToUpper(), expression, len);
                }

                LevenshteinMatches matches = new LevenshteinMatches();

                for (int i = 0; i < strLen; i++) {
                    if (results[i] <= maxDistance) {
                        matches.addMatch(str.Substring(i, len), Math.Round((1.0 - ((double)results[i] / len)) * 100.0, 2), i, len, results[i]);
                    }
                }

                return matches;
            }
            else {
                LevenshteinMatch match = str.LevenshteinCPU(expression, maxDistance);
                if (match != null)
                    return new LevenshteinMatches(match);
                else
                    return new LevenshteinMatches();
            }
        });
    }

rest of the code link

And that's how I call it:

string s = "xcjavxzcbvmrmummuuutmtumuumtryumtryumtrutryumtryumtrymutryumtyumtryumtrmutyumtrurtmutymurtmyutrymut";

        s = string.Concat(Enumerable.Repeat(s, 4000));

        var watch = System.Diagnostics.Stopwatch.StartNew();
        var ret = s.LevenshteinSingleThread("jas", 1);
        var res = ret.Result;
        watch.Stop();

        var elapsedMs = watch.ElapsedMilliseconds;

Body:
There is nothing async about your function, it is entirely CPU bound work. Changing the signature to async Task<LevenshteinMatches> and never using await in the function should have caused a warning in the compiler.

Instead of "making it async" if the thing you are really after is making it work in parallel then just call the code in parallel.

string s = "xcjavxzcbvmrmummuuutmtumuumtryumtryumtrutryumtryumtrymutryumtyumtryumtrmutyumtrurtmutymurtmyutrymut";
s = string.Concat(Enumerable.Repeat(s, 4000));

var expressions = new[] {"jas", "cbv"}

var tasks = new List<Task<LevenshteinMatches>>()
foreach(var expression in expressions)
{
   var task = new Task.Run(()=> message.LevenshteinSingleThread(expression, 1)); //Start multiple threads
   tasks.Add(task);
}
LevenshteinMatches[] results = Task.WaitAll(tasks); //Wait for all the threads to end.

You could even make parts of the internal function multi-threaded by using Parallel.For( to make some of the for loops parallel, just be careful that any collections you call Add on are either synchronized inside a lock or are thread safe collections.

For example if SqueareLevenshtein is thread safe internally you could do

Parallel.For(0, strLen, i => {
                                   //Are you sure ref is needed here?
    results[i] = SqueareLevenshtein(ref dimension[i], str.Substring(i, len).ToUpper(), expression, len);
});

LevenshteinMatches matches = new LevenshteinMatches();

Parallel.For(0, strLen; i => {
    if (results[i] <= maxDistance) {
        lock(matches)
        {
            matches.addMatch(str.Substring(i, len), Math.Round((1.0 - ((double)results[i] / len)) * 100.0, 2), i, len, results[i]);
        }
    }
});

return matches;


问:
angular keyup event does not trigger on child component, but only on parent instead
I created a component that i wish to have multiple versions of it in my app, since i want to keep all the logic in only one place, i created a ParentComponent where all my code resides.

But angular dont inherit component annotations, so i created also a "TemplateComponent", to prevent code duplication. The TemplateComponent holds the input, but it's the ParentComponent that handles the events from the input. That way, every ChildComponent, inherits ParentComponent for the logic, and it's template is a instance of TemplateComponent.

The big deal, is that when i try to listen to keyup event on the input inside TemplateComponent, the click event is being called on ChildComponent, who dont have any inputs or controls.

I've tryed to pass an event binding to template component to connect the keyup input, but it never triggers.

There's a HostListener on the ChildComponent, just to debug that the event is only being triggered there. And it's not that that's causing the event to stop there.

Is there a way to tell angular that the keydown event must be called inside the template component, or another way of linking everything toghether ?

I got a working plunker, it's pretty much self-explanatory:

https://plnkr.co/edit/e4U6DB4d47ULpLppHd4H?p=preview

But also the code:

ParentComponent:

```<code>import {Component, NgModule, VERSION} from '@angular/core'

@Component({
  selector: 'app-parent',
  template: `
    <ng-content></ng-content>
  `,
})
export class ParentComponent {

  printText = 'Not yet';

  constructor() {
  }

  inputKeyDownEnter(event: any) {
    this.printText = 'KeyDown OK!';
  }

  clearButtonClick(event: any) {
    this.printText = "Clear button click!";
  }
}
</code>```

ChildComponent:

```<code>import {Component, HostListener} from '@angular/core';
import {ParentComponent} from './parent.component';

@Component({
  selector: 'app-child',
  template: `
    <div>{{printText}}</div>
    <app-custom-template
      (inputKeyDownEnter)="inputKeyDownEnter"
      (clearButtonClick)="clearButtonClick"
    >
    </app-custom-template>
  `,
})
export class ChildComponent extends ParentComponent {

  constructor() {
    super();
  }

  @HostListener('keydown.enter', ['$event'])
  onKeyDownChild(event: any) {
    console.log('Only here :( !');
  }

}
</code>```

TemplateComponent:

```<code>import {Component, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-custom-template',
  template: `
    <input
      type="text"
      name="my_text"
      (keyup.Enter)="inputKeyDownEnter.emit($event)"
      />
    <button
      type="button"
      (click)="clearButtonClick.emit($event)">Clear</button>
  `,
})
export class CustomTemplateComponent {

  @Output()
  inputKeyDownEnter = new EventEmitter<any>();

  @Output()
  clearButtonClick = new EventEmitter<any>();

  constructor() {
  }

}
</code>```

答:
You should call method

```<code>(inputKeyDownEnter)="inputKeyDownEnter($event)"
                                      ^^^^^^^^^
</code>```

Plunker

Body:
I created a component that i wish to have multiple versions of it in my app, since i want to keep all the logic in only one place, i created a ParentComponent where all my code resides.

But angular dont inherit component annotations, so i created also a "TemplateComponent", to prevent code duplication. The TemplateComponent holds the input, but it's the ParentComponent that handles the events from the input. That way, every ChildComponent, inherits ParentComponent for the logic, and it's template is a instance of TemplateComponent.

The big deal, is that when i try to listen to keyup event on the input inside TemplateComponent, the click event is being called on ChildComponent, who dont have any inputs or controls.

I've tryed to pass an event binding to template component to connect the keyup input, but it never triggers.

There's a HostListener on the ChildComponent, just to debug that the event is only being triggered there. And it's not that that's causing the event to stop there.

Is there a way to tell angular that the keydown event must be called inside the template component, or another way of linking everything toghether ?

I got a working plunker, it's pretty much self-explanatory:

https://plnkr.co/edit/e4U6DB4d47ULpLppHd4H?p=preview

But also the code:

ParentComponent:

import {Component, NgModule, VERSION} from '@angular/core'

@Component({
  selector: 'app-parent',
  template: `
    <ng-content></ng-content>
  `,
})
export class ParentComponent {

  printText = 'Not yet';

  constructor() {
  }

  inputKeyDownEnter(event: any) {
    this.printText = 'KeyDown OK!';
  }

  clearButtonClick(event: any) {
    this.printText = "Clear button click!";
  }
}

ChildComponent:

import {Component, HostListener} from '@angular/core';
import {ParentComponent} from './parent.component';

@Component({
  selector: 'app-child',
  template: `

{{printText}}

    <app-custom-template
      (inputKeyDownEnter)="inputKeyDownEnter"
      (clearButtonClick)="clearButtonClick"
    >
    </app-custom-template>
  `,
})
export class ChildComponent extends ParentComponent {

  constructor() {
    super();
  }

  @HostListener('keydown.enter', ['$event'])
  onKeyDownChild(event: any) {
    console.log('Only here :( !');
  }

}

TemplateComponent:

import {Component, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-custom-template',
  template: `
    <input
      type="text"
      name="my_text"
      (keyup.Enter)="inputKeyDownEnter.emit($event)"
      />
    <button
      type="button"
      (click)="clearButtonClick.emit($event)">Clear</button>
  `,
})
export class CustomTemplateComponent {

  @Output()
  inputKeyDownEnter = new EventEmitter<any>();

  @Output()
  clearButtonClick = new EventEmitter<any>();

  constructor() {
  }

}

Body:
You should call method

(inputKeyDownEnter)="inputKeyDownEnter($event)"
                                      ^^^^^^^^^

Plunker


问:
Why is element always blue surrounded when showing stage
Hey guys I have "bug" if you can call it so.
When starting the program, one element is always blue.

```<code>@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("resource/Start.fxml"));

    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.setTitle("Alc Calc V1.1");
    stage.show();
}
</code>```

=>

答:
The reason that shows up as blue is it is the active element. JavaFX allows you to use CSS to style your program and if you do not put in your own it will use the default. In the default it has the fx-focus-color attribute set to adding that blue that you're referring to.

You can just get rid of the effect on all controls by changing the attribute itself in the code.

```<code>control.setStyle("-fx-focus-color: transparent;");
</code>```

If you plan on changing more than just a thing or two I would recommend making your own CSS file and using that. You can attach it with this:

```<code>scene.getStylesheets().add("your_custom_css_file.css");
</code>```

Then to set this attribute within your CSS file you would want to add this attribute:

```<code>.root { -fx-focus-color: transparent; }
</code>```

Body:
Hey guys I have "bug" if you can call it so.
When starting the program, one element is always blue.

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("resource/Start.fxml"));

    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.setTitle("Alc Calc V1.1");
    stage.show();
}

=>

Body:
The reason that shows up as blue is it is the active element. JavaFX allows you to use CSS to style your program and if you do not put in your own it will use the default. In the default it has the fx-focus-color attribute set to adding that blue that you're referring to.

You can just get rid of the effect on all controls by changing the attribute itself in the code.

control.setStyle("-fx-focus-color: transparent;");

If you plan on changing more than just a thing or two I would recommend making your own CSS file and using that. You can attach it with this:

scene.getStylesheets().add("your_custom_css_file.css");

Then to set this attribute within your CSS file you would want to add this attribute:

.root { -fx-focus-color: transparent; }


问:
Heroku Login cmd permission issue for Windows 10
I installed heroku cli.

```<code>$ heroku --version
heroku-cli/6.14.36-15f8a25 (windows-x64) node-v8.7.0
</code>```

Started cmd.exe as admin

```<code>$ heroku login (asked me for username and password)
</code>```

After I provided the username and password. I get the following error:

```<code>!    EACCES: connect EACCES 34.234.38.27:443
</code>```

I tried using gitbash to login in heroku. I get the same error message if I try same thing in git bash using the following cmd:

```<code>winpty heroku login
</code>```

I have looked everywhere I could. Most places have closed the tickets but there is no solution anywhere. I also tried deleting the heroku folder from appdata/local/ but that also didn't help. I know its permission issue. I get a better error message when I try

```<code>$ heroku update
heroku-cli: Updating plugins... done

 !    Get https://cli-assets.heroku.com/branches/v6/manifest.json: dial tcp 52.84.64.82:443: connectex: An attempt was made to access a socket in a way forbidden by its access permissions.
</code>```

I want to host a small NodeJS app for free. What are my other options because if I have to spend so much time just deploying then maybe it is not an option.

答:
maybe your problem is the firewall or the antivirus, add the exception for the address that shows you (34.234.38.27:443), and do the test. Also check your antivirus if it is not blocking you heroku cli, and always run in administrator mode

You can also do the following. Enable debugging during login. Make sure to redact your password from the output before sending it to support! Enable it by running set HEROKU_DEBUG=true; set HEROKU_DEBUG_HEADERS=1; heroku login on Windows to get more information.

Good luck with your app my friend!

Body:
I installed heroku cli.

$ heroku --version
heroku-cli/6.14.36-15f8a25 (windows-x64) node-v8.7.0

Started cmd.exe as admin

$ heroku login (asked me for username and password)

After I provided the username and password. I get the following error:

!    EACCES: connect EACCES 34.234.38.27:443

I tried using gitbash to login in heroku. I get the same error message if I try same thing in git bash using the following cmd:

winpty heroku login

I have looked everywhere I could. Most places have closed the tickets but there is no solution anywhere. I also tried deleting the heroku folder from appdata/local/ but that also didn't help. I know its permission issue. I get a better error message when I try

$ heroku update
heroku-cli: Updating plugins... done

 !    Get https://cli-assets.heroku.com/branches/v6/manifest.json: dial tcp 52.84.64.82:443: connectex: An attempt was made to access a socket in a way forbidden by its access permissions.

I want to host a small NodeJS app for free. What are my other options because if I have to spend so much time just deploying then maybe it is not an option.


问:
What is the recommended way of deserializing a Firestore document containing an array?
I'm trying to fetch a Firestore document containing an array, however, I can't get the DocumentSnapshot.toObject method to work correctly as soon as I add an array. I don't want to use a collection as the array will likely only contain 1-2 items max.

```<code>java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type com.google.android.gms.internal.zzegf to DocumentReference (found in field 'references.[0]')
</code>```

Below is my model class

```<code>data class SomeModel(
        var references : ArrayList<DocumentReference> = ArrayList(0),
        var title : String? = null,
        var acronym : String? = null,
        var number : Long? = null
){

}
</code>```

My Firestore document contains an array named references with one DocumentReference. If I remove the reference field from the model class the object deserializes just fine.

答: Updating my gradle file entry of firebase-firestore from 11.4.2 to 11.6.0 fixed the deserialization issue.</p>

Body:
I'm trying to fetch a Firestore document containing an array, however, I can't get the DocumentSnapshot.toObject method to work correctly as soon as I add an array. I don't want to use a collection as the array will likely only contain 1-2 items max.

java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type com.google.android.gms.internal.zzegf to DocumentReference (found in field 'references.[0]')

Below is my model class

data class SomeModel(
        var references : ArrayList<DocumentReference> = ArrayList(0),
        var title : String? = null,
        var acronym : String? = null,
        var number : Long? = null
){

}

My Firestore document contains an array named references with one DocumentReference. If I remove the reference field from the model class the object deserializes just fine.


问:
The most efficient way to determine the presence of repeated values in a 2D array, arranged like a table (with some starting ideas)
I am switching the tags for this question as I don't believe it is a C# .NET specific question, and more so a mathematical/algorithms one. Say I have an 2D array of ints, like below:

```<code> 0 | 1 | 2
---+---+---
 0 | 1 | 0
---+---+---
 1 | 0 | 0
</code>```

These could be stored in a different data structure if this would allow a faster solution to the problem. The problem being how to detect (and find the locations of) equal integer values stored adjacently (allowing for diagonals) (and not accounting for "wrapping around" adjacency, for example a corner piece should only need to be compared with 3 other values... that is unless there is a better solution to storing the data).

My first (and I am sure naive) approach would be a 2D array (implemented as a jagged array or just indexed like this) in which I store the integer values. I have no need for any sort property besides just whether or not values are equal (i.e. no need for >, <, etc). I could then do an N^8 (not sure if this is the correct time analysis for this situation but it was my best try)traversal of all N locations in the array, and 8 checks maximum (if not on the edge) per iteration. I think there may be a better way to do this, however. Especially as this approach is very time consuming.

One idea I had is to modify the data structure so that every item has a flag (included in each structure in the array [so not just an array of ints]) of whether it is the same as any adjacent value. This would slow down my insertion and building processes, but may (??) speed up the process of finding pairs in the table. Thanks for any help.

答:
Based on my understanding of the question (without any further constraints), the following straightforward solution should give what you need:</p>

```<code>// Pseudo-code. Did not test it.
public static bool foundSameValuesInARow(int[,] board) { // board: NxN array. We assume it's a square array.
    int N = board.getLength(0);
    for(int i=0;i<N-1;i++) {
        for(int j=0;j<N-1;j++) {
            if(board[i,j] == board[i+1,j] || board[i,j] == board[i,j+1]) {
                return true;
            }
        }
    }
    for(int k=0;k<N-1;k++) {
        if(board[k, N-1] == board[k+1,N-1] || board[N-1,k] == board[N-1,k+1]) {
            return true;
        }
    }
    return false;
}
</code>```

Body:
I am switching the tags for this question as I don't believe it is a C# .NET specific question, and more so a mathematical/algorithms one. Say I have an 2D array of ints, like below:

 0 | 1 | 2
---+---+---
 0 | 1 | 0
---+---+---
 1 | 0 | 0

These could be stored in a different data structure if this would allow a faster solution to the problem. The problem being how to detect (and find the locations of) equal integer values stored adjacently (allowing for diagonals) (and not accounting for "wrapping around" adjacency, for example a corner piece should only need to be compared with 3 other values... that is unless there is a better solution to storing the data).

My first (and I am sure naive) approach would be a 2D array (implemented as a jagged array or just indexed like this) in which I store the integer values. I have no need for any sort property besides just whether or not values are equal (i.e. no need for >, <, etc). I could then do an N^8 (not sure if this is the correct time analysis for this situation but it was my best try)traversal of all N locations in the array, and 8 checks maximum (if not on the edge) per iteration. I think there may be a better way to do this, however. Especially as this approach is very time consuming.

One idea I had is to modify the data structure so that every item has a flag (included in each structure in the array [so not just an array of ints]) of whether it is the same as any adjacent value. This would slow down my insertion and building processes, but may (??) speed up the process of finding pairs in the table. Thanks for any help.

Body:
Based on my understanding of the question (without any further constraints), the following straightforward solution should give what you need:

// Pseudo-code. Did not test it.
public static bool foundSameValuesInARow(int[,] board) { // board: NxN array. We assume it's a square array.
    int N = board.getLength(0);
    for(int i=0;i<N-1;i++) {
        for(int j=0;j<N-1;j++) {
            if(board[i,j] == board[i+1,j] || board[i,j] == board[i,j+1]) {
                return true;
            }
        }
    }
    for(int k=0;k<N-1;k++) {
        if(board[k, N-1] == board[k+1,N-1] || board[N-1,k] == board[N-1,k+1]) {
            return true;
        }
    }
    return false;
}


问:
UserInterface and user separated in Symfony Security
I have an application where the Symfony Security User model (called Account) will just contain login information (username, password). The rest of the user will be stored in another model (called User). There will be a one to many relation between Account and User and the purpose of this is to be able to have multiple Users, for different projects, but have the same login for them.

So, my problem with this is that I want to use the role system in Symfony, but I want the User model to have roles, and not the Account model. I am not really sure how this can be solved, since the UserInterface is the Account model and not the User model.

Does Symfony support this or do I have to roll my own implementation of roles for this system?

答:
You can just fetch the roles from the account model:

```<code>//Account
public function getRoles()
{
    return $this->getUser()->getRoles();
}
</code>```

Using the association you get the roles that way, but you still have the method on the Account level.

Body:
You can just fetch the roles from the account model:

//Account
public function getRoles()
{
    return $this->getUser()->getRoles();
}

Using the association you get the roles that way, but you still have the method on the Account level.


问:
web.config transformations in section
I"m trying to setup web.config transformations. Is it possible to do with sections?

How would I transform all 3 values?

```<code><section name="productinformationsettings" type="ProductInformation.Common.Configuration.ProductInformationConfigurationSection, ProductInformation.Common" />

<productinformationsettings ImageUrlBase="https://www.test.com" apikey="xxxxx" enivironment="test" />
</code>```

When does Web.Debug.Config get used? When I'm debugging?

答: this is what i needed. xdt:Transform="Replace"</p>

Title: web.config transformations in section

Body:
I"m trying to setup web.config transformations. Is it possible to do with sections?

How would I transform all 3 values?

<productinformationsettings ImageUrlBase="https://www.test.com" apikey="xxxxx" enivironment="test" />

When does Web.Debug.Config get used? When I'm debugging?