问:
Dictionary of Optional Keys
Is there any workaround to create a dictionary with Optional keys? I know a proper solution for this would require Conditional Conformances to be implemented, but do I have any options before then?

```<code>let dict: [Int?: Int] = [nil: 1]
// ERROR: type 'Int?' does not conform to protocol 'Hashable'
</code>```

答:
Update: Swift 4.2

Conditional conformances have been implemented in Swift 4.2, woohoo!

This allowed for Optional to be made conditionally Hashable, when the wrapped element is Hashable. So you can use any Optional<T: Hashable> as a dictionary key, directly!

```<code>let d: [Int?: String] = [
    nil: "nil",
    1: "a",
    2: "b",
    3: "c",
]

for (key, value) in d {
    let stringKey = key.map(String.init(describing:)) ?? "nil"
    print("\(stringKey): \(value)")
}
</code>```

Before Swift 4.2

Here's one workaround I found: Create a new HashableOptional enum:

```<code>enum HashableOptional<Wrapped: Hashable> {
    case none
    case some(Wrapped)

    public init(_ some: Wrapped) {
        self = .some(some)
    }

    public init(_ optional: Wrapped?) {
        self = optional.map{ .some($0) } ?? .none
    }

    public var value: Wrapped? {
        switch self {
            case .none: return nil
            case .some(let wrapped): return wrapped
        }
    }
}

extension HashableOptional: Equatable {
    static func ==(lhs: HashableOptional, rhs: HashableOptional) -> Bool {
        switch (lhs, rhs) {
            case (.none, .none): return true
            case (.some(let a), .some(let b)): return a == b
            default: return false
        }
    }
}

extension HashableOptional: Hashable {
    var hashValue: Int {
        switch self {
            case .none: return 0
            case .some(let wrapped): return wrapped.hashValue
        }
    }
}

extension HashableOptional: ExpressibleByNilLiteral {
    public init(nilLiteral: ()) {
        self = .none
    }
}
</code>```

And then you can use it like so:

```<code>let dict: [HashableOptional<Int>: Int] = [nil: 1]
</code>```

Title: Dictionary of Optional Keys

Body:
Is there any workaround to create a dictionary with Optional keys? I know a proper solution for this would require Conditional Conformances to be implemented, but do I have any options before then?

let dict: [Int?: Int] = [nil: 1]
// ERROR: type 'Int?' does not conform to protocol 'Hashable'

Body:
Update: Swift 4.2

Conditional conformances have been implemented in Swift 4.2, woohoo!

This allowed for Optional to be made conditionally Hashable, when the wrapped element is Hashable. So you can use any Optional<T: Hashable> as a dictionary key, directly!

let d: [Int?: String] = [
    nil: "nil",
    1: "a",
    2: "b",
    3: "c",
]

for (key, value) in d {
    let stringKey = key.map(String.init(describing:)) ?? "nil"
    print("\(stringKey): \(value)")
}

Before Swift 4.2

Here's one workaround I found: Create a new HashableOptional enum:

enum HashableOptional<Wrapped: Hashable> {
    case none
    case some(Wrapped)

    public init(_ some: Wrapped) {
        self = .some(some)
    }

    public init(_ optional: Wrapped?) {
        self = optional.map{ .some($0) } ?? .none
    }

    public var value: Wrapped? {
        switch self {
            case .none: return nil
            case .some(let wrapped): return wrapped
        }
    }
}

extension HashableOptional: Equatable {
    static func ==(lhs: HashableOptional, rhs: HashableOptional) -> Bool {
        switch (lhs, rhs) {
            case (.none, .none): return true
            case (.some(let a), .some(let b)): return a == b
            default: return false
        }
    }
}

extension HashableOptional: Hashable {
    var hashValue: Int {
        switch self {
            case .none: return 0
            case .some(let wrapped): return wrapped.hashValue
        }
    }
}

extension HashableOptional: ExpressibleByNilLiteral {
    public init(nilLiteral: ()) {
        self = .none
    }
}

And then you can use it like so:

let dict: [HashableOptional<Int>: Int] = [nil: 1]


来源: stackexchange

问:
Xerces behaving differently on SUN JRE v1.5 and IBM J9 v1.5
I am trying to parse some HTML using NekoHTML.

The problem is that when the below code snippet is executed on the SUN JDK 1.5.0_01 it works fine (this is when i am using eclipse with sun jre). But when the same thing is executed on IBM J9 VM (build 2.3, J2RE 1.5.0 IBM J9 2.3 Windows XP x86-32 j9vmwi3223ifx-20070323 (JIT enabled) then it is not working (this is when i am using the IBM RAD for development).

```<code>NodeList tags = doc.getElementsByTagName("td");

for (int i = 0; i < tags.getLength(); i++)
{
 Element elem = (Element) tags.item(i);
 // do something with elem
}
</code>```

By working fine I mean that I am getting a list of "td" elements which I can process further. In case of the J9 I am not entering the for loop.

I am using latest version of NekoHTML (along with the bundled Xerces jars). The doc in the above code is of type org.w3.dom.Document (the runtime class used is org.apache.html.dom.HTMLDocumentImpl)

The IBM J9 details are as follows:

```<code>java version "1.5.0"
Java(TM) 2 Runtime Environment, Standard Edition (build pwi32devifx-20070323 (ifix 117674: SR4 + 116644 + 114941 + 116110 + 114881))
IBM J9 VM (build 2.3, J2RE 1.5.0 IBM J9 2.3 Windows XP x86-32 j9vmwi3223ifx-20070323 (JIT enabled)
J9VM - 20070322_12058_lHdSMR
JIT  - 20070109_1805ifx3_r8
GC   - WASIFIX_2007)
JCL  - 20070131
</code>```

Any idea, suggestion or workaround is appreciated. Thanks.

答:
I have 2 ideas.

I have just verified that xerces is a part of the JRE installation, so I believe it arrives to the classpath of your application from there. Probably SUN and IBM bring you different versions of xerces. So, as a first approach check it and probably try to replace what you have under IBM to the SUN's version. If it helps you have 2 options: continue running IBM java with xerces from SUN or continue to investigate what's wrong with xerces from IBM.

Are there other differences between your dev and production environments? Are these the same operating systems? Is it a chance that you are using (for example) windows for development and unix for production but your xml is written on Windows with \r\n as a new line? Or even more: if your XML contains unicode characters and written in windows it can contain special (invisible) prefix that indicates that this is unicode. This prefix may cause parser to fail.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to parse some HTML using NekoHTML.

The problem is that when the below code snippet is executed on the SUN JDK 1.5.0_01 it works fine (this is when i am using eclipse with sun jre). But when the same thing is executed on IBM J9 VM (build 2.3, J2RE 1.5.0 IBM J9 2.3 Windows XP x86-32 j9vmwi3223ifx-20070323 (JIT enabled) then it is not working (this is when i am using the IBM RAD for development).

NodeList tags = doc.getElementsByTagName("td");

for (int i = 0; i < tags.getLength(); i++)
{
 Element elem = (Element) tags.item(i);
 // do something with elem
}

By working fine I mean that I am getting a list of "td" elements which I can process further. In case of the J9 I am not entering the for loop.

I am using latest version of NekoHTML (along with the bundled Xerces jars). The doc in the above code is of type org.w3.dom.Document (the runtime class used is org.apache.html.dom.HTMLDocumentImpl)

The IBM J9 details are as follows:

java version "1.5.0"
Java(TM) 2 Runtime Environment, Standard Edition (build pwi32devifx-20070323 (ifix 117674: SR4 + 116644 + 114941 + 116110 + 114881))
IBM J9 VM (build 2.3, J2RE 1.5.0 IBM J9 2.3 Windows XP x86-32 j9vmwi3223ifx-20070323 (JIT enabled)
J9VM - 20070322_12058_lHdSMR
JIT  - 20070109_1805ifx3_r8
GC   - WASIFIX_2007)
JCL  - 20070131

Any idea, suggestion or workaround is appreciated. Thanks.


问:
Running java code in Android Studio
I just started learning java from a beginners book. The book shows how to do everything in Eclipse. I want to learn java in A.S. for making apps.
I finally compiled code in Android Stuido. I got errors when trying to run a java class file even though the code was perfect, until I found a post in here that sais you have to run it in debug mode.
Do I have to run all my "learning examples" in debug mode and select the spesific .java class, or do people do this another way? I Have no experience in coding.

example:

```<code>public class MyApplicationLeet {

    /**
     *
     * param args
     */

    public static void` main(String[] args) {
        System.out.println("Chocolate, royalties, sleep");
    }

}
</code>```

答: I think you are using ' mark after void  public static void main(String[] args) try this maybe you able to run this code.

ContentLicense: CC BY-SA 3.0

Title: Running java code in Android Studio

Body:
I just started learning java from a beginners book. The book shows how to do everything in Eclipse. I want to learn java in A.S. for making apps.
I finally compiled code in Android Stuido. I got errors when trying to run a java class file even though the code was perfect, until I found a post in here that sais you have to run it in debug mode.
Do I have to run all my "learning examples" in debug mode and select the spesific .java class, or do people do this another way? I Have no experience in coding.

example:

public class MyApplicationLeet {

    /**
     *
     * param args
     */

    public static void` main(String[] args) {
        System.out.println("Chocolate, royalties, sleep");
    }

}


问:
Reading pdf files line by line using python
I used the following code to read the pdf file, but it does not read it. What could possibly be the reason?

from PyPDF2 import PdfFileReader

reader = PdfFileReader("example.pdf")
contents = reader.pages[0].extractText().split("\n")
print(contents)
```

The output is [u''] instead of reading the content.

答:
Hello Rahul Pipalia,

If not install PyPDF2 in your python so first install PyPDF2 after use this module.

Installation Steps for Ubuntu (Install python-pypdf)

First, open terminal

After type sudo apt-get install python-pypdf

Your Probelm Solution

Try this below code,

```<code># Import Library
import PyPDF2

# Which you want to read file so give file name with ".pdf" extension
pdf_file = open('Your_Pdf_File_Name.pdf')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()

#Give page number of the pdf file (How many page in pdf file).
# @param Page_Nuber_of_the_PDF_file: Give page number here i.e 1
page = read_pdf.getPage(Page_Nuber_of_the_PDF_file)

page_content = page.extractText()

