问:
Hide header and footer when printing from Internet Explorer using Javascript or CSS
When I print a webpage from Internet Explorer it will automatically add a header and footer including the website title, URL, date, and page number.

Is it possible to hide the header and footer programatically using Javascript or CSS?

Requirements:

works in IE 6 (no other browser support necessary as its for an Intranet)

may use ActiveX, Java Applet, Javascript, CSS

preferably not something that the user needs to install (eg. http://www.meadroid.com/scriptx). feel free to list other third party available plug-ins though as I think this may be the only option

don't require the user to manually update their browser settings

don't render the pages as PDF or Word document or any other format

don't write to the registry (security prevents this)

Thanks

答:
In your print options you can disable this. The only way to do it programatically is with an activeX control which writes to the registry or a script block which is written in VB. The settings for your print options are stored in the registry. The user would have to allow your script to access the registry which most people wouldnt because of security.

If you want to control page content, you can use a css print stylesheet.

Edit: There are 3rd party active x controls which can programatically print for you, but once again, the user would have to choose to download and install it.

OwnerDisplayName: molasses

LastEditorDisplayName: molasses

OwnerDisplayName: Jobo

LastEditorDisplayName: Jobo


来源: stackexchange

问:
Mysterious Ruby Block behavior: &block vs. {block.call}
When writing a helper for printing javascript that can be used from both other helpers and views, I stumbled upon the following problem:

```<code>def javascript(print_tag = false, &block)
  content_for(:javascript) do
    if print_tag
      javascript_tag(&block)          # does not work
      javascript_tag { block.call }   # does work
    else
      capture(&block)
    end
  end
end
</code>```

This helper should be called with javascript { "alert('hurray'); }.

In the first alternative - which I expected to work - the Rails javascript_tag helper renders an empty  tag.

The second alternative, however, works as expected.

What's going on there? How can that be different?

答:
You say you are doing this on your views, right?

```<code><%= javascript { "alert('hurray');" } %>
</code>```

But for content_tag(&block) to work, you should call javascript the way content_tag is intended to be used in views, which is:

```<code><% javascript do %>
  alert('hurray');
<% end %>
</code>```

content_tag's behavior is different depending on where it's called from, see the function block_called_from_erb? in the source code. In the first case this function returns true because the block does come from an erb (and then it's concated, you don't want that!), in the second returns false (you re-created the block from scratch) and content_tag simply returns the string content, which is what you want.

```<code># ./action_view/helpers/javascript_helper.rb
tag = content_tag(:script, javascript_cdata_section(content), html_options.merge(:type => Mime::JS))
if block_called_from_erb?(block)
  concat(tag)
else
  tag
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When writing a helper for printing javascript that can be used from both other helpers and views, I stumbled upon the following problem:

def javascript(print_tag = false, &block)
  content_for(:javascript) do
    if print_tag
      javascript_tag(&block)          # does not work
      javascript_tag { block.call }   # does work
    else
      capture(&block)
    end
  end
end

This helper should be called with javascript { "alert('hurray'); }.

In the first alternative - which I expected to work - the Rails javascript_tag helper renders an empty  tag.

The second alternative, however, works as expected.

What's going on there? How can that be different?

Body:
You say you are doing this on your views, right?

<%= javascript { "alert('hurray');" } %>

But for content_tag(&block) to work, you should call javascript the way content_tag is intended to be used in views, which is:

<% javascript do %>
  alert('hurray');
<% end %>

content_tag's behavior is different depending on where it's called from, see the function block_called_from_erb? in the source code. In the first case this function returns true because the block does come from an erb (and then it's concated, you don't want that!), in the second returns false (you re-created the block from scratch) and content_tag simply returns the string content, which is what you want.

# ./action_view/helpers/javascript_helper.rb
tag = content_tag(:script, javascript_cdata_section(content), html_options.merge(:type => Mime::JS))
if block_called_from_erb?(block)
  concat(tag)
else
  tag
end


问:
Natural Language Processing using apache OpenNLP
How do I find the accuracy of a data in % in Natural Language Processing?

Trying to find accuracy on movie review data

Once the fresh movie review comes, to decide whether the review is positive or not, process followed as below

For training purpose used movie review file of size 400 MB which has 200 K + review comments and its corresponding ratings.

Based on the ratings in the file implemented the bag of words approach
for e.g.: if rating > 5 then put it into the good bag else bad bag

While implementing bag of words approach used below NLP techniques

Tokenization

Stop word Removal

Stemming

Special character removal etc

Once the bag is ready, with fresh review comments using NLP techniques as stated above then looking up in the bags calculating mean on good and bad bags whichever is greater based on that deciding whether the fresh review is positive or not.

Please suggest how to figure out the accuracy in %?

答: Split your data into train ans test set. Then, you can evaluate (calculate the accuracy in %) your model trained on your training set on your test. To achieve more reliable results, you can evaluate your method in cross-fold evaluation manner. </p>

ContentLicense: CC BY-SA 3.0


问:
Export HDFS file with custom delimiter into Mysql via Sqoop

I have file like this:

```<code>1^%~binod^*~1^%~ritesh^*~1^%~shisir^*~1^%~budhdha^*~1^%~romika^*~1^%~rubeena^*~
</code>```

Where --input-fields-terminated-by '^%~' --input-lines-terminated-by '^*~'.

I tried to export via command:

```<code>sqoop export --connect jdbc:mysql://localhost/sqoop --username root -P --table makalu --export-dir sqoop/makalu --input-fields-terminated-by '^%~' --input-lines-terminated-by '^*~'
</code>```

But it writes a single line of:

```
id|name
1|%~binod
```

in MySQL.

Now my question is what would be the command to solve this scenario.

答:
The argument --input-fields-terminated-by 'any delimiter in single quotes'   works. Also do not use --direct in this case as then it overrides the delimiter.
Obviously you would need a table created in mysql whose default delimited is ','</p>

Body:
I have file like this:

1^%~binod^*~1^%~ritesh^*~1^%~shisir^*~1^%~budhdha^*~1^%~romika^*~1^%~rubeena^*~

Where --input-fields-terminated-by '^%~' --input-lines-terminated-by '^*~'.

I tried to export via command:

sqoop export --connect jdbc:mysql://localhost/sqoop --username root -P --table makalu --export-dir sqoop/makalu --input-fields-terminated-by '^%~' --input-lines-terminated-by '^*~'

But it writes a single line of:

id|name
1|%~binod

in MySQL.

Now my question is what would be the command to solve this scenario.


问:
Selenium (Java) message "Unable to locate element" but element and XPath exist
I am new to Selenium WebDriver, using NetBeans Java and Firebug for Firefox to get XPath.

The problem is even though some elements are visible and clickable in the browser, and Firebug finds the XPath expression, I still get an error "Unable to locate element". The problem is, the element is not in a frame (there aren’t any frames), not in another window, it's visible and clickable and it has a clear XPath expression.

I used Wait and Thread.sleep, but it didn't help.
Also, I tried all solutions I could find on Stack Overflow similar to this matter.

The element is inside of the table which has some "div" elements inside. This is the XPath expression:

```<code>.//*[@id='NavigationRadPanelBar_i2_i0_trvStandardView']/ul/li[3]/div/span[3]
</code>```

It seems that the panel is a problem, because it can not locate the panel too. I tried another element inside the same panel which has a title and text with this:

```<code>driver.findElement(By.xpath("//*[contains(text(),'Technical Attributes')]")).click();
</code>```

But still I got same message. Similar for all elements inside this panel and panel itself. It seems whatever I tried, it's unable to locate. Everything outside of this panel is working fine with drivers.

The page has a left panel where these elements are located. Some of them are nodes that can be expanded, and some are just links, but nothing can be located.

What can be the cause of element that is obviously existing and visible, but still cannot be located by WebDriver?

I tried to locate the main panel:

```<code>    driver.findElement(By.xpath(".//*[@id='NavigationRadPane']")).click();
</code>```

but still the same exception.

This is part of the HTML content (it's very long):

```<code><div id="RAD_SLIDING_PANE_CONTENT_navigatiionRadSlidingPane" class="rspSlideContent" style="overflow: hidden; width: 200px; height: 579px;">
  <div id="NavigationRadPanelBarPanel" style="display: block;">
    <div id="NavigationRadPanelBar" class="RadPanelBar RadPanelBar_Office2007" postback="false" style="background-color:GhostWhite;height:100%;width:100%;">
      <ul class="rpRootGroup">
        <li class="rpItem rpFirst">
          <li class="rpItem">
            <li class="rpItem rpLast">
              <a class="rpLink rpExpandable rpExpanded" href="#">
                <div class="rpSlide" style="display:block;">
                  <ul class="rpGroup rpLevel1 111460" style="display: block; height: 274.731px; width: 100%;">
                    <li class="rpItem rpFirst rpLast">
                      <div class="rpTemplate">
                        <div id="NavigationRadPanelBar_i2_i0_trvStandardView" class="RadTreeView RadTreeView_Office2007">
                          <ul class="rtUL rtLines">
                            <li class="rtLI rtFirst">
                              <li class="rtLI">
                                <li class="rtLI">
                                  <div class="rtMid">
                                    <span class="rtSp" />
                                    <span class="rtPlus rtPlusHover" />
                                    <img class="rtImg" src="..." alt="Technical Attributes" />
                                    <span class="rtIn" title="Technical Attributes">Technical Attributes</span>
                                  </div>
                                  <ul class="rtUL" style="display:none;">
                                </li>
                                <li class="rtLI rtLast">
</code>```

答:
Use:

```<code>driver.switchTo().activeElement();
</code>```

This way, the driver will switch to the panel you have clicked. Then you can perform the rest of the operations you want in the panel.

ContentLicense: CC BY-SA 4.0

Body:
I am new to Selenium WebDriver, using NetBeans Java and Firebug for Firefox to get XPath.

The problem is even though some elements are visible and clickable in the browser, and Firebug finds the XPath expression, I still get an error "Unable to locate element". The problem is, the element is not in a frame (there aren’t any frames), not in another window, it's visible and clickable and it has a clear XPath expression.

I used Wait and Thread.sleep, but it didn't help.
Also, I tried all solutions I could find on Stack Overflow similar to this matter.

The element is inside of the table which has some "div" elements inside. This is the XPath expression:

.//*[@id='NavigationRadPanelBar_i2_i0_trvStandardView']/ul/li[3]/div/span[3]

It seems that the panel is a problem, because it can not locate the panel too. I tried another element inside the same panel which has a title and text with this:

driver.findElement(By.xpath("//*[contains(text(),'Technical Attributes')]")).click();

But still I got same message. Similar for all elements inside this panel and panel itself. It seems whatever I tried, it's unable to locate. Everything outside of this panel is working fine with drivers.

The page has a left panel where these elements are located. Some of them are nodes that can be expanded, and some are just links, but nothing can be located.

What can be the cause of element that is obviously existing and visible, but still cannot be located by WebDriver?

I tried to locate the main panel:

    driver.findElement(By.xpath(".//*[@id='NavigationRadPane']")).click();

but still the same exception.

This is part of the HTML content (it's very long):

                                    Technical Attributes

Body:
Use:

driver.switchTo().activeElement();

This way, the driver will switch to the panel you have clicked. Then you can perform the rest of the operations you want in the panel.


问:
GitHub Desktop: "This file is empty"
The file naaclhlt2016.tex is not empty on the client or in the repository, however GitHub Desktop displays "This file is empty". What could explain this?

The file naaclhlt2016.tex is present on GitHub repository:

git status:

It creates conflict when I try to sync:

答:
In addition to the @VonC response.

To dissmiss this alert

Git desktop

unselect all changed files

select only the "this file is empty" files

try to commit

Git will display a commit error, saying that you can't do that. After closing the modal, Git should delete the files from the changes list.

Title: GitHub Desktop: "This file is empty"


问:
sql missing from clause
```<code>  select m_product.name ,c_bpartner.name  from(
  select count(m_product.name)
  from m_product
  union
  select count(c_bpartner.name)
  from c_bpartner
  ) as total
</code>```

I am getting error.

Error:

missing from-clause entry for table m_product.

Im trying to get the total number of products and bpartner in a table.
Thank you for any help.

```<code> |total number of product|total number of bp|
 |     1000              |   1200           |
 |                       |                  |
</code>```

This is what I'am trying to achieve, I'am doing this using the jasper report.

答:
Try this:</p>

```<code> with output as (
   select count(m_product.name) from m_product union
   select count(c_bpartner.name) from c_bpartner
 )
 select * from output;
</code>```

Title: sql missing from clause

Body:
  select m_product.name ,c_bpartner.name  from(
  select count(m_product.name)
  from m_product
  union
  select count(c_bpartner.name)
  from c_bpartner
  ) as total

I am getting error.

Error:

missing from-clause entry for table m_product.

Im trying to get the total number of products and bpartner in a table.
Thank you for any help.

 |total number of product|total number of bp|
 |     1000              |   1200           |
 |                       |                  |

This is what I'am trying to achieve, I'am doing this using the jasper report.

Body:
Try this:

 with output as (
   select count(m_product.name) from m_product union
   select count(c_bpartner.name) from c_bpartner
 )
 select * from output;


问:
Ambiguity with pattern matching records
I learned from this question that it's possible to use pattern matching with records. However, I've noticed that I'm having trouble trying to match different types of records.

My goal in this example is to be able to distinguish between different records. I'm given a record that I'm not entirely sure which type it is, and I'm trying to figure it out using pattern matching.

Here's a simplified example:

```<code>module IceCream = struct
  type t = {
    temperature: float;
    toppings: string list;
  }
end

module Candy = struct
  type t = {
    flavour: string;
    colour: string;
    volume: int;
  }
end

(* Could be Candy or IceCream *)
let example =
  { Candy.
    flavour = "mint";
    colour = "green";
    volume = 10 }

let printFavoriteTreat treat = match treat with
  | { Candy.
      flavour = "mint";
      colour;
      volume } -> "It's Candy"
  | { IceCream.
      temperature;
      toppings } -> "It's IceCream"

let () = printFavoriteTreat example
</code>```

When I try to build this file, I get:

```<code>Error: The field IceCream.temperature belongs to the record type IceCream.t
       but a field was expected belonging to the record type Candy.t
</code>```

Is doing something like this possible?

答:
The answer provided by Pierre is great, but the example not so much. (I've always hated examples named a, b...)

So, as Pierre suggests, you could define your types like this:

```<code>type ice_cream = {
  temperature: float;
  toppings: string
}

type candy = {
  flavor: string;
  color: string;
  volume: int
}
</code>```

Then, you can define a type treat as a variant of these two types:

```<code>type treat =
| Candy of candy
| IceCream of ice_cream
</code>```

Then, using pattern-matching:

```<code>let print_favorite_treat = function
| Candy _ -> print_endline "You love candy!"
| IceCream _ -> print_endline "You love ice cream!"
</code>```

Title: Ambiguity with pattern matching records

Body:
I learned from this question that it's possible to use pattern matching with records. However, I've noticed that I'm having trouble trying to match different types of records.

My goal in this example is to be able to distinguish between different records. I'm given a record that I'm not entirely sure which type it is, and I'm trying to figure it out using pattern matching.

Here's a simplified example:

module IceCream = struct
  type t = {
    temperature: float;
    toppings: string list;
  }
end

module Candy = struct
  type t = {
    flavour: string;
    colour: string;
    volume: int;
  }
end

(* Could be Candy or IceCream *)
let example =
  { Candy.
    flavour = "mint";
    colour = "green";
    volume = 10 }

let printFavoriteTreat treat = match treat with
  | { Candy.
      flavour = "mint";
      colour;
      volume } -> "It's Candy"
  | { IceCream.
      temperature;
      toppings } -> "It's IceCream"

let () = printFavoriteTreat example

When I try to build this file, I get:

Error: The field IceCream.temperature belongs to the record type IceCream.t
       but a field was expected belonging to the record type Candy.t

Is doing something like this possible?

Body:
The answer provided by Pierre is great, but the example not so much. (I've always hated examples named a, b...)

So, as Pierre suggests, you could define your types like this:

type ice_cream = {
  temperature: float;
  toppings: string
}

type candy = {
  flavor: string;
  color: string;
  volume: int
}

Then, you can define a type treat as a variant of these two types:

type treat =
| Candy of candy
| IceCream of ice_cream

Then, using pattern-matching:

let print_favorite_treat = function
| Candy _ -> print_endline "You love candy!"
| IceCream _ -> print_endline "You love ice cream!"


问:
Convert column classes in data.table
I have a problem using data.table: How do I convert column classes? Here is a simple example: With data.frame I don't have a problem converting it, with data.table I just don't know how:

```<code>df <- data.frame(ID=c(rep("A", 5), rep("B",5)), Quarter=c(1:5, 1:5), value=rnorm(10))
#One way: http://stackoverflow.com/questions/2851015/r-convert-data-frame-columns-from-factors-to-characters
df <- data.frame(lapply(df, as.character), stringsAsFactors=FALSE)
#Another way
df[, "value"] <- as.numeric(df[, "value"])

library(data.table)
dt <- data.table(ID=c(rep("A", 5), rep("B",5)), Quarter=c(1:5, 1:5), value=rnorm(10))
dt <- data.table(lapply(dt, as.character), stringsAsFactors=FALSE)
#Error in rep("", ncol(xi)) : invalid 'times' argument
#Produces error, does data.table not have the option stringsAsFactors?
dt[, "ID", with=FALSE] <- as.character(dt[, "ID", with=FALSE])
#Produces error: Error in `[<-.data.table`(`*tmp*`, , "ID", with = FALSE, value = "c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2)") :
#unused argument(s) (with = FALSE)
</code>```

Do I miss something obvious here?

Update due to Matthew's post: I used an older version before, but even after updating to 1.6.6 (the version I use now) I still get an error.

Update 2: Let's say I want to convert every column of class "factor" to a "character" column, but don't know in advance which column is of which class. With a data.frame, I can do the following:

```<code>classes <- as.character(sapply(df, class))
colClasses <- which(classes=="factor")
df[, colClasses] <- sapply(df[, colClasses], as.character)
</code>```

Can I do something similar with data.table?

Update 3:

sessionInfo()
      R version 2.13.1 (2011-07-08)
      Platform: x86_64-pc-mingw32/x64 (64-bit)

```<code>locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] data.table_1.6.6

loaded via a namespace (and not attached):
[1] tools_2.13.1
</code>```

答:
try:</p>

```<code>dt <- data.table(A = c(1:5),
                 B= c(11:15))

x <- ncol(dt)

for(i in 1:x)
{
     dt[[i]] <- as.character(dt[[i]])
}
</code>```

Title: Convert column classes in data.table

Body:
I have a problem using data.table: How do I convert column classes? Here is a simple example: With data.frame I don't have a problem converting it, with data.table I just don't know how:

df <- data.frame(ID=c(rep("A", 5), rep("B",5)), Quarter=c(1:5, 1:5), value=rnorm(10))
#One way: http://stackoverflow.com/questions/2851015/r-convert-data-frame-columns-from-factors-to-characters
df <- data.frame(lapply(df, as.character), stringsAsFactors=FALSE)
#Another way
df[, "value"] <- as.numeric(df[, "value"])

library(data.table)
dt <- data.table(ID=c(rep("A", 5), rep("B",5)), Quarter=c(1:5, 1:5), value=rnorm(10))
dt <- data.table(lapply(dt, as.character), stringsAsFactors=FALSE)
#Error in rep("", ncol(xi)) : invalid 'times' argument
#Produces error, does data.table not have the option stringsAsFactors?
dt[, "ID", with=FALSE] <- as.character(dt[, "ID", with=FALSE])
#Produces error: Error in `[<-.data.table`(`*tmp*`, , "ID", with = FALSE, value = "c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2)") :
#unused argument(s) (with = FALSE)

Do I miss something obvious here?

Update due to Matthew's post: I used an older version before, but even after updating to 1.6.6 (the version I use now) I still get an error.

Update 2: Let's say I want to convert every column of class "factor" to a "character" column, but don't know in advance which column is of which class. With a data.frame, I can do the following:

classes <- as.character(sapply(df, class))
colClasses <- which(classes=="factor")
df[, colClasses] <- sapply(df[, colClasses], as.character)

Can I do something similar with data.table?

Update 3:

sessionInfo()
      R version 2.13.1 (2011-07-08)
      Platform: x86_64-pc-mingw32/x64 (64-bit)

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] data.table_1.6.6

loaded via a namespace (and not attached):
[1] tools_2.13.1

Body:
try:

dt <- data.table(A = c(1:5),
                 B= c(11:15))

x <- ncol(dt)

for(i in 1:x)
{
     dt[[i]] <- as.character(dt[[i]])
}


问:
Recursive delete
I have this code to recursive delete files and directories. It works fine but has a little problem. If $path = /var/www/foo/ it will delete everything inside of foo, but not foo. I want to delete foo directory too. Any idea? </p>

```<code>public function delete($path) {
    if(!file_exists($path)) {
        throw new RecursiveDirectoryException('Directory doesn\'t exist.');
    }

    $directoryIterator = new DirectoryIterator($path);

    foreach($directoryIterator as $fileInfo) {
        $filePath = $fileInfo->getPathname();

        if(!$fileInfo->isDot()) {
            if($fileInfo->isFile()) {
                unlink($filePath);
            }
            else if($fileInfo->isDir()) {
                if($this->emptyDirectory($filePath)) {
                    rmdir($filePath);
                }
                else {
                    $this->delete($filePath);
                    rmdir($filePath);
                }
            }
        }
    }
}
</code>```

答:
You're missing one last rmdir. You could either call it after $this->delete($path) like this:

```<code>$this->delete($path);
rmdir($path);
</code>```

Or you could change the foreach-loop like this:

```<code>public function delete($path) {
    //snip

    foreach($directoryIterator as $fileInfo) {
        //snip
                else {
                    $this->delete($filePath);
                }
            }
        }
    }

    rmdir($path);
}
</code>```

Also, I sure hope you validate what paths you get there, if this is visible to a user (like a "Delete Everything On My Webspace"-function. I mean, you'll have a lot of fun if somebody passes /etc/ into there.

Title: Recursive delete

Body:
I have this code to recursive delete files and directories. It works fine but has a little problem. If $path = /var/www/foo/ it will delete everything inside of foo, but not foo. I want to delete foo directory too. Any idea?

public function delete($path) {
    if(!file_exists($path)) {
        throw new RecursiveDirectoryException('Directory doesn\'t exist.');
    }

    $directoryIterator = new DirectoryIterator($path);

    foreach($directoryIterator as $fileInfo) {
        $filePath = $fileInfo->getPathname();

        if(!$fileInfo->isDot()) {
            if($fileInfo->isFile()) {
                unlink($filePath);
            }
            else if($fileInfo->isDir()) {
                if($this->emptyDirectory($filePath)) {
                    rmdir($filePath);
                }
                else {
                    $this->delete($filePath);
                    rmdir($filePath);
                }
            }
        }
    }
}

Body:
You're missing one last rmdir. You could either call it after $this->delete($path) like this:

$this->delete($path);
rmdir($path);

Or you could change the foreach-loop like this:

public function delete($path) {
    //snip

    foreach($directoryIterator as $fileInfo) {
        //snip
                else {
                    $this->delete($filePath);
                }
            }
        }
    }

    rmdir($path);
}

Also, I sure hope you validate what paths you get there, if this is visible to a user (like a "Delete Everything On My Webspace"-function. I mean, you'll have a lot of fun if somebody passes /etc/ into there.


问:
What Ruby technique does Rails use to make my controller methods render views?
Just curious if anybody knows what Ruby technique is used to accomplish the following in the Rails framework.

If I don't write, say, an index method on a Rails controller, Rails will still render the index view file if the URL matches that route. That makes sense, because my controller inherits from a parent class, which must have its own index method.

However, if I do define an index method, and only tell it to set an instance variable, it still renders the appropriate view. For example:

```<code>def index
  @weasels = Weasel.all

  # If I omit this line, Rails renders the index anyway.
  # If this behavior is defined in the parent class's index method,
  # it seems that by overriding the method, my index wouldn't do it.
  # I'm not explicitly calling super to get the method from
  # ActionController::Base, but maybe Rails is doing something like that?
  render :index
