问:
Enabling syntax hightlighting for Robot Framework in notepad++
I'm working on Robot Framework and I want the syntax highlighting feature of notepad++ for robot framework. I tried doing the below mentioned suggestions which I got from the Robot framework official website :

1) I tired downloading the xml file (lang-robot.xml) from GitHub(https://github.com/vkosuri/npp-robot) and importing it from notpad ++ but it didn't seem to work .

2) Then tried copying the lang-robot.xml file to the c:/program files(x86)/Notepad++ , even that didn't work .

Is there anyone who can help me out Please

Thanks in Advance

答:
1.) Import the xml file (lang-robot.xml) from GitHub(https://github.com/vkosuri/npp-robot).

2.) Go to Notepad++ and define your Language options under Language settings in the toolbar.

3.) Import the xml file.

4.) Save the file as .robot file and try. ( without saving the file ,the highlighting doesnt work).


来源: stackexchange

问:
Set selected value to 0 when passed selected value is not available in binded itemsource list
I wanted to set selected value to 0 when passed selected value is not available in binded itemsource list.

There is a class called Category as mentioned below:

```<code>public class Category
{
   private long _CategoryID;
   public long CategoryID
   {
       get
       {
           return _CategoryID;
       }
       set
       {
           _CategoryID = value;
       }
   }
   private string _CategoryName;
   public string CategoryName
   {
       get
       {
           return _CategoryName;
       }
       set
       {
           _CategoryName = value;
       }
   }
}
</code>```

There is a window and a combobox inside that window. And combobox is defined as below:

```<code><ComboBox  Name="cbCagtegory" TabIndex="7" ItemsSource="{Binding CategoriesList}" SelectedValuePath="CategoryID" DisplayMemberPath="CategoryName" SelectedValue="{Binding Path=CategoryID}">
</ComboBox>
</code>```

In the back end of this window I have prepared a list of categories to bind with combobox and a property to set combobox selected value.

```<code>List<Category> CategoriesList= new List<Category>();

private long _CategoryID;
public long CategoryID
{
   get
   {
      return _CategoryID;
   }
   set
   {
      _CategoryID = value;
      RaisePropertyChanged("CategoryID");
   }
}
</code>```

Now let say, CategoriesList contains two records.

```<code>a. CategoryID=0, CategoryName='Category1'
b. CategoryID=1, CategoryName='Category2'
c. CategoryID=2, CategoryName='Category3'
</code>```

Question.

if I set CategoryId property value to 5. There will be nothing selected in the combobox.
At this time i wanted to set CategoryID=0 as selected value.
And I wanted to achieve this in XAML.

What I have tried so far.

```<code>1.Assigned FallBackValue=0 as below
 <ComboBox  Name="cbCagtegory" TabIndex="7" ItemsSource="{Binding CategoriesList}" SelectedValuePath="CategoryID" DisplayMemberPath="CategoryName" SelectedValue="{Binding Path=CategoryID,FallBackValue=0}">
</ComboBox>

2. Assigned TargetNullValue=0 as below
<ComboBox  Name="cbCagtegory" TabIndex="7" ItemsSource="{Binding CategoriesList}" SelectedValuePath="CategoryID" DisplayMemberPath="CategoryName" SelectedValue="{Binding Path=CategoryID,TargetNullValue=0}">
</ComboBox>
</code>```

Result

None of them worked. nothing got selected in combobox.

答:
i would do this:

change the combobox in xaml in this way

```<code><ComboBox  Name="cbCagtegory" TabIndex="7" ItemsSource="{Binding CategoriesList}"  DisplayMemberPath="CategoryName" SelectedItem="{Binding Selection}">
</ComboBox>
</code>```

add this property

```<code>private Category comboSelection;
public Category ComboSelection
{
    get
    {
        return ComboSelection;
    }
    set
    {
        ComboSelection= value;
        RaisePropertyChanged("ComboSelection");
    }
}
</code>```

Change CategoryID like this

```<code>private long _CategoryID;

public long CategoryID
{
    get
    {
        return _CategoryID;
    }
    set
    {
        _CategoryID = value;
        if((int)CategoryID > CategoriesList.Count -1)
        {ComboSelection= CategoriesList[0];}
        else
        {ComboSelection= CategoriesList[(int)CategoryID ];
         _CategoryID = 0;}
        RaisePropertyChanged("CategoryID");
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wanted to set selected value to 0 when passed selected value is not available in binded itemsource list.

There is a class called Category as mentioned below:

public class Category
{
   private long _CategoryID;
   public long CategoryID
   {
       get
       {
           return _CategoryID;
       }
       set
       {
           _CategoryID = value;
       }
   }
   private string _CategoryName;
   public string CategoryName
   {
       get
       {
           return _CategoryName;
       }
       set
       {
           _CategoryName = value;
       }
   }
}

There is a window and a combobox inside that window. And combobox is defined as below:

<ComboBox  Name="cbCagtegory" TabIndex="7" ItemsSource="{Binding CategoriesList}" SelectedValuePath="CategoryID" DisplayMemberPath="CategoryName" SelectedValue="{Binding Path=CategoryID}">
</ComboBox>

In the back end of this window I have prepared a list of categories to bind with combobox and a property to set combobox selected value.

List<Category> CategoriesList= new List<Category>();

private long _CategoryID;
public long CategoryID
{
   get
   {
      return _CategoryID;
   }
   set
   {
      _CategoryID = value;
      RaisePropertyChanged("CategoryID");
   }
}

Now let say, CategoriesList contains two records.

a. CategoryID=0, CategoryName='Category1'
b. CategoryID=1, CategoryName='Category2'
c. CategoryID=2, CategoryName='Category3'

Question.

if I set CategoryId property value to 5. There will be nothing selected in the combobox.
At this time i wanted to set CategoryID=0 as selected value.
And I wanted to achieve this in XAML.

What I have tried so far.

1.Assigned FallBackValue=0 as below
 <ComboBox  Name="cbCagtegory" TabIndex="7" ItemsSource="{Binding CategoriesList}" SelectedValuePath="CategoryID" DisplayMemberPath="CategoryName" SelectedValue="{Binding Path=CategoryID,FallBackValue=0}">
</ComboBox>

2. Assigned TargetNullValue=0 as below
<ComboBox  Name="cbCagtegory" TabIndex="7" ItemsSource="{Binding CategoriesList}" SelectedValuePath="CategoryID" DisplayMemberPath="CategoryName" SelectedValue="{Binding Path=CategoryID,TargetNullValue=0}">
</ComboBox>

Result

None of them worked. nothing got selected in combobox.

Body:
i would do this:

change the combobox in xaml in this way

<ComboBox  Name="cbCagtegory" TabIndex="7" ItemsSource="{Binding CategoriesList}"  DisplayMemberPath="CategoryName" SelectedItem="{Binding Selection}">
</ComboBox>

add this property

private Category comboSelection;
public Category ComboSelection
{
    get
    {
        return ComboSelection;
    }
    set
    {
        ComboSelection= value;
        RaisePropertyChanged("ComboSelection");
    }
}

Change CategoryID like this

private long _CategoryID;

public long CategoryID
{
    get
    {
        return _CategoryID;
    }
    set
    {
        _CategoryID = value;
        if((int)CategoryID > CategoriesList.Count -1)
        {ComboSelection= CategoriesList[0];}
        else
        {ComboSelection= CategoriesList[(int)CategoryID ];
         _CategoryID = 0;}
        RaisePropertyChanged("CategoryID");
    }
}


问:
Difference between "Step ramp time" and "Step Duration" with Visual Studio test load
I'm currently trying to test a site with Visual Studio load test. However, I'm not really familiar with that and I see really bad result so I'm wondering if my setup is correct. Basically, I want to simulate that 6 000 users comes to my site in a short period of time, so these are the property I put in my test:

From what I understand, I start with 500 users and then I add 500 new users every 5 seconds until I reach 6 000 where it stabilized. Is this a correct assumption ? Are these number realistic ?

Concerning my scenario, I have 7 of these that request some page of my site.

答:
The ramp time is the time that it takes to move from one step to the next.
During the ramp time, it distributes the extra load as it ramps up.

The step duration is how long it holds the constant load for the step, before starting to ramping up to the next one.

ContentLicense: CC BY-SA 4.0


问:
compare two arrays for common Items and return another array with the common items
So the problem is I have two array and have to check them for common items.Usual stuff, very easy.But the tricky thing for me is that I have to return another array with the elements that have been found to be common.I cannot not use any Collections.Thanks in advance.This is my code so far!</p>

```<code>public class checkArrayItems {
    static int[] array1 = { 4, 5, 6, 7, 8 };
    static int[] array2 = { 1, 2, 3, 4, 5 };

    public static void main(String[] args) {
        checkArrayItems obj = new checkArrayItems();
        System.out.println(obj.checkArr(array1, array2));

    }

    int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

}
</code>```

答:
You can use a MIN or MAX default dummy value for the elements in your new array arr using arr[i] = Integer.MIN_VALUE;. In that way you will be able to differentiate between the real and dummy values. Like below:

```<code>int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            arr[i] = Integer.MIN_VALUE;
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }
</code>```

Output

[4, 5, -2147483648, -2147483648, -2147483648]

EDIT

Conclusion
When you iterate over arr all the values other than -2147483648 are common.

EDIT 2

To print the common values as mentioned on the comment below:

```<code>public static void main(String[] args) {
checkArrayItems obj = new checkArrayItems();
int[] arr = obj.checkArr(array1, array2);
        System.out.println("Common values are : ");
        for (int x : arr) {
            if (x != Integer.MIN_VALUE) {
                System.out.print(x+"\t");
            }
        }
}
</code>```

Suggestion: Follow naming convention for class i.e. make checkArrayItems to CheckArrayItems.

Body:
So the problem is I have two array and have to check them for common items.Usual stuff, very easy.But the tricky thing for me is that I have to return another array with the elements that have been found to be common.I cannot not use any Collections.Thanks in advance.This is my code so far!

public class checkArrayItems {
    static int[] array1 = { 4, 5, 6, 7, 8 };
    static int[] array2 = { 1, 2, 3, 4, 5 };

    public static void main(String[] args) {
        checkArrayItems obj = new checkArrayItems();
        System.out.println(obj.checkArr(array1, array2));

    }

    int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

}

Body:
You can use a MIN or MAX default dummy value for the elements in your new array arr using arr[i] = Integer.MIN_VALUE;. In that way you will be able to differentiate between the real and dummy values. Like below:

int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            arr[i] = Integer.MIN_VALUE;
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

Output

[4, 5, -2147483648, -2147483648, -2147483648]

EDIT

Conclusion
When you iterate over arr all the values other than -2147483648 are common.

EDIT 2

To print the common values as mentioned on the comment below:

public static void main(String[] args) {
checkArrayItems obj = new checkArrayItems();
int[] arr = obj.checkArr(array1, array2);
        System.out.println("Common values are : ");
        for (int x : arr) {
            if (x != Integer.MIN_VALUE) {
                System.out.print(x+"\t");
            }
        }
}

Suggestion: Follow naming convention for class i.e. make checkArrayItems to CheckArrayItems.


问:
execute linux command in java
i want to execute the command crontab file.txt in java.

What is the procedure...?

ContentLicense: CC BY-SA 2.5

Title: execute linux command in java

Body: Runtime.getRuntime().exec("crontab file.txt")


问:
Keras : addition layer for embeddings / vectors?
I have 3 word embeddings :

embedding#1 : [w11, w12, w13, w14]

embedding#2 : [w21, w22, w23, w24]

embedding#3 : [w31, w32, w33, w34]

Is there a way to get a fourth embedding by adding all three vectors, with the trainable weights from all of them, like:

embedding#4  : [w11 + w21 + w31, w12 + w22 + w32, w13 + w23 + w33, w14 + w24 + w34]

?  Is there a way to do this in a keras layer?

Problem

I want to learn the word embeddings for Indonesian language.  I plan to do this by training a sequence prediction machine using LSTMs.

However, the grammar of Indonesian language is different from english.  Especially, in Indonesian, you can modify a word using prefixes and suffixes.  A noun word when given a prefix can become a verb, and when given a suffix can become an adjective.   You can put so many into one word, so that a single base word can have 5 or more variations.

For example  :

tani means farm (verb)

pe-tani means farmer

per-tani-an means farm (noun)

ber-tani means farm (verb, with slightly different meaning)

The transformation of semantic done by appending a prefix to a word is consistent between words.  For example  :

pe-tani is to tani is what pe-layan is to layan, what pe-layar is to layar, what pe-tembak is to tembak, and so on.

per-main-an is to main is what per-guru-an is to guru, what per-kira-an is to kira, what per-surat-an is to surat, and so on.

Therefore, i plan to represent the prefixes and suffixes as embeddings, which would be used to do an addition to the base word's embedding, producing a new embedding.  So the meaning of the composite word is derived from the embeddings of the base word and the affixes, not stored as a separate embeddings.   However i don't know how to do this in a Keras layer. If it had been asked before, i cannot find it.

答:
When you say "three word embeddings", I see three Embedding layers, such as:

```<code>input1 = Input((sentenceLength,))
input2 = Input((sentenceLength,))
input3 = Input((sentenceLength,))

