问:
Dynamically create buttons in c# by user at runtime
How to create buttons dynamically after user input in C# (Visual Studio).
There is a text-box to enter how many buttons user wants?
Then my target is to create buttons below the input field as the user wants
then how can I get id's of that buttons?</p>

```<code>private void button1_Click(object sender, EventArgs e)
{
    List<Button> buttons = new List<Button>();
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(buttons[i]);
    }
}
</code>```

答:
Here I first added an event handler to the textbox, which is called whenever the text value is changed. The value is converted to the int value and then is used in a for loop statement. You can set your button's potion to the desired value using location property. Using tag or name property you can assign a unique value to your buttons. I hope the code helps.

Look at the code below :

```<code>private void Form1_Load(object sender, EventArgs e)
{
 textBox1.TextChanged += textBox1_TextChanged;
}

void textBox1_TextChanged(object sender, EventArgs e)
{
 var txtBox = sender as TextBox;
 if (txtBox == null) return;
 var count = Convert.ToInt16(txtBox.Text);
 //
 var xPosition = 0;
 for (var i = 1; i <= count; i++)
 {
  var button = new Button
  {
   Tag = string.Format("Btn{0}", i),
   Text = string.Format("Button{0}",i),
   Location = new Point(xPosition, 0)
  };
 xPosition = xPosition + 100;
 Controls.Add(button);
}
</code>```

Body:
How to create buttons dynamically after user input in C# (Visual Studio).
There is a text-box to enter how many buttons user wants?
Then my target is to create buttons below the input field as the user wants
then how can I get id's of that buttons?

private void button1_Click(object sender, EventArgs e)
{
    List<Button> buttons = new List<Button>();
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(buttons[i]);
    }
}

Body:
Here I first added an event handler to the textbox, which is called whenever the text value is changed. The value is converted to the int value and then is used in a for loop statement. You can set your button's potion to the desired value using location property. Using tag or name property you can assign a unique value to your buttons. I hope the code helps.

Look at the code below :

private void Form1_Load(object sender, EventArgs e)
{
 textBox1.TextChanged += textBox1_TextChanged;
}

void textBox1_TextChanged(object sender, EventArgs e)
{
 var txtBox = sender as TextBox;
 if (txtBox == null) return;
 var count = Convert.ToInt16(txtBox.Text);
 //
 var xPosition = 0;
 for (var i = 1; i <= count; i++)
 {
  var button = new Button
  {
   Tag = string.Format("Btn{0}", i),
   Text = string.Format("Button{0}",i),
   Location = new Point(xPosition, 0)
  };
 xPosition = xPosition + 100;
 Controls.Add(button);
}


来源: stackexchange

问:
Ionic iOS App Error - Custom Scheme URIs are not allowed for 'WEB' client type
I am using this plugin.

https://github.com/EddyVerbruggen/cordova-plugin-googleplus

The implementation works fine for android. But google sign in on iOS opens safari webview and throws 400 invalid_request.

I am using the ios client id and reverse client id generated on google developer console.

Anyways to debug or know what the issue is?

答: The usual cause of this error is having an incorrect REVERSE_CLIENT_ID.  Double check that you have the REVERSE_CLIENT_ID from the plist file downloaded when you set up the iOS application registration on the Google developer console.  Note that if you got it wrong, changing this is difficult, as it gets copied into various locations and won't update automatically if you just try to change it in config.xml.  When I mistakenly used my Android client ID to set up the plugin, I found that as well as config.xml I also needed to change the top level package.json file, and the <appname>-Info.plist in the platforms/ios directory in order to get the correct ID used.

ContentLicense: CC BY-SA 3.0


问:
String substring error
Question:

```<code>Input:-gandhi                      output:- Gandhi
Input:-mahatma gandhi              output:- M. Gandhi
Input:-Mohndas Karamchand ganDhi   output:- M. K. Gandhi
</code>```

Answer:

```<code>public class Chef_NITIKA {

    static Scanner scan=new Scanner(System.in);

    public static void main(String[] args) {
        String name=    myString();
        System.out.println("nam is :"+name);
        mySformatter(name);

    }

    private static void mySformatter(String name) {
           int count=0;
          for(char c:name.toCharArray()){
              if(c==' '){
                  count+=1;
              }
          }
          System.out.println(count+" blank spaces");
          if(count==0){
              char ch=name.charAt(0);
              name=Character.toUpperCase(ch)+name.substring(1);
              System.out.println("nam is :"+name);
          }
          else if(count==1){
              char ch=name.charAt(0);
             name= name.replace(' ', '.');
             String subname=name.substring(name.indexOf(".")+1);
             char c=subname.charAt(0);
             subname=Character.toUpperCase(c)+subname.substring(1);
             name=Character.toUpperCase(ch)+"."+subname;
              System.out.println("nam is :"+name);
          }
          else if(count==2){
              char ch=name.charAt(0);
            // name= name.replace(' ', '.');
             String subname=name.substring(name.indexOf(" ")+1);
             System.out.println(subname);
             String subsubname=subname.substring(name.indexOf(" "));
             System.out.println(subsubname);
             char c=subname.charAt(0);
             char c1=subsubname.charAt(0);
             subname=Character.toUpperCase(c)+subname.substring(1);
             name = Character.toUpperCase(ch)+"."+Character.toUpperCase(c)+"."+Character.toUpperCase(c1)+subsubname.substring(1);
              System.out.println("nam is :"+name);
          }
    }

    private static String myString() {
       System.out.println("enter the string");
       String s=scan.nextLine();
       StringBuffer name=new StringBuffer();
     //  name.append(s);
       return s;
    }
}
</code>```

I am not getting the desired output when i type "abc cde fgh" i get the output as A.C..fgh

Is there any efficient way to solve this problem?

undesired output:-

```<code>enter the string
iam writing onStack
nam is :iam writing onStack
2 blank spaces
writing onStack
ing onStack
nam is :I.W.Ing onStack
</code>```

I want the output as I.W.OnStack

答:
```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package stack;

import java.util.Scanner;
import java.util.StringTokenizer;

/**
 *
 * @author xxz
 */
public class NAmes {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        final String name = sc.nextLine();
        System.out.println(formatedString(name));
        sc.close();
    }

    private static String formatedString(String name) {
        if(name!=null && name.length()!=0){
            final StringTokenizer tokenizer = new StringTokenizer(name, " ");
            StringBuilder result = new StringBuilder("");
              while(tokenizer.hasMoreTokens()){
                StringBuilder currentToken =new StringBuilder(tokenizer.nextToken());

                if(!tokenizer.hasMoreTokens()){
                    result.append(currentToken.toString().toUpperCase());
                } else{
                    result.append(currentToken.toString().toUpperCase().charAt(0)+". ");
                }
            }
            return result.toString();
        }
        return "";
    }
}
</code>```

Title: String substring error

Body:
Question:

Input:-gandhi                      output:- Gandhi
Input:-mahatma gandhi              output:- M. Gandhi
Input:-Mohndas Karamchand ganDhi   output:- M. K. Gandhi

Answer:

public class Chef_NITIKA {

    static Scanner scan=new Scanner(System.in);

    public static void main(String[] args) {
        String name=    myString();
        System.out.println("nam is :"+name);
        mySformatter(name);

    }

    private static void mySformatter(String name) {
           int count=0;
          for(char c:name.toCharArray()){
              if(c==' '){
                  count+=1;
              }
          }
          System.out.println(count+" blank spaces");
          if(count==0){
              char ch=name.charAt(0);
              name=Character.toUpperCase(ch)+name.substring(1);
              System.out.println("nam is :"+name);
          }
          else if(count==1){
              char ch=name.charAt(0);
             name= name.replace(' ', '.');
             String subname=name.substring(name.indexOf(".")+1);
             char c=subname.charAt(0);
             subname=Character.toUpperCase(c)+subname.substring(1);
             name=Character.toUpperCase(ch)+"."+subname;
              System.out.println("nam is :"+name);
          }
          else if(count==2){
              char ch=name.charAt(0);
            // name= name.replace(' ', '.');
             String subname=name.substring(name.indexOf(" ")+1);
             System.out.println(subname);
             String subsubname=subname.substring(name.indexOf(" "));
             System.out.println(subsubname);
             char c=subname.charAt(0);
             char c1=subsubname.charAt(0);
             subname=Character.toUpperCase(c)+subname.substring(1);
             name = Character.toUpperCase(ch)+"."+Character.toUpperCase(c)+"."+Character.toUpperCase(c1)+subsubname.substring(1);
              System.out.println("nam is :"+name);
          }
    }

    private static String myString() {
       System.out.println("enter the string");
       String s=scan.nextLine();
       StringBuffer name=new StringBuffer();
     //  name.append(s);
       return s;
    }
}

I am not getting the desired output when i type "abc cde fgh" i get the output as A.C..fgh

Is there any efficient way to solve this problem?

undesired output:-

enter the string
iam writing onStack
nam is :iam writing onStack
2 blank spaces
writing onStack
ing onStack
nam is :I.W.Ing onStack

I want the output as I.W.OnStack


问:
How to connect AspNetUsers with another table?
Hi there StackOverflow people.
I currently have a table with clients:

```<code> public class Cliente
    {
        public Cliente()
        {
        }

        [Key]
        public int IDCliente { get; set; }

        [Required]
        public string Nome { get; set; }

        [Required]
        public string Morada { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        public string UserName { get; set; }
    }
}
</code>```

And I have the AspNetUsers table...

Also, this is my client table data.

I have that UserName on the table Cliente, and I want to connect it to the aspnetUsers, so that when I create a user, that it will automatically add information between both automatically.
How can that be done?

Thanks in advance.

答: You can customize your own UserManager which is inheriting base UserManager , then add Cliente in override CreateUser function implementation.</p>

Body:
Hi there StackOverflow people.
I currently have a table with clients:

 public class Cliente
    {
        public Cliente()
        {
        }

        [Key]
        public int IDCliente { get; set; }

        [Required]
        public string Nome { get; set; }

        [Required]
        public string Morada { get; set; }

        [Required]
        public string Email { get; set; }

        [Required]
        public string UserName { get; set; }
    }
}