end
</code>```

In pure Ruby, I would expect to have to call super to get that behavior.

I assume that Rails uses some kind of metaprogramming technique to guarantee that my controller methods will call super. If so, can anyone explain it? Can you point to the source code that does this?

Update

As Mladen Jablanović has pointed out, my initial mental model was wrong; the controller method doesn't normally render the view; instead, both the controller method and the view rendering are called by some framework code. This is apparent because I can make a controller method with any name - for example, search - and the search view will get rendered. So clearly I'm not overriding a parent method in that case, and some framework code is parsing the controller method name and looking for the matching view.

Still, the framework must be able to detect whether or not the controller method has already called render. So that's another small mystery to me.

答:
When rendering a view, Rails initializes an instance of the appropriate view template with copies of the instance variables in the controller.  So the instance variables aren't actually inherited by the view, but rather copied from the controller into the view before the view is rendered.

I haven't looked up the exact details in the source, but the above explanation should at least outline the general idea of how it works.

Body:
Just curious if anybody knows what Ruby technique is used to accomplish the following in the Rails framework.

If I don't write, say, an index method on a Rails controller, Rails will still render the index view file if the URL matches that route. That makes sense, because my controller inherits from a parent class, which must have its own index method.

However, if I do define an index method, and only tell it to set an instance variable, it still renders the appropriate view. For example:

def index
  @weasels = Weasel.all

  # If I omit this line, Rails renders the index anyway.
  # If this behavior is defined in the parent class's index method,
  # it seems that by overriding the method, my index wouldn't do it.
  # I'm not explicitly calling super to get the method from
  # ActionController::Base, but maybe Rails is doing something like that?
  render :index
end

In pure Ruby, I would expect to have to call super to get that behavior.

I assume that Rails uses some kind of metaprogramming technique to guarantee that my controller methods will call super. If so, can anyone explain it? Can you point to the source code that does this?

Update

As Mladen Jablanović has pointed out, my initial mental model was wrong; the controller method doesn't normally render the view; instead, both the controller method and the view rendering are called by some framework code. This is apparent because I can make a controller method with any name - for example, search - and the search view will get rendered. So clearly I'm not overriding a parent method in that case, and some framework code is parsing the controller method name and looking for the matching view.

Still, the framework must be able to detect whether or not the controller method has already called render. So that's another small mystery to me.


问:
UIImage to another UIImage
In my project, I have two UIViewControllers. On my first ViewController, I have a UIImageView and there is an image from an url. On the second ViewController, I have an empty UIImageView.

When the user clicks on the image in the UIImageView on the first ViewController, the image in the second ViewController (which was empty before) should be the same like the clicked one on the first ViewController.

Is something like that possible? The image is from a url (like I wrote before), so i think it should work, but I have no idea how I can do that.

答:
Please follow below steps :  Swift

1) Create var in appDelegate :

```<code>var imageUrl = ""
</code>```

2) Create instance of appDelegate and set the url after click on image from firstView controller:  On click of UIImage From firstViewController....

```<code>let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate.imageUrl = self.imageUrl
</code>```

3) In ViewDidLoad() write code

```<code>let appDelegate = UIApplication.shared.delegate as? AppDelegate
let url = URL(string: appDelegate.imageUrl)
let data = try? Data(contentsOf: url)