emb1 = Embedding(...options...)(input1)
emb2 = Embedding(...options...)(input2)
emb3 = Embedding(...options...)(input3)
</code>```

You can use a simple Add() layer to sum the three:

```<code>summed = Add()([emb1,emb2,emb3])
</code>```

Then you continue your modeling...

```<code>#after creating the rest of the layers and getting the desired output:
model = Model([input1,input2,input3],output)
</code>```

If you're not using embedding layers, but you're inputting three vectors:

```<code>input1 = Input((4,)) #or perhaps (sentenceLength,4)
input2 = Input((4,))
input3 = Input((4,))

added = Add()([input1,input2,input3])
</code>```

And the rest is the same.

If this is not your question, please give more details about where the three "word embeddings" are coming from, how you intend to select them, etc.

Body:
When you say "three word embeddings", I see three Embedding layers, such as:

input1 = Input((sentenceLength,))
input2 = Input((sentenceLength,))
input3 = Input((sentenceLength,))

emb1 = Embedding(...options...)(input1)
emb2 = Embedding(...options...)(input2)
emb3 = Embedding(...options...)(input3)

You can use a simple Add() layer to sum the three:

summed = Add()([emb1,emb2,emb3])

Then you continue your modeling...

#after creating the rest of the layers and getting the desired output:
model = Model([input1,input2,input3],output)

If you're not using embedding layers, but you're inputting three vectors:

input1 = Input((4,)) #or perhaps (sentenceLength,4)
input2 = Input((4,))
input3 = Input((4,))

added = Add()([input1,input2,input3])

And the rest is the same.

If this is not your question, please give more details about where the three "word embeddings" are coming from, how you intend to select them, etc.


问:
How do I install odoo v8.0 and development environment on windows 10?
I am trying to install odoo 8.0 in windows 10 OS so far these are the steps I have been following but when I run odoo.py on command line the odoo server is not initializing.

Install Odoo for development:

Install Pycharm

Install Python 2.7

Download get-pip.py

python get-pip.py

cd your odoopath

c:\python\scripts\pip.exe install -r requirements.txt

Or C:\Python27\Scripts\pip.exe install --upgrade -r requirements.txt

install simplejson

Install NodeJs

Install VCForPython27.msi

pip install pypiwin32

odoo.py

Create db on pgadmin

Start Odoo with db credentials -- odoo.py -d DHS -r aahi-admin -w DHSNAIROBI

odoo.py -d databasename -r username -w password

First login is admin/admin

答:
If you are working in window environment then download and install the
latest build EXE file from the odoo nightly server.

This Package build merged all the odoo related python packages and other dependent files.We have no need to install it separately in our machine.

Every night, a new set of packages is generated for the branches listed below. This set consists of deb and rpm packages for Debian and RedHat distributions, an EXE package for Windows and a source package.

Please pick your favorite odoo version with latest build EXE and use and install it in your system from which same as normal EXE file in the window.

After Installed the odoo.exe file on your machine.
Odoo setup create a new directory in default drive C: which named as Odoo
and you will also find all add-ons and other server related modules in it.

Also, find the .bat file for starting the odoo instant.
double click on it and run and then odoo servers will start with 8069 port

And see the result in your favourite browser.

I hope my answer may helpful for you :)


问:
How to fix Javascript code with error on split() undefined and onclick event?
My background: I learned CSS & HTML a few years ago and I am learning Javascript & JQuery. Currently, I've got to improve the e-commerce website of my company.

Here's what I am trying to do.

I've got a product page where there is a picture of a product (inside a window) and some colour buttons.

When you click on a colour button, it gets selected but the photo doesn't change.

You probably guessed it, I want to add code that shows the picture of the product when you click/select the colour that matches it.

I wrote a JS code and my idea behind it, is to isolate the url of the picture and to change it by the one corresponding to the colour.

The problem is that I get this error: Uncaught TypeError: Cannot read property 'split' of undefined.

I searched for solutions but none of them seem to correspond to my problem. Thus, I need help.

Here's the HTML (the window/block showing the picture of the product):

```<code><div
    style="z-index: 999;
    overflow: hidden;
    margin-left: 0px; margin-top: 0px;
    background-position: -144px 0px;
    width: 456px; height: 343px;
    float: left;
    cursor: crosshair;
    background-repeat: no-repeat; position: absolute;
    background-image: url("https://be-goji.com/wp-
    content/uploads/2017/01/OSSO-ROSE.jpg");
    top: 0px; left: 0px; display: none;"
    class="zoomWindow">
</div>
</code>```

Here's a snippet of a Javascript code that I wrote in order to fix it (with comments):

```<code>// isolates the HTML from the window
var colorSwitch = document.getElementsByClassName('zoomWindow');

// splits the code in several strings in an array
var colorSwitchUrl = colorSwitch[0].split(';')

// extracts the string I want to change
var colorSwitchChange = colorSwitchUrl.slice(12,13);

// gets the element I want to put the event onto
var chooseColorNoir = document.getElementsByTagName('label');

//function that brings picture to show in the window on click
chooseColorNoir[0].onclick = function(){

   // makes the string disappear
   colorSwitchChange.pop();

   // replaces it with a good one
   colorSwitchChange.push("https://be-goji.com/wp-
   content/uploads/2017/01/coco_noir.jpg");
};
</code>```

Could you help me find where the problem lies? Do you have another method that you recommend?

Thanks a million!

Nat

Note: I have got to call the picture with an url since it isn't available on the page.

答:
Why you want to do this much. If I understood your question Properly, you want to change the image based on user selection. You can simply do that like this.

I added two labels and gave those a unique color attribute and on click I am checking for that attribute value and accordingly changing the background image of the product div. No need to do any kind of string manipulations.

HTML:

```<code><div
    style="z-index: 999;
    overflow: hidden;
    margin-left: 0px; margin-top: 0px;
    background-position: -144px 0px;
    width: 456px; height: 343px;
    float: left;
    cursor: crosshair;
    background-repeat: no-repeat; position: absolute;
    background-image: url('https://be-goji.com/wp-content/uploads/2017/01/OSSO-ROSE.jpg');
    top: 0px; left: 0px;"
    class="zoomWindow">
</div>

<div style="float:right">
  <label itemColor="Rose">Rose</label> <label itemColor="Coco">Coco</label>
</div>
</code>```

JS:

```<code>// isolates the HTML from the window
var colorSwitch = document.getElementsByClassName('zoomWindow')[0];

//function that brings picture to show in the window on click
var myFunction = function(){
  if(this.getAttribute("itemColor") == "Rose"){
    colorSwitch.style.backgroundImage = "url('https://be-goji.com/wp-content/uploads/2017/01/OSSO-ROSE.jpg')";
  }
  else if(this.getAttribute("itemColor") == "Coco"){
      colorSwitch.style.backgroundImage = "url('https://be-goji.com/wp-content/uploads/2017/01/coco_noir.jpg')";
  }
};

// gets the element I want to put the event onto
var chooseColorNoir = document.getElementsByTagName('label');
for (var i = 0; i < chooseColorNoir.length; i++) {
    chooseColorNoir[i].addEventListener('click', myFunction, false);
}
</code>```

Working Pen for your reference

Body:
My background: I learned CSS & HTML a few years ago and I am learning Javascript & JQuery. Currently, I've got to improve the e-commerce website of my company.

Here's what I am trying to do.

I've got a product page where there is a picture of a product (inside a window) and some colour buttons.

When you click on a colour button, it gets selected but the photo doesn't change.

You probably guessed it, I want to add code that shows the picture of the product when you click/select the colour that matches it.

I wrote a JS code and my idea behind it, is to isolate the url of the picture and to change it by the one corresponding to the colour.

The problem is that I get this error: Uncaught TypeError: Cannot read property 'split' of undefined.

I searched for solutions but none of them seem to correspond to my problem. Thus, I need help.

Here's the HTML (the window/block showing the picture of the product):

Here's a snippet of a Javascript code that I wrote in order to fix it (with comments):

// isolates the HTML from the window
var colorSwitch = document.getElementsByClassName('zoomWindow');

// splits the code in several strings in an array
var colorSwitchUrl = colorSwitch[0].split(';')

// extracts the string I want to change
var colorSwitchChange = colorSwitchUrl.slice(12,13);

// gets the element I want to put the event onto
var chooseColorNoir = document.getElementsByTagName('label');

//function that brings picture to show in the window on click
chooseColorNoir[0].onclick = function(){

   // makes the string disappear
   colorSwitchChange.pop();

   // replaces it with a good one
   colorSwitchChange.push("https://be-goji.com/wp-
   content/uploads/2017/01/coco_noir.jpg");
};

Could you help me find where the problem lies? Do you have another method that you recommend?

Thanks a million!

Nat

Note: I have got to call the picture with an url since it isn't available on the page.

Body:
Why you want to do this much. If I understood your question Properly, you want to change the image based on user selection. You can simply do that like this.

I added two labels and gave those a unique color attribute and on click I am checking for that attribute value and accordingly changing the background image of the product div. No need to do any kind of string manipulations.

HTML:

<div
    style="z-index: 999;
    overflow: hidden;
    margin-left: 0px; margin-top: 0px;
    background-position: -144px 0px;
    width: 456px; height: 343px;
    float: left;
    cursor: crosshair;
    background-repeat: no-repeat; position: absolute;
    background-image: url('https://be-goji.com/wp-content/uploads/2017/01/OSSO-ROSE.jpg');
    top: 0px; left: 0px;"
    class="zoomWindow">&nbsp;
</div>

<div style="float:right">
  <label itemColor="Rose">Rose</label> <label itemColor="Coco">Coco</label>
</div>

JS:

// isolates the HTML from the window
var colorSwitch = document.getElementsByClassName('zoomWindow')[0];

//function that brings picture to show in the window on click
var myFunction = function(){
  if(this.getAttribute("itemColor") == "Rose"){
    colorSwitch.style.backgroundImage = "url('https://be-goji.com/wp-content/uploads/2017/01/OSSO-ROSE.jpg')";
  }
  else if(this.getAttribute("itemColor") == "Coco"){
      colorSwitch.style.backgroundImage = "url('https://be-goji.com/wp-content/uploads/2017/01/coco_noir.jpg')";
  }
};

// gets the element I want to put the event onto
var chooseColorNoir = document.getElementsByTagName('label');
for (var i = 0; i < chooseColorNoir.length; i++) {
    chooseColorNoir[i].addEventListener('click', myFunction, false);
}

Working Pen for your reference


问:
Iterate multiple Enumerations and return a value in Elixir
I have the following set of Enum's as key value pairs

```<code>list_of_vehicles = [{"Toyota" => "Corolla"},{"Honda"=> "Insight"}]
list_of_colors = [{"C01"=> "Green"},{"C02"=> "White"}]
list_of_capacity = [{"S01"=> "4"},{"S02"=> "2"}]
</code>```

I need to iterate through each list and generate a single string with all possibilities.

So far i have done following :

```<code>defp process_output(list_of_vehicles,list_of_colors,list_of_capacity)
    Enum.each(list_of_vehicles, fn{k,v}->
          final_output = "#{k}"
          if(Enum.any?(list_of_colors)) do
            Enum.each(list_of_colors, fn{k,v}->
              final_output = final_output<>"#{k}"
              if(Enum.any?(list_of_capacity)) do
                Enum.each(list_of_capacity, fn{k,v}->
                  final_output = final_output <>"#{k}"
                end)
              else
                final_output
              end
            end)
          else
            if(Enum.any?(list_of_capacity))do
              Enum.each(list_of_capacity, fn{k,v}->
                final_output = final_output<>"#{k}"
              end)
            else
              final_output
            end
          end
        end)
end
</code>```

I need to return this final output to another method.

```<code>list_of_outputs = process_output(vehicle_list,color_list_capacity_list)
</code>```

But could not find a way to generate the final output list

Desired O/P

```<code>["ToyotaC01S01","ToyotaC01S02","ToyotaC02S01","ToyotaC02S02",
 "HondaC01S01","HondaC01S02","HondaC02S01","HondaC02S02",...etc]
</code>```

答:
If You want to get possibilities of all keys of your desire variables, then you can get all possibilities by using 3 nested loop.

for example

```<code>Enum.map(list_of_vehicles,
  fn v -> (
    Enum.map(list_of_colors,
     fn c -> (
      Enum.map(list_of_capacities,
       fn cap ->(
        List.first(Map.keys v)<> List.first(Map.keys c) <> List.first(Map.keys cap))
       end)
      )
     end)
    )
  end
  )
|> List.flatten
</code>```

After looping you can flatten all your list and you will get desire output

```<code>#["ToyotaC01S01", "ToyotaC01S02", "ToyotaC02S01", "ToyotaC02S02", "HondaC01S01",
 "HondaC01S02", "HondaC02S01", "HondaC02S02"]
</code>```

Let me know if you didn't get the answer

Body:
I have the following set of Enum's as key value pairs

list_of_vehicles = [{"Toyota" => "Corolla"},{"Honda"=> "Insight"}]
list_of_colors = [{"C01"=> "Green"},{"C02"=> "White"}]
list_of_capacity = [{"S01"=> "4"},{"S02"=> "2"}]

I need to iterate through each list and generate a single string with all possibilities.

So far i have done following :

defp process_output(list_of_vehicles,list_of_colors,list_of_capacity)
    Enum.each(list_of_vehicles, fn{k,v}->
          final_output = "#{k}"
          if(Enum.any?(list_of_colors)) do
            Enum.each(list_of_colors, fn{k,v}->
              final_output = final_output<>"#{k}"
              if(Enum.any?(list_of_capacity)) do
                Enum.each(list_of_capacity, fn{k,v}->
                  final_output = final_output <>"#{k}"
                end)
              else
                final_output
              end
            end)
          else
            if(Enum.any?(list_of_capacity))do
              Enum.each(list_of_capacity, fn{k,v}->
                final_output = final_output<>"#{k}"
              end)
            else
              final_output
            end
          end
        end)
end

I need to return this final output to another method.

list_of_outputs = process_output(vehicle_list,color_list_capacity_list)

But could not find a way to generate the final output list

Desired O/P

["ToyotaC01S01","ToyotaC01S02","ToyotaC02S01","ToyotaC02S02",
 "HondaC01S01","HondaC01S02","HondaC02S01","HondaC02S02",...etc]

Body:
If You want to get possibilities of all keys of your desire variables, then you can get all possibilities by using 3 nested loop.

for example

Enum.map(list_of_vehicles,
  fn v -> (
    Enum.map(list_of_colors,
     fn c -> (
      Enum.map(list_of_capacities,
       fn cap ->(
        List.first(Map.keys v)<> List.first(Map.keys c) <> List.first(Map.keys cap))
       end)
      )
     end)
    )
  end
  )
|> List.flatten

After looping you can flatten all your list and you will get desire output

#["ToyotaC01S01", "ToyotaC01S02", "ToyotaC02S01", "ToyotaC02S02", "HondaC01S01",
 "HondaC01S02", "HondaC02S01", "HondaC02S02"]

Let me know if you didn't get the answer


问:
Tell When a UIPageViewController is Scrolling (for Parallax Scrolling of an Image)
I am trying to make an effect similar to that found in the new Yahoo weather app. Basically, each page in the UIPageViewController has a background image, and when scrolling through the page view, the Image's location only scrolls about half the speed. How would I do that? I thought I could use some sort of Delegate Method in the UIPageViewController to get the current offset and then update the images like that. The only problem is that I cannot find anyway to tell if the UIPageViewController is being scrolled! Is there a method for that? Thanks!

答:
```<code>extension UIPageViewController {

    var scrollView: UIScrollView? {

        return view.subviews.filter { $0 is UIScrollView }.first as? UIScrollView
    }
}
</code>```

Using:

```<code>pageController.scrollView?.delegate = self
</code>```

Body:
extension UIPageViewController {

    var scrollView: UIScrollView? {

        return view.subviews.filter { $0 is UIScrollView }.first as? UIScrollView
    }
}

Using:

pageController.scrollView?.delegate = self


问:
build-impl.xml:1045: NetBeans
After running the project I'm getting this error, My NetBeans is newly installed and I just copied the project files from my other laptop.

Here's my log details:

```<code>Severe:   Exception while loading the app
Severe:   Undeployment failed for context /EntJavaProject
Severe:   Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: java.lang.ClassNotFoundException: com.javatpoint.MyListener
</code>```

答: I got it working now, what I did was I deleted and copied again the .java files. I also realized that there's a duplicate file in src package so I think that's the reason why the project isn't deploying.</p>

Title: build-impl.xml:1045: NetBeans

Body:
After running the project I'm getting this error, My NetBeans is newly installed and I just copied the project files from my other laptop.

Here's my log details:

Severe:   Exception while loading the app
Severe:   Undeployment failed for context /EntJavaProject
Severe:   Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: java.lang.ClassNotFoundException: com.javatpoint.MyListener


问:
Why change xml file in Eclipse project will trigger project auto build
If there is a xml file in a Eclipse java project, and with "build Automatically" enabled, every time I change the xml file, and save, it will trigger Eclipse to build the project, and sometimes it cause much time to finish.

I just thought that xml files are just resource files, or at least it is not code change and should not trigger project build. What's the reason for this, and is there anyway to disable it?

答:
You are right there xml files are resource files. If the project code depends on the xml listed resource and there is some change in the xml file, auto build gets triggered to verify if the valid resource is available to the project, if not it shows warnings, or errors as the case may be.

To stop auto build in Eclipse:
Window > Preferences > General > Workspace > Uncheck the checkbox 'Build automatically'


问:
Print out all subsets in an array that equal an given sum recursively
I have a weird homework that I have to write a program with a method that takes an array of non-negative integers (array elements can have repeated values) and a value sum as parameters. The method then prints out all the combinations of the elements in array whose sum is equal to sum. The weird part is, the teacher forces us to strictly follow the below structure:

```<code>public class Combinations {

    public static void printCombinations(int[] arr, int sum) {
       // Body of the method
    }

    public static void main(String[] args) {
       // Create 2-3 arrays of integers and 2-3 sums here then call the above
       // method with these arrays and sums to test the correctness of your method
    }

}
</code>```

We are not allow to add neither more methods nor more parameters for the current program. I have researched and understood several ways to do this recursively, but with this restriction, I don't really know how to do it. Therefore, I appreciate if you guys help me out.

EDIT: The array can have repeated elements. Here's an example run of the program.

```<code>arr = {1, 3, 2, 2, 25} and sum = 3
</code>```

Outputs:

(1, 2)  // 1st and 3rd element

(1, 2) // 1st and 4th element

(3) // 2nd element

答:
This is extremely suited for recursive algorithm.

Think about function, let's call it fillRemaining, that gets the current state of affairs in parameters. For example, usedItems would be a list that holds the items that were already used, availableItems would be a list that holds the items that haven't been tried, currentSum would be the sum of usedItems and goal would be the sum you are searching for.

Then, in each call of fillRemaining, you just have to walk over availableItems and check each one of them. If currentSum + item == goal, you have found a solution. If currentSum + item > goal, you skip the item because it's too large. If currentSum + item < goal, you add item to usedItems and remove it from availableItems, and call fillRemaining again. Of course, in this call currentSum should also be increased by item.

So in printCombinations, you initialize availableItems to contain all elements of arr, and usedItems to empty list. You set currentSum to 0 and goal to sum, and call fillRemaining. It should do the magic.

With the restriction of not being able to add any other methods or parameters, you can also make fields for availableItems, usedItems, currentSum and goal. This way, you don't have to pass them as parameters, but you can still use them. The fields will have to be static, and you would set them in main as described above.

If neither adding fields is allowed, then you have to somehow simulate nested loops with variable depth. In effect, this simulates what would otherwise be passed via stack, but the algorithm is still the same.

In effect, this algorithm would do a depth-first search of (pruned) tree of all possible combinations. Beware however, that there are 2^n combinations, so the time complexity is also O(2^n).

Body:
I have a weird homework that I have to write a program with a method that takes an array of non-negative integers (array elements can have repeated values) and a value sum as parameters. The method then prints out all the combinations of the elements in array whose sum is equal to sum. The weird part is, the teacher forces us to strictly follow the below structure:

public class Combinations {

    public static void printCombinations(int[] arr, int sum) {
       // Body of the method
    }

    public static void main(String[] args) {
       // Create 2-3 arrays of integers and 2-3 sums here then call the above
       // method with these arrays and sums to test the correctness of your method
    }

}

We are not allow to add neither more methods nor more parameters for the current program. I have researched and understood several ways to do this recursively, but with this restriction, I don't really know how to do it. Therefore, I appreciate if you guys help me out.

EDIT: The array can have repeated elements. Here's an example run of the program.

arr = {1, 3, 2, 2, 25} and sum = 3

Outputs:

(1, 2)  // 1st and 3rd element

(1, 2) // 1st and 4th element

(3) // 2nd element


问:
How can i get my program to remove from end of list instead of start in python
```<code>class Node:
    def __init__(self):
        self.data = None
        self.next = None

class Stack:

    def __init__(self):
        self.size = 0
        self.head = None
        self.tail = None

    def append(self, data):
        node = Node()
        node.data = data
        if not self.head:
            self.head = node
            self.tail = node
            self.size = 1
            return
        self.tail.next = node
        self.tail = node
        self.size += 1

    def __repr__(self):
        return 'Stack(%s)' % str(self)

    def __iter__(self):
        current = self.head
        while current:
            yield current.data
            current = current.next

    def __str__(self):
        return '[%s]' % ', '.join([x for x in self])

    def __len__(self):
        return self.size

    def pop(self):
        data = self.head.data
        self.head = self.head.next
        return data

if __name__ == '__main__':
    list = Stack()

    reply = 0

    while reply!="5":

        print("1. Add to list")
        print("2. Display list")
        print("3. Size of list")
        print("4. Remove from list")
        print("5. Exit")

        reply = int(input("what would you like to do?"))

        if reply == 1:
            data = input("Add an element:")
            list.append(data)
        if reply == 2:
            print(list)
        if reply == 3:
            print(len(list))
        if reply == 4:
            list.pop()

        if reply == 5:
            print("good bye")
</code>```

I'm a fairly new to python , and for a class assignment i have been asked to implement a stack linked list with interface, i understand the basics of a linked list however, when i press 4 it should remove the last element which i have inputted , however it removes the first which is not (stack - last in first out)
Any help would be appreciated .

答:
Try using:

```<code>del l[-1]
</code>```

Instead of pop, because in pop it removes the head data.

Body:
class Node:
    def __init__(self):
        self.data = None
        self.next = None

class Stack:

    def __init__(self):
        self.size = 0
        self.head = None
        self.tail = None

    def append(self, data):
        node = Node()
        node.data = data
        if not self.head:
            self.head = node
            self.tail = node
            self.size = 1
            return
        self.tail.next = node
        self.tail = node
        self.size += 1

    def __repr__(self):
        return 'Stack(%s)' % str(self)

    def __iter__(self):
        current = self.head
        while current:
            yield current.data
            current = current.next

    def __str__(self):
        return '[%s]' % ', '.join([x for x in self])

    def __len__(self):
        return self.size

    def pop(self):
        data = self.head.data
        self.head = self.head.next
        return data

if __name__ == '__main__':
    list = Stack()

    reply = 0

    while reply!="5":

        print("1. Add to list")
        print("2. Display list")
        print("3. Size of list")
        print("4. Remove from list")
        print("5. Exit")

        reply = int(input("what would you like to do?"))

        if reply == 1:
            data = input("Add an element:")
            list.append(data)
        if reply == 2:
            print(list)
        if reply == 3:
            print(len(list))
        if reply == 4:
            list.pop()

        if reply == 5:
            print("good bye")

I'm a fairly new to python , and for a class assignment i have been asked to implement a stack linked list with interface, i understand the basics of a linked list however, when i press 4 it should remove the last element which i have inputted , however it removes the first which is not (stack - last in first out)
Any help would be appreciated .

Body:
Try using:

del l[-1]

Instead of pop, because in pop it removes the head data.


问:
Adding the quantities of products in a dataframe column in Python
I'm trying to calculate the sum of weights in a column of an excel sheet that contains the product title with the help of Numpy/Pandas. I've already managed to load the sheet into a dataframe, and isolate the rows that contain the particular product that I'm looking for:

```<code>dframe = xlsfile.parse('Sheet1')
dfFent = dframe[dframe['Product:'].str.contains("ABC") == True]
</code>```

But, I can't seem to find a way to sum up its weights, due to the obvious complexity of the problem (as shown below). For eg. if the column 'Product Title' contains values like -

1 gm ABC

98% pure 12 grams ABC

0.25 kg ABC Powder

ABC 5gr

where, ABC is the product whose weight I'm looking to add up. Is there any way that I can add these weights all up to get a total of 268 gm. Any help or resources pointing to the solution would be highly appreciated. Thanks! :)

答:
You can use extractall for values with units or percentage:

(?P\d+\.\d+|\d+) means extract float or int to column a

\s* - is zero or more spaces between number and unit

(?P[a-z%]+) is extract lowercase unit or percentage after number to b

```<code>#add all possible units to dictonary
d = {'gm':1,'gr':1,'grams':1,'kg':1000,'%':.01}
df1 =  df['Product:'].str.extractall('(?P<a>\d+\.\d+|\d+)\s*(?P<b>[a-z%]+)')
print (df1)
            a      b
  match
0 0         1     gm
1 0        98      %
  1        12  grams
2 0      0.25     kg
3 0         5     gr
</code>```

Then convert first column to numeric and second map by dictionary of all units. Then reshape by unstack and multiple columns by prod, last sum:

```<code>a = df1['a'].astype(float).mul(df1['b'].map(d)).unstack().prod(axis=1).sum()
print (a)
267.76
</code>```

Similar solution:

```<code>a = df1['a'].astype(float).mul(df1['b'].map(d)).prod(level=0).sum()
</code>```

Body:
I'm trying to calculate the sum of weights in a column of an excel sheet that contains the product title with the help of Numpy/Pandas. I've already managed to load the sheet into a dataframe, and isolate the rows that contain the particular product that I'm looking for:

dframe = xlsfile.parse('Sheet1')
dfFent = dframe[dframe['Product:'].str.contains("ABC") == True]

But, I can't seem to find a way to sum up its weights, due to the obvious complexity of the problem (as shown below). For eg. if the column 'Product Title' contains values like -

1 gm ABC

98% pure 12 grams ABC

0.25 kg ABC Powder

ABC 5gr

where, ABC is the product whose weight I'm looking to add up. Is there any way that I can add these weights all up to get a total of 268 gm. Any help or resources pointing to the solution would be highly appreciated. Thanks! :)

Body:
You can use extractall for values with units or percentage:

(?P<a>\d+\.\d+|\d+) means extract float or int to column a

\s* - is zero or more spaces between number and unit

(?P<b>[a-z%]+) is extract lowercase unit or percentage after number to b

#add all possible units to dictonary
d = {'gm':1,'gr':1,'grams':1,'kg':1000,'%':.01}
df1 =  df['Product:'].str.extractall('(?P<a>\d+\.\d+|\d+)\s*(?P<b>[a-z%]+)')
print (df1)
            a      b
  match
0 0         1     gm
1 0        98      %
  1        12  grams
2 0      0.25     kg
3 0         5     gr

Then convert first column to numeric and second map by dictionary of all units. Then reshape by unstack and multiple columns by prod, last sum:

a = df1['a'].astype(float).mul(df1['b'].map(d)).unstack().prod(axis=1).sum()
print (a)
267.76

Similar solution:

a = df1['a'].astype(float).mul(df1['b'].map(d)).prod(level=0).sum()


问:
scroll at the left when first open excel-macro
I have a macro and it perfectly run. however, the result is always shown at the right (latest column).

I tried to add the macro:

```<code>select.range("A1")
</code>```

or

```<code>Application.Goto Reference:="R1C1"
</code>```

and it still is not working.

Is there anyone know how to make the scroll bar at the left (column A) when first open?

答:
You're missing Scroll:=True from your code, to scroll the worksheet to the activated range.

Try this:

```<code>Application.Goto Reference:=Sheet1.Range("A1"), Scroll:=True
</code>```

Body:
I have a macro and it perfectly run. however, the result is always shown at the right (latest column).

I tried to add the macro:

select.range("A1")

or

Application.Goto Reference:="R1C1"

and it still is not working.

Is there anyone know how to make the scroll bar at the left (column A) when first open?

Body:
You're missing Scroll:=True from your code, to scroll the worksheet to the activated range.

Try this:

Application.Goto Reference:=Sheet1.Range("A1"), Scroll:=True


问:
MSSQL temp table returns all rows when using IN subquery
I recently stumbled upon this example. Why does query return all rows when using non-defined column on temp table "id". This only works for id and it only works when using IN subquery.</p>

```<code>DECLARE @test TABLE
( Id INT)

INSERT INTO @test
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3

SELECT * FROM @test

SELECT 1 AS 'myid'
INTO #tmpId

--Returns one rows - OK
SELECT * FROM @test WHERE id in (SELECT myId FROM #tmpId)
--Returns all rowns - WHY
SELECT * FROM @test WHERE id in (SELECT id FROM #tmpId)
--ERROR - no column - OK
SELECT * FROM @test WHERE id in (SELECT asdf FROM #tmpId)
--ERROR - no column - OK
SELECT id FROM #tmpId

DROP TABLE #tmpId
</code>```

答:
Always use table aliases when you have multiple tables.  The first query should be written as:

```<code>SELECT t.* FROM @test t WHERE t.id in (SELECT tt.myid FROM #tmpId tt)
</code>```

This does what you want.

If you write the second query as:

```<code>SELECT t.* FROM @test t WHERE t.id in (SELECT tt.id FROM #tmpId tt)
</code>```

You will get an error.  Your version is interpreted as a correlated subquery:

```<code>SELECT t.* FROM @test t WHERE t.id in (SELECT t.id FROM #tmpId tt)
</code>```

That is not what you want.  It is equivalent to:

```<code>SELECT t.* FROM @test t WHERE t.id IS NOT NULL;
</code>```

Body:
I recently stumbled upon this example. Why does query return all rows when using non-defined column on temp table "id". This only works for id and it only works when using IN subquery.

DECLARE @test TABLE
( Id INT)

INSERT INTO @test
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3

SELECT * FROM @test

SELECT 1 AS 'myid'
INTO #tmpId

--Returns one rows - OK
SELECT * FROM @test WHERE id in (SELECT myId FROM #tmpId)
--Returns all rowns - WHY
SELECT * FROM @test WHERE id in (SELECT id FROM #tmpId)
--ERROR - no column - OK
SELECT * FROM @test WHERE id in (SELECT asdf FROM #tmpId)
--ERROR - no column - OK
SELECT id FROM #tmpId

DROP TABLE #tmpId

Body:
Always use table aliases when you have multiple tables.  The first query should be written as:

SELECT t.* FROM @test t WHERE t.id in (SELECT tt.myid FROM #tmpId tt)

This does what you want.

If you write the second query as:

SELECT t.* FROM @test t WHERE t.id in (SELECT tt.id FROM #tmpId tt)

You will get an error.  Your version is interpreted as a correlated subquery:

SELECT t.* FROM @test t WHERE t.id in (SELECT t.id FROM #tmpId tt)

That is not what you want.  It is equivalent to:

SELECT t.* FROM @test t WHERE t.id IS NOT NULL;


问:
How to create Heterogenous Layouts from json response
Hi please help me inflate layout based on json response type
I am trying to merge http://androidcss.com/android/fetch-json-data-android/ this tutorial with this https://github.com/codepath/android_guides/wiki/Heterogenous-Layouts-inside-RecyclerView

But i'm facing some issues

my json response form

```<code>[
   { "type":"sports",
      "image":"http://example.com/image.jpg",
      "name":"Super Commando Dhruva"
   },
   {
"type":"health",
      "image":"http://example.com/image.jp",
      "name":"Parmanu"
   }
]
</code>```

MainActivity

```<code>package com.androidcss.jsonexample;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFishPrice;
    private AdapterFish mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Make call to AsyncTask
        new AsyncLogin().execute();
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                url = new URL("http://example.com/response.json");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }

        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();
            List<DataFeed> data=new ArrayList<>();

            pdLoading.dismiss();
            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFeed fishData = new DataFeed();
                    fishData.fishImage= json_data.getString("image");
                    fishData.fishName= json_data.getString("type");
                    fishData.catName= json_data.getString("name");
                   // fishData.sizeName= json_data.getString("size_name");
                    //fishData.price= json_data.getInt("price");
                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(MainActivity.this, data);
                mRVFishPrice.setAdapter(mAdapter);
                mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));

            } catch (JSONException e) {
                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }
}
</code>```

My adapter

```<code>package com.androidcss.jsonexample;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;

import java.util.Collections;
import java.util.List;

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataFeed> data= Collections.emptyList();
    DataFeed current;
    int currentPos=0;
    private final int USER = 0, IMAGE = 1;
    // create constructor to innitilize context and data sent from MainActivity
    public AdapterFish(Context context, List<DataFeed> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }

    @Override
    public int getItemViewType(int position) {
        DataFeed current=data.get(position);
        if (data.get(position) instanceof DataFeed) {
            return USER;
        } else if (data.get(position) instanceof String) {
            return IMAGE;
        }
        return -1;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        RecyclerView.ViewHolder viewHolder;
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());

        switch (viewType) {
            case USER:
                View v1 = inflater.inflate(R.layout.layout_viewholder1, viewGroup, false);
                viewHolder = new ViewHolder1(v1);
                break;
            case IMAGE:
                View v2 = inflater.inflate(R.layout.layout_viewholder2, viewGroup, false);
                viewHolder = new ViewHolder2(v2);
                break;
            default:
                View v = inflater.inflate(R.layout.container_fish, viewGroup, false);
                viewHolder = new MyHolder(v);
                break;
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        switch (viewHolder.getItemViewType()) {
            case USER:
                ViewHolder1 vh1 = (ViewHolder1) viewHolder;
                configureViewHolder1(vh1, position);
                break;
            case IMAGE:
                ViewHolder2 vh2 = (ViewHolder2) viewHolder;
                configureViewHolder2 (vh2, position, int);
                break;
            //default:
              //  RecyclerViewSimpleTextViewHolder vh = (RecyclerViewSimpleTextViewHolder) viewHolder;
               // configureDefaultViewHolder(vh, position);
               // break;
        }
    }

    //private void configureDefaultViewHolder(RecyclerViewSimpleTextViewHolder vh, int position) {
      //  vh.getLabel().setText((CharSequence) items.get(position));
    //}

    private void configureViewHolder1(ViewHolder1 vh1, int position) {
        DataFeed current =  data.get(position);
        if (current != null) {
            vh1.getLabel1().setText("Name: " + current.fishName);
            //vh1.getLabel2().setText("Hometown: " + current.hometown);
        }
    }

    private void configureViewHolder2(ViewHolder2 vh2) {
        vh2.getImageView().setImageResource(R.drawable.robbie);
    }

    class MyHolder extends RecyclerView.ViewHolder{

        TextView textFishName;
        ImageView ivFish;
        TextView textSize;
        TextView textType;
        TextView textPrice;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            textFishName= (TextView) itemView.findViewById(R.id.textFishName);
            ivFish= (ImageView) itemView.findViewById(R.id.banner);

        }

    }

}
</code>```

答:
Try this </p>

```<code>String type="sports";
String type1="health";