# Display content of the pdf
print page_content
</code>```

Download the PDF from below link and try this code,
https://www.dropbox.com/s/4qad66r2361hvmu/sample.pdf?dl=1

I hope my answer is helpful.

If any query so comments, please.

ContentLicense: CC BY-SA 4.0

Body:
I used the following code to read the pdf file, but it does not read it. What could possibly be the reason?

from PyPDF2 import PdfFileReader

reader = PdfFileReader("example.pdf")
contents = reader.pages[0].extractText().split("\n")
print(contents)

The output is [u''] instead of reading the content.

Body:
Hello Rahul Pipalia,

If not install PyPDF2 in your python so first install PyPDF2 after use this module.

Installation Steps for Ubuntu (Install python-pypdf)

First, open terminal

After type sudo apt-get install python-pypdf

Your Probelm Solution

Try this below code,

# Import Library
import PyPDF2

# Which you want to read file so give file name with ".pdf" extension
pdf_file = open('Your_Pdf_File_Name.pdf')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()

#Give page number of the pdf file (How many page in pdf file).
# @param Page_Nuber_of_the_PDF_file: Give page number here i.e 1
page = read_pdf.getPage(Page_Nuber_of_the_PDF_file)

page_content = page.extractText()

# Display content of the pdf
print page_content

Download the PDF from below link and try this code,
https://www.dropbox.com/s/4qad66r2361hvmu/sample.pdf?dl=1

I hope my answer is helpful.

If any query so comments, please.


问:
Using DNS to redirect to another URL with a path
I'm trying to redirect a domain to another via DNS.

I know that using IN CNAME it's posible.

```<code>www.proof.com IN CNAME www.proof-two.com.
</code>```

What i need is a redirection with a path. When someone types www.proof.com, it should take them to to www.proof-two.com/path/index.htm

I know it can be done using Web Server facilities, but I need DNS redirection.

Is this possible?

答:
A related work concluded all the below:

Problem:

http://a.com/p1/p2.html  should go to  http://B.com/p1/p2.html

today, but later when configured manually/automatically, the same

http://a.com/p1/p2.html  should go to  http://C.com/p1/p2.html

Answers:

DNS - converts name to IP address

Though it can do a lot of redirects, always output is IP address
DNS does not understand the path or protocol part of URL, understands domain part only, that is, a.com  only is converted to IP address, so when you hit http://a.com/p1/p2.html may be converted to http://152.132.121.11/p1/p2.html
if you configure wrong in DNS, then you will get 152.132.121.11 (not http://152.132.121.11/p1/p2.html), so you would get some 400s error (400, 403, etc.)

Redirection - this is http://a.com/p1/p2.html can be converted to http://b.com/p1/p2.html

All the methods like GET, POST can work, with if any headers and body, but there is a web server is involved, it could be point of failure, so scalability and availability will be key

If you are on AWS, Route 53 -> API Gateway is possible though custom domains, internally using the Cloud front

It is possible with Amazon Certification Manager, AWS Gateway custom domains & Route53, note the us-east-1 restriction on ACM

Hope that helps someone

Body:
I'm trying to redirect a domain to another via DNS.

I know that using IN CNAME it's posible.

www.proof.com IN CNAME www.proof-two.com.

What i need is a redirection with a path. When someone types www.proof.com, it should take them to to www.proof-two.com/path/index.htm

I know it can be done using Web Server facilities, but I need DNS redirection.

Is this possible?


问:
Please check a newbie's script
Please check my script below.

Im trying to add some color to some of the text... this is what i have managed to work out thus far.. is it correct?

```<code><center> You will be redirected to the number one proven training system in <span style="color:blue;font-weight:bold"> <span id="countdowntimer">12 </span> Seconds </span> </center>

<script type="text/javascript">
var timeleft = 12;
var downloadTimer = setInterval(function(){
timeleft--;
document.getElementById("countdowntimer").textContent = timeleft;
if(timeleft <= 0)
    clearInterval(downloadTimer);
},1000);
</code>```

答:
Yes, the text of the countdown is blue if that is what you mean. Ifyou want to change the color when the timer runs out try something like...

```<code>if(timeleft <= 0)
clearInterval(downloadTimer);
document.getElementById("countdowntimer").style = "color:red";
</code>```

You might find tools like https://jsfiddle.net/vnjgngo1/ helpful in the future. In this fiddle you can paste your code and html in two separate blocks.

Title: Please check a newbie's script

Body:
Please check my script below.

Im trying to add some color to some of the text... this is what i have managed to work out thus far.. is it correct?

 You will be redirected to the number one proven training system in  12  Seconds

Body:
Yes, the text of the countdown is blue if that is what you mean. Ifyou want to change the color when the timer runs out try something like...

if(timeleft <= 0)
clearInterval(downloadTimer);
document.getElementById("countdowntimer").style = "color:red";

You might find tools like https://jsfiddle.net/vnjgngo1/ helpful in the future. In this fiddle you can paste your code and html in two separate blocks.


问:
Applying images on top of a background image
I seem to be having problems with my CSS code. I want to have a background image at 100% of the page width and height, and then other images strategically placed on top of the background image. The problem I am having is that when I absolutely place the images on top, unless I specify an actual height of the background image, the actual image does not show up in the background. Can anyone suggest a way around actually specifying a height for the background image?

#map {
  background-image: url("images/middleearth_map.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

#registermap {
  position: absolute;
  top: 5%;
  right: 2%;
}

#gollum {
  position: absolute;
  top: 40%;
  right: 15%;
}

#playtrailer {
  position: absolute;
  top: 30%;
  left: 0%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="map">
  <div id="registermap">

      <img src="images/middle-earth_map1.png" alt="Registration Link" class="wobble" />

  </div>

  <div id="gollum">

      <img src="images/gollum.png" alt="Cast and Crew Link" class="wobble" />

  </div>

  <div id="playtrailer">

      <img src="images/play_button.png" alt="Movie Trailer Link" class="wobble" />

  </div>
</div></code>```

答:
Your div with map id not fill all the window size, Change the css to this:

```<code>#map {
  background-image: url("images/middleearth_map.png");
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: 100% 100%;
  width: 100vw;
  height: 100vh;
  margin:0;
  padding:0;
}
</code>```

Body:
Your div with map id not fill all the window size, Change the css to this:

#map {
  background-image: url("images/middleearth_map.png");
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: 100% 100%;
  width: 100vw;
  height: 100vh;
  margin:0;
  padding:0;
}


问:
Problems with e-mail validation Regex on Ruby
I've just started to learn how to use Regex and I'm trying to create a regex to validate an e-mail adress in Ruby. This is what I got so far:

```<code>emailregex = /([a-zA-Z]+([_\-.][a-zA-Z]*)*@\D+[.]\D+)/
str = "abc_def@hotmail.com"
puts str.scan emailregex
</code>```

Expected Output:

```<code>abc_def@hotmail.com
</code>```

Actual Output:

```<code>abc_def@hotmail.com
_def
</code>```

I've seen a few e-mail regex validations, but I want to know what is wrong with my regex. Thanks in advice.

答:
It’s String#scan not Regexp, who is to blame. Check:

```<code>str = "abc_def@hotmail.com"
str.scan /\w+/
#⇒ ["abc_def", "hotmail", "com"]
</code>```

You probably want to e.g. use String#[]:

```<code>str[emailregex]
#⇒ "abc_def@hotmail.com"
</code>```

But please don’t use a regular expression to match emails and here is why. Sooner or later your regexp-based validation will fail. To validate the email just check for @ in the string and send the validation email there. This is the only valid modern way to validate emails.

Body:
I've just started to learn how to use Regex and I'm trying to create a regex to validate an e-mail adress in Ruby. This is what I got so far:

emailregex = /([a-zA-Z]+([_\-.][a-zA-Z]*)*@\D+[.]\D+)/
str = "abc_def@hotmail.com"
puts str.scan emailregex

Expected Output:

abc_def@hotmail.com

Actual Output:

abc_def@hotmail.com
_def

I've seen a few e-mail regex validations, but I want to know what is wrong with my regex. Thanks in advice.

Body:
It’s String#scan not Regexp, who is to blame. Check:

str = "abc_def@hotmail.com"
str.scan /\w+/
#⇒ ["abc_def", "hotmail", "com"]

You probably want to e.g. use String#[]:

str[emailregex]
#⇒ "abc_def@hotmail.com"

But please don’t use a regular expression to match emails and here is why. Sooner or later your regexp-based validation will fail. To validate the email just check for @ in the string and send the validation email there. This is the only valid modern way to validate emails.


问:
How to set textListener to dynamically generated editTexts in android
I have dynamically added a layout with editBox's ,and I want to set textListener to each editBox so that I can can perform some calculations on the values that I retrieve from the editBox's. I am using the the code below to inflate the layout. Is it possible to set a counter on the View object that I am using to inflate the layout. Any ideas are welcome.</p>

```<code>    public void addField1(View v) {
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View rowView = inflater.inflate(R.layout.field, null);
          parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
             }
    int count1 = parentLinearLayout.getChildCount();
                 for (int n = 0; n < count1; n++) {
                    LinearLayout linearLayout = (LinearLayout) parentLinearLayout.getChildAt(n);
        editValues3 = (EditText) linearLayout.getChildAt(3);
        editValues3.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                            Log.e("inside", "before" + s);

                        }
                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            Log.e("inside", "on text" + s);
                        }
                        @Override
                        public void afterTextChanged(Editable s) {
                            Log.e("inside", "afterText" + s);
                           if(editValues3.getText().length()>0){
                                valCalculations();
                            }
                        }
                    });
                }
</code>```

答: I think you should create your CustomEditText that implementsaddTextChangedListener and inside that custom class make the proper calculations.

Body:
I have dynamically added a layout with editBox's ,and I want to set textListener to each editBox so that I can can perform some calculations on the values that I retrieve from the editBox's. I am using the the code below to inflate the layout. Is it possible to set a counter on the View object that I am using to inflate the layout. Any ideas are welcome.

    public void addField1(View v) {
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View rowView = inflater.inflate(R.layout.field, null);
          parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
             }
    int count1 = parentLinearLayout.getChildCount();
                 for (int n = 0; n < count1; n++) {
                    LinearLayout linearLayout = (LinearLayout) parentLinearLayout.getChildAt(n);
        editValues3 = (EditText) linearLayout.getChildAt(3);
        editValues3.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                            Log.e("inside", "before" + s);

                        }
                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            Log.e("inside", "on text" + s);
                        }
                        @Override
                        public void afterTextChanged(Editable s) {
                            Log.e("inside", "afterText" + s);
                           if(editValues3.getText().length()>0){
                                valCalculations();
                            }
                        }
                    });
                }


问:
Esper pattern timer:interval() is not working
I have this basic POC code. I can see the events getting published but not getting any alert in listeners.
In the code below, none of the the statements pattern1 or pattern2 is getting alerted.
Config's setInternalTimerEnabled is by default is True but I tried setting it True in code but still the same issue.
Am I missing something?
Any clue would be really helpful. </p>