if let imageData = data {
  let image = UIImage(data: data)
  myImageView.image =  image
}
</code>```

Or

```<code>let appDelegate = UIApplication.shared.delegate as? AppDelegate
backgroundImageView.downloadedFrom(link : appDelegate.imageUrl )
</code>```

Title: UIImage to another UIImage

Body:
Please follow below steps :  Swift

1) Create var in appDelegate :

var imageUrl = ""

2) Create instance of appDelegate and set the url after click on image from firstView controller:  On click of UIImage From firstViewController....

let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate.imageUrl = self.imageUrl

3) In ViewDidLoad() write code

let appDelegate = UIApplication.shared.delegate as? AppDelegate
let url = URL(string: appDelegate.imageUrl)
let data = try? Data(contentsOf: url)

if let imageData = data {
  let image = UIImage(data: data)
  myImageView.image =  image
}

Or

let appDelegate = UIApplication.shared.delegate as? AppDelegate
backgroundImageView.downloadedFrom(link : appDelegate.imageUrl )


问:
jQuery.click not working after adding element to the DOM
I have a simple jQuery('div#star').click(function.

The function works once when the DOM is initially loaded, but at a later time, I add a div#star to the DOM, and at that point the click function is not working.

I am using jQuery 1.4.4, and as far as I know, I shouldn't need to use .live or .bind anymore. There is never more than one div#star in the DOM at any one time. I tried changing from id="star" to class="star" but that didn't help.

Any suggestions on how to get this working or why it isn't working?

I've had the .click inside the jQuery(document).ready, and in an external js file, and neither works after adding the div to the DOM.

答:
You can use delegate instead on :

```<code>$(document).delegate('click', "selector", function() {
    //your code
});
</code>```

I hope it will help.

Body:
You can use delegate instead on :

$(document).delegate('click', "selector", function() {
    //your code
});

I hope it will help.


问:
String not Added to Observable Collection Xamarin Forms
I have created an observable collection that is updating correctly. But is only updating one of the strings in the observable collection. I have thrown a debug point in loop that is doing this and the list of strings is showing as having two items but only one of them gets added to the observable collection.

The function that sets the observable collection:

```<code>public async Task GetNotificationData()
    {
       List<string> intermediary =  _database.getMessages();

        foreach (var variable in intermediary)
        {
            DataBaseList = new ObservableCollection<string> { variable };
        }
        _DataBaseList = DataBaseList;
    }
</code>```

and the function (getMessages) that returns the data from an SQLite database:

```<code>   public List<string> getMessages()
    {

        var DataBaseSelection =  _connection.Query<MessageTable>("Select * From [MessageTable]");
        List<string> dataList = new List<string>();

        for (var i=0;i<DataBaseSelection.Count;i++)
        {
            dataList.Add(DataBaseSelection[i].message);
        }
        return dataList;

    }
</code>```

And for completeness the Xaml:

```<code><ListView
    x:Name="notificationList"
    ItemsSource="{Binding DataBaseList}">
</ListView>
</code>```

Just to be clear this is showing one of the strings in the list on the front end but not the other, like its skipping the second string in the list.
The first string in the list is "test" the second one is called "test2" but only test is showing in the list view.

Any insights?

答:
There is two approach for using an empty ObservableColletion:

Instance the ObservableColletion only once, and then use Clear() to remove all elements.

Instance a new ObservableCollection that implements the INotifyPropertyChanged interface.

Your error is due to the ObservableCollection implements INotifyCollectionChanged but it doesn't implement the INotifyPropertyChanged interface.

I hope this can help you.

Body:
I have created an observable collection that is updating correctly. But is only updating one of the strings in the observable collection. I have thrown a debug point in loop that is doing this and the list of strings is showing as having two items but only one of them gets added to the observable collection.

The function that sets the observable collection:

public async Task GetNotificationData()
    {
       List<string> intermediary =  _database.getMessages();

        foreach (var variable in intermediary)
        {
            DataBaseList = new ObservableCollection<string> { variable };
        }
        _DataBaseList = DataBaseList;
    }

and the function (getMessages) that returns the data from an SQLite database:

   public List<string> getMessages()
    {

        var DataBaseSelection =  _connection.Query<MessageTable>("Select * From [MessageTable]");
        List<string> dataList = new List<string>();

        for (var i=0;i<DataBaseSelection.Count;i++)
        {
            dataList.Add(DataBaseSelection[i].message);
        }
        return dataList;

    }

And for completeness the Xaml:

<ListView
    x:Name="notificationList"
    ItemsSource="{Binding DataBaseList}">
</ListView>

Just to be clear this is showing one of the strings in the list on the front end but not the other, like its skipping the second string in the list.
The first string in the list is "test" the second one is called "test2" but only test is showing in the list view.

Any insights?


问:
SQL Query - Find Duplicates with a Different Key
I have the following data:

```<code>id  userid  name    group
1   1       A       x
2   1       A       y
3   1       A       z
4   2       B       x
5   2       B       y
6   3       C       y
7   4       D       x
8   5       E       x
9   5       E       z
10  6       F       x
</code>```

I want to find those records that meet all this condition:

Select all rows where the a userid belongs to a group other than y but the userid also belongs to group y.

The resulting dataset will be as follows:

```<code>id  userid  name    group
1   1       A       x
3   1       A       z
4   2       B       x
</code>```

If you see, it has resulted in two records for userid a because these are two two records belong to groups other than y but the userid 1 also belongs to group y. Same for userid 2.

I have been breaking my head on how to get this in an SQL statement but not even close to a solution.

Any help is appreciated.

答:
You can get all the users that meet the condition using aggregation and having:

```<code>select userid
from t
group by userid
having sum( group = 'y' ) > 0 and
       sum( group <> 'y') > 0;