JSONObject json_data = jArray.getJSONObject(i);

type = json_data.getString("type");

if (Objects.equals(type,type)){
    fishData.fishImage= json_data.getString("image");
}

else if (Objects.equals(type,type1)){
    fishData.fishImage= json_data.getString("image");
}
</code>```

Body:
Hi please help me inflate layout based on json response type
I am trying to merge http://androidcss.com/android/fetch-json-data-android/ this tutorial with this https://github.com/codepath/android_guides/wiki/Heterogenous-Layouts-inside-RecyclerView

But i'm facing some issues

my json response form

[
   { "type":"sports",
      "image":"http://example.com/image.jpg",
      "name":"Super Commando Dhruva"
   },
   {
"type":"health",
      "image":"http://example.com/image.jp",
      "name":"Parmanu"
   }
]

MainActivity

package com.androidcss.jsonexample;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFishPrice;
    private AdapterFish mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Make call to AsyncTask
        new AsyncLogin().execute();
    }

    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                url = new URL("http://example.com/response.json");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }

        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();
            List<DataFeed> data=new ArrayList<>();

            pdLoading.dismiss();
            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFeed fishData = new DataFeed();
                    fishData.fishImage= json_data.getString("image");
                    fishData.fishName= json_data.getString("type");
                    fishData.catName= json_data.getString("name");
                   // fishData.sizeName= json_data.getString("size_name");
                    //fishData.price= json_data.getInt("price");
                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(MainActivity.this, data);
                mRVFishPrice.setAdapter(mAdapter);
                mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));

            } catch (JSONException e) {
                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }
}

My adapter

package com.androidcss.jsonexample;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;

import java.util.Collections;
import java.util.List;

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataFeed> data= Collections.emptyList();
    DataFeed current;
    int currentPos=0;
    private final int USER = 0, IMAGE = 1;
    // create constructor to innitilize context and data sent from MainActivity
    public AdapterFish(Context context, List<DataFeed> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }

    @Override
    public int getItemViewType(int position) {
        DataFeed current=data.get(position);
        if (data.get(position) instanceof DataFeed) {
            return USER;
        } else if (data.get(position) instanceof String) {
            return IMAGE;
        }
        return -1;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        RecyclerView.ViewHolder viewHolder;
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());

        switch (viewType) {
            case USER:
                View v1 = inflater.inflate(R.layout.layout_viewholder1, viewGroup, false);
                viewHolder = new ViewHolder1(v1);
                break;
            case IMAGE:
                View v2 = inflater.inflate(R.layout.layout_viewholder2, viewGroup, false);
                viewHolder = new ViewHolder2(v2);
                break;
            default:
                View v = inflater.inflate(R.layout.container_fish, viewGroup, false);
                viewHolder = new MyHolder(v);
                break;
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        switch (viewHolder.getItemViewType()) {
            case USER:
                ViewHolder1 vh1 = (ViewHolder1) viewHolder;
                configureViewHolder1(vh1, position);
                break;
            case IMAGE:
                ViewHolder2 vh2 = (ViewHolder2) viewHolder;
                configureViewHolder2 (vh2, position, int);
                break;
            //default:
              //  RecyclerViewSimpleTextViewHolder vh = (RecyclerViewSimpleTextViewHolder) viewHolder;
               // configureDefaultViewHolder(vh, position);
               // break;
        }
    }

    //private void configureDefaultViewHolder(RecyclerViewSimpleTextViewHolder vh, int position) {
      //  vh.getLabel().setText((CharSequence) items.get(position));
    //}

    private void configureViewHolder1(ViewHolder1 vh1, int position) {
        DataFeed current =  data.get(position);
        if (current != null) {
            vh1.getLabel1().setText("Name: " + current.fishName);
            //vh1.getLabel2().setText("Hometown: " + current.hometown);
        }
    }

    private void configureViewHolder2(ViewHolder2 vh2) {
        vh2.getImageView().setImageResource(R.drawable.robbie);
    }

    class MyHolder extends RecyclerView.ViewHolder{

        TextView textFishName;
        ImageView ivFish;
        TextView textSize;
        TextView textType;
        TextView textPrice;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            textFishName= (TextView) itemView.findViewById(R.id.textFishName);
            ivFish= (ImageView) itemView.findViewById(R.id.banner);

        }

    }

}

Body:
Try this

String type="sports";
String type1="health";

JSONObject json_data = jArray.getJSONObject(i);

type = json_data.getString("type");

if (Objects.equals(type,type)){
    fishData.fishImage= json_data.getString("image");
}

else if (Objects.equals(type,type1)){
    fishData.fishImage= json_data.getString("image");
}


问:
Webmethod Stops Working
I,m trying to pass value from jquery to webmethod. but when ever 1 pass value webmethod does not starts. and when i remove the passing value code it starts working properly What is the problem?
JS code.

```<code>$(function () {
    $.ajax({
        type: "POST",
        url: "ContryCityDDL.aspx/GetCountry",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var ddlcontry = $("[id*=ddlcontry]");
            ddlcontry.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(r.d, function () {
                ddlcontry.append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        }
    });

    $("#ddlcontry").change(function () {
        alert($('option:selected', $(this)).val());
       var countyId = $(this).val();

        $("#HiddenField1").val($('option:selected', $(this)).val());

        $.ajax({
            type: "POST",
            url: "ContryCityDDL.aspx/GetCity&countryId='"+countryId+"'",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                var ddlcity = $("[id*=ddlcity]");
                ddlcity.empty().append('<option selected="selected" value="0">Please select</option>');
                $.each(r.d, function () {
                    ddlcity.append($("<option></option>").val(this['Value']).html(this['Text']));
                });
            }
        });
    });
});
</code>```

C#

```<code>[WebMethod]
public static List<ListItem> GetCity(string countryId)
{

    string constrng;
            string query = "Select CityId,CityName From City";
    //string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

     constrng = "Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Desktop\\DropdownAJAX\\DropdownAJAX\\App_Data\\ContryCity.mdf';Integrated Security=True";

    using (SqlConnection con = new SqlConnection(constrng))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            List<ListItem> customers = new List<ListItem>();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(new ListItem
                    {
                        Value = sdr["CityId"].ToString(),
                        Text = sdr["CityName"].ToString()
                    });
                }
            }
            con.Close();
            return customers;
        }
    }
}
</code>```

when i remove 'string countryId' from c# code and  `var countyId = $(this).val();&countryId='"+countryId+"'" from js the code runs properly.