```<code>public class PatternSimpleQue {

    public static void main(String args[]) throws InterruptedException {
        Configuration configuration = new Configuration();
        configuration.addEventType("TestEvent", TestEvent.class);
        configuration.getEngineDefaults().getThreading().setInternalTimerEnabled(true);
        configuration.getEngineDefaults().getLogging().setEnableTimerDebug(true);

        EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(configuration);
        EPRuntime runtime = engine.getEPRuntime();
        EPAdministrator admin = engine.getEPAdministrator();
        engine.initialize();

        String pattern1 = "select * from pattern [every timer:interval(1 sec) -> every TestEvent]";
        String pattern2 = "select (select qty from TestEvent.std:lastevent()) as qty from pattern [every timer:interval(1 sec)]";

        admin.createEPL(pattern1).addListener((eventBeans, eventBeen1) -> {
            System.out.println("In event S3");
            try {
                for (EventBean anEventBean : eventBeans) {
                    System.out.println("****S3**** Pattern bean -> " + anEventBean.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        admin.createEPL(pattern2).addListener((eventBeans, eventBeen1) -> {
            System.out.println("In event S4");
            try {
                for (EventBean anEventBean : eventBeans) {
                    System.out.println("--S4--Pattern bean -> " + " :: " + anEventBean.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        while (true) {
            sendEvent(runtime, new TestEvent(String.valueOf(new Random().nextInt(100)), 10, 1));
            sendEvent(runtime, new TestEvent(String.valueOf(new Random().nextInt(100)), 20, -1));
            Thread.sleep(5000);
        }
    }

    private static void sendEvent(EPRuntime runtime, TestEvent testEvent) {
        System.out.println("\n-- New event: " + testEvent);
        runtime.sendEvent(testEvent);
    }
}

public class TestEvent {

    private String instanceId;
    private int qty;
    private int side;

    public String getInstanceId() {
        return instanceId;
    }

    public int getQty() {
        return qty;
    }

    public int getSide() {
        return side;
    }

    public TestEvent(String instanceId, int qty, int side) {
        this.instanceId = instanceId;
        this.qty = qty;
        this.side = side;
    }

    @Override
    public String toString() {
        return "TestEvent{" +
                "instanceId='" + instanceId + '\'' +
                ", qty=" + qty +
                ", side=" + side +
                '}';
    }
}
</code>```

答:
Try running this code, this should work.

```<code>public class PatternSimpleQue {

    public static void main(String args[]) throws InterruptedException {
        Configuration configuration = new Configuration();
        configuration.addEventType("TestEvent", TestEvent.class);
        configuration.getEngineDefaults().getThreading().setInternalTimerEnabled(true);
        configuration.getEngineDefaults().getLogging().setEnableTimerDebug(true);

        EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(configuration);
        EPRuntime runtime = engine.getEPRuntime();
        EPAdministrator admin = engine.getEPAdministrator();
        engine.initialize();

        String pattern1 = "select * from pattern [every timer:interval(1 sec) -> every TestEvent]";
        String pattern2 = "select (select qty from TestEvent.std:lastevent()) as qty from pattern [every timer:interval(1 sec)]";

        admin.createEPL(pattern1).addListener((eventBeans, eventBeen1) -> {
            System.out.println("In event S3");
            try {
                for (EventBean anEventBean : eventBeans) {
                    System.out.println("****S3**** Pattern bean -> " + anEventBean.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        admin.createEPL(pattern2).addListener((eventBeans, eventBeen1) -> {
            System.out.println("In event S4");
            try {
                for (EventBean anEventBean : eventBeans) {
                    System.out.println("--S4--Pattern bean -> " + " :: " + anEventBean.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        while (true) {
            sendEvent(runtime, new TestEvent(String.valueOf(new Random().nextInt(100)), 10, 1));
            sendEvent(runtime, new TestEvent(String.valueOf(new Random().nextInt(100)), 20, -1));
            Thread.sleep(5000);
        }
    }

    private static void sendEvent(EPRuntime runtime, TestEvent testEvent) {
        System.out.println("\n-- New event: " + testEvent);
        runtime.sendEvent(new CurrentTimeEvent(currentTimeMillis()));
        runtime.sendEvent(testEvent);
    }
}
</code>```

Basically, there is a reported issue on Esper's internal timer.
Another similar issue.

More on config settings.

Body:
I have this basic POC code. I can see the events getting published but not getting any alert in listeners.
In the code below, none of the the statements pattern1 or pattern2 is getting alerted.
Config's setInternalTimerEnabled is by default is True but I tried setting it True in code but still the same issue.
Am I missing something?
Any clue would be really helpful.

public class PatternSimpleQue {