</code>```

I leave it to your to put this into a query to get all the original rows.

Body:
I have the following data:

id  userid  name    group
1   1       A       x
2   1       A       y
3   1       A       z
4   2       B       x
5   2       B       y
6   3       C       y
7   4       D       x
8   5       E       x
9   5       E       z
10  6       F       x

I want to find those records that meet all this condition:

Select all rows where the a userid belongs to a group other than y but the userid also belongs to group y.

The resulting dataset will be as follows:

id  userid  name    group
1   1       A       x
3   1       A       z
4   2       B       x

If you see, it has resulted in two records for userid a because these are two two records belong to groups other than y but the userid 1 also belongs to group y. Same for userid 2.

I have been breaking my head on how to get this in an SQL statement but not even close to a solution.

Any help is appreciated.

Body:
You can get all the users that meet the condition using aggregation and having:

select userid
from t
group by userid
having sum( group = 'y' ) > 0 and
       sum( group <> 'y') > 0;

I leave it to your to put this into a query to get all the original rows.


问:
How to get reference to store in react/redux?
In my reactjs-universal component I wrote this:

```<code>const mapStateToProps = (store) => {
  return {
    cars: store
  }
}

export default connect(mapStateToProps)(SearchForm)
</code>```

In the same component I would like to dispatch an action like :

```<code> store.dispatch({type: 'SHOWDETAIL', data: 'hi'});
</code>```

When this is run I get:

```<code>Uncaught TypeError: _create2.default.dispatch is not a function
</code>```

Is it possible to get a reference to the store somehow in my component so I can dispatch the action?

答:
connect will call mapStateToProps with the state as argument not the store.

It seems that in your case you don't need reference to the store, and using connect to map dispatch to the props is enough.

```<code>const mapStateToProps = (store) => {
  return {
    cars: store
  }
}