答:
You want to pass the ContryId as query string from your ajax call and in that case use ? character and not & like

```<code>"ContryCityDDL.aspx/GetCity?countryId='"
</code>```

Title: Webmethod Stops Working

Body:
I,m trying to pass value from jquery to webmethod. but when ever 1 pass value webmethod does not starts. and when i remove the passing value code it starts working properly What is the problem?
JS code.

$(function () {
    $.ajax({
        type: "POST",
        url: "ContryCityDDL.aspx/GetCountry",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var ddlcontry = $("[id*=ddlcontry]");
            ddlcontry.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(r.d, function () {
                ddlcontry.append($("<option></option>").val(this['Value']).html(this['Text']));
            });
        }
    });

    $("#ddlcontry").change(function () {
        alert($('option:selected', $(this)).val());
       var countyId = $(this).val();

        $("#HiddenField1").val($('option:selected', $(this)).val());

        $.ajax({
            type: "POST",
            url: "ContryCityDDL.aspx/GetCity&countryId='"+countryId+"'",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                var ddlcity = $("[id*=ddlcity]");
                ddlcity.empty().append('<option selected="selected" value="0">Please select</option>');
                $.each(r.d, function () {
                    ddlcity.append($("<option></option>").val(this['Value']).html(this['Text']));
                });
            }
        });
    });
});