And I have the AspNetUsers table...

Also, this is my client table data.

I have that UserName on the table Cliente, and I want to connect it to the aspnetUsers, so that when I create a user, that it will automatically add information between both automatically.
How can that be done?

Thanks in advance.


问:
Design patterns to avoid
A lot of people seem to agree, that the Singleton pattern has a number of drawbacks and some even suggest avoiding the pattern entirely. There's an excellent discussion here. Please direct any comments about the Singleton pattern to that question.

My question: Are there other design patterns, that should be avoided or used with great care?

答: I hope I won't get beaten too much for this. Christer Ericsson wrote two articles (one, two) on the topic of design patterns in his real time collision detection blog. His tone is rather harsh, and perhaps a bit provocative, but the man knows his stuff, so I wouldn't dismiss it as ravings of a lunatic.</p>

OwnerDisplayName: Brian Rasmussen

ContentLicense: CC BY-SA 2.5

Title: Design patterns to avoid

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: roe

LastEditorDisplayName: roe


问:
Ways to make it easier to work with shared pointers in C++
I am busy designing a new C++ application.  In this application I want to minimize potential errors with pointers, and since the application should be plain C++ (no .Net or other fancy things), I am investigating shared pointers and I am considering using shared pointers everywhere (instead of normal pointers).

I worked out some tricks to make it easier to work with shared pointers, e.g.: using a typedef within the class, like this:

```<code>class X
   {
   public:
      ...
      typedef std::shared_ptr<X> Ptr;
   };
</code>```

That way you can easily write X::Ptr, which is easier to write than "std::shared_ptr" everywhere.

I also noticed some disadvantages to shared pointers:

Everywhere I use a shared pointer I need to include <memory>

I can't use forward declaration anymore if I just want to use the pointer

Are there any other tricks to make shared pointers easier to work with?

答:
It is quite common in code to have a "convention" which you then follow, and as long as it is done consistently across your team etc. people will be able to understand it.

It is far better to declare your shared pointer typedefs in a "forward" file. Something like this:

```<code>namespace boost { template< typename T > class shared_ptr; }

namespace MyStuff
{
   class Foo;
   class Bar;
   class Baz;

   typedef boost::shared_ptr<Foo> FooPtr;
   typedef boost::shared_ptr<Bar> BarPtr;
   typedef boost::shared_ptr<Baz> BazPtr;

}
</code>```

You will sometimes want to use other pointers than shared_ptr but your convention would then be to use a different notation with XPtr meaning shared_ptr.

Of course you might use a different notation.

I think we use FooWeakPtr to mean weak_ptr<Foo>
FooConstPtr to mean shared_ptr<const Foo>

for example.

Should be in your coding standards document.

Body:
I am busy designing a new C++ application.  In this application I want to minimize potential errors with pointers, and since the application should be plain C++ (no .Net or other fancy things), I am investigating shared pointers and I am considering using shared pointers everywhere (instead of normal pointers).

I worked out some tricks to make it easier to work with shared pointers, e.g.: using a typedef within the class, like this:

class X
   {
   public:
      ...
      typedef std::shared_ptr<X> Ptr;
   };

That way you can easily write X::Ptr, which is easier to write than "std::shared_ptr" everywhere.

I also noticed some disadvantages to shared pointers:

Everywhere I use a shared pointer I need to include <memory>

I can't use forward declaration anymore if I just want to use the pointer

Are there any other tricks to make shared pointers easier to work with?

Body:
It is quite common in code to have a "convention" which you then follow, and as long as it is done consistently across your team etc. people will be able to understand it.

It is far better to declare your shared pointer typedefs in a "forward" file. Something like this:

namespace boost { template< typename T > class shared_ptr; }

namespace MyStuff
{
   class Foo;
   class Bar;
   class Baz;

   typedef boost::shared_ptr<Foo> FooPtr;
   typedef boost::shared_ptr<Bar> BarPtr;
   typedef boost::shared_ptr<Baz> BazPtr;

}

You will sometimes want to use other pointers than shared_ptr but your convention would then be to use a different notation with XPtr meaning shared_ptr.

Of course you might use a different notation.

I think we use FooWeakPtr to mean weak_ptr<Foo>
FooConstPtr to mean shared_ptr<const Foo>

for example.

Should be in your coding standards document.


问:
Finding even permutations using Haskell
I tried to figure out how to find the even permutations out of the set {permutations [1..n]}. I have asked this question before on a different forum, and got an answer that worked namely the code was:

```<code>Import Data.List

-- number of inversions in a permutation
inversions as = sum $ map go (tails as)
where go [] = 0
go (x:xs) = length $ filter (<x) xs

evenPerm as = even (inversions as)

alternating n = [ p | p <- permutations [1..n], evenPerm p ]
</code>```

I understand the last line in the code: alternating n =[p | p <- permutations [1..n], evenPerm p]. That is, the p of the set {permutations [1..n]} such that they are even permutations. The function evenPerm as I think I understand too. It is just the even elements of the set {inversion as}. The thing I truly don't understand how it is working is the inversion as function. Naively, how I would imagine things to work is take the element of the set {permutations [1..n]} [1..n] i.e. (1,2,3,..,n) and compare every other element in the set to this one and count how many moves you have to make to get it in that form, but how you go about doing that in Haskell?

答:
To take a bird’s-eye view, what we want to do is count how many swaps we would need to sort the list in place.  (Equivalently, in the language of group theory, to decompose the permutation into transpositions.) Which sorting algorithm we use to count swaps doesn’t matter for correctness: an even permutation will generate an even number of swaps and an odd permutation an odd number of swaps regardless of how we sort.

Let’s look first at:

```<code>go [] = 0
go (x:xs) = length $ filter (<x) xs
</code>```

The indentation in that sample is confusing, but go is a nested local function of inversions.  It appears inside a where clause.  The go function counts the number of elements in a list that need to be moved before the first element in the list, that is, the elements smaller than the head of the list.  It does this by filtering the tail and taking its length.  An empty list has no head, so there’s another pattern matching it for completeness.  (Otherwise, the compiler would complain that some inputs do not match any pattern.)

```<code>inversions as = sum $ map go (tails as)
</code>```

The tails function is from the Data.List library that we imported.  It generates a list of shorter and shorter final segments: tails [1,2,3] = [[1,2,3] [2,3], [3]].  We then map go onto each final segment in the list, giving us a list of the inversion count for each final segment.  Finally, we sum the counts.

You will often see things like this written as a composition of functions: inversions = sum . map go . tails.  That just applies each function from right to left: tails, then map go on the result, then sum on the result of that.

For example.

```<code>list == [4,3,2,1]
tails list == [[4,3,2,1], [3,2,1], [2,1], [1]]
map go (tails list) == [3,2,1,0]
sum $ map go (tails list) == 6
</code>```

This counts the number of swaps for a bubble sort.  We could theoretically perform the following swaps to sort the list:

```<code>[4,3,2,1] -- 0 swaps needed to sort [1]
[4,3,1,2] -- 1 swap to sort final sequence [2,1]
[4,1,3,2] -- Which equals go [2,1]
[4,1,2,3] -- 2 additional swaps to sort [3,2,1]
[1,4,2,3] -- Which equals go [3,2,1]
[1,2,4,3]
[1,2,3,4] -- 3 additional swaps to sort [4,3,2,1]
          -- Which equals go [4,3,2,1]
</code>```

This is far from a minimal number of swaps, but we just need some count for some sorting algorithm, and that one is simple.

The next step is

```<code>evenPerm as = even (inversions as)
</code>```

This is a predicate that simply tells us whether the result of the computation we just looked at was even or odd.  It could also have been defined as even . inversions, or even . sum . map go . tails.

```<code>alternating n = [ p | p <- permutations [1..n], evenPerm p ]
</code>```

This is a list comprehension.  It calls another function from Data.List, permutations, to generate a list of all permutations.  It then adds a permutation p to our output list if and only if evenPerm p is true.

This could also have been written as evenPerms = filter evenPerm . permutations, which is shorter and works with more types, with alternating n = evenPerms [1..n].  That is, given an input list, generate its permutations and apply a filter to them.  (This version of alternating only works on numbers, because it uses [1..n], but the algorithm could work just as well on anything with a less-than operator.)

Cleaned-up Version

```<code>import Data.List

{- In the type signatures below, capitalized type names are specific types.
 - Lowercase type parameters are generic.  Ord, to the left of the => sign,
 - is the type class of all types with an ordering relation.  So, the argu-
 - ment is a list of some type a that can be ordered, and the return value
 - is a Bool, True or False.
 -}
isEvenPerm :: Ord a => [a] -> Bool
isEvenPerm = even . sum . map go . tails
  where go []     = 0
        go (x:xs) = length . filter (<x) $ xs

evenPerms :: Ord a => [a] -> [[a]]
evenPerms = filter isEvenPerm . permutations

{- This only makes sense for positive whole numbers. -}
alternating :: Integral a => a -> [[a]]
alternating n | n >= 1    = evenPerms [1..n]
              | otherwise = error "Argument must be positive."
</code>```

You can try evenPerms "abcd" and alternating 4.

Title: Finding even permutations using Haskell

Body:
I tried to figure out how to find the even permutations out of the set {permutations [1..n]}. I have asked this question before on a different forum, and got an answer that worked namely the code was:

Import Data.List

-- number of inversions in a permutation
inversions as = sum $ map go (tails as)
where go [] = 0
go (x:xs) = length $ filter (<x) xs

evenPerm as = even (inversions as)

alternating n = [ p | p <- permutations [1..n], evenPerm p ]

I understand the last line in the code: alternating n =[p | p <- permutations [1..n], evenPerm p]. That is, the p of the set {permutations [1..n]} such that they are even permutations. The function evenPerm as I think I understand too. It is just the even elements of the set {inversion as}. The thing I truly don't understand how it is working is the inversion as function. Naively, how I would imagine things to work is take the element of the set {permutations [1..n]} [1..n] i.e. (1,2,3,..,n) and compare every other element in the set to this one and count how many moves you have to make to get it in that form, but how you go about doing that in Haskell?