const mapDispatchToProps = dispatch => {
  return {
    action : () => dispatch({
      type : 'ACTION_NAME'
    })
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchForm)
</code>```

If you really want the store you should just export it from where you create it and import it where you need it, it isn't the purpose of connect to pass the store.

Body:
In my reactjs-universal component I wrote this:

const mapStateToProps = (store) => {
  return {
    cars: store
  }
}

export default connect(mapStateToProps)(SearchForm)

In the same component I would like to dispatch an action like :

 store.dispatch({type: 'SHOWDETAIL', data: 'hi'});

When this is run I get:

Uncaught TypeError: _create2.default.dispatch is not a function

Is it possible to get a reference to the store somehow in my component so I can dispatch the action?

Body:
connect will call mapStateToProps with the state as argument not the store.

It seems that in your case you don't need reference to the store, and using connect to map dispatch to the props is enough.

const mapStateToProps = (store) => {
  return {
    cars: store
  }
}

const mapDispatchToProps = dispatch => {
  return {
    action : () => dispatch({
      type : 'ACTION_NAME'
    })
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchForm)

If you really want the store you should just export it from where you create it and import it where you need it, it isn't the purpose of connect to pass the store.


问:
Unable to validate form with single field, with ajax post
I've been unable to find a solution to my problem from searching. So I'd like to ask what might be wrong with my code. I'm trying to validate a form from forms.ModelForm but in my views function it won't pass the form.is_valid(). printing form.errors gives me:

```<code><li>title<ul class="errorlist"><li>This field is required.</li></ul>
</code>```

Model:

```<code>class Paper(models.Model):
    title = models.CharField(max_length=100, help_text='Hello World!')
</code>```

forms.FormModel

```<code>class eventCreateForm(forms.ModelForm):

    class Meta:
        Model = Paper
        fields = ['title']

        widgets = {
            'title': forms.TextInput(attrs={'class' :'form-control', 'placeholder' : 'Place title'}),
        }
</code>```

Views

```<code>def create_paper(request):

    context = {}

    if request.method == 'POST':
        form = paperCreateForm(request.POST or None, request.FILES or None)

        if form.is_valid():

            form_data = form.cleaned_data
            t1 = form_data['title']
            print(t1)

        else:

            context['create_paper_form'] = form

    form_template = "user/paper-event-template.html"

    return HttpResponse(render_to_string(form_template, {'context' : context}))
</code>```

The form dosen't get validated, and in the else clause it'll pass the error when trying to retrieve it from the cleaned_data

I did try and print the form, and it shows:

```<code><tr><th><label for="id_title">Title:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input class="form-control" id="id_title" maxlength="100" name="title" placeholder="Place Title" type="text" required /></td></tr>
</code>```

But it dosen't contain any value, which I guess it should: I use a jax method for sending the forms data:

ajax

```<code>$('#create_paper_form_id').submit(function (event) {
        event.preventDefault();

        $.ajax({
            type: "POST",
            url: "{% url 'Eapp:create_paper' %}",
            data: {
                csrfmiddlewaretoken : '{{ csrf_token }}',
                form_data : $('#create_paper_form_id').serializeArray(),

                },
            success: function (data) {
                console.log(data);
                $('.create-paper').html(data);
            },
            error: function() {
                console.log('err');
            }
        });
  });
</code>```

html

```<code><div class="create-paper">
    <div class="container-fluid">
        <form class="form" id="create_paper_form_id" novalidate="novalidate" action="{% url 'Eapp:create_event' %}" method="POST">
            {% for field in create_paper_form %}
            <div class="form-group">
                <div class="col-xs-12">
                    {{ field.label_tag }}
                </div>
                <div class="col-xs-12">
                    {{ field }}
                </div>
                <div class="col-xs-6">
                    {{ field.help_text }}
                </div>
                <div class="col-xs-6">
                    {{ field.errors }}
                </div>
            </div>
            {% endfor %}
            <div class="form-group">
                <div class="col-xs-6  col-sm-6 col-md-2 col-lg-2">
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
            </div>
        </form>
    </div>
</div>
</code>```

答:
That's expected behaviour, the cleaned_data is only available on a valid form when there's actually cleaned data available.

The form.data is still available though, you can use that.

To quote the manual:

A Form instance has an is_valid() method, which runs validation
  routines for all its fields. When this method is called, if all fields
  contain valid data, it will:

return True

place the form’s data in its cleaned_data attribute.

[edit] As @fazil-zaid mentioned, you need to include model in your Meta class for it to function as a modelform.

Body:
I've been unable to find a solution to my problem from searching. So I'd like to ask what might be wrong with my code. I'm trying to validate a form from forms.ModelForm but in my views function it won't pass the form.is_valid(). printing form.errors gives me:

title

This field is required.

Model:

class Paper(models.Model):
    title = models.CharField(max_length=100, help_text='Hello World!')

forms.FormModel

class eventCreateForm(forms.ModelForm):

    class Meta:
        Model = Paper
        fields = ['title']

        widgets = {
            'title': forms.TextInput(attrs={'class' :'form-control', 'placeholder' : 'Place title'}),
        }

Views

def create_paper(request):

    context = {}

    if request.method == 'POST':
        form = paperCreateForm(request.POST or None, request.FILES or None)

        if form.is_valid():

            form_data = form.cleaned_data
            t1 = form_data['title']
            print(t1)

        else:

            context['create_paper_form'] = form

    form_template = "user/paper-event-template.html"

    return HttpResponse(render_to_string(form_template, {'context' : context}))

The form dosen't get validated, and in the else clause it'll pass the error when trying to retrieve it from the cleaned_data

I did try and print the form, and it shows:

Title:

This field is required.

<input class="form-control" id="id_title" maxlength="100" name="title" placeholder="Place Title" type="text" required />

But it dosen't contain any value, which I guess it should: I use a jax method for sending the forms data:

ajax

$('#create_paper_form_id').submit(function (event) {
        event.preventDefault();

        $.ajax({
            type: "POST",
            url: "{% url 'Eapp:create_paper' %}",
            data: {
                csrfmiddlewaretoken : '{{ csrf_token }}',
                form_data : $('#create_paper_form_id').serializeArray(),

                },
            success: function (data) {
                console.log(data);
                $('.create-paper').html(data);
            },
            error: function() {
                console.log('err');
            }
        });
  });

html

        <form class="form" id="create_paper_form_id" novalidate="novalidate" action="{% url 'Eapp:create_event' %}" method="POST">
            {% for field in create_paper_form %}

                    {{ field.label_tag }}

                    {{ field }}

                    {{ field.help_text }}

                    {{ field.errors }}

            {% endfor %}

                    <button type="submit" class="btn btn-primary">Submit</button>

        </form>


答:
Use exists

```<code>select *
from MyTable a2
where name_group <> 'y'
and exists (select 1
            from MyTable a2
            where a2.name_group = 'y'
            and a2.userid = a1.userid)
</code>```

Title: SQL Query - Find Duplicates with a Different Key

Body:
Use exists

select *
from MyTable a2
where name_group <> 'y'
and exists (select 1
            from MyTable a2
            where a2.name_group = 'y'
            and a2.userid = a1.userid)


问:
Why Won't HTML Table Rows Sort Using Flexbox?
This code does not reorder the display of rows to c, b, a as desired. Changing table and tr to divs (and removing tds) does work. Does anyone know why, or a way to keep semantic HTML tables and sort using flexbox?

#results { display: flex; }
#rowa { order: 3; }
#rowb { order: 2; }
#rowc { order: 1; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="results">
    <tr id="rowa"><td>a</td></tr>
    <tr id="rowb"><td>b</td></tr>
    <tr id="rowc"><td>c</td></tr>
</table></code>```

答:
This won't work as between the table and tr exist a tbody, which you either add yourself, or it will be added as an anonymous one.

So in this case it's not the tr that becomes flex item, the tbody is.

Add tbody to your rule and it will work

#results tbody { display: flex; }
#rowa { order: 3; }
#rowb { order: 2; }
#rowc { order: 1; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="results">
    <tr id="rowa"><td>a</td></tr>
    <tr id="rowb"><td>b</td></tr>
    <tr id="rowc"><td>c</td></tr>
</table></code>```

Updated

Based on the fact that with table this would lay out vertical, and for that to happen with Flexbox, we need to add flex-direction: column

#results tbody { display: flex; flex-direction: column; }
#rowa { order: 3; }
#rowb { order: 2; }
#rowc { order: 1; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="results">
    <tr id="rowa"><td>a</td></tr>
    <tr id="rowb"><td>b</td></tr>
    <tr id="rowc"><td>c</td></tr>
</table></code>```

Body:
This code does not reorder the display of rows to c, b, a as desired. Changing table and tr to divs (and removing tds) does work. Does anyone know why, or a way to keep semantic HTML tables and sort using flexbox?

#results { display: flex; }
#rowa { order: 3; }
#rowb { order: 2; }
#rowc { order: 1; }

a

b

c

Body:
This won't work as between the table and tr exist a tbody, which you either add yourself, or it will be added as an anonymous one.

So in this case it's not the tr that becomes flex item, the tbody is.

Add tbody to your rule and it will work

#results tbody { display: flex; }
#rowa { order: 3; }
#rowb { order: 2; }
#rowc { order: 1; }

<table id="results">
    <tr id="rowa"><td>a</td></tr>
    <tr id="rowb"><td>b</td></tr>
    <tr id="rowc"><td>c</td></tr>
</table>

Updated

Based on the fact that with table this would lay out vertical, and for that to happen with Flexbox, we need to add flex-direction: column

#results tbody { display: flex; flex-direction: column; }
#rowa { order: 3; }
#rowb { order: 2; }
#rowc { order: 1; }

<table id="results">
    <tr id="rowa"><td>a</td></tr>
    <tr id="rowb"><td>b</td></tr>
    <tr id="rowc"><td>c</td></tr>
</table>


答:
```<code>function delete($path){
    if(!file_exists($path)) {
        throw new RecursiveDirectoryException('Directory doesn\'t exist.');
    }

    $directoryIterator = new DirectoryIterator($path);

    foreach($directoryIterator as $fileInfo) {
        $filePath = $fileInfo->getPathname();

        if(!$fileInfo->isDot()) {
            if($fileInfo->isFile()) {
                unlink($filePath);
            }
            else if($fileInfo->isDir()) {
                if($this->emptyDirectory($filePath)) {
                    rmdir($filePath);
                }
                else {
                    $this->delete($filePath);
                    rmdir($filePath);
                }
            }
        }
    }
    rmdir($path);
}
</code>```

<p>?</p>

Title: Recursive delete

Body:
function delete($path){
    if(!file_exists($path)) {
        throw new RecursiveDirectoryException('Directory doesn\'t exist.');
    }

    $directoryIterator = new DirectoryIterator($path);

    foreach($directoryIterator as $fileInfo) {
        $filePath = $fileInfo->getPathname();

        if(!$fileInfo->isDot()) {
            if($fileInfo->isFile()) {
                unlink($filePath);
            }
            else if($fileInfo->isDir()) {
                if($this->emptyDirectory($filePath)) {
                    rmdir($filePath);
                }
                else {
                    $this->delete($filePath);
                    rmdir($filePath);
                }
            }
        }
    }
    rmdir($path);
}

?


问:
Is it possible to FTP from a file server directly to S3 without going through EC2?
I need to transfer files from a FTP server to S3. Usually, I would FTP to EC2 and from there load to S3. Was wondering if there is a way to transfer directly from FTP server to S3?</p>

答:
Amazon S3 does not support the FTP protocol.

However, you could certainly run some software on the machine that is hosting FTP, which talks directly with Amazon S3. There is no need to use an Amazon EC2 instance to communicate with S3.

For example, the AWS Command-Line Interface (CLI) has an aws s3 sync command that synchronizes files to/from Amazon S3. You could have users send their files to the FTP Server, which stores the files in a given directory. The server could then run the aws s3 sync command at regular intervals (eg every 5 minutes), which ensures that the files are copied up to S3.

You would simply need to load the AWS CLI onto the FTP Host.


问:
stop user to go login page when user logged in using ionic
I want that if a user is logged in he can't go to the login and OTP page by hardware back button.

```<code>.controller('viewoemCtrl', function($rootScope,$scope,$http,$ionicPopup,$state,$ionicHistory,$ionicLoading,productService,$ionicPlatform) {
$scope.user = {};  //declares the object user

 $ionicPlatform.onHardwareBackButton(function () {
    if (true) { // your check here
        $ionicPopup.confirm({
            title: 'Exit from App!',
            template: 'are you sure you want to exit?'
        }).then(function (res) {
            if (res) {
                navigator.app.exitApp();
            }
        })
    }
 })
 })
</code>```

答:
You don't need to check the click on the back button, because that itself will call a state transition from ui-router.
just register a callback to the $stateChangeStart event fired by ui-router and control there if the user is logged in and if the target state is login, in this case you prevent the transition.
This will handle any case of state transition (the back button, a direct link from the menu etc.)

```<code> $rootScope.$on('$stateChangeStart', function(event, toState, toParams,
  fromState, fromParams){
   //userIsLogged is a flag you should retrieve from your code
   if(userIsLogged && toState === 'login'){
     event.preventDefault();
   }
 })
</code>```

take a look at the documentation

Body:
I want that if a user is logged in he can't go to the login and OTP page by hardware back button.

.controller('viewoemCtrl', function($rootScope,$scope,$http,$ionicPopup,$state,$ionicHistory,$ionicLoading,productService,$ionicPlatform) {
$scope.user = {};  //declares the object user

 $ionicPlatform.onHardwareBackButton(function () {
    if (true) { // your check here
        $ionicPopup.confirm({
            title: 'Exit from App!',
            template: 'are you sure you want to exit?'
        }).then(function (res) {
            if (res) {
                navigator.app.exitApp();
            }
        })
    }
 })
 })

Body:
You don't need to check the click on the back button, because that itself will call a state transition from ui-router.
just register a callback to the $stateChangeStart event fired by ui-router and control there if the user is logged in and if the target state is login, in this case you prevent the transition.
This will handle any case of state transition (the back button, a direct link from the menu etc.)

 $rootScope.$on('$stateChangeStart', function(event, toState, toParams,
  fromState, fromParams){
   //userIsLogged is a flag you should retrieve from your code
   if(userIsLogged && toState === 'login'){
     event.preventDefault();
   }
 })

take a look at the documentation


问:
Create an enum with string values
Following code can be used to create an enum in TypeScript:

```<code>enum e {
    hello = 1,
    world = 2
};
</code>```

And the values can be accessed by:

```<code>e.hello;
e.world;
</code>```

How do I create an enum with string values?

```<code>enum e {
    hello = "hello", // error: cannot convert string to e
    world = "world"  // error
};
</code>```

答:
If what you want is mainly easy debug (with fairly type check) and don't need to specify special values for the enum, this is what I'm doing:

```<code>export type Enum = { [index: number]: string } & { [key: string]: number } | Object;

/**
 * inplace update
 * */
export function enum_only_string<E extends Enum>(e: E) {
  Object.keys(e)
    .filter(i => Number.isFinite(+i))
    .forEach(i => {
      const s = e[i];
      e[s] = s;
      delete e[i];
    });
}

enum AuthType {
  phone, email, sms, password
}
enum_only_string(AuthType);
</code>```

If you want to support legacy code/data storage, you might keep the numeric keys.

This way, you can avoid typing the values twice.

Title: Create an enum with string values

Body:
Following code can be used to create an enum in TypeScript:

enum e {
    hello = 1,
    world = 2
};

And the values can be accessed by:

e.hello;
e.world;

How do I create an enum with string values?

enum e {
    hello = "hello", // error: cannot convert string to e
    world = "world"  // error
};

Body:
If what you want is mainly easy debug (with fairly type check) and don't need to specify special values for the enum, this is what I'm doing:

export type Enum = { [index: number]: string } & { [key: string]: number } | Object;

/**
 * inplace update
 * */
export function enum_only_string<E extends Enum>(e: E) {
  Object.keys(e)
    .filter(i => Number.isFinite(+i))
    .forEach(i => {
      const s = e[i];
      e[s] = s;
      delete e[i];
    });
}

enum AuthType {
  phone, email, sms, password
}
enum_only_string(AuthType);

If you want to support legacy code/data storage, you might keep the numeric keys.

This way, you can avoid typing the values twice.


问:
Pusher is not working on Production server- Laravel Broadcasting
Hi i am trying to up and running pusher on production server but it is only logging events to logs.

here are my settings for this

```<code>PUSHER_APP_ID=myappid
PUSHER_APP_KEY=myappkey
PUSHER_APP_SECRET=myappsecret
</code>```

here is broadcasting.php

```<code>  'default' => 'pusher',

'connections' => [

    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' =>'eu'
        ],
    ],
</code>```

Broadcast service provider is also uncommented

```<code>App\Providers\BroadcastServiceProvider::class,
</code>```

but it is still logging events to log i dont know why is there a solution. it is working fine on local

答:
Laravel caches the config in the bootstrap/cache/ directory, you can check this by doing:

```<code>$ php artisan tinker
</code>```

And output the current config with:

```<code>config('broadcasting');
</code>```

Now you see what Laravel uses for config.

If that is different than your config file or .env or env, perform:

```<code>$ php artisan config:clear
</code>```

If you want to prevent this in the future, do a config:clear after deploying your code.

Body:
Hi i am trying to up and running pusher on production server but it is only logging events to logs.

here are my settings for this

PUSHER_APP_ID=myappid
PUSHER_APP_KEY=myappkey
PUSHER_APP_SECRET=myappsecret

here is broadcasting.php

  'default' => 'pusher',

'connections' => [

    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' =>'eu'
        ],
    ],

Broadcast service provider is also uncommented

App\Providers\BroadcastServiceProvider::class,

but it is still logging events to log i dont know why is there a solution. it is working fine on local

Body:
Laravel caches the config in the bootstrap/cache/ directory, you can check this by doing:

$ php artisan tinker

And output the current config with:

config('broadcasting');

Now you see what Laravel uses for config.

If that is different than your config file or .env or env, perform:

$ php artisan config:clear

If you want to prevent this in the future, do a config:clear after deploying your code.