C#

[WebMethod]
public static List<ListItem> GetCity(string countryId)
{

    string constrng;
            string query = "Select CityId,CityName From City";
    //string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

     constrng = "Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Desktop\\DropdownAJAX\\DropdownAJAX\\App_Data\\ContryCity.mdf';Integrated Security=True";

    using (SqlConnection con = new SqlConnection(constrng))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            List<ListItem> customers = new List<ListItem>();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(new ListItem
                    {
                        Value = sdr["CityId"].ToString(),
                        Text = sdr["CityName"].ToString()
                    });
                }
            }
            con.Close();
            return customers;
        }
    }
}

when i remove 'string countryId' from c# code and  `var countyId = $(this).val();&countryId='"+countryId+"'" from js the code runs properly.

Body:
You want to pass the ContryId as query string from your ajax call and in that case use ? character and not & like

"ContryCityDDL.aspx/GetCity?countryId='"


问:
Custom CIColorKernel in Xamarin IOS
I'm trying to create a functionnality in Xamarin Forms that allow the application to change [1..N] colors to [1..N] of an images.

Example:

Change all blue & purple pixels to yellow & orange pixels

After some investigation, It seems that I need to create a custom CIColorKernel to achieve it.

The problem is that is very difficult to find examples and the documentation is light.

If someone have a tutorial or a basic example to start...