Body:
To take a bird’s-eye view, what we want to do is count how many swaps we would need to sort the list in place.  (Equivalently, in the language of group theory, to decompose the permutation into transpositions.) Which sorting algorithm we use to count swaps doesn’t matter for correctness: an even permutation will generate an even number of swaps and an odd permutation an odd number of swaps regardless of how we sort.

Let’s look first at:

go [] = 0
go (x:xs) = length $ filter (<x) xs

The indentation in that sample is confusing, but go is a nested local function of inversions.  It appears inside a where clause.  The go function counts the number of elements in a list that need to be moved before the first element in the list, that is, the elements smaller than the head of the list.  It does this by filtering the tail and taking its length.  An empty list has no head, so there’s another pattern matching it for completeness.  (Otherwise, the compiler would complain that some inputs do not match any pattern.)

inversions as = sum $ map go (tails as)

The tails function is from the Data.List library that we imported.  It generates a list of shorter and shorter final segments: tails [1,2,3] = [[1,2,3] [2,3], [3]].  We then map go onto each final segment in the list, giving us a list of the inversion count for each final segment.  Finally, we sum the counts.

You will often see things like this written as a composition of functions: inversions = sum . map go . tails.  That just applies each function from right to left: tails, then map go on the result, then sum on the result of that.

For example.

list == [4,3,2,1]
tails list == [[4,3,2,1], [3,2,1], [2,1], [1]]
map go (tails list) == [3,2,1,0]
sum $ map go (tails list) == 6

This counts the number of swaps for a bubble sort.  We could theoretically perform the following swaps to sort the list:

[4,3,2,1] -- 0 swaps needed to sort [1]
[4,3,1,2] -- 1 swap to sort final sequence [2,1]
[4,1,3,2] -- Which equals go [2,1]
[4,1,2,3] -- 2 additional swaps to sort [3,2,1]
[1,4,2,3] -- Which equals go [3,2,1]
[1,2,4,3]
[1,2,3,4] -- 3 additional swaps to sort [4,3,2,1]
          -- Which equals go [4,3,2,1]

This is far from a minimal number of swaps, but we just need some count for some sorting algorithm, and that one is simple.

The next step is

evenPerm as = even (inversions as)

This is a predicate that simply tells us whether the result of the computation we just looked at was even or odd.  It could also have been defined as even . inversions, or even . sum . map go . tails.

alternating n = [ p | p <- permutations [1..n], evenPerm p ]

This is a list comprehension.  It calls another function from Data.List, permutations, to generate a list of all permutations.  It then adds a permutation p to our output list if and only if evenPerm p is true.

This could also have been written as evenPerms = filter evenPerm . permutations, which is shorter and works with more types, with alternating n = evenPerms [1..n].  That is, given an input list, generate its permutations and apply a filter to them.  (This version of alternating only works on numbers, because it uses [1..n], but the algorithm could work just as well on anything with a less-than operator.)

Cleaned-up Version

import Data.List

{- In the type signatures below, capitalized type names are specific types.
 - Lowercase type parameters are generic.  Ord, to the left of the => sign,
 - is the type class of all types with an ordering relation.  So, the argu-
 - ment is a list of some type a that can be ordered, and the return value
 - is a Bool, True or False.
 -}
isEvenPerm :: Ord a => [a] -> Bool
isEvenPerm = even . sum . map go . tails
  where go []     = 0
        go (x:xs) = length . filter (<x) $ xs

evenPerms :: Ord a => [a] -> [[a]]
evenPerms = filter isEvenPerm . permutations

{- This only makes sense for positive whole numbers. -}
alternating :: Integral a => a -> [[a]]
alternating n | n >= 1    = evenPerms [1..n]
              | otherwise = error "Argument must be positive."

You can try evenPerms "abcd" and alternating 4.


问:
Angular 4 Refresh section of page only
Hi community I have a Plunker where I have implemented this flow:

Updated Plunker: I solved but header component gets called each time and I have to put my header component in each html is there a better way to do it?

Login

Show list of countries (User info on top)

Click on one of the  countries and show details about it (Problem is here)

Go back to list

I need to refresh only the section of the countries list, but in my plunker you can see the whole page is refreshing I want to keep the user info on top (static).

I have little experience.
Thanks a lot!

```<code>@Component({
selector : 'login',
template: `
<input type="text" value="james">
<input type="password" value="123">
<button (click)="logIn()">Login</button>
`
})
class LoginComponent {
constructor(private route: ActivatedRoute,
            private router: Router) { }

    logIn () {
        //LOGIN LOGIC
        this.router.navigate(['/base']);
    }
}
</code>```

答:
first create common header component and render your components using routerLink and router.navigate

angular doc have good example
https://angular.io/guide/router

plunker https://plnkr.co/edit/ApjJkNwS6hfS56DjL7vt?p=preview

Title: Angular 4 Refresh section of page only

Body:
Hi community I have a Plunker where I have implemented this flow:

Updated Plunker: I solved but header component gets called each time and I have to put my header component in each html is there a better way to do it?

Login

Show list of countries (User info on top)

Click on one of the  countries and show details about it (Problem is here)

Go back to list

I need to refresh only the section of the countries list, but in my plunker you can see the whole page is refreshing I want to keep the user info on top (static).

I have little experience.
Thanks a lot!

@Component({
selector : 'login',
template: `
<input type="text" value="james">
<input type="password" value="123">
<button (click)="logIn()">Login</button>
`
})
class LoginComponent {
constructor(private route: ActivatedRoute,
            private router: Router) { }

    logIn () {
        //LOGIN LOGIC
        this.router.navigate(['/base']);
    }
}


问:
Store ProtoBuf object in SharedPreferences
I am meaning to store a ProtoBuf object in SharedPreferences. Protocol Buffers only allow parsing from ByteString or Byte Array. But SharedPreferences support neither. I was wondering if there was a way to do it without having to create another serializable model and mapping to it first.

I Tried this way, but i get InvalidProtocolBufferException:

```<code>public static void setProtoData(ProtoData data) {
    Prefs.putString(Constants.SHARED_PREF_PROTO_DATA, String.valueOf(data.toByteString()));
}

public static ProtoData getProtoData() {
    String str = Prefs.getString(Constants.SHARED_PREF_PROTO_DATA, null);
    ProtoData data = null;

    try {
        data = ProtoData.parseFrom(ByteString.copyFromUtf8(str));
    } catch (InvalidProtocolBufferException e) {
        e.printStackTrace();
    }

    return data;
}
</code>```

答:
You can save a byte array in SharedPreferences by using android.util.Base64.

For saving:

```<code>String saveThis = Base64.encodeToString(array, Base64.DEFAULT);
</code>```

For loading:

```<code>byte[] array = Base64.decode(stringFromSharedPrefs, Base64.DEFAULT);
</code>```

Body:
I am meaning to store a ProtoBuf object in SharedPreferences. Protocol Buffers only allow parsing from ByteString or Byte Array. But SharedPreferences support neither. I was wondering if there was a way to do it without having to create another serializable model and mapping to it first.

I Tried this way, but i get InvalidProtocolBufferException:

public static void setProtoData(ProtoData data) {
    Prefs.putString(Constants.SHARED_PREF_PROTO_DATA, String.valueOf(data.toByteString()));
}

public static ProtoData getProtoData() {
    String str = Prefs.getString(Constants.SHARED_PREF_PROTO_DATA, null);
    ProtoData data = null;

    try {
        data = ProtoData.parseFrom(ByteString.copyFromUtf8(str));
    } catch (InvalidProtocolBufferException e) {
        e.printStackTrace();
    }

    return data;
}

Body:
You can save a byte array in SharedPreferences by using android.util.Base64.

For saving:

String saveThis = Base64.encodeToString(array, Base64.DEFAULT);

For loading:

byte[] array = Base64.decode(stringFromSharedPrefs, Base64.DEFAULT);


问:
How to prevent more than one click on an Anchor tag button
I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .

I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.

When the button is clicked more than once it takes me to an empty page or an error page.

I want to prevent more than one click on the button.

I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that.
Any other way?

My JS code:

```<code>$('.cancel-btn').on('click',function(evt){
            //evt.preventDefault();
           //My Code

        });
</code>```

答:
Here you go with one more way to do it using pointer-events as none
https://jsfiddle.net/w2wnuyv6/1/</p>

```<code>$('a[value="cancel"]').click(function(){
    $(this).css({
        'pointer-events': 'none'
    });
});
</code>```

Body:
I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .

I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.

When the button is clicked more than once it takes me to an empty page or an error page.

I want to prevent more than one click on the button.

I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that.
Any other way?

My JS code:

$('.cancel-btn').on('click',function(evt){
            //evt.preventDefault();
           //My Code

        });

Body:
Here you go with one more way to do it using pointer-events as none
https://jsfiddle.net/w2wnuyv6/1/

$('a[value="cancel"]').click(function(){
    $(this).css({
        'pointer-events': 'none'
    });
});


问:
Ghostly outline around image after resize
I'm working on a website that will sell hand made jewelry and I'm finishing the image editor, but it's not behaving quite right.

Basically, the user uploads an image which will be saved as a source and then it will be resized to fit the user's screen and saved as a temp. The user will then go to a screen that will allow them to crop the image and then save it to it's final versions.

All of that works fine, except, the final versions have 3 bugs. First is some black horizontal line on the very bottom of the image. Second is an outline of sorts that follows the edges. I thought it was because I was reducing the quality, but even at 100% it still shows up... And lastly, I've noticed that the cropped image is always a couple of pixels lower than what I'm specifying...

Anyway, I'm hoping someone whose got experience in editing images with C# can maybe take a look at the code and see where I might be going off the right path.

Oh, by the way, this in an ASP.NET MVC application.

Here's the code:

<s>