问:
On widget ready in CKEditor
How do i trigger something when a widget is ready in CKEditor? I see that widgets have a ready event, and i need to execute some code after everything is ready.

I tried something like this:

```<code> editor.widgets.add("cool widget name", {
            button: "Do stuff",
            template: "<span class='class'><span class='some-class'></span><span class='some-otherclass'></span></span>",
            editables: {
                content: {
                    selector: ".class",
                    allowedContent: 'span[*](*);'
                }
            },
            allowedContent: 'span[*];',
            upcast: function (element) {
                return element.name == 'span' && element.hasClass(".class");
            },
            init: function () {
                $(this).on('ready', function() {
                    // stuff
                }
                doStuff(this);
            }
        });
</code>```

答:
... So i just removed the jQuery stuff and it seems to work.</p>

```<code>init: function () {
           this.on('ready', function() {
                // stuff
            }
            doStuff(this);
        }
</code>```

Title: On widget ready in CKEditor

Body:
How do i trigger something when a widget is ready in CKEditor? I see that widgets have a ready event, and i need to execute some code after everything is ready.

I tried something like this:

 editor.widgets.add("cool widget name", {
            button: "Do stuff",
            template: "",
            editables: {
                content: {
                    selector: ".class",
                    allowedContent: 'span[*](*);'
                }
            },
            allowedContent: 'span[*];',
            upcast: function (element) {
                return element.name == 'span' && element.hasClass(".class");
            },
            init: function () {
                $(this).on('ready', function() {
                    // stuff
                }
                doStuff(this);
            }
        });

Body:
... So i just removed the jQuery stuff and it seems to work.

init: function () {
           this.on('ready', function() {
                // stuff
            }
            doStuff(this);
        }


问:
Unable to encode aztec codes correctly
I am trying to create an aztec code with the payload below for android app with the help of zxing. However, after feeding this into the aztec generator, I am unable to read this payload after scanning the barcode. The reader linked to zxing decodes a completely different barcode payload.

Has anyone else seen this issue? Or am I generating the Aztec code incorrectly?

Thanks for the help

barcode_payload:

i¼\u0000\u0003\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)X“}ôZv\u0002ô\u0000\u0000˜\u0012\u0012äNMGX†Ô\u0000\u0001Zv\u0002ô05\u0002\u0018T 64\u0011k\u0007m[\u000fç“‰¿RÙƒ¨<úýá‹M\u0002\u0019\u0000 É¼ÏØ\u0010Ë¢\u0003d·ã Í\u000bÚæ? Ÿ#+\u0017˜\u0000

Code:

```<code>public static Bitmap createAztec(String str, int mQrWidth, int mQrHeight, String timestampStr) {
    String aztecStr;
    if (!TextUtils.isEmpty(timestampStr)) {
        aztecStr = str + "|" + timestampStr;
    } else {
        aztecStr = str;
    }
    AztecCode aztecCode = com.google.zxing.aztec.encoder.Encoder.encode(aztecStr.getBytes());
    BitMatrix matrix = aztecCode.getMatrix();
    if (matrix != null) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = matrix.get(x, y) ? Color.BLACK : Color.WHITE;
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return Bitmap.createScaledBitmap(bitmap, mQrWidth, mQrHeight, false);
    }
    return null;
}
</code>```

答: The solution was simple, instead of getting default UTF-8 charset, I had to use ISO-8859-1, ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1</p>

Title: Unable to encode aztec codes correctly

Body:
I am trying to create an aztec code with the payload below for android app with the help of zxing. However, after feeding this into the aztec generator, I am unable to read this payload after scanning the barcode. The reader linked to zxing decodes a completely different barcode payload.

Has anyone else seen this issue? Or am I generating the Aztec code incorrectly?

Thanks for the help

barcode_payload:

i¼\u0000\u0003\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000)X“}ôZv\u0002ô\u0000\u0000˜\u0012\u0012äNMGX†Ô\u0000\u0001Zv\u0002ô05\u0002\u0018T 64\u0011k\u0007m[\u000fç“‰¿RÙƒ¨<úýá‹M\u0002\u0019\u0000 É¼ÏØ\u0010Ë¢\u0003d·ã Í\u000bÚæ? Ÿ#+\u0017˜\u0000

Code:

public static Bitmap createAztec(String str, int mQrWidth, int mQrHeight, String timestampStr) {
    String aztecStr;
    if (!TextUtils.isEmpty(timestampStr)) {
        aztecStr = str + "|" + timestampStr;
    } else {
        aztecStr = str;
    }
    AztecCode aztecCode = com.google.zxing.aztec.encoder.Encoder.encode(aztecStr.getBytes());
    BitMatrix matrix = aztecCode.getMatrix();
    if (matrix != null) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = matrix.get(x, y) ? Color.BLACK : Color.WHITE;
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return Bitmap.createScaledBitmap(bitmap, mQrWidth, mQrHeight, false);
    }
    return null;
}


答: You don't get a reference to the store object, but to the state inside of the store. The second parameter of the connect function is mapDispatchToProps. This gives you access to the dispatch function.</p>

Title: How to get reference to store in react/redux?


问:
Unable to type in input after adding value in React Js
I have tried with the following code with react js

```<code>import React, { Component } from 'react';
import Sidebar from './../Sidebar';
import Header from './../Header';
import {get_profile} from './../services/Services';
import $ from 'jquery';

export default class Profile extends Component {
  constructor(props) {
    super(props);
    this.state = { userDetails: '' } ;
  }
  componentWillMount() {
    $(window).scrollTop(0)
    console.log('sdfds')
    get_profile().then((response) => {

        var userResults = $.parseJSON(response.text);
        this.setState({ userDetails: userResults.response });
         console.log(userResults);
    }).catch((error) => {
            //alert(error)
        console.log(error);

    });
  }
  handleChange(event) {
        console.log(event.target.id)
        this.setState({[event.target.name]: event.target.value});
 }

  render() {
    return (
    <div className="admin-panel">
        <Sidebar />
        <Header />
        <div className="main-content">
            <div className="contents">
                <div className="container-fluid">
                    <div className="row">
                        <div className="col-sm-6">
                            <h2 className="page-title">Profile</h2>
                            <div className="form-group">
                                <label >First Name</label>
                                <input type="text" id="firstName"  className="form-control" value={this.state.userDetails.firstName}  />
                            </div>
                            <div className="form-group">
                                <label >Last Name</label>
                                <input type="text" id="lastName"  className="form-control" value={this.state.userDetails.lastName} />
                            </div>
                            <div className="form-group">
                                <label >Email</label>
                                <input type="text" id="email" name="email" className="form-control" value={this.state.userDetails.email} />
                            </div>
                            <button type="button" className="btn btn-squared btn-success margin-inline" onClick={(e)=> {this.profileUpdate()}}>Update</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    );
  }
}
</code>```

After fetching the results i'm unable to edit the input box value. I have tried with defaultValue but that also not working for me. I'm struck with this issue, Kindly help me to solve the issue.

答:
Just pass an onChange handler to the input which will update the value of the corresponding key of userDetails like this:

```<code>    <input
      ...
      value={this.state.userDetails.firstName}
      onChange={this.onChange}
      />
    onChange(e) {
      this.setState((previousState) => {
        const userDetails = previousState.userDetails
        return { userDetails: {...userDetails, firstName: e.target.value} }
      })
    }
</code>```

or you can write a common onChange function like this:

```<code>    <input
      ...
      value={this.state.userDetails.firstName}
      onChange={(e) => {this.onChange(e.target.value, 'firstName')}}
      />
    <input
      ...
      value={this.state.userDetails.lastName}
      onChange={(e) => {this.onChange(e.target.value, 'lastName')}}
    />
    <input
      ...
      value={this.state.userDetails.email}
      onChange={(e) => {this.onChange(e.target.value, 'email')}}
    />

    onChange(value, key) {
      this.setState((previousState) => {
        const userDetails = previousState.userDetails
        return { userDetails: {...userDetails, [key]: value} }
      })
    }
</code>```

Body:
I have tried with the following code with react js

import React, { Component } from 'react';
import Sidebar from './../Sidebar';
import Header from './../Header';
import {get_profile} from './../services/Services';
import $ from 'jquery';

export default class Profile extends Component {
  constructor(props) {
    super(props);
    this.state = { userDetails: '' } ;
  }
  componentWillMount() {
    $(window).scrollTop(0)
    console.log('sdfds')
    get_profile().then((response) => {

        var userResults = $.parseJSON(response.text);
        this.setState({ userDetails: userResults.response });
         console.log(userResults);
    }).catch((error) => {
            //alert(error)
        console.log(error);

    });
  }
  handleChange(event) {
        console.log(event.target.id)
        this.setState({[event.target.name]: event.target.value});
 }

  render() {
    return (

        <Sidebar />

Profile

                                First Name
                                <input type="text" id="firstName"  className="form-control" value={this.state.userDetails.firstName}  />

                                Last Name
                                <input type="text" id="lastName"  className="form-control" value={this.state.userDetails.lastName} />

                                Email
                                <input type="text" id="email" name="email" className="form-control" value={this.state.userDetails.email} />

                            <button type="button" className="btn btn-squared btn-success margin-inline" onClick={(e)=> {this.profileUpdate()}}>Update</button>

    );
  }
}

After fetching the results i'm unable to edit the input box value. I have tried with defaultValue but that also not working for me. I'm struck with this issue, Kindly help me to solve the issue.

Body:
Just pass an onChange handler to the input which will update the value of the corresponding key of userDetails like this:

    <input
      ...
      value={this.state.userDetails.firstName}
      onChange={this.onChange}
      />
    onChange(e) {
      this.setState((previousState) => {
        const userDetails = previousState.userDetails
        return { userDetails: {...userDetails, firstName: e.target.value} }
      })
    }

or you can write a common onChange function like this:

    <input
      ...
      value={this.state.userDetails.firstName}
      onChange={(e) => {this.onChange(e.target.value, 'firstName')}}
      />
    <input
      ...
      value={this.state.userDetails.lastName}
      onChange={(e) => {this.onChange(e.target.value, 'lastName')}}
    />
    <input
      ...
      value={this.state.userDetails.email}
      onChange={(e) => {this.onChange(e.target.value, 'email')}}
    />

    onChange(value, key) {
      this.setState((previousState) => {
        const userDetails = previousState.userDetails
        return { userDetails: {...userDetails, [key]: value} }
      })
    }


问:
Redirect from http to https using Angular and Apache not working
I have an SSL cert installed and I'd like to redirect all traffic from http to https. I've added this section to my Apache server:

```<code>IncludeOptional conf.d/*.conf
<VirtualHost *:80>
    ServerName www.memoriesgameseries.com
    Redirect "/" "https://www.memoriesgameseries.com/"
</VirtualHost>
Listen 443
<VirtualHost *:443>
    ServerName www.memoriesgameseries.com
    SSLEngine on
    SSLCertificateFile "/etc/httpd/memoriesgameseries_com.crt"
    SSLCACertificateFile "/etc/httpd/memoriesgameseries_com.ca-bundle"
    SSLCertificateKeyFile "/etc/httpd/memoriesgameseries.com.key"
</VirtualHost>
</code>```

As per the Apache documentation. My Angular routing file looks like this:

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { MemoriesComponent }  from '../memories/memories.component';
import { TearsComponent }  from '../tears/tears.component';

const routes: Routes = [
  { path: '', redirectTo: 'memories', pathMatch: 'full' },
  { path: 'memories', component: MemoriesComponent },
  { path: 'tears', component: TearsComponent }
]

@NgModule({
  imports: [ RouterModule.forRoot(routes)],
  exports: [ RouterModule ]
})

export class RoutingModule {};
</code>```

However, whenever I attempt to access the website via http, instead of correctly redirecting, when I type in a root address, such as www.memoriesgameseries.com and http://memoriesgameseries the redirect fails to kick in at all. When I type in a URL above the root domain, such as http://memoriesgameseries.com/memories the redirect kicks in and I see the https URL in the browser (e.g. https://www.memoriesgameseries.com/memories), but I get a:

Not Found

The requested URL /memories was not found on this server.

Response from the server. What's likely to be causing this issue?

答:
The point is that server are trying to manage 404. That's no life, let SPA do that for you. </p>

<p>When 404 redirect to index.html </p>

```<code>  RewriteEngine On
  # If an existing asset or directory is requested go to it as it is
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
  RewriteRule ^ - [L]

  # If the requested resource doesn't exist, use index.html
  RewriteRule ^ /index.html
</code>```

Body:
I have an SSL cert installed and I'd like to redirect all traffic from http to https. I've added this section to my Apache server:

IncludeOptional conf.d/*.conf
<VirtualHost *:80>
    ServerName www.memoriesgameseries.com
    Redirect "/" "https://www.memoriesgameseries.com/"
</VirtualHost>
Listen 443
<VirtualHost *:443>
    ServerName www.memoriesgameseries.com
    SSLEngine on
    SSLCertificateFile "/etc/httpd/memoriesgameseries_com.crt"
    SSLCACertificateFile "/etc/httpd/memoriesgameseries_com.ca-bundle"
    SSLCertificateKeyFile "/etc/httpd/memoriesgameseries.com.key"
</VirtualHost>

As per the Apache documentation. My Angular routing file looks like this:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { MemoriesComponent }  from '../memories/memories.component';
import { TearsComponent }  from '../tears/tears.component';

const routes: Routes = [
  { path: '', redirectTo: 'memories', pathMatch: 'full' },
  { path: 'memories', component: MemoriesComponent },
  { path: 'tears', component: TearsComponent }
]

@NgModule({
  imports: [ RouterModule.forRoot(routes)],
  exports: [ RouterModule ]
})

export class RoutingModule {};

However, whenever I attempt to access the website via http, instead of correctly redirecting, when I type in a root address, such as www.memoriesgameseries.com and http://memoriesgameseries the redirect fails to kick in at all. When I type in a URL above the root domain, such as http://memoriesgameseries.com/memories the redirect kicks in and I see the https URL in the browser (e.g. https://www.memoriesgameseries.com/memories), but I get a:

Not Found

The requested URL /memories was not found on this server.

Response from the server. What's likely to be causing this issue?

Body:
The point is that server are trying to manage 404. That's no life, let SPA do that for you.

When 404 redirect to index.html

  RewriteEngine On
  # If an existing asset or directory is requested go to it as it is
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
  RewriteRule ^ - [L]

  # If the requested resource doesn't exist, use index.html
  RewriteRule ^ /index.html


问:
How to send GPS cordinates and current moving speed to phone db with timestamp
I'm new in to Android. I tried several ways to store GPS coordinates in my phone db.

Now the problem is I want to store GPS cordinates every x seconds with current moving vehicle speed and the time.

Also this function should start after a button click event.

答:
create a service and start a timer like shown below.Hope this helps</p>

```<code> public void starttimer(){
   timer = new CountDownTimer(300000, 2000) {
    @Override
    public void onTick(long millisUntilFinished) {
           locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    try {
        location = locationManager.getLastKnownLocation(provider);
    }
    catch (Exception e)
    {

    }
    if(location==null) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    if (location != null) {
        double lat = location.getLatitude();
        double longg = location.getLongitude();
        mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(lat,longg) , 14.0f) );

    } else {
        Toast.makeText(MainActivity.this, "Device Failed To Fetch Lat Long", Toast.LENGTH_LONG).show();
    }
    }

    @Override
    public void onFinish() {
        //your code when timer finishes
    }
}.start();
  }
</code>```

Body:
create a service and start a timer like shown below.Hope this helps

 public void starttimer(){
   timer = new CountDownTimer(300000, 2000) {
    @Override
    public void onTick(long millisUntilFinished) {
           locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    try {
        location = locationManager.getLastKnownLocation(provider);
    }
    catch (Exception e)
    {

    }
    if(location==null) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    if (location != null) {
        double lat = location.getLatitude();
        double longg = location.getLongitude();
        mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(lat,longg) , 14.0f) );

    } else {
        Toast.makeText(MainActivity.this, "Device Failed To Fetch Lat Long", Toast.LENGTH_LONG).show();
    }
    }

    @Override
    public void onFinish() {
        //your code when timer finishes
    }
}.start();
  }


问:
How to match the second invocation on mock?
As shown below, I want to check the mock.fireEvent() get invoked with specific event(event2 here)

```<code>mock.fireEvent(event1);

mock.fireEvent(event2);

verify(mock).fireEvent(matcherToCheckTheFieldOfEvent2);
</code>```

But get an error indicating that

```<code>  verify(mock).fireEvent(matcherToCheckTheFieldOfEvent2);
</code>```

will try to match first invoking

```<code>  mock.fireEvent(argThat(event1));
</code>```

The question is how to let event2 get matched?

Matcher looks like this:

```<code>    private class IsEvent2 extends ArgumentMatcher<Event2>
    {
      @Override
      public boolean matches(Object arg)
      {
                return ((Event2) arg).methodGotCalled();
      }
    }
</code>```

答:
This is and old thread but I got into this problem recently and solved it by using ArgumentCaptor to capture the List of fired events and asserting the expected events are present on the list.

```<code>ArgumentCaptor<SomeEvent> argument = ArgumentCaptor.forClass(SomeEvent.class);
verify(mock, times(2)).fire(argument.capture());
</code>```

argument will then have a list of captured events and you can assert them individually

```<code>assertThat(argument.getAllValues(), hasItems(
    new SomeEventMatcher(event1),
    new SomeEventMatcher(event2)
));
</code>```

And the matcher looks like this:

```<code>static class SomeEventMatcher extends ArgumentMatcher<SomeEvent> {
    private SomeEvent expected;

    public SomeEventMatcher(SomeEvent expected) {
        this.expected = expected;
    }

    @Override
    public boolean matches(Object argument) {
        if (argument == null) {
            return false;
        }
        else {
            SomeEvent event = (SomeEvent) argument;
            // the fields that you want to compare with the matcher
            return new EqualsBuilder()
                    .append(expected.getField1(), event.getField1())
                    .append(expected.getField2(), event.getField2())
                    .build();
        }
    }
}
</code>```

Body:
As shown below, I want to check the mock.fireEvent() get invoked with specific event(event2 here)

mock.fireEvent(event1);

mock.fireEvent(event2);

verify(mock).fireEvent(matcherToCheckTheFieldOfEvent2);

But get an error indicating that

  verify(mock).fireEvent(matcherToCheckTheFieldOfEvent2);

will try to match first invoking

  mock.fireEvent(argThat(event1));

The question is how to let event2 get matched?

Matcher looks like this:

    private class IsEvent2 extends ArgumentMatcher<Event2>
    {
      @Override
      public boolean matches(Object arg)
      {
                return ((Event2) arg).methodGotCalled();
      }
    }

Body:
This is and old thread but I got into this problem recently and solved it by using ArgumentCaptor to capture the List of fired events and asserting the expected events are present on the list.

ArgumentCaptor<SomeEvent> argument = ArgumentCaptor.forClass(SomeEvent.class);
verify(mock, times(2)).fire(argument.capture());

argument will then have a list of captured events and you can assert them individually

assertThat(argument.getAllValues(), hasItems(
    new SomeEventMatcher(event1),
    new SomeEventMatcher(event2)
));

And the matcher looks like this:

static class SomeEventMatcher extends ArgumentMatcher<SomeEvent> {
    private SomeEvent expected;

    public SomeEventMatcher(SomeEvent expected) {
        this.expected = expected;
    }

    @Override
    public boolean matches(Object argument) {
        if (argument == null) {
            return false;
        }
        else {
            SomeEvent event = (SomeEvent) argument;
            // the fields that you want to compare with the matcher
            return new EqualsBuilder()
                    .append(expected.getField1(), event.getField1())
                    .append(expected.getField2(), event.getField2())
                    .build();
        }
    }
}


问:
Simulation from a customised distribution in R
Does anyone know how to simulate random variables from the following probability density function (pdf):

where g(x) is the pdf for standard normal distribution N(0,1).
I understand that simulating random variables from customised distribution involves finding the cumulative density function and using the uniform distribution (as there were similar questions on this topic in this platform also). However, the pdf I have here looks a bit more complicated than the other examples I came across before. For example, I would imagine that finding the cumulative density function (need to integrate) is not so straight forward. Can anyone give me advice on how to solve this? Or is there another simpler method to simulate from the above distribution?
Look forward to your advice. Thanks!

Body:
Doesn't this work?

special <- function(x) {
               if (x <= -1) {
                  val <- dnorm(x) / (1+exp(-x-1))
               } else if ((x > -1) & (x < 1)) {
                  val <- dnorm(x) / 2
               } else {
                  val <- dnorm(x) / (1+exp(-x+1))
               }
               return(val)
           }

special(-2)
[1] 0.01452041

special(-0.5)
[1] 0.1760327


答:
Use a join:

```<code>SELECT t1.*
FROM mytable t1
INNER JOIN mytable t2
ON t1.user_id = t2.user_id AND t1.group <> t2.group AND t2.group = 'y'
</code>```

I think that would be the fastest query (but please feel free to try the other solutions as well).
Add an index on user_id if not already there and maybe play with some other indexes as well (maybe a composite index on group and user_id can be utilized)

Body:
I have the following data:

id  userid  name    group
1   1       A       x
2   1       A       y
3   1       A       z
4   2       B       x
5   2       B       y
6   3       C       y
7   4       D       x
8   5       E       x
9   5       E       z
10  6       F       x

I want to find those records that meet all this condition:

Select all rows where the a userid belongs to a group other than y but the userid also belongs to group y.

The resulting dataset will be as follows:

id  userid  name    group
1   1       A       x
3   1       A       z
4   2       B       x

If you see, it has resulted in two records for userid a because these are two two records belong to groups other than y but the userid 1 also belongs to group y. Same for userid 2.

I have been breaking my head on how to get this in an SQL statement but not even close to a solution.

Any help is appreciated.

Body:
Use a join:

SELECT t1.*
FROM mytable t1
INNER JOIN mytable t2
ON t1.user_id = t2.user_id AND t1.group <> t2.group AND t2.group = 'y'

I think that would be the fastest query (but please feel free to try the other solutions as well).
Add an index on user_id if not already there and maybe play with some other indexes as well (maybe a composite index on group and user_id can be utilized)


问:
How to use JavaScript regex over multiple lines?
```<code>var ss= "```aaaa\nbbb\nccc```ddd";
var arr= ss.match( /<pre.*?<\/pre>/gm );
alert(arr);     // null
</code>```

I'd want the PRE block be picked up, even though it spans over newline characters. I thought the 'm' flag does it. Does not.

Found the answer here before posting. SInce I thought I knew JavaScript (read three books, worked hours) and there wasn't an existing solution at SO, I'll dare to post anyways. throw stones here

So the solution is:

```<code>var ss= "```aaaa\nbbb\nccc```ddd";
var arr= ss.match( /<pre[\s\S]*?<\/pre>/gm );
alert(arr);     // ```...``` :)
</code>```

Does anyone have a less cryptic way?

Edit: this is a duplicate but since it's harder to find than mine, I don't remove.

It proposes [^] as a "multiline dot". What I still don't understand is why [.\n] does not work. Guess this is one of the sad parts of JavaScript..

答:
I have tested it (Chrome) and it's working for me (both [^] and [^\0]), by changing the dot (.) with either [^\0] or [^] , because dot doesn't match line break (See here: http://www.regular-expressions.info/dot.html).

var ss= "```aaaa\nbbb\nccc```ddd";
var arr= ss.match( /<pre[^\0]*?<\/pre>/gm );
alert(arr);     //Working```