Thanks

EDIT :

I implemented the soutioion of @SushiHangover and I Call it in the second method of the code sample :

```<code> private IImageSourceHandler GetHandler(ImageSource source)
        {
            IImageSourceHandler returnValue = null;
            if (source is UriImageSource)
            {
                returnValue = new ImageLoaderSourceHandler();
            }
            else if (source is FileImageSource)
            {
                returnValue = new FileImageSourceHandler();
            }
            else if (source is StreamImageSource)
            {
                returnValue = new StreamImagesourceHandler();
            }
            return returnValue;
        }

        public async Task<ImageSource> ChangeImageColor(ImageSource source, string oldColor, string newColor)
        {
            var handler = GetHandler(source);
            var uiImage = (UIImage)null;

            uiImage = await handler.LoadImageAsync(source);
            UIImage uiImageOutput = null;

            using (var context = new EAGLContext(EAGLRenderingAPI.OpenGLES3))
            using (var filter = new ColorReplaceFilter
            {
                InputImage = new CIImage(uiImage),
                MatchColor = CIColor.FromRgb(200, 200, 200),
                ReplaceWithColor = CIColor.RedColor,
                Threshold = 1f // Exact match, values >0 & <=1 to make a fuzzy match
            })
            {
                uiImageOutput = UIImage.FromImage(filter.OutputImage);
            }

            return Xamarin.Forms.ImageSource.FromStream(() => uiImageOutput.AsPNG().AsStream()); ;
        }
</code>```