```<code>public class ImageProvider {
    private readonly ProductProvider ProductProvider = null;

    private readonly EncoderParameters HighQualityEncoder = new EncoderParameters();
    private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single(
        c => (c.MimeType == "image/jpeg"));

    private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products");
    private readonly short[][] Dimensions = new short[3][] {
        new short[2] { 640, 480 },
        new short[2] { 240, 0 },
        new short[2] { 80, 60 }
    }

    public ImageProvider(ProductProvider ProductProvider) {
        this.ProductProvider = ProductProvider;

        HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
    }

    public void Crop(string FileName, Image Image, Crop Crop) {
        using (Bitmap Source = new Bitmap(Image)) {
            using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
                using (Graphics Graphics = Graphics.FromImage(Target)) {
                    Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Graphics.SmoothingMode = SmoothingMode.HighQuality;
                    Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Graphics.CompositingQuality = CompositingQuality.HighQuality;

                    Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel);
                }

                Target.Save(FileName, JpegCodecInfo, HighQualityEncoder);
            }
        }
    }

    public void CropAndResize(Product Product, Crop Crop) {
        using (Image Source = Image.FromFile(String.Format("{0}/{1}.source", Path, Product.ProductId))) {
            using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) {
                float Percent = ((float)Source.Width / (float)Temp.Width);

                short Width = (short)(Temp.Width * Percent);
                short Height = (short)(Temp.Height * Percent);

                Crop.Height = (short)(Crop.Height * Percent);
                Crop.Left = (short)(Crop.Left * Percent);
                Crop.Top = (short)(Crop.Top * Percent);
                Crop.Width = (short)(Crop.Width * Percent);

                Img Img = new Img();

                this.ProductProvider.AddImageAndSave(Product, Img);

                this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Source, Crop);

                using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) {
                    this.Resize(this.Dimensions[0], String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                    this.Resize(this.Dimensions[1], String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                    this.Resize(this.Dimensions[2], String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                }
            }
        }

        this.Purge(Product);
    }

    public void QueueFor( Product Product, HttpPostedFileBase PostedFile) {
        using (Image Image = Image.FromStream(PostedFile.InputStream)) {
            this.Resize(new short[2] {
                1152,
                0
            }, String.Format("{0}/{1}.temp", Path, Product.ProductId), Image, HighQualityEncoder);
        }

        PostedFile.SaveAs(String.Format("{0}/{1}.source", Path, Product.ProductId));
    }

    private void Purge(Product Product) {
        string Source = String.Format("{0}/{1}.source", Path, Product.ProductId);
        string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId);

        if (File.Exists(Source)) {
            File.Delete(Source);
        }
        if (File.Exists(Temp)) {
            File.Delete(Temp);
        }

        foreach (Img Img in Product.Imgs) {
            string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId);

            if (File.Exists(Cropped)) {
                File.Delete(Cropped);
            }
        }
    }

    public void Resize( short[] Dimensions, string FileName, Image Image, EncoderParameters EncoderParameters) {
        if (Dimensions[1] == 0) {
            Dimensions[1] = (short)(Image.Height / ((float)Image.Width / (float)Dimensions[0]));
        }

        using (Bitmap Bitmap = new Bitmap(Dimensions[0], Dimensions[1])) {
            using (Graphics Graphics = Graphics.FromImage(Bitmap)) {
                Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Graphics.SmoothingMode = SmoothingMode.HighQuality;
                Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                Graphics.CompositingQuality = CompositingQuality.HighQuality;

                Graphics.DrawImage(Image, 0, 0, Dimensions[0], Dimensions[1]);
            };

            Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters);
        }
    }
}
</code>```

Here's one of the images this produces:

</s>

UPDATE

So, I sat down and read through MSDN for like 2 hours after I posted, verified the code I had. As far as I can tell, I'm using the highest possible quality settings when performing the manipulation.

Either way, I ended up cleaning up and streamlining the code a bit. I contemplated the need for the source file and decided to remove it because it was requiring me to do additional work to figure out the cropping dimensions that are based on the temp file. So, it's gone.

Also, somewhere along the streamlining, the black line disappeared, so I can only assume that the aspect ratio issues should have been corrected as @StefanE stated.

Also, as @VinayC said, the re-sizer was generating a value of 479 for the height (which I still don't get how, but whatever...), but that seems to have been corrected when I switched to using the System.Drawing.Size and System.Drawing.Rectangle classes all the way through instead of using my own classes which essentially do the same thing.

So, here's the updated code. The remaining <s>two bugs</s> bug still stand, so I have a "ghosting" outline all the way around the image (see second attachment) which I can narrow down to the resizing because it shows up in the first re-size where no cropping has occurred. <s>And the second bug is that the cropped versions are always positioned lower on the y axis than what I pass in as the cropper. I'd estimate it's a good 5%-8% lower than what I tell it, so not sure about that one (the positions shouldn't be changing... unless I'm passing in a bad number from jQuery, gotta check on that...).</s>

(My second bug ended up me sending bad values to begin with, the cropping div was getting its relative position based on the master content div, not the image container div. All fixed now.)

```<code>using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace Website.Models.Providers {
    public class ImageProvider {
        private readonly ProductProvider ProductProvider = null;

        private readonly EncoderParameters DefaultQualityEncoder = new EncoderParameters();
        private readonly EncoderParameters HighQualityEncoder = new EncoderParameters();
        private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single(
            c =>
                (c.MimeType == "image/jpeg"));
        private readonly Size[] Sizes = new Size[3] {
            new Size(640, 0),
            new Size(240, 0),
            new Size(80, 0)
        };

        private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products");

        public ImageProvider(
            ProductProvider ProductProvider) {
            this.ProductProvider = ProductProvider;

            this.DefaultQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
            this.HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
        }

        public void Crop(
            string FileName,
            Image Image,
            Crop Crop) {
            using (Bitmap Source = new Bitmap(Image)) {
                using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
                    using (Graphics Graphics = Graphics.FromImage(Target)) {
                        Graphics.CompositingMode = CompositingMode.SourceCopy;
                        Graphics.CompositingQuality = CompositingQuality.HighQuality;
                        Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        Graphics.SmoothingMode = SmoothingMode.HighQuality;

                        Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel);
                    };

                    Target.Save(FileName, JpegCodecInfo, HighQualityEncoder);
                };
            };
        }

        public void CropAndResize(
            Product Product,
            Crop Crop) {
            using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) {
                Img Img = new Img();

                this.ProductProvider.AddImageAndSave(Product, Img);

                this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Temp, Crop);

                using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) {
                    this.Resize(String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), this.Sizes[0], Cropped, HighQualityEncoder);
                    this.Resize(String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), this.Sizes[1], Cropped, HighQualityEncoder);
                    this.Resize(String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), this.Sizes[2], Cropped, HighQualityEncoder);
                };
            };

            this.Purge(Product);
        }

        public void QueueFor(
            Product Product,
            Size Size,
            HttpPostedFileBase PostedFile) {
            using (Image Image = Image.FromStream(PostedFile.InputStream)) {
                this.Resize(String.Format("{0}/{1}.temp", Path, Product.ProductId), Size, Image, HighQualityEncoder);
            };
        }

        private void Purge(
            Product Product) {
            string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId);

            if (File.Exists(Temp)) {
                File.Delete(Temp);
            };

            foreach (Img Img in Product.Imgs) {
                string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId);

                if (File.Exists(Cropped)) {
                    File.Delete(Cropped);
                };
            };
        }

        public void Resize(
            string FileName,
            Size Size,
            Image Image,
            EncoderParameters EncoderParameters) {
            if (Size.Height == 0) {
                Size.Height = (int)(Image.Height / ((float)Image.Width / (float)Size.Width));
            };

            using (Bitmap Bitmap = new Bitmap(Size.Width, Size.Height)) {
                using (Graphics Graphics = Graphics.FromImage(Bitmap)) {
                    Graphics.CompositingMode = CompositingMode.SourceCopy;
                    Graphics.CompositingQuality = CompositingQuality.HighQuality;
                    Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Graphics.SmoothingMode = SmoothingMode.HighQuality;

                    Graphics.DrawImage(Image, new Rectangle(0, 0, Size.Width, Size.Height));
                };

                Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters);
            };
        }
    }
}
</code>```

This image shows the "ghosting" outline pointed to by red arrows.

答:
Regarding the black lines in the bottom is because you don't handle the Aspect Ratio.

```<code>double aspectRatio = imageWidth/imageHeight;
double boxRatio = maxWidth/maxHeight;
double scaleFactor = 0;
if (boxRatio > aspectRatio)
 //Use height, since that is the most restrictive dimension of box.
 scaleFactor = maxHeight / imageHeight;
else
 scaleFactor = maxWidth / imageWidth;

double newWidth = imageWidth * scaleFactor;
double newHeight = imageHeight * scaleFactor;
</code>```

Source: http://nathanaeljones.com/163/20-image-resizing-pitfalls/

Body:
I'm working on a website that will sell hand made jewelry and I'm finishing the image editor, but it's not behaving quite right.

Basically, the user uploads an image which will be saved as a source and then it will be resized to fit the user's screen and saved as a temp. The user will then go to a screen that will allow them to crop the image and then save it to it's final versions.

All of that works fine, except, the final versions have 3 bugs. First is some black horizontal line on the very bottom of the image. Second is an outline of sorts that follows the edges. I thought it was because I was reducing the quality, but even at 100% it still shows up... And lastly, I've noticed that the cropped image is always a couple of pixels lower than what I'm specifying...

Anyway, I'm hoping someone whose got experience in editing images with C# can maybe take a look at the code and see where I might be going off the right path.

Oh, by the way, this in an ASP.NET MVC application.

Here's the code:

<s>

public class ImageProvider {
    private readonly ProductProvider ProductProvider = null;

    private readonly EncoderParameters HighQualityEncoder = new EncoderParameters();
    private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single(
        c => (c.MimeType == "image/jpeg"));

    private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products");
    private readonly short[][] Dimensions = new short[3][] {
        new short[2] { 640, 480 },
        new short[2] { 240, 0 },
        new short[2] { 80, 60 }
    }

    public ImageProvider(ProductProvider ProductProvider) {
        this.ProductProvider = ProductProvider;

        HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
    }

    public void Crop(string FileName, Image Image, Crop Crop) {
        using (Bitmap Source = new Bitmap(Image)) {
            using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
                using (Graphics Graphics = Graphics.FromImage(Target)) {
                    Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Graphics.SmoothingMode = SmoothingMode.HighQuality;
                    Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Graphics.CompositingQuality = CompositingQuality.HighQuality;

                    Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel);
                }

                Target.Save(FileName, JpegCodecInfo, HighQualityEncoder);
            }
        }
    }

    public void CropAndResize(Product Product, Crop Crop) {
        using (Image Source = Image.FromFile(String.Format("{0}/{1}.source", Path, Product.ProductId))) {
            using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) {
                float Percent = ((float)Source.Width / (float)Temp.Width);

                short Width = (short)(Temp.Width * Percent);
                short Height = (short)(Temp.Height * Percent);

                Crop.Height = (short)(Crop.Height * Percent);
                Crop.Left = (short)(Crop.Left * Percent);
                Crop.Top = (short)(Crop.Top * Percent);
                Crop.Width = (short)(Crop.Width * Percent);

                Img Img = new Img();

                this.ProductProvider.AddImageAndSave(Product, Img);

                this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Source, Crop);

                using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) {
                    this.Resize(this.Dimensions[0], String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                    this.Resize(this.Dimensions[1], String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                    this.Resize(this.Dimensions[2], String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                }
            }
        }

        this.Purge(Product);
    }

    public void QueueFor( Product Product, HttpPostedFileBase PostedFile) {
        using (Image Image = Image.FromStream(PostedFile.InputStream)) {
            this.Resize(new short[2] {
                1152,
                0
            }, String.Format("{0}/{1}.temp", Path, Product.ProductId), Image, HighQualityEncoder);
        }

        PostedFile.SaveAs(String.Format("{0}/{1}.source", Path, Product.ProductId));
    }

    private void Purge(Product Product) {
        string Source = String.Format("{0}/{1}.source", Path, Product.ProductId);
        string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId);

        if (File.Exists(Source)) {
            File.Delete(Source);
        }
        if (File.Exists(Temp)) {
            File.Delete(Temp);
        }

        foreach (Img Img in Product.Imgs) {
            string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId);

            if (File.Exists(Cropped)) {
                File.Delete(Cropped);
            }
        }
    }

    public void Resize( short[] Dimensions, string FileName, Image Image, EncoderParameters EncoderParameters) {
        if (Dimensions[1] == 0) {
            Dimensions[1] = (short)(Image.Height / ((float)Image.Width / (float)Dimensions[0]));
        }

        using (Bitmap Bitmap = new Bitmap(Dimensions[0], Dimensions[1])) {
            using (Graphics Graphics = Graphics.FromImage(Bitmap)) {
                Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Graphics.SmoothingMode = SmoothingMode.HighQuality;
                Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                Graphics.CompositingQuality = CompositingQuality.HighQuality;

                Graphics.DrawImage(Image, 0, 0, Dimensions[0], Dimensions[1]);
            };

            Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters);
        }
    }
}