Body:
var ss= "
aaaa\nbbb\nccc
ddd";
var arr= ss.match( /<pre.*?<\/pre>/gm );
alert(arr);     // null

I'd want the PRE block be picked up, even though it spans over newline characters. I thought the 'm' flag does it. Does not.

Found the answer here before posting. SInce I thought I knew JavaScript (read three books, worked hours) and there wasn't an existing solution at SO, I'll dare to post anyways. throw stones here

So the solution is:

var ss= "
aaaa\nbbb\nccc
ddd";
var arr= ss.match( /<pre[\s\S]*?<\/pre>/gm );
alert(arr);     //
...
 :)

Does anyone have a less cryptic way?

Edit: this is a duplicate but since it's harder to find than mine, I don't remove.

It proposes [^] as a "multiline dot". What I still don't understand is why [.\n] does not work. Guess this is one of the sad parts of JavaScript..

Body:
I have tested it (Chrome) and it's working for me (both [^] and [^\0]), by changing the dot (.) with either [^\0] or [^] , because dot doesn't match line break (See here: http://www.regular-expressions.info/dot.html).

var ss= "<pre>aaaa\nbbb\nccc</pre>ddd";
var arr= ss.match( /<pre[^\0]*?<\/pre>/gm );
alert(arr);     //Working


问:
alias mismatch of .pfx file or .p12 file between keytool and java keystore.aliases()
I am trying to get aliases from pfx/p12 file using

keytool -v -list -storetype pkcs12 -keystore servercert.p12 -storepass 1234

which gives me

```<code>Keystore type: PKCS12
Keystore provider: SunJSSE

Your keystore contains 1 entry

Alias name: 1
Creation date: Jul 4, 2017
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=CSIT CA, O="CSIT CA,Ltd.", L=Dhaka, ST=Dhaka, C=BD
Issuer: EMAILADDRESS=csit@csit.com, CN=CSIT CA, OU=Software Department, O=CSIT CA, L=Dhaka, ST=Dhaka, C=BD
Serial number: 1
Valid from: Tue Jul 04 15:41:40 BDT 2017 until: Mon Mar 30 15:41:40 BDT 2020
Certificate fingerprints:
     MD5:  5C:CC:77:17:6C:91:FC:81:58:5A:D4:B0:FE:D8:B9:A8
     SHA1: 9A:34:32:64:29:BF:0B:7E:4F:63:1B:27:99:54:41:0F:9D:55:CF:C8
     SHA256: 27:01:BE:9D:F6:0E:38:35:AE:9C:07:B9:64:AB:76:50:06:D3:5D:8E:25:C4:59:87:D0:E9:A1:5A:96:41:D7:70
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:
#1: ObjectId: 2.16.840.1.113730.1.13 Criticality=false
0000: 16 1D 4F 70 65 6E 53 53   4C 20 47 65 6E 65 72 61  ..OpenSSL Genera
0010: 74 65 64 20 43 65 72 74   69 66 69 63 61 74 65     ted Certificate

#2: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 32 0F 04 D5 F6 1B 84 E5   87 EB 64 70 C7 D8 F2 5F  2.........dp..._
0010: FA 92 4D 57                                        ..MW
]
]

#3: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
  CA:false
  PathLen: undefined
]

#4: ObjectId: 2.5.29.15 Criticality=false
KeyUsage [
  DigitalSignature
  Key_Encipherment
]

#5: ObjectId: 2.5.29.17 Criticality=false
SubjectAlternativeName [
  DNSName: example.com
  DNSName: www.example.com
  DNSName: mail.example.com
  DNSName: ftp.example.com
]

#6: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 1C 59 74 4B 59 3B 1D 76   99 C2 10 4D 09 12 94 BB  .YtKY;.v...M....
0010: 20 95 2C 21                                         .,!
]
]

*******************************************
*******************************************
</code>```

The alias is "1" here.

However, I also try using java

```<code>KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
InputStream input = PdfSigner.class.getResourceAsStream(KEYSTORE_LOCATION);
keystore.load(input, PASSWORD.toCharArray());
System.out.println(keystore.size());
Enumeration<String> s=keystore.aliases();
while(s.hasMoreElements()){
    System.out.println("alias:"+s.nextElement());
}
</code>```

which gives me

```<code>1
alias:326bbd5c3d1ad4c6013ee70938d2c76b3c7a29d0
</code>```

Which shows mismatch in alias.

Note: I generate my certificate using this

Q1: Why there is mismatch?

Q2: if there is mismatch, how can my client provide me with pfx/p12 file, alias and pass,which will be used to sign pdf on the fly?

答:
Alias is a friendly name but it is optional. May be each tool is using a different way to calculate it if it is not set. When you exported .p12 file, check the "name" that you set to alias. </p>

<p>For example using </p>

```<code> openssl pkcs12 -export -in my-cert.crt -inkey my-priv-key.key -certfile my-ca-bundle -out my-pfx.pfx -name "alias"
</code>```

Body:
I am trying to get aliases from pfx/p12 file using

keytool -v -list -storetype pkcs12 -keystore servercert.p12 -storepass 1234

which gives me

Keystore type: PKCS12
Keystore provider: SunJSSE

Your keystore contains 1 entry

Alias name: 1
Creation date: Jul 4, 2017
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=CSIT CA, O="CSIT CA,Ltd.", L=Dhaka, ST=Dhaka, C=BD
Issuer: EMAILADDRESS=csit@csit.com, CN=CSIT CA, OU=Software Department, O=CSIT CA, L=Dhaka, ST=Dhaka, C=BD
Serial number: 1
Valid from: Tue Jul 04 15:41:40 BDT 2017 until: Mon Mar 30 15:41:40 BDT 2020
Certificate fingerprints:
     MD5:  5C:CC:77:17:6C:91:FC:81:58:5A:D4:B0:FE:D8:B9:A8
     SHA1: 9A:34:32:64:29:BF:0B:7E:4F:63:1B:27:99:54:41:0F:9D:55:CF:C8
     SHA256: 27:01:BE:9D:F6:0E:38:35:AE:9C:07:B9:64:AB:76:50:06:D3:5D:8E:25:C4:59:87:D0:E9:A1:5A:96:41:D7:70
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:
#1: ObjectId: 2.16.840.1.113730.1.13 Criticality=false
0000: 16 1D 4F 70 65 6E 53 53   4C 20 47 65 6E 65 72 61  ..OpenSSL Genera
0010: 74 65 64 20 43 65 72 74   69 66 69 63 61 74 65     ted Certificate

#2: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: 32 0F 04 D5 F6 1B 84 E5   87 EB 64 70 C7 D8 F2 5F  2.........dp..._
0010: FA 92 4D 57                                        ..MW
]
]

#3: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
  CA:false
  PathLen: undefined
]

#4: ObjectId: 2.5.29.15 Criticality=false
KeyUsage [
  DigitalSignature
  Key_Encipherment
]

#5: ObjectId: 2.5.29.17 Criticality=false
SubjectAlternativeName [
  DNSName: example.com
  DNSName: www.example.com
  DNSName: mail.example.com
  DNSName: ftp.example.com
]

#6: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 1C 59 74 4B 59 3B 1D 76   99 C2 10 4D 09 12 94 BB  .YtKY;.v...M....
0010: 20 95 2C 21                                         .,!
]
]

*******************************************
*******************************************

The alias is "1" here.

However, I also try using java

KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
InputStream input = PdfSigner.class.getResourceAsStream(KEYSTORE_LOCATION);
keystore.load(input, PASSWORD.toCharArray());
System.out.println(keystore.size());
Enumeration<String> s=keystore.aliases();
while(s.hasMoreElements()){
    System.out.println("alias:"+s.nextElement());
}

which gives me

1
alias:326bbd5c3d1ad4c6013ee70938d2c76b3c7a29d0

Which shows mismatch in alias.

Note: I generate my certificate using this

Q1: Why there is mismatch?

Q2: if there is mismatch, how can my client provide me with pfx/p12 file, alias and pass,which will be used to sign pdf on the fly?

Body:
Alias is a friendly name but it is optional. May be each tool is using a different way to calculate it if it is not set. When you exported .p12 file, check the "name" that you set to alias.

For example using

 openssl pkcs12 -export -in my-cert.crt -inkey my-priv-key.key -certfile my-ca-bundle -out my-pfx.pfx -name "alias"