This two methods are in a class named BitmapHelper that is called in Xamarin Forms project with Dependecy Injection.

```<code>var bitmap = DependencyService.Get<IBitmapHelper>().ChangeImageColor(AmbiancePicture.Source, oldColor, newColor);
            AmbiancePicture.Source = bitmap.Result;
</code>```

The result contains as expected the new Image but AmbiancePicture.Source but is not updated.

Here the image I try to change :

EDIT 2 :

If I set the AmbiancePicture.Source to null before the update, The image stay empty.
The image seems to not be empty ( I see some correct properties in the stream ).

WORKING EDIT :

So after the error comes from the UIImage creation and convertion.

This is the working code :

```<code>  using (var context = new EAGLContext(EAGLRenderingAPI.OpenGLES3))
            using (var filter = new ColorReplaceFilter
            {
                InputImage = new CIImage(uiImage),
                MatchColor = CIColor.FromString(oldColor),
                ReplaceWithColor = CIColor.FromString(newColor),
                Threshold = 1f // Exact match, values >0 & <=1 to make a fuzzy match
            })
           {
            var output = context.CreateCGImage(filter.OutputImage, filter.OutputImage.Extent); // This line is slow...
            var img = UIImage.FromImage(output);
            jpegData = img.AsJPEG(1.0f);

        }
        return Xamarin.Forms.ImageSource.FromStream(() => jpegData.AsStream());
</code>```

答:
Change all blue & purple pixels to yellow & orange pixels

Lets break that down into two distinct steps:

blue pixels to yellow pixels

purple pixels to orange pixels

This means we need just one CIFilter that changes a single color to another color and we can chain two (or more) of those filter together to change as many colors as needed.

In terms of a custom CIFilter, if we are changing only the color, we can use a CIColorKernel to process this on a GPU or a CPU vector unit (the OS will determine which one based on availability and kernel features requested). CIKernel subclasses use a modified version of GLSL (OpenGL Shading Language) as the language in a kernel (this code gets compiled at runtime as each device might have a different CPU and/or GPU).

So we need a CIColorKernel function that accepts the source "color" in RGA8 format as a vec4, a vec4 that represents the color to match, another vec4 to represent the color to change to if the source vec4 matches. Also we can supply a threshold that provides how "close" the original color needs to be (like chroma-keying). Taking all that and writing some GLSL, we get:

```<code>kernel vec4 main(__sample s, __color o, __color r, float threshold) {
    vec4 diff = s.rgba - o;
    float distance = length( diff );
    float alpha = compare( distance - threshold, 0.0, 1.0 );
     if (alpha == 0.0)
        return r;
     return s;
}
</code>```

Now we need a CIFilter subclass to create/compile that kernel and provide the Core Image inputs and outputs to that kernel:

```<code>public class ColorReplaceFilter : CIFilter
{
    const string filterName = "colorReplace";
    const int numArgs = 4;
    const string coreImageShaderProgram =
        @"
            kernel vec4 main(__sample s, __color o, __color r, float threshold) {
                vec4 diff = s.rgba - o;
                float distance = length( diff );
                float alpha = compare( distance - threshold, 0.0, 1.0 );
                 if (alpha == 0.0)
                    return r;
                 return s;
            }
        ";

    NSObject[] arguments;
    CIColorKernel colorKernel;

    public ColorReplaceFilter() { Initializer(); }
    public ColorReplaceFilter(NSCoder coder) : base(coder) { Initializer(); }
    public ColorReplaceFilter(NSObjectFlag t) : base(t) { Initializer(); }
    public ColorReplaceFilter(IntPtr handle) : base(handle) { Initializer(); }

    public CIImage InputImage { get; set; }
    public CIColor MatchColor { get; set; }
    public CIColor ReplaceWithColor { get; set; }

    NSNumber _threshold;
    public nfloat Threshold
    {
        get { return _threshold.NFloatValue; }
        set { _threshold = NSNumber.FromNFloat(value); }
    }

    void Initializer()
    {
        arguments = new NSObject[numArgs];
        colorKernel = CIColorKernel.FromProgramSingle(coreImageShaderProgram);
        MatchColor = CIColor.WhiteColor;
        ReplaceWithColor = CIColor.WhiteColor;
        _threshold = new NSNumber(0.2f);
    }

    public override string Name
    {
        get => filterName;
    }

    public override CIImage OutputImage
    {
        get => CreateOutputImage();
    }

    CIImage CreateOutputImage()
    {
        if (InputImage != null) // Avoid object creation to allow fast filter chaining
        {
            arguments[0] = InputImage as NSObject;
            arguments[1] = MatchColor as NSObject;
            arguments[2] = ReplaceWithColor as NSObject;
            arguments[3] = _threshold as NSObject;
            var ciImage = colorKernel.ApplyWithExtent(InputImage.Extent, arguments);
            return ciImage;
        }
        return null;
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        arguments = null;
        InputImage = null;
        MatchColor = null;
        ReplaceWithColor = null;
        colorKernel.Dispose();
    }
}
</code>```

A simple CIContext example:

```<code>var uiImageInput = inputVIew.Image;
UIImage uiImageOutput;
using (var context = CIContext.Create())
using (var filter = new ColorReplaceFilter
{
    InputImage = new CIImage(uiImageInput),
    MatchColor = CIColor.BlueColor,
    ReplaceWithColor = CIColor.RedColor,
    Threshold = 0.0f // Exact match, values >0 & <=1 to make a fuzzy match
})
{
    uiImageOutput  = UIImage.FromImage(filter.OutputImage);
}
// Do something with your new uiImageOutput
</code>```

Note: There are EAGLContext based contexts also if you have special needs for real-time image/video processing.

Note: As creating a context has overhead, you do not need the CIContext if you are rendering that CIImage directly to a UIImage holder that already has a context. A UIImageView would have a context since it is displaying an image on the screen, so remove the context creation and create/assign the CIImage backed UIImage directly to the UIImageView:

```<code>aUIImageViewObject.Image = UIImage.FromImage(replaceFilter.OutputImage);
</code>```

In chaining filters, you take the CIImage output of one filter and apply that as the CIImage input to the next filter.

```<code>var uiImageInput = inputVIew.Image;
UIImage uiImageOutput;
using (var context = CIContext.Create())
using (var filter1 = new ColorReplaceFilter
{
    InputImage = new CIImage(uiImageInput),
    MatchColor = CIColor.BlueColor,
    ReplaceWithColor = CIColor.RedColor,
    Threshold = 0
})
using (var filter2 = new ColorReplaceFilter
{
    InputImage = filter1.OutputImage,
    MatchColor = CIColor.WhiteColor,
    ReplaceWithColor = CIColor.BlackColor,
    Threshold = 0
})
{
    uiImageOutput = UIImage.FromImage(filter2.OutputImage);
}
// Do something with your new UIImage
</code>```

As Apple puts it, a CIImage object is a “recipe” for producing an image and since we do not "render" a UIImage|CGImage until the end of the chain above, this chained filter rendering happens in one pass as we are only passing CIImages through the chain.

Note: If you are processing a number of images with different color replacements, create the CIFilters once and keep changing the CIImage input and replacement colors to process each image reusing the filters. When you are done remember to dispose the CIFilter(s). This way the GLSL kernel only has to be compiled once per filter for an unlimited number of input/output images.

Here is an example where the input colors of the filters are being changed. The filters are created and maintained a class level objects of the UIViewController and disposed of when the view controller is closed.

Another example using the threshold to interactively replace "blue" pixels with red.

Re:Core Image Kernel Language
Re: CIContext
Re: CIColorKernel

Title: Custom CIColorKernel in Xamarin IOS

Body:
I'm trying to create a functionnality in Xamarin Forms that allow the application to change [1..N] colors to [1..N] of an images.

Example:

Change all blue & purple pixels to yellow & orange pixels

After some investigation, It seems that I need to create a custom CIColorKernel to achieve it.

The problem is that is very difficult to find examples and the documentation is light.

If someone have a tutorial or a basic example to start...

Thanks

EDIT :