Here's one of the images this produces:

</s>

UPDATE

So, I sat down and read through MSDN for like 2 hours after I posted, verified the code I had. As far as I can tell, I'm using the highest possible quality settings when performing the manipulation.

Either way, I ended up cleaning up and streamlining the code a bit. I contemplated the need for the source file and decided to remove it because it was requiring me to do additional work to figure out the cropping dimensions that are based on the temp file. So, it's gone.

Also, somewhere along the streamlining, the black line disappeared, so I can only assume that the aspect ratio issues should have been corrected as @StefanE stated.

Also, as @VinayC said, the re-sizer was generating a value of 479 for the height (which I still don't get how, but whatever...), but that seems to have been corrected when I switched to using the System.Drawing.Size and System.Drawing.Rectangle classes all the way through instead of using my own classes which essentially do the same thing.

So, here's the updated code. The remaining <s>two bugs</s> bug still stand, so I have a "ghosting" outline all the way around the image (see second attachment) which I can narrow down to the resizing because it shows up in the first re-size where no cropping has occurred. <s>And the second bug is that the cropped versions are always positioned lower on the y axis than what I pass in as the cropper. I'd estimate it's a good 5%-8% lower than what I tell it, so not sure about that one (the positions shouldn't be changing... unless I'm passing in a bad number from jQuery, gotta check on that...).</s>

(My second bug ended up me sending bad values to begin with, the cropping div was getting its relative position based on the master content div, not the image container div. All fixed now.)

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace Website.Models.Providers {
    public class ImageProvider {
        private readonly ProductProvider ProductProvider = null;

        private readonly EncoderParameters DefaultQualityEncoder = new EncoderParameters();
        private readonly EncoderParameters HighQualityEncoder = new EncoderParameters();
        private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single(
            c =>
                (c.MimeType == "image/jpeg"));
        private readonly Size[] Sizes = new Size[3] {
            new Size(640, 0),
            new Size(240, 0),
            new Size(80, 0)
        };

        private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products");

        public ImageProvider(
            ProductProvider ProductProvider) {
            this.ProductProvider = ProductProvider;

            this.DefaultQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
            this.HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
        }

        public void Crop(
            string FileName,
            Image Image,
            Crop Crop) {
            using (Bitmap Source = new Bitmap(Image)) {
                using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
                    using (Graphics Graphics = Graphics.FromImage(Target)) {
                        Graphics.CompositingMode = CompositingMode.SourceCopy;
                        Graphics.CompositingQuality = CompositingQuality.HighQuality;
                        Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        Graphics.SmoothingMode = SmoothingMode.HighQuality;

                        Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel);
                    };

                    Target.Save(FileName, JpegCodecInfo, HighQualityEncoder);
                };
            };
        }

        public void CropAndResize(
            Product Product,
            Crop Crop) {
            using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) {
                Img Img = new Img();

                this.ProductProvider.AddImageAndSave(Product, Img);

                this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Temp, Crop);

                using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) {
                    this.Resize(String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), this.Sizes[0], Cropped, HighQualityEncoder);
                    this.Resize(String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), this.Sizes[1], Cropped, HighQualityEncoder);
                    this.Resize(String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), this.Sizes[2], Cropped, HighQualityEncoder);
                };
            };

            this.Purge(Product);
        }

        public void QueueFor(
            Product Product,
            Size Size,
            HttpPostedFileBase PostedFile) {
            using (Image Image = Image.FromStream(PostedFile.InputStream)) {
                this.Resize(String.Format("{0}/{1}.temp", Path, Product.ProductId), Size, Image, HighQualityEncoder);
            };
        }

        private void Purge(
            Product Product) {
            string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId);

            if (File.Exists(Temp)) {
                File.Delete(Temp);
            };

            foreach (Img Img in Product.Imgs) {
                string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId);

                if (File.Exists(Cropped)) {
                    File.Delete(Cropped);
                };
            };
        }

        public void Resize(
            string FileName,
            Size Size,
            Image Image,
            EncoderParameters EncoderParameters) {
            if (Size.Height == 0) {
                Size.Height = (int)(Image.Height / ((float)Image.Width / (float)Size.Width));
            };

            using (Bitmap Bitmap = new Bitmap(Size.Width, Size.Height)) {
                using (Graphics Graphics = Graphics.FromImage(Bitmap)) {
                    Graphics.CompositingMode = CompositingMode.SourceCopy;
                    Graphics.CompositingQuality = CompositingQuality.HighQuality;
                    Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Graphics.SmoothingMode = SmoothingMode.HighQuality;

                    Graphics.DrawImage(Image, new Rectangle(0, 0, Size.Width, Size.Height));
                };

                Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters);
            };
        }
    }
}

This image shows the "ghosting" outline pointed to by red arrows.

Body:
Regarding the black lines in the bottom is because you don't handle the Aspect Ratio.

double aspectRatio = imageWidth/imageHeight;
double boxRatio = maxWidth/maxHeight;
double scaleFactor = 0;
if (boxRatio > aspectRatio)
 //Use height, since that is the most restrictive dimension of box.
 scaleFactor = maxHeight / imageHeight;
else
 scaleFactor = maxWidth / imageWidth;

double newWidth = imageWidth * scaleFactor;
double newHeight = imageHeight * scaleFactor;

Source: http://nathanaeljones.com/163/20-image-resizing-pitfalls/


问:
Image preprocessing of finetune in ResNet
I want to finetune ResNet50 ImageNet pretrained model, and I have a few question about image preprocessing of finetune.

In ImageNet preprocessing, we need to subtract the mean of pixel ([103.939, 116.779, 123.68]). When I use my dataset to finetune, should I subtract mean of ImageNet or subtract the mean of my data.

I do see many people rescale the data to [0,1], but the pretrained model(ImageNet) use image scale in [0,255]. Why do people do that? Is it reasonable?

答:
I would try both. Subtracting your mean makes sense because generally one tries to get mean 0. Subtracting image net mean makes sense because you want the network as a feature extractor. If you change something that early in the feature extractor it could be that it doesn't work at all.

Just like the mean 0 thing, it is generally seen as a desirable property to have features within a fixed range or with a fixed standard deviation. Again, I can't really tell you what is better but you can easily try it. My guess is that there aren't too big differences.

Most important: Make sure you apply the same preprocessing steps to your training / testing / evaluation data.

ContentLicense: CC BY-SA 4.0


问:
Angular4 Material theme not working properly on ASP.NET Core project
I've just created a project using the ASP.NET Core Angular SPA template mentioned on this site: Building Single Page Applications on ASP.NET Core with JavaScriptServices

After that, I added the @angular/material, @angular/cdk and the @angular/flex-layout npm packages.

I made a pretty simple page using an Angular Material toolbar and a menu.
I linked the Pink-BlueGrey.css prebuilt-theme on the _Layout.cshtml (manually copied the css file to wwwroot to make things simple).

And the result is that all the Angular Material components are now styled, but every html that is not contained within a material component, stays not styled. I don't understand why. Because if I create a project using Angular CLI, everything works the expected way.

This theme that I have chosen, has a dark background. I need the font to be white so that people can read. But that is not what's happening on the ASP.NET Core project.

I think that maybe this is a webpack configuration problem. I have tried to remove the link to the css file from the _Layout.cshtml and added to the vendors bundle in the webpack.config.vendor.js. But the result is the same. It works, but not the way I want.

Is this supposed to happen? Is this by design? Am I supposed to write a CSS file that styles all HTML that is not contained within an Angular Material component?