    public static void main(String args[]) throws InterruptedException {
        Configuration configuration = new Configuration();
        configuration.addEventType("TestEvent", TestEvent.class);
        configuration.getEngineDefaults().getThreading().setInternalTimerEnabled(true);
        configuration.getEngineDefaults().getLogging().setEnableTimerDebug(true);

        EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(configuration);
        EPRuntime runtime = engine.getEPRuntime();
        EPAdministrator admin = engine.getEPAdministrator();
        engine.initialize();

        String pattern1 = "select * from pattern [every timer:interval(1 sec) -> every TestEvent]";
        String pattern2 = "select (select qty from TestEvent.std:lastevent()) as qty from pattern [every timer:interval(1 sec)]";

        admin.createEPL(pattern1).addListener((eventBeans, eventBeen1) -> {
            System.out.println("In event S3");
            try {
                for (EventBean anEventBean : eventBeans) {
                    System.out.println("****S3**** Pattern bean -> " + anEventBean.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        admin.createEPL(pattern2).addListener((eventBeans, eventBeen1) -> {
            System.out.println("In event S4");
            try {
                for (EventBean anEventBean : eventBeans) {
                    System.out.println("--S4--Pattern bean -> " + " :: " + anEventBean.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        while (true) {
            sendEvent(runtime, new TestEvent(String.valueOf(new Random().nextInt(100)), 10, 1));
            sendEvent(runtime, new TestEvent(String.valueOf(new Random().nextInt(100)), 20, -1));
            Thread.sleep(5000);
        }
    }

    private static void sendEvent(EPRuntime runtime, TestEvent testEvent) {
        System.out.println("\n-- New event: " + testEvent);
        runtime.sendEvent(testEvent);
    }
}

public class TestEvent {

    private String instanceId;
    private int qty;
    private int side;

    public String getInstanceId() {
        return instanceId;
    }

    public int getQty() {
        return qty;
    }

    public int getSide() {
        return side;
    }

    public TestEvent(String instanceId, int qty, int side) {
        this.instanceId = instanceId;
        this.qty = qty;
        this.side = side;
    }

    @Override
    public String toString() {
        return "TestEvent{" +
                "instanceId='" + instanceId + '\'' +
                ", qty=" + qty +
                ", side=" + side +
                '}';
    }
}

Body:
Try running this code, this should work.

public class PatternSimpleQue {

    public static void main(String args[]) throws InterruptedException {
        Configuration configuration = new Configuration();
        configuration.addEventType("TestEvent", TestEvent.class);
        configuration.getEngineDefaults().getThreading().setInternalTimerEnabled(true);
        configuration.getEngineDefaults().getLogging().setEnableTimerDebug(true);

        EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(configuration);
        EPRuntime runtime = engine.getEPRuntime();
        EPAdministrator admin = engine.getEPAdministrator();
        engine.initialize();

        String pattern1 = "select * from pattern [every timer:interval(1 sec) -> every TestEvent]";
        String pattern2 = "select (select qty from TestEvent.std:lastevent()) as qty from pattern [every timer:interval(1 sec)]";

        admin.createEPL(pattern1).addListener((eventBeans, eventBeen1) -> {
            System.out.println("In event S3");
            try {
                for (EventBean anEventBean : eventBeans) {
                    System.out.println("****S3**** Pattern bean -> " + anEventBean.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        admin.createEPL(pattern2).addListener((eventBeans, eventBeen1) -> {
            System.out.println("In event S4");
            try {
                for (EventBean anEventBean : eventBeans) {
                    System.out.println("--S4--Pattern bean -> " + " :: " + anEventBean.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        while (true) {
            sendEvent(runtime, new TestEvent(String.valueOf(new Random().nextInt(100)), 10, 1));
            sendEvent(runtime, new TestEvent(String.valueOf(new Random().nextInt(100)), 20, -1));
            Thread.sleep(5000);
        }
    }

    private static void sendEvent(EPRuntime runtime, TestEvent testEvent) {
        System.out.println("\n-- New event: " + testEvent);
        runtime.sendEvent(new CurrentTimeEvent(currentTimeMillis()));
        runtime.sendEvent(testEvent);
    }
}

Basically, there is a reported issue on Esper's internal timer.
Another similar issue.

More on config settings.


问:
Why is this syntax not working in creating Java String array with nashorn
I see New Java Array of Strings in Nashorn, and find the solution.

But I just wonder why my origin code throws exception:

```<code>var JStringArray = Java.type("java.lang.String[]");
var validExtensions = new JStringArray(".java", ".class", ".jar", ".xml");
</code>```

The exception is

```<code>Exception in thread "main" javax.script.ScriptException: TypeError: Can not create new object with constructor [Ljava.lang.String; with the passed arguments; they do not match any of its method signatures. in ~/scriptMonkey/js/samples/FileStatistics.js at line number 9
    at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:454)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
    at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
    at Debugger.main(Debugger.java:16)
Caused by: ~/scriptMonkey/js/samples/FileStatistics.js:9 TypeError: Can not create new object with constructor [Ljava.lang.String; with the passed arguments; they do not match any of its method signatures.
    at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
    at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:213)
    at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:185)
    at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:172)
    at jdk.nashorn.internal.runtime.linker.NashornStaticClassLinker.checkNullConstructor(NashornStaticClassLinker.java:108)
    at jdk.nashorn.internal.runtime.linker.NashornStaticClassLinker.getGuardedInvocation(NashornStaticClassLinker.java:96)
    at jdk.internal.dynalink.support.CompositeTypeBasedGuardingDynamicLinker.getGuardedInvocation(CompositeTypeBasedGuardingDynamicLinker.java:176)
    at jdk.internal.dynalink.support.CompositeGuardingDynamicLinker.getGuardedInvocation(CompositeGuardingDynamicLinker.java:124)
    at jdk.internal.dynalink.support.LinkerServicesImpl.getGuardedInvocation(LinkerServicesImpl.java:154)
    at jdk.internal.dynalink.DynamicLinker.relink(DynamicLinker.java:253)
    at jdk.nashorn.internal.scripts.Script$1$FileStatistics.:program(~/scriptMonkey/js/samples/FileStatistics.js:9)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
    at jdk.nashorn.internal.runtime.Context.evaluateSource(Context.java:1222)
    at jdk.nashorn.internal.runtime.Context.load(Context.java:839)
    at jdk.nashorn.internal.objects.Global.load(Global.java:1545)
    at jdk.nashorn.internal.scripts.Script$\^eval\_.:program(<eval>:1)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:449)
    ... 5 more
</code>```

答:
To the JStringArray constructor, you can pass only number of elements of the array.

```<code>var JStringArray = Java.type("java.lang.String[]");
var validExtensions = new JStringArray(4);
validExtensions[0] = ".java";
...
</code>```

All Java array type objects are constructors that accept single argument that is the "length" of the array.

Body:
I see New Java Array of Strings in Nashorn, and find the solution.

But I just wonder why my origin code throws exception:

var JStringArray = Java.type("java.lang.String[]");
var validExtensions = new JStringArray(".java", ".class", ".jar", ".xml");

The exception is

Exception in thread "main" javax.script.ScriptException: TypeError: Can not create new object with constructor [Ljava.lang.String; with the passed arguments; they do not match any of its method signatures. in ~/scriptMonkey/js/samples/FileStatistics.js at line number 9
    at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:454)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
    at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
    at Debugger.main(Debugger.java:16)
Caused by: ~/scriptMonkey/js/samples/FileStatistics.js:9 TypeError: Can not create new object with constructor [Ljava.lang.String; with the passed arguments; they do not match any of its method signatures.
    at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
    at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:213)
    at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:185)
    at jdk.nashorn.internal.runtime.ECMAErrors.typeError(ECMAErrors.java:172)
    at jdk.nashorn.internal.runtime.linker.NashornStaticClassLinker.checkNullConstructor(NashornStaticClassLinker.java:108)
    at jdk.nashorn.internal.runtime.linker.NashornStaticClassLinker.getGuardedInvocation(NashornStaticClassLinker.java:96)
    at jdk.internal.dynalink.support.CompositeTypeBasedGuardingDynamicLinker.getGuardedInvocation(CompositeTypeBasedGuardingDynamicLinker.java:176)
    at jdk.internal.dynalink.support.CompositeGuardingDynamicLinker.getGuardedInvocation(CompositeGuardingDynamicLinker.java:124)
    at jdk.internal.dynalink.support.LinkerServicesImpl.getGuardedInvocation(LinkerServicesImpl.java:154)
    at jdk.internal.dynalink.DynamicLinker.relink(DynamicLinker.java:253)
    at jdk.nashorn.internal.scripts.Script$1$FileStatistics.:program(~/scriptMonkey/js/samples/FileStatistics.js:9)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
    at jdk.nashorn.internal.runtime.Context.evaluateSource(Context.java:1222)
    at jdk.nashorn.internal.runtime.Context.load(Context.java:839)
    at jdk.nashorn.internal.objects.Global.load(Global.java:1545)
    at jdk.nashorn.internal.scripts.Script$\^eval\_.:program(<eval>:1)
    at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
    at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
    at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:449)
    ... 5 more

Body:
To the JStringArray constructor, you can pass only number of elements of the array.

var JStringArray = Java.type("java.lang.String[]");
var validExtensions = new JStringArray(4);
validExtensions[0] = ".java";
...

All Java array type objects are constructors that accept single argument that is the "length" of the array.


问:
How to change the onclick of a button to another function using JavaScript?
This is my first question I'm asking. Is it possible to change the onclick="change()" to another function like onclick="change1()"

My code is like this:

```<code><a href="#" onclick="changeSrc()" id="a1"><img src="images/transparent-arrow-hi.png" style="position:absolute; top:525px; left:1000px; height:50px; width:50px;" ></a>
<img src="images/keyboard.png" id="pic1">
<img src="images/mouse1.png" id="pic2">
<img src="images/PCstand.png" id="pic3">
<img src="images/monitor.png" id="pic4">
</code>```

My Javascript is as follows:

```<code><script>
function changeSrc() {
document.getElementById('pic1').src="images/robber1.jpg";
document.getElementById('pic2').src="images/guarding entrance 1.jpg";
document.getElementById('pic3').src="images/Lock.ico";
document.getElementById('pic4').src="images/Number pads.jpg";
}
</script>
</code>```

This works so far in changing the img src , But I want to click the same button many times to change the img src to others.

So its like this button that when onclick , can call the first function to change the img src and at the same time prepare the onclick to call the second funtion.

Is that even possible?

I can add more code if needed.

答:
you can have counter and every time call your function increase number of counter and select what actions you need.or you can use switch in changeSrc function

```<code><script>
var counter = 0;
function changeSrc() {
 if(counter==0){
    document.getElementById('pic1').src="images/robber1.jpg";
    document.getElementById('pic2').src="images/guarding entrance 1.jpg";
    document.getElementById('pic3').src="images/Lock.ico";
    document.getElementById('pic4').src="images/Number pads.jpg";
}
 if(counter==1){
    document.getElementById('pic1').src="images/robber2.jpg";
    document.getElementById('pic2').src="images/guarding entrance 2.jpg";
    document.getElementById('pic3').src="images/Lock2.ico";
    document.getElementById('pic4').src="images/Number pads2.jpg";
}
    counter++;
}
</script>
</code>```

if your images have pattern like numbers you can do this

```<code><script>
var counter = 0;
function changeSrc() {
    document.getElementById('pic1').src="images/robber"+counter+".jpg";
    document.getElementById('pic2').src="images/guarding entrance "+counter+".jpg";;
    document.getElementById('pic3').src="images/Lock "+counter+".ico";;
    document.getElementById('pic4').src="images/Number pads"+counter+".jpg";;
 counter++;
}
</script>
</code>```

Body:
This is my first question I'm asking. Is it possible to change the onclick="change()" to another function like onclick="change1()"

My code is like this:

My Javascript is as follows:

This works so far in changing the img src , But I want to click the same button many times to change the img src to others.

So its like this button that when onclick , can call the first function to change the img src and at the same time prepare the onclick to call the second funtion.

Is that even possible?

I can add more code if needed.

Body:
you can have counter and every time call your function increase number of counter and select what actions you need.or you can use switch in changeSrc function

<script>
var counter = 0;
function changeSrc() {
 if(counter==0){
    document.getElementById('pic1').src="images/robber1.jpg";
    document.getElementById('pic2').src="images/guarding entrance 1.jpg";
    document.getElementById('pic3').src="images/Lock.ico";
    document.getElementById('pic4').src="images/Number pads.jpg";
}
 if(counter==1){
    document.getElementById('pic1').src="images/robber2.jpg";
    document.getElementById('pic2').src="images/guarding entrance 2.jpg";
    document.getElementById('pic3').src="images/Lock2.ico";
    document.getElementById('pic4').src="images/Number pads2.jpg";
}
    counter++;
}
</script>

if your images have pattern like numbers you can do this

<script>
var counter = 0;
function changeSrc() {
    document.getElementById('pic1').src="images/robber"+counter+".jpg";
    document.getElementById('pic2').src="images/guarding entrance "+counter+".jpg";;
    document.getElementById('pic3').src="images/Lock "+counter+".ico";;
    document.getElementById('pic4').src="images/Number pads"+counter+".jpg";;
 counter++;
}
</script>


问:
How to order a list of paragraphs
A have a list:

§ 21 Item

§ 1 Item

§ 13 Item

§ 3 Item

§ 2 Item

I need to order it like this:

§ 1 Item

§ 2 Item

§ 3 Item

§ 13 Item

§ 21 Item

But after

```<code>newList = (from a in list orderby a.Name ascending select a).ToList();
</code>```

I get this:

§ 1 Item

§ 13 Item

§ 2 Item

§ 21 Item

§ 3 Item

How to fix it?

答:
Google has the answer: Getting Linq to OrderBy an attribute value numerically.</p>

```<code>from a in list
orderby int.Parse(a.Name)
select ...
</code>```

Title: How to order a list of paragraphs

Body:
A have a list:

§ 21 Item

§ 1 Item

§ 13 Item

§ 3 Item

§ 2 Item

I need to order it like this:

§ 1 Item

§ 2 Item

§ 3 Item

§ 13 Item

§ 21 Item

But after

newList = (from a in list orderby a.Name ascending select a).ToList();

I get this:

§ 1 Item

§ 13 Item

§ 2 Item

§ 21 Item

§ 3 Item

How to fix it?

Body:
Google has the answer: Getting Linq to OrderBy an attribute value numerically.

from a in list
orderby int.Parse(a.Name)
select ...


问:
Need faster method to replace colors in an image based on another color
I'm looking for a faster method of replacing colors in an image based on another color. For example, I have an image that is mostly black with shades of gray and I want to recolor it based on red. Right now I pass it into this function with black as my base color and red as my new color. Then I go pixel by pixel to determine its RGB and recalculate that to the new red shade. So pure black becomes pure red and grays become a lighter red and so on.

Is there a quicker way to do this? Possibly using a separate image manipulation library? I looked into ImageMagick but I can't find the exact functionality I'm looking for.

Here's my current function. It works but is slow.

```<code>Public Function doRecolorImage(ByRef inBMP As Bitmap, ByVal baseColor As Color, ByVal newColor As Color) As Bitmap
        Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)

            Using gIcons As Graphics = Graphics.FromImage(newimg)
                For x = 0 To inBMP.Width - 1
                    For y = 0 To inBMP.Height - 1
                        Dim ltrans As Byte = inBMP.GetPixel(x, y).A
                        Dim lR As Byte = inBMP.GetPixel(x, y).R
                        Dim lG As Byte = inBMP.GetPixel(x, y).G
                        Dim lB As Byte = inBMP.GetPixel(x, y).B

                        Dim newpixR As Integer = CInt(newColor.R) + (CInt(lR) - CInt(baseColor.R))

                        Dim newpixG As Integer = CInt(newColor.G) + (CInt(lG) - CInt(baseColor.G))

                        Dim newpixB As Integer = CInt(newColor.B) + (CInt(lB) - CInt(baseColor.B))

                        newimg.SetPixel(x, y, System.Drawing.Color.FromArgb(ltrans, newpixR, newpixG, newpixB))
                    Next
                Next
            End Using

        Return newimg

    End Function
</code>```

Here I tried using ColorMatrix but it didn't work, not sure why...maybe my understanding of how ColorMatrix works is wrong.

```<code>Public Function doNewRecolorImage(ByRef inBMP As Bitmap, ByVal baseColor As Color, ByVal newColor As Color) As Bitmap
        Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)

            Dim iaImageProps As New ImageAttributes

            Dim cmNewColors As ColorMatrix

            cmNewColors = New ColorMatrix(New Single()() _
                {New Single() {newColor.R / baseColor.R, 0, 0, 0, 0}, _
                 New Single() {0, newColor.G / baseColor.G, 0, 0, 0}, _
                 New Single() {0, 0, newColor.B / baseColor.B, 0, 0}, _
                 New Single() {0, 0, 0, 1, 0}, _
                 New Single() {0, 0, 0, 0, 1}})

            iaImageProps.SetColorMatrix(cmNewColors)

            Using g As Graphics = Graphics.FromImage(newimg)
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
                g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, iaImageProps)
            End Using

        Return newimg

    End Function
</code>```

UPDATE 1:

Here's my updated function based on Ryan's answer below. It runs but it isn't returning the expected recolored image. The image is one solid color...the base color. So I'm passing in the base color and the new color and getting the result. However, the result should be the new color (dark blue) because the image is a solid color so it should be an exact color swap.

```<code>Private Function calcColorSwap(_base As Byte, _new As Byte) As Single
    If _new > _base Then
        Return (CInt(_new) - CInt(_base)) / 255.0!
    Else
        Return (CInt(_base) - CInt(_new)) / 255.0!
    End If
End Function

Public Function doNewRecolorImage(inBMP As Bitmap, baseColor As Color, newColor As Color) As Bitmap
    Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)
    Dim transformation As New ColorMatrix(New Single()() {
          New Single() {1, 0, 0, 0, 0},
          New Single() {0, 1, 0, 0, 0},
          New Single() {0, 0, 1, 0, 0},
          New Single() {0, 0, 0, 1, 0},
          New Single() {calcColorSwap(baseColor.R, newColor.R), calcColorSwap(baseColor.G, newColor.G), calcColorSwap(baseColor.B, newColor.B), 0, 1}
      })

    Dim imageAttributes As New ImageAttributes()
    imageAttributes.SetColorMatrix(transformation)

    Using g As Graphics = Graphics.FromImage(newimg)
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, imageAttributes)
    End Using

Return newimg

End Function
</code>```

UPDATE 2 (SOLUTION):

Here's the solution: based on Ryan's answer below.

```<code>Private Function calcColorSwap(_base As Byte, _new As Byte) As Single
        Return (CInt(_new) - CInt(_base)) / 255.0!
End Function

Public Function doNewRecolorImage(inBMP As Bitmap, baseColor As Color, newColor As Color) As Bitmap
    Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)
    Dim transformation As New ColorMatrix(New Single()() {
          New Single() {1, 0, 0, 0, 0},
          New Single() {0, 1, 0, 0, 0},
          New Single() {0, 0, 1, 0, 0},
          New Single() {0, 0, 0, 1, 0},
          New Single() {calcColorSwap(baseColor.R, newColor.R), calcColorSwap(baseColor.G, newColor.G), calcColorSwap(baseColor.B, newColor.B), 0, 1}
      })

    Dim imageAttributes As New ImageAttributes()
    imageAttributes.SetColorMatrix(transformation)

    Using g As Graphics = Graphics.FromImage(newimg)
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, imageAttributes)
    End Using

Return newimg

End Function
</code>```

答:
The matrix equivalent to your original – adding a fixed value to R, G, and B – looks like this:

```<code>New Single()() {
    New Single() {1, 0, 0, 0, 0},
    New Single() {0, 1, 0, 0, 0},
    New Single() {0, 0, 1, 0, 0},
    New Single() {0, 0, 0, 1, 0},
    New Single() {(CInt(newColor.R) - CInt(baseColor.R)) / 255!, (CInt(newColor.G) - CInt(baseColor.G)) / 255!, (CInt(newColor.B) - CInt(baseColor.B)) / 255!, 0, 1}
}
</code>```

Overall:

```<code>Public Function doRecolorImage(image As Image, baseColor As Color, newColor As Color) As Bitmap
    Dim transformation As New ColorMatrix(New Single()() {
        New Single() {1, 0, 0, 0, 0},
        New Single() {0, 1, 0, 0, 0},
        New Single() {0, 0, 1, 0, 0},
        New Single() {0, 0, 0, 1, 0},
        New Single() {(CInt(newColor.R) - CInt(baseColor.R)) / 255!, (CInt(newColor.G) - CInt(baseColor.G)) / 255!, (CInt(newColor.B) - CInt(baseColor.B)) / 255!, 0, 1}
    })

    Dim imageAttributes As New ImageAttributes()
    imageAttributes.SetColorMatrix(transformation)

    Dim result As New Bitmap(image.Width, image.Height)

    Using g As Graphics = Graphics.FromImage(result)
        g.DrawImage(image, New Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes)
    End Using

    Return result
End Function
</code>```

(Don’t use ByRef for no reason!)

Body:
I'm looking for a faster method of replacing colors in an image based on another color. For example, I have an image that is mostly black with shades of gray and I want to recolor it based on red. Right now I pass it into this function with black as my base color and red as my new color. Then I go pixel by pixel to determine its RGB and recalculate that to the new red shade. So pure black becomes pure red and grays become a lighter red and so on.

Is there a quicker way to do this? Possibly using a separate image manipulation library? I looked into ImageMagick but I can't find the exact functionality I'm looking for.

Here's my current function. It works but is slow.

Public Function doRecolorImage(ByRef inBMP As Bitmap, ByVal baseColor As Color, ByVal newColor As Color) As Bitmap
        Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)

            Using gIcons As Graphics = Graphics.FromImage(newimg)
                For x = 0 To inBMP.Width - 1
                    For y = 0 To inBMP.Height - 1
                        Dim ltrans As Byte = inBMP.GetPixel(x, y).A
                        Dim lR As Byte = inBMP.GetPixel(x, y).R
                        Dim lG As Byte = inBMP.GetPixel(x, y).G
                        Dim lB As Byte = inBMP.GetPixel(x, y).B

                        Dim newpixR As Integer = CInt(newColor.R) + (CInt(lR) - CInt(baseColor.R))

                        Dim newpixG As Integer = CInt(newColor.G) + (CInt(lG) - CInt(baseColor.G))

                        Dim newpixB As Integer = CInt(newColor.B) + (CInt(lB) - CInt(baseColor.B))

                        newimg.SetPixel(x, y, System.Drawing.Color.FromArgb(ltrans, newpixR, newpixG, newpixB))
                    Next
                Next
            End Using

        Return newimg

    End Function

Here I tried using ColorMatrix but it didn't work, not sure why...maybe my understanding of how ColorMatrix works is wrong.

Public Function doNewRecolorImage(ByRef inBMP As Bitmap, ByVal baseColor As Color, ByVal newColor As Color) As Bitmap
        Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)

            Dim iaImageProps As New ImageAttributes

            Dim cmNewColors As ColorMatrix

            cmNewColors = New ColorMatrix(New Single()() _
                {New Single() {newColor.R / baseColor.R, 0, 0, 0, 0}, _
                 New Single() {0, newColor.G / baseColor.G, 0, 0, 0}, _
                 New Single() {0, 0, newColor.B / baseColor.B, 0, 0}, _
                 New Single() {0, 0, 0, 1, 0}, _
                 New Single() {0, 0, 0, 0, 1}})

            iaImageProps.SetColorMatrix(cmNewColors)

            Using g As Graphics = Graphics.FromImage(newimg)
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
                g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
                g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, iaImageProps)
            End Using

        Return newimg

    End Function

UPDATE 1:

Here's my updated function based on Ryan's answer below. It runs but it isn't returning the expected recolored image. The image is one solid color...the base color. So I'm passing in the base color and the new color and getting the result. However, the result should be the new color (dark blue) because the image is a solid color so it should be an exact color swap.

Private Function calcColorSwap(_base As Byte, _new As Byte) As Single
    If _new > _base Then
        Return (CInt(_new) - CInt(_base)) / 255.0!
    Else
        Return (CInt(_base) - CInt(_new)) / 255.0!
    End If
End Function

Public Function doNewRecolorImage(inBMP As Bitmap, baseColor As Color, newColor As Color) As Bitmap
    Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)
    Dim transformation As New ColorMatrix(New Single()() {
          New Single() {1, 0, 0, 0, 0},
          New Single() {0, 1, 0, 0, 0},
          New Single() {0, 0, 1, 0, 0},
          New Single() {0, 0, 0, 1, 0},
          New Single() {calcColorSwap(baseColor.R, newColor.R), calcColorSwap(baseColor.G, newColor.G), calcColorSwap(baseColor.B, newColor.B), 0, 1}
      })

    Dim imageAttributes As New ImageAttributes()
    imageAttributes.SetColorMatrix(transformation)

    Using g As Graphics = Graphics.FromImage(newimg)
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, imageAttributes)
    End Using

Return newimg

End Function

UPDATE 2 (SOLUTION):

Here's the solution: based on Ryan's answer below.

Private Function calcColorSwap(_base As Byte, _new As Byte) As Single
        Return (CInt(_new) - CInt(_base)) / 255.0!
End Function

Public Function doNewRecolorImage(inBMP As Bitmap, baseColor As Color, newColor As Color) As Bitmap
    Dim newimg As New Bitmap(inBMP.Width, inBMP.Height)
    Dim transformation As New ColorMatrix(New Single()() {
          New Single() {1, 0, 0, 0, 0},
          New Single() {0, 1, 0, 0, 0},
          New Single() {0, 0, 1, 0, 0},
          New Single() {0, 0, 0, 1, 0},
          New Single() {calcColorSwap(baseColor.R, newColor.R), calcColorSwap(baseColor.G, newColor.G), calcColorSwap(baseColor.B, newColor.B), 0, 1}
      })

    Dim imageAttributes As New ImageAttributes()
    imageAttributes.SetColorMatrix(transformation)

    Using g As Graphics = Graphics.FromImage(newimg)
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality
        g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
        g.DrawImage(inBMP, New Rectangle(0, 0, inBMP.Width, inBMP.Height), 0, 0, inBMP.Width, inBMP.Height, GraphicsUnit.Pixel, imageAttributes)
    End Using

Return newimg

End Function

Body:
The matrix equivalent to your original – adding a fixed value to R, G, and B – looks like this:

New Single()() {
    New Single() {1, 0, 0, 0, 0},
    New Single() {0, 1, 0, 0, 0},
    New Single() {0, 0, 1, 0, 0},
    New Single() {0, 0, 0, 1, 0},
    New Single() {(CInt(newColor.R) - CInt(baseColor.R)) / 255!, (CInt(newColor.G) - CInt(baseColor.G)) / 255!, (CInt(newColor.B) - CInt(baseColor.B)) / 255!, 0, 1}
}

Overall:

Public Function doRecolorImage(image As Image, baseColor As Color, newColor As Color) As Bitmap
    Dim transformation As New ColorMatrix(New Single()() {
        New Single() {1, 0, 0, 0, 0},
        New Single() {0, 1, 0, 0, 0},
        New Single() {0, 0, 1, 0, 0},
        New Single() {0, 0, 0, 1, 0},
        New Single() {(CInt(newColor.R) - CInt(baseColor.R)) / 255!, (CInt(newColor.G) - CInt(baseColor.G)) / 255!, (CInt(newColor.B) - CInt(baseColor.B)) / 255!, 0, 1}
    })

    Dim imageAttributes As New ImageAttributes()
    imageAttributes.SetColorMatrix(transformation)

    Dim result As New Bitmap(image.Width, image.Height)

    Using g As Graphics = Graphics.FromImage(result)
        g.DrawImage(image, New Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes)
    End Using

    Return result
End Function

(Don’t use ByRef for no reason!)


问:
mule dataweave invoking a spring bean
I have a spring bean defined to handle the resource bundle of my app as follows:

```<code><spring:bean id="renewMobileEngagementApiMessages" class="org.springframework.context.support.ResourceBundleMessageSource">
    <spring:property name="basename" value="messages/renew-mobile-engagement-api-messages"></spring:property>
    <spring:property name="defaultEncoding" value="UTF-8"></spring:property>
    <spring:property name="fallbackToSystemLocale" value="false"></spring:property>
</spring:bean>
</code>```

In my app I can access it in a variable or logger object for example with the following MEL command:

```<code>#[app.registry.renewMobileEngagementApiMessages.getMessage('error.clic_unavailable.description', null, sessionVars.REQUESTED_LOCALE)]
</code>```

It returns correctly my property as expected, no problem until here.

The problem is that now I need to access my properties in a dw:transform-message and I can't figure out how to do it. I tried with a global-function but I didn't got how to access my "renewMobileEngagementApiMessages" object reference to then call the "getMessage" method.

Any help would be great. Thanks in advance!

答: You can reference any Property (System or Spring) that exists in the server while DataWeave is processing your transformation, to do so use the p('prop_name') function.</p>

Title: mule dataweave invoking a spring bean

Body:
I have a spring bean defined to handle the resource bundle of my app as follows:

<spring:bean id="renewMobileEngagementApiMessages" class="org.springframework.context.support.ResourceBundleMessageSource">
    <spring:property name="basename" value="messages/renew-mobile-engagement-api-messages"></spring:property>
    <spring:property name="defaultEncoding" value="UTF-8"></spring:property>
    <spring:property name="fallbackToSystemLocale" value="false"></spring:property>
</spring:bean>

In my app I can access it in a variable or logger object for example with the following MEL command:

#[app.registry.renewMobileEngagementApiMessages.getMessage('error.clic_unavailable.description', null, sessionVars.REQUESTED_LOCALE)]

It returns correctly my property as expected, no problem until here.

The problem is that now I need to access my properties in a dw:transform-message and I can't figure out how to do it. I tried with a global-function but I didn't got how to access my "renewMobileEngagementApiMessages" object reference to then call the "getMessage" method.

Any help would be great. Thanks in advance!


问:
Date Filter Not Works on First Day of Month
```<code>I have one dropdown and two textbox on my page. Now i have to bind the value
based on dropdown value.

My question is when i am select This Week from dropdown that time it will
display wrong date when first date of month on second textbox.
</code>```

Look at the below example. It is working fine on other date of month but when
   select '07/01/2017' then it's display like this '01/06/2017' rather then
   '01/07/2017' on second textbox when we select This Week.

$(document).on("change","#selectDates",function() {
            var dropValue = document.getElementById('selectDates').value;
            //All
            if (dropValue == "1") {
                $('#txtDateFrom').val('');
                $('#txtDateTo').val('');
            }
                //Today
            else if (dropValue == "2") {
                var back_GTM = new Date();
                $('#txtDateFrom').val(Back_date(back_GTM));
                $('#txtDateTo').val(Back_date(back_GTM));

            }
                //This Week
            else if (dropValue == "3") {
                //var curr = new Date; // get current date
                var curr = new Date('07/01/2017'); // get current date
                var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
                var last = first + 6; // last day is the first day + 6

                var firstday = new Date(curr.setDate(first));
                var lastday = new Date(curr.setDate(last));

                $('#txtDateFrom').val(Back_date(firstday));
                $('#txtDateTo').val(Back_date(lastday));

            }
            });

            function Back_date(back_GTM) {
            var b_dd = back_GTM.getDate();
            var b_mm = back_GTM.getMonth() + 1;
            var b_yyyy = back_GTM.getFullYear();
            if (b_dd < 10) {
                b_dd = '0' + b_dd
            }
            if (b_mm < 10) {
                b_mm = '0' + b_mm
            }
            return back_date = b_dd + '/' + b_mm + '/' + b_yyyy;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-style">
                <select id="selectDates">
                    <option value="1" selected>All</option>
                    <option value="2">Today</option>
                    <option value="3">This Week</option>
                     </select>
            </div>
            <br />            <br />

            <div class="input-group input-large" data-date="13/07/2013" data-date-format="dd/mm/yyyy">
                <span class="input-group-addon">From</span>
                <input type="text" id="txtDateFrom" class="form-control dpd1" name="from">
                <span class="input-group-addon">To</span>
                <input type="text" id="txtDateTo" class="form-control dpd2" name="to">
            </div></code>```

答:
For creating new date you should pass year, month index and date of month as prameters.
Example as follows:

```<code>var curr = new Date(2017,6,1);
</code>```

Following needs to be fixed in your code:

```<code>// Needs to fix this
var curr = new Date('07/01/2017');
</code>```

Body:
I have one dropdown and two textbox on my page. Now i have to bind the value
based on dropdown value.

My question is when i am select This Week from dropdown that time it will
display wrong date when first date of month on second textbox.

Look at the below example. It is working fine on other date of month but when
   select '07/01/2017' then it's display like this '01/06/2017' rather then
   '01/07/2017' on second textbox when we select This Week.

$(document).on("change","#selectDates",function() {
            var dropValue = document.getElementById('selectDates').value;
            //All
            if (dropValue == "1") {
                $('#txtDateFrom').val('');
                $('#txtDateTo').val('');
            }
                //Today
            else if (dropValue == "2") {
                var back_GTM = new Date();
                $('#txtDateFrom').val(Back_date(back_GTM));
                $('#txtDateTo').val(Back_date(back_GTM));

            }
                //This Week
            else if (dropValue == "3") {
                //var curr = new Date; // get current date
                var curr = new Date('07/01/2017'); // get current date
                var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
                var last = first + 6; // last day is the first day + 6

                var firstday = new Date(curr.setDate(first));
                var lastday = new Date(curr.setDate(last));

                $('#txtDateFrom').val(Back_date(firstday));
                $('#txtDateTo').val(Back_date(lastday));

            }
            });

            function Back_date(back_GTM) {
            var b_dd = back_GTM.getDate();
            var b_mm = back_GTM.getMonth() + 1;
            var b_yyyy = back_GTM.getFullYear();
            if (b_dd < 10) {
                b_dd = '0' + b_dd
            }
            if (b_mm < 10) {
                b_mm = '0' + b_mm
            }
            return back_date = b_dd + '/' + b_mm + '/' + b_yyyy;
        }

                <select id="selectDates">
                    <option value="1" selected>All</option>
                    <option value="2">Today</option>
                    <option value="3">This Week</option>
                     </select>

                From
                <input type="text" id="txtDateFrom" class="form-control dpd1" name="from">
                To
                <input type="text" id="txtDateTo" class="form-control dpd2" name="to">

Body:
For creating new date you should pass year, month index and date of month as prameters.
Example as follows:

var curr = new Date(2017,6,1);

Following needs to be fixed in your code:

// Needs to fix this
var curr = new Date('07/01/2017');


问:
Dividing a dataframe into several dataframes
I have a dataframe wit more than 1000 rows and around 20 columns like this:

```<code>   UserID    C1    C2     C3  ...
    100      0    0.34   0.45
    100      2    0.5    0.45
    104      0.2   0.2   0.8
    107      1.2   2.3   0.5
    107      5    0.8   0.9
    107      3    0.4   0.4
   ...
</code>```

So I need to divide this data-frame into several data-frames based on the USerID that I can do the other process on each data-frame.

答:
If you want a dataframe per UserID in a list of dataframes you can use the follow code:

```<code>list_df = []

for n,g in df.groupby('UserID'):
    list_df.append(g)
</code>```

For dictionary:

```<code>dict_df = dict(tuple(df.groupby('UserID')))
</code>```

Body:
I have a dataframe wit more than 1000 rows and around 20 columns like this:

   UserID    C1    C2     C3  ...
    100      0    0.34   0.45
    100      2    0.5    0.45
    104      0.2   0.2   0.8
    107      1.2   2.3   0.5
    107      5    0.8   0.9
    107      3    0.4   0.4
   ...

So I need to divide this data-frame into several data-frames based on the USerID that I can do the other process on each data-frame.

Body:
If you want a dataframe per UserID in a list of dataframes you can use the follow code:

list_df = []

for n,g in df.groupby('UserID'):
    list_df.append(g)

For dictionary:

dict_df = dict(tuple(df.groupby('UserID')))


问:
preventing hardcoded url to delete in django
I have a link and button inside it that deletes a record associated with the button

```<code><a href="{% url 'parts:stock_delete' stock.id  %}">
  <button class="delete" type="submit" name="delete_btn" style="position: absolute; right: 40px;" >Delete</button>
</a>
</code>```

but I want the record to be deleted only when the button is pressed but not when URL is typed in the address bar like:

http://127.0.0.1:8000/parts/stock_delete/16/

what can be done for this?

答: You can do as Kye said, use DeleteView via post to exclude the registry. There is a concern with CSRF, but Django already provides a way for AJAX requests to bring the token. You can check in the documentation:https://docs.djangoproject.com/en/1.11/ref/csrf/#setting-the-token-on-the-ajax-request</p>

Body:
I have a link and button inside it that deletes a record associated with the button

  <button class="delete" type="submit" name="delete_btn" style="position: absolute; right: 40px;" >Delete</button>

but I want the record to be deleted only when the button is pressed but not when URL is typed in the address bar like:

http://127.0.0.1:8000/parts/stock_delete/16/

what can be done for this?


问:
Mutating join in r and writing function
I come from excel background. Vlookup has been answered before but that doesn't help me to solve my problem.

I have dataframe named data1 & vlook. I am trying to vlookup vlook$Jul.16 against data1 for the month of 2016-07-01 only and so on.I also want to fill vlook$data with same value vlook$Jul.16 if there is match otherwise NO.

Actual csv file has 50,000+ rows and 12 months. I am also looking for advise which could eliminate writing similar code 12 times.

datas:

```<code>df <- structure(list(Market = c("DOM", "INT", "INT", "INT", "DOM",
"INT", "INT", "DOM", "DOM", "DOM", "INT", "DOM", "INT", "INT",
"DOM", "DOM", "INT", "DOM", "DOM", "INT", "INT", "DOM", "DOM",
"INT"), Code = c("ZNO", "ZBE", "ZAC", "ZJY", "DCC", "ZXL", "ZNO",
"ZBE", "ZAC", "ZJY", "DCC", "ZXL", "YNO", "ZNO", "ZNO", "YNO",
"DCC", "YNO", "ZNO", "ZBE", "ZAC", "ZJY", "ZXL", "ZNO"), Departure = c("2016-07-01",
"2016-07-01", "2016-07-01", "2016-07-01", "2016-07-01", "2016-07-01",
"2016-07-01", "2016-07-01", "2016-07-01", "2016-07-01", "2016-07-01",
"2016-07-01", "2016-08-01", "2016-08-01", "2016-08-01", "2016-08-01",
"2016-08-01", "2016-08-01", "2016-08-01", "2016-09-01", "2016-09-01",
"2016-09-01", "2016-09-01", "2016-09-01"), Amount.per.km = c(0.36,
0.34, 0.23, 0.26, 0.18, 0.28, 1.08, 0.38, 0.24, 0.34, 0.27, 0.13,
0.11, 0.22, 0.13, 0.06, 0.76, 0.26, 0.23, 0.57, 0.18, 0.09, 0.84,
0.28)), .Names = c("Market", "Code", "Departure", "Amount.per.km"
), class = "data.frame", row.names = c(NA, -24L))

vlook <- structure(list(Jul.16 = c("ZNO", "ZBE", "YNO", "ZAC", "ZJY",
"DCC", "ZXL"), Data = c(NA, NA, NA, NA, NA, NA, NA), Aug.16 = c("ZNO",
"ZBE", "YNO", "ZAC", "", "", ""), Data.1 = c(NA, NA, NA, NA,
NA, NA, NA)), .Names = c("Jul.16", "Data", "Aug.16", "Data.1"
), class = "data.frame", row.names = c(NA, -7L))
</code>```

My expected end result:

```<code>expected <- structure(list(Jul.16 = c("ZNO", "ZBE", "YNO", "ZAC", "ZJY",
"DCC", "ZXL"), Data = c("ZNO", "ZBE", "NO", "ZAC", "ZJY", "DCC",
"ZXL"), Aug.16 = c("ZNO", "ZBE", "YNO", "ZAC", "", "", ""), Data.1 = c("ZNO",
"NO", "YNO", "NO", "", "", "")), .Names = c("Jul.16", "Data",
"Aug.16", "Data.1"), class = "data.frame", row.names = c(NA,
-7L))
</code>```

My attempt to vlookup:

```<code>vlook %>%
  select(Jul.16) %>%
  left_join(.,data1, by = c("Jul.16" = "Code")) %>%
  filter(Departure == "2016-07-01")

vlook %>%
      select(Aug.16) %>%
      left_join(.,data1, by = c("Aug.16" = "Code")) %>%
      filter(Departure == "2016-08-01")
</code>```

The above code correctly join two dataframes for given month. However this doesn't show me code which has no match. E.g. vlook$Jul.16 has "YNO" but data1 doesn't have "YNO" for month of July hence my code doesn't show me "YNO" as NA.

I also need help in putting values in vlook$Data and vlook$Data.1 for given month just like my expected output.

This is related to my work. I'll very grateful for your help. Thank you.

答:
Your vlook table is in a very un-R-like data format which makes this quite messy. You could do something like this:

```<code>vlook %>%
    mutate(Data=ifelse(Jul.16 %in% filter(df, Departure=="2016-07-01")$Code, Jul.16,"NO")) %>%
    mutate(Data.1=ifelse(Aug.16 %in% filter(df, Departure=="2016-08-01")$Code, Aug.16,"NO"))
</code>```

Title: Mutating join in r and writing function

Body:
I come from excel background. Vlookup has been answered before but that doesn't help me to solve my problem.

I have dataframe named data1 & vlook. I am trying to vlookup vlook$Jul.16 against data1 for the month of 2016-07-01 only and so on.I also want to fill vlook$data with same value vlook$Jul.16 if there is match otherwise NO.

Actual csv file has 50,000+ rows and 12 months. I am also looking for advise which could eliminate writing similar code 12 times.

datas:

df <- structure(list(Market = c("DOM", "INT", "INT", "INT", "DOM",
"INT", "INT", "DOM", "DOM", "DOM", "INT", "DOM", "INT", "INT",
"DOM", "DOM", "INT", "DOM", "DOM", "INT", "INT", "DOM", "DOM",
"INT"), Code = c("ZNO", "ZBE", "ZAC", "ZJY", "DCC", "ZXL", "ZNO",
"ZBE", "ZAC", "ZJY", "DCC", "ZXL", "YNO", "ZNO", "ZNO", "YNO",
"DCC", "YNO", "ZNO", "ZBE", "ZAC", "ZJY", "ZXL", "ZNO"), Departure = c("2016-07-01",
"2016-07-01", "2016-07-01", "2016-07-01", "2016-07-01", "2016-07-01",
"2016-07-01", "2016-07-01", "2016-07-01", "2016-07-01", "2016-07-01",
"2016-07-01", "2016-08-01", "2016-08-01", "2016-08-01", "2016-08-01",
"2016-08-01", "2016-08-01", "2016-08-01", "2016-09-01", "2016-09-01",
"2016-09-01", "2016-09-01", "2016-09-01"), Amount.per.km = c(0.36,
0.34, 0.23, 0.26, 0.18, 0.28, 1.08, 0.38, 0.24, 0.34, 0.27, 0.13,
0.11, 0.22, 0.13, 0.06, 0.76, 0.26, 0.23, 0.57, 0.18, 0.09, 0.84,
0.28)), .Names = c("Market", "Code", "Departure", "Amount.per.km"
), class = "data.frame", row.names = c(NA, -24L))

vlook <- structure(list(Jul.16 = c("ZNO", "ZBE", "YNO", "ZAC", "ZJY",
"DCC", "ZXL"), Data = c(NA, NA, NA, NA, NA, NA, NA), Aug.16 = c("ZNO",
"ZBE", "YNO", "ZAC", "", "", ""), Data.1 = c(NA, NA, NA, NA,
NA, NA, NA)), .Names = c("Jul.16", "Data", "Aug.16", "Data.1"
), class = "data.frame", row.names = c(NA, -7L))

My expected end result:

expected <- structure(list(Jul.16 = c("ZNO", "ZBE", "YNO", "ZAC", "ZJY",
"DCC", "ZXL"), Data = c("ZNO", "ZBE", "NO", "ZAC", "ZJY", "DCC",
"ZXL"), Aug.16 = c("ZNO", "ZBE", "YNO", "ZAC", "", "", ""), Data.1 = c("ZNO",
"NO", "YNO", "NO", "", "", "")), .Names = c("Jul.16", "Data",
"Aug.16", "Data.1"), class = "data.frame", row.names = c(NA,
-7L))

My attempt to vlookup:

vlook %>%
  select(Jul.16) %>%
  left_join(.,data1, by = c("Jul.16" = "Code")) %>%
  filter(Departure == "2016-07-01")

vlook %>%
      select(Aug.16) %>%
      left_join(.,data1, by = c("Aug.16" = "Code")) %>%
      filter(Departure == "2016-08-01")

The above code correctly join two dataframes for given month. However this doesn't show me code which has no match. E.g. vlook$Jul.16 has "YNO" but data1 doesn't have "YNO" for month of July hence my code doesn't show me "YNO" as NA.

I also need help in putting values in vlook$Data and vlook$Data.1 for given month just like my expected output.

This is related to my work. I'll very grateful for your help. Thank you.

Body:
Your vlook table is in a very un-R-like data format which makes this quite messy. You could do something like this:

vlook %>%
    mutate(Data=ifelse(Jul.16 %in% filter(df, Departure=="2016-07-01")$Code, Jul.16,"NO")) %>%
    mutate(Data.1=ifelse(Aug.16 %in% filter(df, Departure=="2016-08-01")$Code, Aug.16,"NO"))


问:
C#, variable value as a part of an object name?
For example i have a player object with a list of suits of cards it has.

```<code>player.card[0] = "diamonds";
player.card[1] = "clubs";
player.card[2] = "spades";
etc...
</code>```

also i have 4 hidden pictureboxes with an image of suites ( pb_spades , pb_hearts m etc. )

and another 4 pictureboxs ( pb_playerCard1 , pb_playerCard2 , etc. ) to which I have to assign an image from a hidden pb corresponding to the suit of card the player object has.

Therefor

```<code>if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }
</code>```

of course, doing it all with IFs would take quite a long time... Can I somehow use variable value as a part of an objects name?

kinda

```<code>for (int i = 1; i != 5; i++)
{
pb_playerCard+'i'.Image = pb_+'player.card[i+1]'.Image;
}
</code>```

答:
First, there's no reason to have a hidden PictureBox control just so you can use it's Image property to store an image. Just create Image objects.

You could store the images in a dictionary, indexable by name:

```<code>  var cards = new Dictionary<string, Image>() {
     { "diamonds", Image.FromFile("diamonds.jpg") }
     { "clubs",    Image.FromFile("clubs.jpg") }
     //...
  };
</code>```

Then instead of this:

```<code>if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }
</code>```

You would write:

```<code>pb_playerCard1.Image = images[player.card[0]];
</code>```

This code is still not great (any time you see variables like foo1, foo2, foo3, you should be putting those in an array so they can be indexed by number). The next step might be to refactor the code so you have something like:

```<code>pb_playerCard[0].Image = images[player.card[0]];
</code>```

Or:

```<code>pb_playerCard[0].Image = player.card[0].Image;
</code>```

Body:
For example i have a player object with a list of suits of cards it has.

player.card[0] = "diamonds";
player.card[1] = "clubs";
player.card[2] = "spades";
etc...

also i have 4 hidden pictureboxes with an image of suites ( pb_spades , pb_hearts m etc. )

and another 4 pictureboxs ( pb_playerCard1 , pb_playerCard2 , etc. ) to which I have to assign an image from a hidden pb corresponding to the suit of card the player object has.

Therefor

if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }

of course, doing it all with IFs would take quite a long time... Can I somehow use variable value as a part of an objects name?

kinda

for (int i = 1; i != 5; i++)
{
pb_playerCard+'i'.Image = pb_+'player.card[i+1]'.Image;
}

Body:
First, there's no reason to have a hidden PictureBox control just so you can use it's Image property to store an image. Just create Image objects.

You could store the images in a dictionary, indexable by name:

  var cards = new Dictionary<string, Image>() {
     { "diamonds", Image.FromFile("diamonds.jpg") }
     { "clubs",    Image.FromFile("clubs.jpg") }
     //...
  };

Then instead of this:

if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }

You would write:

pb_playerCard1.Image = images[player.card[0]];

This code is still not great (any time you see variables like foo1, foo2, foo3, you should be putting those in an array so they can be indexed by number). The next step might be to refactor the code so you have something like:

pb_playerCard[0].Image = images[player.card[0]];

Or:

pb_playerCard[0].Image = player.card[0].Image;


问:
Test DbSet with RhinoMock
I need to mock a DbSet with RhinoMock. I found a way to mock IDbSet, but not DbSet. I found a way with another mocking framework, but i have to use RhinoMock. Can somebody please translate it to rhino mock?

I found this on http://www.loganfranken.com/blog/517/mocking-dbset-queries-in-ef6/:

```<code>private static DbSet<T> GetQueryableMockDbSet<T>(params T[] sourceList) where T : class
{
   var queryable = sourceList.AsQueryable();

   var dbSet = new Mock<DbSet<T>>();
   dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
   dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
   dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
   dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());

   return dbSet.Object;
}
</code>```

Thanks

答:
Update

While RhinoMocks supports mocking multiple interfaces with the same mock, as I utilized in my initial answer, it apparently doesn't support explicit intefaces, which DbSet utilizes for IQueryable. As @Dosihris pointed out in the comment, it throws an exception saying

Due to how CLR handles explicit interface implementation, we're not able to proxy this method.

This appears to be an exception from the version of Castle.DynamicProxy  (v2.1.0.5967) embedded in RhinoMocks, which is from pre-2010. Newer versions of DynamicProxy support this, so if you really wanted to be adventurous, you could recompile RhinoMocks with an updated version of DynamicProxy.

Or, you could try referencing DynamicProxy directly in your test project and using binding redirects to force RhinoMocks to use the newer version. Given the age of the version in RhinoMocks, there's likely incompatibilities with the newer DynamicProxy APIs, so this is likely not going to be successful.

Or, you could move to a framework that is still actively maintained, such as Moq or NSubstitute (which both use newer versions of DynamicProxy).

This is the equivalent logic using RhinoMocks:

using Rhino.Mocks;

private static DbSet<T> GetQueryableMockDbSet<T>(params T[] sourceList) where T : class
{
    var queryable = sourceList.AsQueryable();

    var dbSet = Rhino.Mocks.MockRepository.GenerateMock<DbSet<T>, IQueryable<T>>();

    ((IQueryable<T>)dbSet).Expect(m => m.Provider).Return(queryable.Provider);
    ((IQueryable<T>)dbSet).Expect(m => m.Expression).Return(queryable.Expression);
    ((IQueryable<T>)dbSet).Expect(m => m.ElementType).Return(queryable.ElementType);
    ((IQueryable<T>)dbSet).Expect(m => m.GetEnumerator())
            .Return(null) // will be ignored but still the API requires it
            .WhenCalled((methodInvokation) =>  methodInvokation.ReturnValue = queryable.GetEnumerator());

    return dbSet;
}
```

Depending on whether you want to do verification that the properties were called or not, you may want to use .Stub() instead of .Expect() in each of the above.

Title: Test DbSet with RhinoMock

Body:
I need to mock a DbSet with RhinoMock. I found a way to mock IDbSet, but not DbSet. I found a way with another mocking framework, but i have to use RhinoMock. Can somebody please translate it to rhino mock?

I found this on http://www.loganfranken.com/blog/517/mocking-dbset-queries-in-ef6/:

private static DbSet<T> GetQueryableMockDbSet<T>(params T[] sourceList) where T : class
{
   var queryable = sourceList.AsQueryable();

   var dbSet = new Mock<DbSet<T>>();
   dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
   dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
   dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
   dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());

   return dbSet.Object;
}

Thanks

Body:
Update

While RhinoMocks supports mocking multiple interfaces with the same mock, as I utilized in my initial answer, it apparently doesn't support explicit intefaces, which DbSet utilizes for IQueryable. As @Dosihris pointed out in the comment, it throws an exception saying

Due to how CLR handles explicit interface implementation, we're not able to proxy this method.

This appears to be an exception from the version of Castle.DynamicProxy  (v2.1.0.5967) embedded in RhinoMocks, which is from pre-2010. Newer versions of DynamicProxy support this, so if you really wanted to be adventurous, you could recompile RhinoMocks with an updated version of DynamicProxy.

Or, you could try referencing DynamicProxy directly in your test project and using binding redirects to force RhinoMocks to use the newer version. Given the age of the version in RhinoMocks, there's likely incompatibilities with the newer DynamicProxy APIs, so this is likely not going to be successful.

Or, you could move to a framework that is still actively maintained, such as Moq or NSubstitute (which both use newer versions of DynamicProxy).

This is the equivalent logic using RhinoMocks:

using Rhino.Mocks;

private static DbSet<T> GetQueryableMockDbSet<T>(params T[] sourceList) where T : class
{
    var queryable = sourceList.AsQueryable();

    var dbSet = Rhino.Mocks.MockRepository.GenerateMock<DbSet<T>, IQueryable<T>>();

    ((IQueryable<T>)dbSet).Expect(m => m.Provider).Return(queryable.Provider);
    ((IQueryable<T>)dbSet).Expect(m => m.Expression).Return(queryable.Expression);
    ((IQueryable<T>)dbSet).Expect(m => m.ElementType).Return(queryable.ElementType);
    ((IQueryable<T>)dbSet).Expect(m => m.GetEnumerator())
            .Return(null) // will be ignored but still the API requires it
            .WhenCalled((methodInvokation) =>  methodInvokation.ReturnValue = queryable.GetEnumerator());

    return dbSet;
}

Depending on whether you want to do verification that the properties were called or not, you may want to use .Stub() instead of .Expect() in each of the above.


问:
What is the default scope of a method in Java?
If I type:

```<code> void doThis(){
     System.out.println("Hello Stackoverflow.");
 }
</code>```

what is the default scope of doThis()?

Public? Protected? Private?

答: Java 8 now allows implementation of methods inside an interface itself with default scope (and static only).

OwnerDisplayName: joe

Body:
If I type:

 void doThis(){
     System.out.println("Hello Stackoverflow.");
 }

what is the default scope of doThis()?

Public? Protected? Private?


问:
My <input> box won't display single quotes
If it has a single quote in it, any string that I try to enter into my HTML input box is truncated in the input box once it is submitted.  Its POST value comes thru unchanged, but the string shows as truncated in the input box, whether I use htmlspecialchars() or not. A noobie question, no doubt, but I've tried hard to figure it out and run out of ideas. Thanks for any help.

```<code>    <!DOCTYPE html>
    <body><title> Self-inserting input_box_SO.php </title>
    <?php
    //  POST form initiation.
    ECHO "<form action='input_box_SO.php' method='post'>";

    // GET POSTed value and escape it for HTML use
    $Caption_htmlspecialchars=$_POST['Caption_htmlspecialchars'];
    $Caption_htmlspecialchars=htmlspecialchars($Caption_htmlspecialchars);
    ECHO "The echo of the variable <em> \$Caption_htmlspecialchars </em> looks like this:<br>";
    ECHO "<b> $Caption_htmlspecialchars </b><br>";
    ECHO "But in the input box, \$Caption_htmlspecialchars is truncated by a single quote: <br>";
    // ETA: Bad old line that caused the problem, now commented:
    // ECHO "<input type='text' name='Caption_htmlspecialchars' size=100 value='$Caption_htmlspecialchars' maxlength = 100 required /><br><br>";
    // ETA: Newly added line that fixes the problem:
echo '<input type="text" name="Caption_htmlspecialchars" size=100 value="'.$Caption_htmlspecialchars.'" maxlength = 100 required /><br><br>';
    // SUBMIT button.  Submits back to the same page: input_box.php
    echo "<b><input type='Submit' name='submit' value='Submit'/></b></br></br>";
    ?>
    </body></html>
</code>```

Here is what Inspect Elements > Elements shows for the input element:

 input_box_SO.php
The echo of the variable  $Caption_htmlspecialchars  looks like this:
 test with special chars. & " < > and a single quote ('), which causes truncation in the input box.
But in the input box, $Caption_htmlspecialchars is truncated by a single quote:
 and a single quote (" ),="" which="" causes="" truncation="" in="" the="" input="" box.="" '="" maxlength="100" required="">

With the Source looking like this:  value='test with special chars. & " < > and a single quote ('), which causes truncation in the input box. '

答:
You need to change your sequence of single quotes nad double quotes to display string. change your echo <input as below

```<code>echo '<input type="text" name="Caption_htmlspecialchars" size=100 value="'.$Caption_htmlspecialchars.'" maxlength = 100 required /><br><br>';
</code>```

Body:
If it has a single quote in it, any string that I try to enter into my HTML input box is truncated in the input box once it is submitted.  Its POST value comes thru unchanged, but the string shows as truncated in the input box, whether I use htmlspecialchars() or not. A noobie question, no doubt, but I've tried hard to figure it out and run out of ideas. Thanks for any help.

    <!DOCTYPE html>
    <title> Self-inserting input_box_SO.php </title>
    <?php
    //  POST form initiation.
    ECHO "<form action='input_box_SO.php' method='post'>";

    // GET POSTed value and escape it for HTML use
    $Caption_htmlspecialchars=$_POST['Caption_htmlspecialchars'];
    $Caption_htmlspecialchars=htmlspecialchars($Caption_htmlspecialchars);
    ECHO "The echo of the variable  \$Caption_htmlspecialchars  looks like this:
";
    ECHO " $Caption_htmlspecialchars
";
    ECHO "But in the input box, \$Caption_htmlspecialchars is truncated by a single quote:
";
    // ETA: Bad old line that caused the problem, now commented:
    // ECHO "<input type='text' name='Caption_htmlspecialchars' size=100 value='$Caption_htmlspecialchars' maxlength = 100 required />

";
    // ETA: Newly added line that fixes the problem:
echo '<input type="text" name="Caption_htmlspecialchars" size=100 value="'.$Caption_htmlspecialchars.'" maxlength = 100 required />

';
    // SUBMIT button.  Submits back to the same page: input_box.php
    echo "<input type='Submit' name='submit' value='Submit'/>

";
    ?>

Here is what Inspect Elements > Elements shows for the input element:

 input_box_SO.php
The echo of the variable  $Caption_htmlspecialchars  looks like this:
 test with special chars. & " < > and a single quote ('), which causes truncation in the input box.
But in the input box, $Caption_htmlspecialchars is truncated by a single quote:
 and a single quote (" ),="" which="" causes="" truncation="" in="" the="" input="" box.="" '="" maxlength="100" required="">

With the Source looking like this:  value='test with special chars. & " < > and a single quote ('), which causes truncation in the input box. '

Body:
You need to change your sequence of single quotes nad double quotes to display string. change your echo <input as below

echo '<input type="text" name="Caption_htmlspecialchars" size=100 value="'.$Caption_htmlspecialchars.'" maxlength = 100 required /><br><br>';


问:
refreshing a page after deletion Javascript
I have a page filled with a list from a database, when clicking any element of this list, the details of this element will appear on another page to be edited. user also have the option of deletion here.
the problem is after deletion process completes the original page with the list doesnt refresh, so it still displays the deleted element in the list.
i tried different methods mentioned here in stackoverflow.com but none worked as i want.
for example this answer was mentioned here:

```<code>$sql = "delete from `lesson_plans` where `LP_ID` = '" . $_SESSION['LP_ID_S']."';";
if ($conn->query($sql) === TRUE)
    {
        echo "<script>var hWndB = window.open('myplans.php'),
                hWndA = window.self;
                hWndB.onunload = function(){ hWndA.location.reload(); }
              </script>";
    }
</code>```

the problem in this code that is opens a new page with new list successfully and keeps the old one open as well, so it doesnt refresh the old one, it only open a new link in a new tab.

答:
You can refresh page in php add the below code
header('Location: '.$_SERVER['REQUEST_URI']);
if header already exist error comes then add the ob_start() in top of the page

you need to refresh page in javascript then add below code

location.reload();

Body:
I have a page filled with a list from a database, when clicking any element of this list, the details of this element will appear on another page to be edited. user also have the option of deletion here.
the problem is after deletion process completes the original page with the list doesnt refresh, so it still displays the deleted element in the list.
i tried different methods mentioned here in stackoverflow.com but none worked as i want.
for example this answer was mentioned here:

$sql = "delete from `lesson_plans` where `LP_ID` = '" . $_SESSION['LP_ID_S']."';";
if ($conn->query($sql) === TRUE)
    {
        echo "";
    }

the problem in this code that is opens a new page with new list successfully and keeps the old one open as well, so it doesnt refresh the old one, it only open a new link in a new tab.