I implemented the soutioion of @SushiHangover and I Call it in the second method of the code sample :

 private IImageSourceHandler GetHandler(ImageSource source)
        {
            IImageSourceHandler returnValue = null;
            if (source is UriImageSource)
            {
                returnValue = new ImageLoaderSourceHandler();
            }
            else if (source is FileImageSource)
            {
                returnValue = new FileImageSourceHandler();
            }
            else if (source is StreamImageSource)
            {
                returnValue = new StreamImagesourceHandler();
            }
            return returnValue;
        }

        public async Task<ImageSource> ChangeImageColor(ImageSource source, string oldColor, string newColor)
        {
            var handler = GetHandler(source);
            var uiImage = (UIImage)null;

            uiImage = await handler.LoadImageAsync(source);
            UIImage uiImageOutput = null;

            using (var context = new EAGLContext(EAGLRenderingAPI.OpenGLES3))
            using (var filter = new ColorReplaceFilter
            {
                InputImage = new CIImage(uiImage),
                MatchColor = CIColor.FromRgb(200, 200, 200),
                ReplaceWithColor = CIColor.RedColor,
                Threshold = 1f // Exact match, values >0 & <=1 to make a fuzzy match
            })
            {
                uiImageOutput = UIImage.FromImage(filter.OutputImage);
            }

            return Xamarin.Forms.ImageSource.FromStream(() => uiImageOutput.AsPNG().AsStream()); ;
        }

This two methods are in a class named BitmapHelper that is called in Xamarin Forms project with Dependecy Injection.

var bitmap = DependencyService.Get<IBitmapHelper>().ChangeImageColor(AmbiancePicture.Source, oldColor, newColor);
            AmbiancePicture.Source = bitmap.Result;

The result contains as expected the new Image but AmbiancePicture.Source but is not updated.

Here the image I try to change :

EDIT 2 :

If I set the AmbiancePicture.Source to null before the update, The image stay empty.
The image seems to not be empty ( I see some correct properties in the stream ).

WORKING EDIT :

So after the error comes from the UIImage creation and convertion.

This is the working code :

  using (var context = new EAGLContext(EAGLRenderingAPI.OpenGLES3))
            using (var filter = new ColorReplaceFilter
            {
                InputImage = new CIImage(uiImage),
                MatchColor = CIColor.FromString(oldColor),
                ReplaceWithColor = CIColor.FromString(newColor),
                Threshold = 1f // Exact match, values >0 & <=1 to make a fuzzy match
            })
           {
            var output = context.CreateCGImage(filter.OutputImage, filter.OutputImage.Extent); // This line is slow...
            var img = UIImage.FromImage(output);
            jpegData = img.AsJPEG(1.0f);

        }
        return Xamarin.Forms.ImageSource.FromStream(() => jpegData.AsStream());

Body:
Change all blue & purple pixels to yellow & orange pixels

Lets break that down into two distinct steps:

blue pixels to yellow pixels

purple pixels to orange pixels

This means we need just one CIFilter that changes a single color to another color and we can chain two (or more) of those filter together to change as many colors as needed.

In terms of a custom CIFilter, if we are changing only the color, we can use a CIColorKernel to process this on a GPU or a CPU vector unit (the OS will determine which one based on availability and kernel features requested). CIKernel subclasses use a modified version of GLSL (OpenGL Shading Language) as the language in a kernel (this code gets compiled at runtime as each device might have a different CPU and/or GPU).

So we need a CIColorKernel function that accepts the source "color" in RGA8 format as a vec4, a vec4 that represents the color to match, another vec4 to represent the color to change to if the source vec4 matches. Also we can supply a threshold that provides how "close" the original color needs to be (like chroma-keying). Taking all that and writing some GLSL, we get:

kernel vec4 main(__sample s, __color o, __color r, float threshold) {
    vec4 diff = s.rgba - o;
    float distance = length( diff );
    float alpha = compare( distance - threshold, 0.0, 1.0 );
     if (alpha == 0.0)
        return r;
     return s;
}

Now we need a CIFilter subclass to create/compile that kernel and provide the Core Image inputs and outputs to that kernel:

public class ColorReplaceFilter : CIFilter
{
    const string filterName = "colorReplace";
    const int numArgs = 4;
    const string coreImageShaderProgram =
        @"
            kernel vec4 main(__sample s, __color o, __color r, float threshold) {
                vec4 diff = s.rgba - o;
                float distance = length( diff );
                float alpha = compare( distance - threshold, 0.0, 1.0 );
                 if (alpha == 0.0)
                    return r;
                 return s;
            }
        ";

    NSObject[] arguments;
    CIColorKernel colorKernel;

    public ColorReplaceFilter() { Initializer(); }
    public ColorReplaceFilter(NSCoder coder) : base(coder) { Initializer(); }
    public ColorReplaceFilter(NSObjectFlag t) : base(t) { Initializer(); }
    public ColorReplaceFilter(IntPtr handle) : base(handle) { Initializer(); }

    public CIImage InputImage { get; set; }
    public CIColor MatchColor { get; set; }
    public CIColor ReplaceWithColor { get; set; }

    NSNumber _threshold;
    public nfloat Threshold
    {
        get { return _threshold.NFloatValue; }
        set { _threshold = NSNumber.FromNFloat(value); }
    }

    void Initializer()
    {
        arguments = new NSObject[numArgs];
        colorKernel = CIColorKernel.FromProgramSingle(coreImageShaderProgram);
        MatchColor = CIColor.WhiteColor;
        ReplaceWithColor = CIColor.WhiteColor;
        _threshold = new NSNumber(0.2f);
    }

    public override string Name
    {
        get => filterName;
    }

    public override CIImage OutputImage
    {
        get => CreateOutputImage();
    }

    CIImage CreateOutputImage()
    {
        if (InputImage != null) // Avoid object creation to allow fast filter chaining
        {
            arguments[0] = InputImage as NSObject;
            arguments[1] = MatchColor as NSObject;
            arguments[2] = ReplaceWithColor as NSObject;
            arguments[3] = _threshold as NSObject;
            var ciImage = colorKernel.ApplyWithExtent(InputImage.Extent, arguments);
            return ciImage;
        }
        return null;
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        arguments = null;
        InputImage = null;
        MatchColor = null;
        ReplaceWithColor = null;
        colorKernel.Dispose();
    }
}

A simple CIContext example:

var uiImageInput = inputVIew.Image;
UIImage uiImageOutput;
using (var context = CIContext.Create())
using (var filter = new ColorReplaceFilter
{
    InputImage = new CIImage(uiImageInput),
    MatchColor = CIColor.BlueColor,
    ReplaceWithColor = CIColor.RedColor,
    Threshold = 0.0f // Exact match, values >0 & <=1 to make a fuzzy match
})
{
    uiImageOutput  = UIImage.FromImage(filter.OutputImage);
}
// Do something with your new uiImageOutput

Note: There are EAGLContext based contexts also if you have special needs for real-time image/video processing.

Note: As creating a context has overhead, you do not need the CIContext if you are rendering that CIImage directly to a UIImage holder that already has a context. A UIImageView would have a context since it is displaying an image on the screen, so remove the context creation and create/assign the CIImage backed UIImage directly to the UIImageView:

aUIImageViewObject.Image = UIImage.FromImage(replaceFilter.OutputImage);

In chaining filters, you take the CIImage output of one filter and apply that as the CIImage input to the next filter.

var uiImageInput = inputVIew.Image;
UIImage uiImageOutput;
using (var context = CIContext.Create())
using (var filter1 = new ColorReplaceFilter
{
    InputImage = new CIImage(uiImageInput),
    MatchColor = CIColor.BlueColor,
    ReplaceWithColor = CIColor.RedColor,
    Threshold = 0
})
using (var filter2 = new ColorReplaceFilter
{
    InputImage = filter1.OutputImage,
    MatchColor = CIColor.WhiteColor,
    ReplaceWithColor = CIColor.BlackColor,
    Threshold = 0
})
{
    uiImageOutput = UIImage.FromImage(filter2.OutputImage);
}
// Do something with your new UIImage

As Apple puts it, a CIImage object is a “recipe” for producing an image and since we do not "render" a UIImage|CGImage until the end of the chain above, this chained filter rendering happens in one pass as we are only passing CIImages through the chain.

Note: If you are processing a number of images with different color replacements, create the CIFilters once and keep changing the CIImage input and replacement colors to process each image reusing the filters. When you are done remember to dispose the CIFilter(s). This way the GLSL kernel only has to be compiled once per filter for an unlimited number of input/output images.

Here is an example where the input colors of the filters are being changed. The filters are created and maintained a class level objects of the UIViewController and disposed of when the view controller is closed.

Another example using the threshold to interactively replace "blue" pixels with red.

Re:Core Image Kernel Language
Re: CIContext
Re: CIColorKernel


问:
Type casting to datetime
I got data from JSON like "/Date(1285871400000)/" ,but i want to convert in "dd/mm/yyyy".</p>

答:
To answer my own question from the comments.. someone makes the effort to provide a solution (+ he is candidating to be a moderator on SO :p)</p>

```<code>var data     = "/Date(1285871400000)/",
    stamp    = /Date\((\d+)\)/.exec(data),
    date     = new Date(+stamp[1]);

alert(date.getDate() + "/" + date.getMonth() + "/" + date.getFullYear());
</code>```

Title: Type casting to datetime

Body:
To answer my own question from the comments.. someone makes the effort to provide a solution (+ he is candidating to be a moderator on SO :p)

var data     = "/Date(1285871400000)/",
    stamp    = /Date\((\d+)\)/.exec(data),
    date     = new Date(+stamp[1]);

alert(date.getDate() + "/" + date.getMonth() + "/" + date.getFullYear());


问:
import variables into stylus and scss
I use stylus and scss in my project.
Is it possible to have one common variables file that I can use with both?

I have tried:

variables.scss

```<code>$primary: #00A9E0
</code>```

main.styl

```<code>@import 'variables.scss"
</code>```

which obviously did not work because of the different syntax

答:
Move your variables to _variables.scss(partial file) and import it.
@import 'variables';

Title: import variables into stylus and scss

Body:
I use stylus and scss in my project.
Is it possible to have one common variables file that I can use with both?

I have tried:

variables.scss

$primary: #00A9E0

main.styl

@import 'variables.scss"

which obviously did not work because of the different syntax