I have tried to disable the Server Side Pre-rendering by removing the "Microsoft.AspNetCore.SpaServices" tagHelper from the _ViewImports.cshtml and the asp-prerender-module directive from the Index.cshtml. Everything stays the same. I don't know what is wrong.

I am new to web-development and I think that this should be simple stuff. But I can't find anyone that has had this exact setup and problem.

答:
So, the thing is that I was wrong about the Angular CLI. The project that I have made with it, is using mdSidenav. The moment I replaced the md-sidenav-container directive with a simple div, and removed the sidenav component, the Pink-BlueGrey's dark background vanished, and all my text became black again. The same behavior I was having with the ASP.NET Core project. So it is not an issue with the ASP.NET Core setup.

The approach that I decided to use to solve the problem described above, is to instead of putting the "mat-app-background" class in the body tag, and have to use material containers for every text in the pages, I used a md-sidenav-container directive on the root app component. I'm not using the sidenav itself. Just it's container so that every text used, even if it's just an h1 tag, will be styled because it is contained in a material component.

Maybe that is not the most elegant solution. So if someone have a better suggestion...


问:
How to create a conditional stored procedure
Can't seem to find one with a format close enough to get a solid answer. Trying to mess with select case statements, but it's proving to be a pain. I've got a basic payroll database I'm setting up (diagram shown below), and the idea is I want to do the following statement IF an employee's employee category (EmpCat) is 1, but a separate statement if it is 2 (basically hourly vs salary). Still fairly new to fiddling with T SQL, so any assistance would be greatly appreciated.

EDIT: I've adjusted the procedure. It looks like it should do what I want now, and should even auto-sum the total hours worked in the pay period, but I'm now receiving an error stating that it is not contained in an aggregate function or a GROUP BY clause. Having trouble figuring out where this is an issue.

```<code>CREATE PROCEDURE NewTimesheet(
@LName varchar(50),
@FName varchar(50),
@ShiftType char(2),
@StartDate date,
@EndDate date,
@OTHours decimal(18,2),
@HolidayHours decimal(18,2)
)
AS
BEGIN
INSERT INTO tblTimesheet(
EmpID,
ShiftType,
StartDate,
EndDate,
TotalHours,
OTHours,
HolidayHours,
NetPay
)
SELECT e.EmpID, @ShiftType, @StartDate, @EndDate, SUM(HoursWorked) ,
@OTHours, @HolidayHours,
CASE WHEN ed.EmpCat = 1
THEN (SUM(HoursWorked) * PayRate)
ELSE (e.PayRate / 24)
END
FROM tblEmployee e INNER JOIN tblEmployeeDetail ed ON e.EmpID = ed.EmpID
inner join tblShifts on e.EmpID = tblShifts.EmpID
WHERE LName=@LName AND FName=@FName AND Date > @StartDate AND Date <
@EndDate
GROUP BY e.EmpID, ed.EmpCat, e.PayRate, tblShifts.HoursWorked
END
</code>```

答:
If you want one sp to deal with both you need to have the SELECT statement within the StoredProc looking something like:

```<code>SELECT e.EmpID, @ShiftType, @StartDate, @EndDate, @TotalHours, @OTHours,
@HolidayHours, CASE WHEN ed.EmpCat = 1 THEN (@TotalHours *
tblEmployee.PayRate) ELSE (insert logic for salary) END
FROM tblEmployee e INNER JOIN tblEmployeeDetail ed ON e.EmpID = ed.EmpID
WHERE LName=@LName AND FName=@FName
</code>```

Otherwise if you want this only to deal with the hourly works, then you use:

```<code>SELECT e.EmpID, @ShiftType, @StartDate, @EndDate, @TotalHours, @OTHours,
@HolidayHours, @TotalHours * tblEmployee.PayRate
FROM tblEmployee e INNER JOIN tblEmployeeDetail ed ON e.EmpID = ed.EmpID
WHERE LName=@LName AND FName=@FName AND ed.EmpCat = 1
</code>```

HTH

Body:
Can't seem to find one with a format close enough to get a solid answer. Trying to mess with select case statements, but it's proving to be a pain. I've got a basic payroll database I'm setting up (diagram shown below), and the idea is I want to do the following statement IF an employee's employee category (EmpCat) is 1, but a separate statement if it is 2 (basically hourly vs salary). Still fairly new to fiddling with T SQL, so any assistance would be greatly appreciated.

EDIT: I've adjusted the procedure. It looks like it should do what I want now, and should even auto-sum the total hours worked in the pay period, but I'm now receiving an error stating that it is not contained in an aggregate function or a GROUP BY clause. Having trouble figuring out where this is an issue.

CREATE PROCEDURE NewTimesheet(
@LName varchar(50),
@FName varchar(50),
@ShiftType char(2),
@StartDate date,
@EndDate date,
@OTHours decimal(18,2),
@HolidayHours decimal(18,2)
)
AS
BEGIN
INSERT INTO tblTimesheet(
EmpID,
ShiftType,
StartDate,
EndDate,
TotalHours,
OTHours,
HolidayHours,
NetPay
)
SELECT e.EmpID, @ShiftType, @StartDate, @EndDate, SUM(HoursWorked) ,
@OTHours, @HolidayHours,
CASE WHEN ed.EmpCat = 1
THEN (SUM(HoursWorked) * PayRate)
ELSE (e.PayRate / 24)
END
FROM tblEmployee e INNER JOIN tblEmployeeDetail ed ON e.EmpID = ed.EmpID
inner join tblShifts on e.EmpID = tblShifts.EmpID
WHERE LName=@LName AND FName=@FName AND Date > @StartDate AND Date <
@EndDate
GROUP BY e.EmpID, ed.EmpCat, e.PayRate, tblShifts.HoursWorked
END

Body:
If you want one sp to deal with both you need to have the SELECT statement within the StoredProc looking something like:

SELECT e.EmpID, @ShiftType, @StartDate, @EndDate, @TotalHours, @OTHours,
@HolidayHours, CASE WHEN ed.EmpCat = 1 THEN (@TotalHours *
tblEmployee.PayRate) ELSE (insert logic for salary) END
FROM tblEmployee e INNER JOIN tblEmployeeDetail ed ON e.EmpID = ed.EmpID
WHERE LName=@LName AND FName=@FName

Otherwise if you want this only to deal with the hourly works, then you use:

SELECT e.EmpID, @ShiftType, @StartDate, @EndDate, @TotalHours, @OTHours,
@HolidayHours, @TotalHours * tblEmployee.PayRate
FROM tblEmployee e INNER JOIN tblEmployeeDetail ed ON e.EmpID = ed.EmpID
WHERE LName=@LName AND FName=@FName AND ed.EmpCat = 1

HTH


问:
VLOOKUP for different sheets
I have value in Sheet1 "B" column which is to be vlookup in Sheet2 from Column "A to K" and copy the corresponding C column value of Sheet2 and paste it in Sheet1's E column.

I have tried with below code but it shows error as

Run-time error '1004':
Unable to get the Vlookup Property of the worksheetfunction class.

```<code>Sub vlook_up()
  For i = 2 To 11
       Cells("D" & i).Value = WorksheetFunction.VLookup(Sheets("Sheet1").Range("B" & i), Sheets("Sheet2").Range("A1:K500"), 3, 0)
  Next i
End Sub
</code>```

答:
Try with this

```<code>Sub vlook_up()
  For i = 2 To 11
       Range("D" & i).Value = Application.WorksheetFunction.VLookup(Sheets("Sheet1").Range("B" & i), Sheets("Sheet2").Range("A1:K500"), 3, False);
  Next i
End Sub
</code>```

or

```<code> Sub vlook_up()
      For i = 2 To 11
           Range("D" & i).Value = Application.VLookup(Sheets("Sheet1").Range("B" & i), Sheets("Sheet2").Range("A1:K500"), 3, False);
      Next i
    End Sub
</code>```

Title: VLOOKUP for different sheets

Body:
I have value in Sheet1 "B" column which is to be vlookup in Sheet2 from Column "A to K" and copy the corresponding C column value of Sheet2 and paste it in Sheet1's E column.

I have tried with below code but it shows error as

Run-time error '1004':
Unable to get the Vlookup Property of the worksheetfunction class.

Sub vlook_up()
  For i = 2 To 11
       Cells("D" & i).Value = WorksheetFunction.VLookup(Sheets("Sheet1").Range("B" & i), Sheets("Sheet2").Range("A1:K500"), 3, 0)
  Next i
End Sub

Body:
Try with this

Sub vlook_up()
  For i = 2 To 11
       Range("D" & i).Value = Application.WorksheetFunction.VLookup(Sheets("Sheet1").Range("B" & i), Sheets("Sheet2").Range("A1:K500"), 3, False);
  Next i
End Sub

or

 Sub vlook_up()
      For i = 2 To 11
           Range("D" & i).Value = Application.VLookup(Sheets("Sheet1").Range("B" & i), Sheets("Sheet2").Range("A1:K500"), 3, False);
      Next i
    End Sub


问:
How to using ajax function in calendar event
My JS code Here

```<code>type = "t1";
$(document).ready(function(){
getServiceFeed(type);
});
function getServiceFeed(type){
    typeshow = type;
    console.log(typeshow);
    $('.calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },

    height: 540,
    editable: false,
    eventLimit: true,
    events:
    {
        type: "POST",
        data: 'typeshow='+typeshow,
        url: 'svFeed.php',
        success: function(data){
            console.log(typeshow);
        }
    },
    timeFormat: 'H:mm',

    loading: function(bool) {
        $('#loading').toggle(bool);
    },
    eventClick: function(event) {
        if (event.describe) {
            alert(event.describe);
            return false;
        }
    }
});
}
</code>```

My HTML Code Here

```<code><button onclick="getServiceFeed('t1')" >Public</button>
<button onclick="getServiceFeed('t2')" >Self</button>
<button onclick="getServiceFeed('t3')" >Private</button>
</code>```

I want change event in my calendar when I click button. I try using above code, still display 't1' calendar only. I try to using console.log() for debug, just only display once, the 1st typeshow, that's mean no running calendar.

答:
My reputation is not enough to comment so I am writing it as an answer.

Your success callback is not running because you are getting error callback.

Write error callback also in events object so you can fix that error then you will get success callback.

Body:
My JS code Here

type = "t1";
$(document).ready(function(){
getServiceFeed(type);
});
function getServiceFeed(type){
    typeshow = type;
    console.log(typeshow);
    $('.calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },

    height: 540,
    editable: false,
    eventLimit: true,
    events:
    {
        type: "POST",
        data: 'typeshow='+typeshow,
        url: 'svFeed.php',
        success: function(data){
            console.log(typeshow);
        }
    },
    timeFormat: 'H:mm',

    loading: function(bool) {
        $('#loading').toggle(bool);
    },
    eventClick: function(event) {
        if (event.describe) {
            alert(event.describe);
            return false;
        }
    }
});
}

My HTML Code Here

<button onclick="getServiceFeed('t1')" >Public</button>
<button onclick="getServiceFeed('t2')" >Self</button>
<button onclick="getServiceFeed('t3')" >Private</button>

I want change event in my calendar when I click button. I try using above code, still display 't1' calendar only. I try to using console.log() for debug, just only display once, the 1st typeshow, that's mean no running calendar.


问:
Recommended hardware to learn tensorflow?
I'm a software developer and I want to experiment with AI, machine learning etc. I want to learn about the different algorithms and techniques that are readily available, how to use them and what algos are appropriate for different types of challenges. TensorFlow looks like good software to start experimenting with, so I will start with TF.

I'm not interested in image processing. I'm mostly interested in making sense of patterns in data and making predictions.

Will I be able to experiment with all of the common examples and try out all the algorithms and features of TF with just a modern i7 with 8 threads or will I definitely need a GPU in order to not wait hours between each experiment?

If I do need a GPU, would an entry-level CUDA 3.0+ GPU suffice (example Geforce 730M with 2GB RAM, probably the cheapest compatible GPU)
Or would I need something with more punch and RAM like the 1050Ti/1080GTX/Ti etc?

Is it practical to learn on google or AWS or am I better off buying the hardware?

My fear is that I drop a lot of cash on a fancy graphics card and then don't really get into ML programming, and then it's a waste of money.
I have no idea if I'll even find it interesting/useful. So I'm not trying to conquer the world with ML just yet.

To sum up, my short term goals:

Get some experience with ML so that I know what techniques/algos are available/good for diff types of tasks.

See if I find ML interesting

Learn what kind of hardware I need if I want to invest further.

I can afford to buy a 1080Ti to experiment with, but I don't want to waste money without knowing more. If I buy a cheaper GPU like 1050Ti can I add a 1080Ti later or is it best if all my GPU's are the same?

答:
Simply googling will give you most of your answers. But in short, yes you can use your CPU with TensorFlow.

You will need at least CUDA 7.5 and a compute capability of at least 3.0 on your GPU (http://www.nvidia.com/object/gpu-accelerated-applications-tensorflow-installation.html)

If you have no experience with machine learning yet I would suggest playing around with Scikit learn first (http://scikit-learn.org/). It's very easy to learn and playing around with something other than neural networks will give you a better understanding in the fundamentals of machine learning. Scikit learn does not require a GPU (GPU support is actually not provided).


问:
How to adjust or format the column width in output of Package Manager Console
I ran below command in Package Manager Console in Visual Studio:

```<code>Find-Package analysisservices
</code>```

This command gives below output:

For several packages whose name is relatively longer than the width of the Id column it shows three dots ... in the end. It doesn't show any tool-tip when I hover mouse over the long names having three dots ....

Is there any way to adjust the width of the displayed columns so that long names don't get truncated?

Update: One thing which is still not solved. Is there any other additional parameter to the command Get-Package | ft -AutoSize which I can use so that all three output columns get expanded in table view itself. I don't mind if that results in a horizontal scroll bar.

答:
Try formatting the output stream like this

```<code>Find-Package analysisservices | ft -AutoSize
</code>```

More information about formatting in Powershell

Body:
I ran below command in Package Manager Console in Visual Studio:

Find-Package analysisservices

This command gives below output:

For several packages whose name is relatively longer than the width of the Id column it shows three dots ... in the end. It doesn't show any tool-tip when I hover mouse over the long names having three dots ....

Is there any way to adjust the width of the displayed columns so that long names don't get truncated?

Update: One thing which is still not solved. Is there any other additional parameter to the command Get-Package | ft -AutoSize which I can use so that all three output columns get expanded in table view itself. I don't mind if that results in a horizontal scroll bar.

Body:
Try formatting the output stream like this

Find-Package analysisservices | ft -AutoSize

More information about formatting in Powershell


问:
You have an error in your SQL syntax; when try to submit form

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '','1','7','123tw')' at line 2

I got the above error when submitting the form.

```<code> <?php
    session_start();
    $branch=$_SESSION['branch'];
    include('../dist/includes/dbcon.php');
        $name = $_POST['prod_name'];
        $price = $_POST['prod_price'];
        $desc = $_POST['prod_desc'];
        $supplier = $_POST['supplier'];
        $reorder = $_POST['reorder'];
        $category = $_POST['category'];
        //$quantity = $_POST['prod_qty'];
        $serialn = $_POST['serialn'];

        $query2=mysqli_query($con,"select * from product where prod_name='$name' and branch_id='$branch'")or die(mysqli_error($con));
            $count=mysqli_num_rows($query2);

            if ($count>0)
            {
                echo "<script type='text/javascript'>alert('Product already exist!');</script>";
                echo "<script>document.location='product.php'</script>";
            }
            else
            {

                $pic = $_FILES["image"]["name"];
                if ($pic=="")
                {
                    $pic="default.gif";
                }
                else
                {
                    $pic = $_FILES["image"]["name"];
                    $type = $_FILES["image"]["type"];
                    $size = $_FILES["image"]["size"];
                    $temp = $_FILES["image"]["tmp_name"];
                    $error = $_FILES["image"]["error"];

                    if ($error > 0)
                    {
                        die("Error uploading file! Code $error.");
                        }
                    else{
                        if($size > 100000000000) //conditions for the file
                            {
                            die("Format is not allowed or file size is too big!");
                            }
                    else
                          {
                        move_uploaded_file($temp, "../dist/uploads/".$pic);
                          }
                        }
                }

                mysqli_query($con,"INSERT INTO product(prod_name,prod_price,prod_desc,prod_pic,cat_id,reorder,supplier_id,branch_id,serialn)
                VALUES('$name','$price','$desc','$pic','$category', $reorder','$supplier','$branch','$serialn')")or die(mysqli_error($con));

                echo "<script type='text/javascript'>alert('Successfully added new product!');</script>";
                          echo "<script>document.location='product.php'</script>";
            }
    ?>
</code>```

答: Looks like you're missing a single quote before $reorder' ?

Body:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '','1','7','123tw')' at line 2

I got the above error when submitting the form.

 <?php
    session_start();
    $branch=$_SESSION['branch'];
    include('../dist/includes/dbcon.php');
        $name = $_POST['prod_name'];
        $price = $_POST['prod_price'];
        $desc = $_POST['prod_desc'];
        $supplier = $_POST['supplier'];
        $reorder = $_POST['reorder'];
        $category = $_POST['category'];
        //$quantity = $_POST['prod_qty'];
        $serialn = $_POST['serialn'];

        $query2=mysqli_query($con,"select * from product where prod_name='$name' and branch_id='$branch'")or die(mysqli_error($con));
            $count=mysqli_num_rows($query2);

            if ($count>0)
            {
                echo "";
                echo "";
            }
            else
            {

                $pic = $_FILES["image"]["name"];
                if ($pic=="")
                {
                    $pic="default.gif";
                }
                else
                {
                    $pic = $_FILES["image"]["name"];
                    $type = $_FILES["image"]["type"];
                    $size = $_FILES["image"]["size"];
                    $temp = $_FILES["image"]["tmp_name"];
                    $error = $_FILES["image"]["error"];

                    if ($error > 0)
                    {
                        die("Error uploading file! Code $error.");
                        }
                    else{
                        if($size > 100000000000) //conditions for the file
                            {
                            die("Format is not allowed or file size is too big!");
                            }
                    else
                          {
                        move_uploaded_file($temp, "../dist/uploads/".$pic);
                          }
                        }
                }

                mysqli_query($con,"INSERT INTO product(prod_name,prod_price,prod_desc,prod_pic,cat_id,reorder,supplier_id,branch_id,serialn)
                VALUES('$name','$price','$desc','$pic','$category', $reorder','$supplier','$branch','$serialn')")or die(mysqli_error($con));

                echo "";
                          echo "";
            }
    ?>


问:
Xamarin Forms - Change cursor colour and bottom border using XAML
I want to change the colour of the cursor and the bottom border of an Entry field using XAML. (It is pink in colour at the moment). Changing the font colour didn't help and I can't see anything informative in the IntelliSense either. Can someone please tell me how to do this in XAML? Thank you.

```<code><Entry
    x:Name="editorEmailAddress"
    TextColor="Purple" />
</code>```

In Android, it shows in pink.

答:
https://developer.xamarin.com/guides/android/user_interface/material_theme/

follow the guidelines to resolve your problem.

or if you want to change it by Custom Render  than follow below link.

Is it possible to change the colour of the line below / Border of a TextBox (Entry)

Body:
I want to change the colour of the cursor and the bottom border of an Entry field using XAML. (It is pink in colour at the moment). Changing the font colour didn't help and I can't see anything informative in the IntelliSense either. Can someone please tell me how to do this in XAML? Thank you.

<Entry
    x:Name="editorEmailAddress"
    TextColor="Purple" />

In Android, it shows in pink.


问:
Delphi chromium1.Browser.MainFrame.ExecuteJavaScript Only 255 chars?
I want to execute large javascript but im stuck.

```<code>procedure ExecuteJavaScript(const code, scriptUrl: ustring; startLine: Integer);
</code>```

In code there is a restriction of 255 chars. How to bypass this restriction?

(Delphi 10 Seattle)

Thanx.

答:
I tried a simple document.write(""); with a 600 char length string in the latest version of CEF4Delphi and it showed the whole string in the MiniBrowser demo compiled with Delphi 10.

DCEF3 has basically the same code for the ExecuteJavaScript function so it should work too.

There's no string length restriction in CEF4Delphi, DCEF3 or the CEF3 libraries.

Maybe you're using a shortstring or an InputBox to type the javascript code.

Body:
I want to execute large javascript but im stuck.

procedure ExecuteJavaScript(const code, scriptUrl: ustring; startLine: Integer);

In code there is a restriction of 255 chars. How to bypass this restriction?

(Delphi 10 Seattle)

Thanx.


问:
python importerror no module named zope.interface twisted
I am new in python.I installed "scrapy" but it giving error "importerror no module named zope.interface twisted".Please help me.

Thanks in advance..........

答: Scrapy requires a few additional libraries, namely Twisted and libxml2 (and optionally pyopenssl and simplejson).  The installation instructions describes how to install these libraries.</p>


问:
Cannot create tasks to upload Proguard Mapping File.java.lang.IllegalStateException: Resolving configuration 'androidTestAnnotationProcessor'
Upgraded to Android Studio 3.0 canary 3 and with it gradle-4.0-milestone-1-all Due to the new way of evaluating dependencies the current plugin used in https://firebase.google.com/docs/crash/android#uploading_proguard_mapping_files_with_gradle no longer works, running the task:

```<code>$ gradlew app:firebaseUploadReleaseProguardMapping
</code>```

Yields an error:

Cannot create tasks to upload Proguard Mapping
  File.java.lang.IllegalStateException: Resolving configuration
  'androidTestAnnotationProcessor' directly is not allowed

Any suggestions to make this work?

答:
Updates from - groups.google.com/forum/#!topic/firebase-talk/JqnlnGK2ddY

Change from

```<code>    classpath('com.google.firebase:firebase-plugins:1.1.0') {
</code>```

to

```<code>    classpath('com.google.firebase:firebase-plugins:1.1.0-alpha1') {
</code>```

Body:
Upgraded to Android Studio 3.0 canary 3 and with it gradle-4.0-milestone-1-all Due to the new way of evaluating dependencies the current plugin used in https://firebase.google.com/docs/crash/android#uploading_proguard_mapping_files_with_gradle no longer works, running the task:

$ gradlew app:firebaseUploadReleaseProguardMapping

Yields an error:

Cannot create tasks to upload Proguard Mapping
  File.java.lang.IllegalStateException: Resolving configuration
  'androidTestAnnotationProcessor' directly is not allowed

Any suggestions to make this work?

Body:
Updates from - groups.google.com/forum/#!topic/firebase-talk/JqnlnGK2ddY

Change from

    classpath('com.google.firebase:firebase-plugins:1.1.0') {

to

    classpath('com.google.firebase:firebase-plugins:1.1.0-alpha1') {


问:
Magento clear extendware cache programmatically
I am using 'Extendware Full page cache' magento extension. how to programmatically clear product page cache in extendware.</p>

答:
To programmatically clear product page cache please follow http://vagento.com/magento-automatically-cache-refresh-using-cron/ site article. In this link it'll help you to Cache Refresh programmatically as well as you can set cron to Automatically Cache Refresh Using Cron.

let us know that'll help you or not.


问:
Issue casting to string in google sheets script
I have the following function for a google sheets document:

```<code>function names(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var str = String(nameCells[i]);
    var splitted = str.split(", ");
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}
</code>```

The function is supposed take a list of cells with names that are comma separated and return and single list of all the names.

For example:

```<code>James
Reese, Peter
Ryan, Monica
Reba

Nick
</code>```

Should produce

```<code>James
Reese
Peter
Ryan
Monica
Nick
</code>```

However I seem to be having an issue casting the cell values to string values and it says "Internal error executing the custom function" without giving me any more specifics than that. The following more basic program does work as expected:

```<code>function namesSimple(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
      roomieNames.push(nameCells[i]);
  }
  return roomieNames;
}
</code>```

However the following produces the error seen in the comments in line 4:

```<code>function namesBroken(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var splitted = nameCells[i].split(", ");  //TypeError: Cannot find function split in object James. (line 4).
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}
</code>```

Which leads to me to believe I need to cast the object to a string but as stated above that doesn't seem to be working either.

I tried googling casting techniques and feel that this should work. I have also tried .toString(); with no luck. Can someone help me out please. Thanks :)

答:
See if this custom function works:

```<code>function namesSimple(values) {
    return values.toString().split(",").map(function (r) {
        return r.trim();
    }).filter(String);
}
</code>```

In your spreadsheet enter

```<code>=namesSimple(A1:A20)
</code>```

Body:
I have the following function for a google sheets document:

function names(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var str = String(nameCells[i]);
    var splitted = str.split(", ");
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}

The function is supposed take a list of cells with names that are comma separated and return and single list of all the names.

For example:

James
Reese, Peter
Ryan, Monica
Reba

Nick

Should produce

James
Reese
Peter
Ryan
Monica
Nick

However I seem to be having an issue casting the cell values to string values and it says "Internal error executing the custom function" without giving me any more specifics than that. The following more basic program does work as expected:

function namesSimple(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
      roomieNames.push(nameCells[i]);
  }
  return roomieNames;
}

However the following produces the error seen in the comments in line 4:

function namesBroken(nameCells) {
  var roomieNames = new Array();
  for (i = 0; i < nameCells.length; i++) {
    var splitted = nameCells[i].split(", ");  //TypeError: Cannot find function split in object James. (line 4).
    for (k = 0; splitted.length; i++) {
      roomieNames.push(splitted[i]);
    }
  }
  return roomieNames;
}

Which leads to me to believe I need to cast the object to a string but as stated above that doesn't seem to be working either.

I tried googling casting techniques and feel that this should work. I have also tried .toString(); with no luck. Can someone help me out please. Thanks :)

Body:
See if this custom function works:

function namesSimple(values) {
    return values.toString().split(",").map(function (r) {
        return r.trim();
    }).filter(String);
}

In your spreadsheet enter

=namesSimple(A1:A20)


问:
Response is null when I used Restsharp library's GET request to access Json data
I am using Restsharp library to do Webservice operations.I tried to access data from the link(http://www.mocky.io/v2/595616d92900003d02cd7191) and print it in Console but I am not getting any response.When I used breakpoints,Response is showing null.Here's my code to get data from the link.

```<code>private async void GetItemsFromJSON()
    {
        IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
        IRestRequest request = new RestRequest(Method.GET);
        request.RequestFormat = DataFormat.Json;

        try
        {
            await Task.Run(() =>
            {
                IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
                var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
                Console.WriteLine(response.Content);
</code>```

}

```<code>  public class ItemDetails
{
    public List<Itemschema> items { get; set; }
}
 public class Itemschema
{
    public int id { get; set; }
    public string sku { get; set; }
    public string name { get; set; }
    public int attribute_set_id { get; set; }
    public int price { get; set; }
    public int status { get; set; }
    public int visibility { get; set; }
    public string type_id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public int weight { get; set; }
}
</code>```

Am I missing something here?My schema class which corresponds to the Json data is shown above.

答:
I suspect that:

```<code>IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
</code>```

should be:

```<code>IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
</code>```

http://www.mocky.io/v2/595616d92900003d02cd7191 seems to return an items property which contains an array of schemas. That maps closer to ItemDetails than List<ItemDetails>.

This complete sample works, so you may want to compare it with your code:

```<code>using System;
using System.Collections.Generic;
using RestSharp;

namespace Test
{
    public class ItemDetails
    {
        public List<Itemschema> items { get; set; }
    }
    public class Itemschema
    {
        public int id { get; set; }
        public string sku { get; set; }
        public string name { get; set; }
        public int attribute_set_id { get; set; }
        public int price { get; set; }
        public int status { get; set; }
        public int visibility { get; set; }
        public string type_id { get; set; }
        public string created_at { get; set; }
        public string updated_at { get; set; }
        public int weight { get; set; }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
            IRestRequest request = new RestRequest(Method.GET);
            request.RequestFormat = DataFormat.Json;

            IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
            var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
            Console.WriteLine(Items.items.Count);
            Console.ReadLine();
        }
    }
}
</code>```

Body:
I am using Restsharp library to do Webservice operations.I tried to access data from the link(http://www.mocky.io/v2/595616d92900003d02cd7191) and print it in Console but I am not getting any response.When I used breakpoints,Response is showing null.Here's my code to get data from the link.

private async void GetItemsFromJSON()
    {
        IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
        IRestRequest request = new RestRequest(Method.GET);
        request.RequestFormat = DataFormat.Json;

        try
        {
            await Task.Run(() =>
            {
                IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
                var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
                Console.WriteLine(response.Content);

}

  public class ItemDetails
{
    public List<Itemschema> items { get; set; }
}
 public class Itemschema
{
    public int id { get; set; }
    public string sku { get; set; }
    public string name { get; set; }
    public int attribute_set_id { get; set; }
    public int price { get; set; }
    public int status { get; set; }
    public int visibility { get; set; }
    public string type_id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public int weight { get; set; }
}

Am I missing something here?My schema class which corresponds to the Json data is shown above.

Body:
I suspect that:

IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);

should be:

IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);

http://www.mocky.io/v2/595616d92900003d02cd7191 seems to return an items property which contains an array of schemas. That maps closer to ItemDetails than List<ItemDetails>.

This complete sample works, so you may want to compare it with your code:

using System;
using System.Collections.Generic;
using RestSharp;

namespace Test
{
    public class ItemDetails
    {
        public List<Itemschema> items { get; set; }
    }
    public class Itemschema
    {
        public int id { get; set; }
        public string sku { get; set; }
        public string name { get; set; }
        public int attribute_set_id { get; set; }
        public int price { get; set; }
        public int status { get; set; }
        public int visibility { get; set; }
        public string type_id { get; set; }
        public string created_at { get; set; }
        public string updated_at { get; set; }
        public int weight { get; set; }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
            IRestRequest request = new RestRequest(Method.GET);
            request.RequestFormat = DataFormat.Json;

            IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
            var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
            Console.WriteLine(Items.items.Count);
            Console.ReadLine();
        }
    }
}