问:
Idiomatic Python: Propagating yields or flattening sequences?
I'm writing a breadth depth-first tree traversal function, and what I want to do is this:

```<code>def traverse(node):
    yield node
    for n in node.children:
        yield_all traverse(n) # << if Python had a yield_all statement
</code>```

The idea is to end up with a (flat) sequence of nodes in the tree.

Approach #1: (propagating yields)

```<code>def traverse(node):
    yield node
    for n in node.children:
        for m in traverse(n):
            yield m
</code>```

Approach #2: (flattening sequences)

```<code>def traverse(node):
    return itertools.chain([node],*(traverse(n) for n in node.children))
</code>```

The first approach seems more clean, but I feel weird explicitly yielding each node in the subtree at each level.

The second approach is terse and slightly dirty, but it matches what I would write in Haskell:

```<code>traverse node = node : concatMap traverse (children node)
</code>```

So my question is: Which is better? Or am I missing a best 3rd option?

答: I'd go with first. You'll get over propagating yields after a couple of times. :-)</p>

Body:
I'm writing a breadth depth-first tree traversal function, and what I want to do is this:

def traverse(node):
    yield node
    for n in node.children:
        yield_all traverse(n) # << if Python had a yield_all statement

The idea is to end up with a (flat) sequence of nodes in the tree.

Approach #1: (propagating yields)

def traverse(node):
    yield node
    for n in node.children:
        for m in traverse(n):
            yield m

Approach #2: (flattening sequences)

def traverse(node):
    return itertools.chain([node],*(traverse(n) for n in node.children))

The first approach seems more clean, but I feel weird explicitly yielding each node in the subtree at each level.

The second approach is terse and slightly dirty, but it matches what I would write in Haskell:

traverse node = node : concatMap traverse (children node)

So my question is: Which is better? Or am I missing a best 3rd option?


来源: stackexchange

问:
How to disable copy paste buttons in Edittext
I am developing an App in android, i want to disable copy paste buttons onLongClick,
I am using the following code:

```<code>edittext.setCustomSelectionActionModeCallback(new Callback() {

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
    });
</code>```

But it is showing error as
"The method setCustomSelectionActionModeCallback(ActionMode.Callback) in the type TextView is not applicable for the arguments (new ActionMode.Callback(){})".
I am searching for hours to get the solution. Please provide me solution.

答:
I found one hack. It's working charm:

```<code>OnLongClickListener mOnLongClickListener = new OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
        //since nothing is in here, nothing will happen.
        setEnabled(false);
        setEnabled(true);
        return false;
    }
};
</code>```

Do same for onClick event of OnClickListener.

ContentLicense: CC BY-SA 3.0

Body:
I am developing an App in android, i want to disable copy paste buttons onLongClick,
I am using the following code:

edittext.setCustomSelectionActionModeCallback(new Callback() {

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
    });

But it is showing error as
"The method setCustomSelectionActionModeCallback(ActionMode.Callback) in the type TextView is not applicable for the arguments (new ActionMode.Callback(){})".
I am searching for hours to get the solution. Please provide me solution.

Body:
I found one hack. It's working charm:

OnLongClickListener mOnLongClickListener = new OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
        //since nothing is in here, nothing will happen.
        setEnabled(false);
        setEnabled(true);
        return false;
    }
};

Do same for onClick event of OnClickListener.


问:
Excel to Access Import Error
Purpose:
To import data from excel to ms access (.mdb) database.

Reference: https://www.mikesdotnetting.com/article/79/import-data-from-excel-to-access-with-asp-net

Technology: C#.net Windows Forms

Error: "The Microsoft Jet database engine cannot find the input table or query 'Persons$'.  Make sure it exists and that its name is spelled correctly."

Code:

```<code> private void button6_Click(object sender, EventArgs e)
        {
            string Access = @"c:\exportdb\DestinationDB.mdb";
            string connect = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\exportdb\DestinationDB.mdb;";

            using (OleDbConnection conn = new OleDbConnection(connect))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "INSERT INTO [MS Access;Database=" + Access + "].[Persons] SELECT * FROM [Persons$]";
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }
</code>```

Note:
I have created a MS Access database named "DestinationDB.mdb" with table name as "Persons" with the following fields:
ContactID,  FirstName,  SecondName, Age

Thereafter i have exported the same to excel in order to retain the header structure.

Once this excel is exported, i added some 10 records to it manually.

Both the files are located under "c://exportdb/source.xls" & "c://exportdb/DestinationDB.mdb".

Excel Snapshot:

Ms Access Snapshot:

Please help me to resolve the error stated above.

Thanks!

答:
Your Connection String doesn't match the reference you're following:

Your Connection String:

```<code> string connect = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\exportdb\DestinationDB.mdb;";
</code>```

His Connection String has the Extended Properties and is specifying Excel 8.0:

```<code>string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel +";Extended Properties=Excel 8.0;";
</code>```

The other problem is that your datasource is the Access Database DestinationDB.mdb, notice how the reference you're following specifies Excel as the datasource.

Title: Excel to Access Import Error

Body:
Purpose:
To import data from excel to ms access (.mdb) database.

Reference: https://www.mikesdotnetting.com/article/79/import-data-from-excel-to-access-with-asp-net

Technology: C#.net Windows Forms

Error: "The Microsoft Jet database engine cannot find the input table or query 'Persons$'.  Make sure it exists and that its name is spelled correctly."

Code:

 private void button6_Click(object sender, EventArgs e)
        {
            string Access = @"c:\exportdb\DestinationDB.mdb";
            string connect = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\exportdb\DestinationDB.mdb;";

            using (OleDbConnection conn = new OleDbConnection(connect))
            {
                using (OleDbCommand cmd = new OleDbCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "INSERT INTO [MS Access;Database=" + Access + "].[Persons] SELECT * FROM [Persons$]";
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        }

Note:
I have created a MS Access database named "DestinationDB.mdb" with table name as "Persons" with the following fields:
ContactID,  FirstName,  SecondName, Age

Thereafter i have exported the same to excel in order to retain the header structure.

Once this excel is exported, i added some 10 records to it manually.

Both the files are located under "c://exportdb/source.xls" & "c://exportdb/DestinationDB.mdb".

Excel Snapshot:

Ms Access Snapshot:

Please help me to resolve the error stated above.

Thanks!

Body:
Your Connection String doesn't match the reference you're following:

Your Connection String:

 string connect = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\exportdb\DestinationDB.mdb;";

His Connection String has the Extended Properties and is specifying Excel 8.0:

string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel +";Extended Properties=Excel 8.0;";

The other problem is that your datasource is the Access Database DestinationDB.mdb, notice how the reference you're following specifies Excel as the datasource.


问:
Obtaining JavaScript import object entries from a WebAssembly .wasm module
I want to understand what a Rust program actually exports when it is compiled to a wasm file so I can provide a valid importObject to the instantiate function:

```<code>WebAssembly.instantiate(bufferSource, importObject);
</code>```

As far as I understand, the only way to do this is by exporting an s-syntax like file of the compiled code.  I can't find how to do this in their docs or through web searches.

答:
You can use a tool such as wabt's wasm2wast to translate a .wasm file to the equivalent .wast. That would do what you ask for.

However, you don't necessarily need to do this! The JavaScript API gives you most of what you want:

```<code>let arrayBuffer = ...; // Somehow get your .wasm file into an ArrayBuffer. XHR, from a string, or what have you.
let module = WebAssembly.Module(arrayBuffer); // This is the synchronous API! Only use it for testing / offline things.

let importObject = {};
for (let imp of WebAssembly.Module.imports(module)) {
    if (typeof importObject[imp.module] === "undefined")
        importObject[imp.module] = {};
    switch (imp.kind) {
    case "function": importObject[imp.module][imp.name] = () => {}; break;
    case "table": importObject[imp.module][imp.name] = new WebAssembly.Table({ initial: ???, maximum: ???, element: "anyfunc" }); break;
    case "memory": importObject[imp.module][imp.name] = new WebAssembly.Memory({ initial: ??? }); break;
    case "global": importObject[imp.module][imp.name] = 0; break;
    }
}
</code>```

Note that Table and Memory initial / maximum are currently guesses! I'm proposing that we add the missing information to the JS API. I think at the next WebAssembly meeting may be a good time to discuss such an addition.

Body:
I want to understand what a Rust program actually exports when it is compiled to a wasm file so I can provide a valid importObject to the instantiate function:

WebAssembly.instantiate(bufferSource, importObject);

As far as I understand, the only way to do this is by exporting an s-syntax like file of the compiled code.  I can't find how to do this in their docs or through web searches.

Body:
You can use a tool such as wabt's wasm2wast to translate a .wasm file to the equivalent .wast. That would do what you ask for.

However, you don't necessarily need to do this! The JavaScript API gives you most of what you want:

let arrayBuffer = ...; // Somehow get your .wasm file into an ArrayBuffer. XHR, from a string, or what have you.
let module = WebAssembly.Module(arrayBuffer); // This is the synchronous API! Only use it for testing / offline things.

let importObject = {};
for (let imp of WebAssembly.Module.imports(module)) {
    if (typeof importObject[imp.module] === "undefined")
        importObject[imp.module] = {};
    switch (imp.kind) {
    case "function": importObject[imp.module][imp.name] = () => {}; break;
    case "table": importObject[imp.module][imp.name] = new WebAssembly.Table({ initial: ???, maximum: ???, element: "anyfunc" }); break;
    case "memory": importObject[imp.module][imp.name] = new WebAssembly.Memory({ initial: ??? }); break;
    case "global": importObject[imp.module][imp.name] = 0; break;
    }
}

Note that Table and Memory initial / maximum are currently guesses! I'm proposing that we add the missing information to the JS API. I think at the next WebAssembly meeting may be a good time to discuss such an addition.


问:
How can I convert an int number from decimal to binary?
How can I convert an int number from decimal to binary. For example:

```<code>int x=10; // radix 10
</code>```

How can I make another integer has the binary representation of x, such as:

```<code>int y=1010; // radix 2
</code>```

by using c only?

答:
Converting an integer to another base (string representation):

```<code>int num = 15;
String fifteen = Integer.toString(num, 2);
// fifteen = "1111"
</code>```

Converting the string back into an integer

```<code>String fifteen = "1111";
int num = Integer.valueOf(fifteen, 2);
// num = 15
</code>```

This covers the general case for any base. There's no way to explicitly assign an integer as binary (only decimal, octal, and hexadecimal)

```<code>int x = 255; // decimal
int y = 0377; // octal (leading zero)
int z = 0xFF; // hex (prepend 0x)
</code>```

Body:
How can I convert an int number from decimal to binary. For example:

int x=10; // radix 10

How can I make another integer has the binary representation of x, such as:

int y=1010; // radix 2

by using c only?

Body:
Converting an integer to another base (string representation):

int num = 15;
String fifteen = Integer.toString(num, 2);
// fifteen = "1111"

Converting the string back into an integer

String fifteen = "1111";
int num = Integer.valueOf(fifteen, 2);
// num = 15

This covers the general case for any base. There's no way to explicitly assign an integer as binary (only decimal, octal, and hexadecimal)

int x = 255; // decimal
int y = 0377; // octal (leading zero)
int z = 0xFF; // hex (prepend 0x)

ContentLicense: CC BY-SA 2.5


问:
Splitting a list element by a separator | 'Can't convert 'list' object to str implicitly' error (Python)
I have a list json_data:

```<code>> print(json_data)
> ['abc', 'bcd/chg', 'sdf', 'bvd', 'wer/ewe', 'sbc & osc']
</code>```

I need to split those elements with '/', '&' or 'and' into two different elements. The result I am looking for should look like this:

```<code>>['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc' , 'osc']
</code>```

The code is:

```<code>separators = ['/', 'and', '&']

titles = []
for i in json_data:
    titles.extend([t.strip() for t in i.split(separators)
                  if i.strip() != ''])
</code>```

When running it, I am getting an error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-d0db85078f05> in <module>()
      5 titles = []
      6 for i in json_data:
----> 7     titles.extend([t.strip() for t in i.split(separators)
      8                   if i.strip() != ''])

TypeError: Can't convert 'list' object to str implicitly
</code>```

How can this be fixed?

答:
I believe what you are looking for in your list comprehension is

```<code>[t.strip() for separator in separators for t in i.split(separator) if i.strip() != '']
</code>```

Python does not have automatic seperation by a list of delimeters.

Body:
I have a list json_data:

> print(json_data)
> ['abc', 'bcd/chg', 'sdf', 'bvd', 'wer/ewe', 'sbc & osc']

I need to split those elements with '/', '&' or 'and' into two different elements. The result I am looking for should look like this:

>['abc', 'bcd', 'chg', 'sdf', 'bvd', 'wer', 'ewe', 'sbc' , 'osc']

The code is:

separators = ['/', 'and', '&']

titles = []
for i in json_data:
    titles.extend([t.strip() for t in i.split(separators)
                  if i.strip() != ''])

When running it, I am getting an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-d0db85078f05> in <module>()
      5 titles = []
      6 for i in json_data:
----> 7     titles.extend([t.strip() for t in i.split(separators)
      8                   if i.strip() != ''])

TypeError: Can't convert 'list' object to str implicitly

How can this be fixed?

Body:
I believe what you are looking for in your list comprehension is

[t.strip() for separator in separators for t in i.split(separator) if i.strip() != '']

Python does not have automatic seperation by a list of delimeters.


答:
The problem occurs in i.split(separators) where the call to split is expecting a string to split i by, but gets a list of strings.
You could try having another for loop, iterating over your separators, and split i by that.

Edit: You're better off viewing @Uriel's answer, it is the more Pythonic way!

Title: Splitting a list element by a separator | 'Can't convert 'list' object to str implicitly' error (Python)


问:
I want to retrieve all data from table between two dates

The above screenshot shows table data where ClNum - 97 has three rows of data with different dates. I want to get all dates data for CLNum-97 from

```<code>EntryDate >= '1-6-2017' to EntryDate <= '30-6-2017'
</code>```

and order by EntryDate ASC but retrieve only the last date data.

Please help me out here I want all data of that employee between this two dates.

答:
Because of the system locale in your PC, the date format may be different.

try changing '1-6-2017' to '2017-06-01'
and '30-6-2017' to '2017-06-30'

Body:
The above screenshot shows table data where ClNum - 97 has three rows of data with different dates. I want to get all dates data for CLNum-97 from

EntryDate >= '1-6-2017' to EntryDate <= '30-6-2017'

and order by EntryDate ASC but retrieve only the last date data.

Please help me out here I want all data of that employee between this two dates.


问:
detect file changes in vagrant guest machine
I'm using Vagrant 1.8.4, running Ubuntu 14.04 box. I have installed node v6.2.2 and I'm running windows 10 x64-bit on the host machine, when I change js files and run gulp watch / babel script.js --watch --out-file compiled.js
The problem the changes are not detected by the guest machine.

I tried the following but no luck:

```<code> config.vm.synced_folder ".", "/var/www",
     :nfs => true,
     :mount_options => ["dmode=777", "fmode=666", "lookupcache=none"]

and this
     :mount_options => ["dmode=777", "fmode=666", "actimeo=1"]
</code>```

Please advice,

答:
So I was running into this same problem with Vagrant and an Angular 4 + Angular CLI project. While running the development server, file changes weren't triggering a rebuild of the files and a reload of the app. The issue is that file system events aren't forwarded to the Vagrant virtual machine. Installing the vagrant-notification-forwarder vagrant plugin solved the problem for me:

https://github.com/mhallin/vagrant-notify-forwarder

Body:
I'm using Vagrant 1.8.4, running Ubuntu 14.04 box. I have installed node v6.2.2 and I'm running windows 10 x64-bit on the host machine, when I change js files and run gulp watch / babel script.js --watch --out-file compiled.js
The problem the changes are not detected by the guest machine.

I tried the following but no luck:

 config.vm.synced_folder ".", "/var/www",
     :nfs => true,
     :mount_options => ["dmode=777", "fmode=666", "lookupcache=none"]

and this
     :mount_options => ["dmode=777", "fmode=666", "actimeo=1"]

Please advice,


问:
Execute a shell script from HTML
I have written a simple HTML code that upon submit, it executes a bash script.
The script is in the correct folder, (cgi-bin).
When I load this page on firefox. It gives an error as

```<code>/somePATH/cgi-bin/script.sh could not be opened because an unknown error occurred.
</code>```

Is the problem about script permissions? I have tried:

```<code>chmod 777
</code>```

Here is a a part of the HTML code.

```<code><form action="cgi-bin/script.sh" method="post">
<input type="submit" value="Call my Shell Script">
</form>
</code>```

EDIT:
The script basically just prints the date:

```<code>#!/bin/bash
# get today's date
OUTPUT=$(date)
# script
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Demo</title></head><body>"
echo "Today is $OUTPUT <br>"
echo "You can do anything with this Schell Script"
echo "</body></html>"
</code>```

答:
You can use a server side language. This is fairly easy with PHP

```<code><?php
 if(isset($_POST['submit']))
 {
   $output=shell_exec('sh /somePATH/cgi-bin/script.sh');
   echo $output;
 }
?>

<form action="" method="post">
<input type="submit" name="submit" value="Call my Shell Script">
</form>
</code>```

Include all your other HTML and save the file with an extension .php

Title: Execute a shell script from HTML

Body:
I have written a simple HTML code that upon submit, it executes a bash script.
The script is in the correct folder, (cgi-bin).
When I load this page on firefox. It gives an error as

/somePATH/cgi-bin/script.sh could not be opened because an unknown error occurred.

Is the problem about script permissions? I have tried:

chmod 777

Here is a a part of the HTML code.

<form action="cgi-bin/script.sh" method="post">
<input type="submit" value="Call my Shell Script">
</form>

EDIT:
The script basically just prints the date:

#!/bin/bash
# get today's date
OUTPUT=$(date)
# script
echo "Content-type: text/html"
echo ""
echo "<title>Demo</title>"
echo "Today is $OUTPUT
"
echo "You can do anything with this Schell Script"
echo ""

Body:
You can use a server side language. This is fairly easy with PHP

<?php
 if(isset($_POST['submit']))
 {
   $output=shell_exec('sh /somePATH/cgi-bin/script.sh');
   echo $output;
 }
?>

<form action="" method="post">
<input type="submit" name="submit" value="Call my Shell Script">
</form>

Include all your other HTML and save the file with an extension .php


问:
how do i unhide spaces between words in a hangman game?
I am making a hangman game, but there's something i can't figure out.

I am able to hide the letters using

```<code>guessed = "_"*len(guess)
</code>```

but it also hides the spaces. for example if my word is 'the avengers' it will hide 12 characters instead of 11. how do unhide/leave the spaces alone? this is what i have so far:

```<code>def getHiddenWord():
    guess = getRandomWord().lower()
    guessed = "_"*len(guess)
    if "_" in guessed is " ":
        print(guessed.replace("_", " "))
    else:
        print("The Word is:", guessed)
    return guessed
</code>```

答:
A simple way to do that:

```<code>def getHiddenWord(guess):
    guessed = ''
    for c in guess.lower():
        if c != ' ':
            guessed += '_'
        else:
            guessed += ' '
    return guessed
</code>```

The problem with your approach is that you use this:

```<code>guessed = "_"*len(guess)
</code>```

It takes the whole length of the string and the empty space is also counted. If for some reason you need to exclude empty space in the count of len you need to use this:

```<code>guessed = "_" * (len(guess) - guess.count(' '))
</code>```

But in your case you most likely don't need it.

Also note that the function getHiddenWord(guess) does not change your original word but creates a new one and returns it.

Body:
I am making a hangman game, but there's something i can't figure out.

I am able to hide the letters using

guessed = "_"*len(guess)

but it also hides the spaces. for example if my word is 'the avengers' it will hide 12 characters instead of 11. how do unhide/leave the spaces alone? this is what i have so far:

def getHiddenWord():
    guess = getRandomWord().lower()
    guessed = "_"*len(guess)
    if "_" in guessed is " ":
        print(guessed.replace("_", " "))
    else:
        print("The Word is:", guessed)
    return guessed

Body:
A simple way to do that:

def getHiddenWord(guess):
    guessed = ''
    for c in guess.lower():
        if c != ' ':
            guessed += '_'
        else:
            guessed += ' '
    return guessed

The problem with your approach is that you use this:

guessed = "_"*len(guess)

It takes the whole length of the string and the empty space is also counted. If for some reason you need to exclude empty space in the count of len you need to use this:

guessed = "_" * (len(guess) - guess.count(' '))

But in your case you most likely don't need it.

Also note that the function getHiddenWord(guess) does not change your original word but creates a new one and returns it.


问:
How to identiy caller mathod from ajaxSuccess in Jquery?
Let me say, I have a document and it have 10 Ajax function calls to the web method. So, I have update in common for all ajax success so, i used

```<code>$(document)ajaxSuccess()
</code>```

It done the job well.
But, in among the 10 ajax function, I need to ignore only one function's success call to the method or need to handle it different way.

So is there a way to find the caller method details in the ajaxSuccess function and handle.

Thanks in advance.
Happy Coding.

答:
You can use beforeSend option of $.ajax() settings object to set a Boolean flag at jqXHR object and if condition at success callback to check for flag.

```<code>setTimeout(function() {
    jQuery.ajax({
      url: "/path/to/server",
      beforeSend: function(jqxhr, settings) {
                    jqxhr.not = true;
                  }
    })
}, duration);
</code>```

```<code>function commonForAllAjaxSuccess(data, textStatus, jqxhr) {
  if (!jqxhr.not) { // do common stuff }
  else { // do not do stuff }
}

jQuery(document).ajaxSuccess(commonForAllAjaxSuccess);
</code>```

Body:
Let me say, I have a document and it have 10 Ajax function calls to the web method. So, I have update in common for all ajax success so, i used

$(document)ajaxSuccess()

It done the job well.
But, in among the 10 ajax function, I need to ignore only one function's success call to the method or need to handle it different way.

So is there a way to find the caller method details in the ajaxSuccess function and handle.

Thanks in advance.
Happy Coding.

Body:
You can use beforeSend option of $.ajax() settings object to set a Boolean flag at jqXHR object and if condition at success callback to check for flag.

setTimeout(function() {
    jQuery.ajax({
      url: "/path/to/server",
      beforeSend: function(jqxhr, settings) {
                    jqxhr.not = true;
                  }
    })
}, duration);

function commonForAllAjaxSuccess(data, textStatus, jqxhr) {
  if (!jqxhr.not) { // do common stuff }
  else { // do not do stuff }
}

jQuery(document).ajaxSuccess(commonForAllAjaxSuccess);


问:
NHibernate - is there any point in setting length attribute for properties/columns?
typically definition of property/column looks like this:

```<code><property name="DocumentSummary" column="DocumentSummary" length="100" type="String">
   <column name="DocumentSummary" />
</property>
</code>```

I was assuming that NHibernate will validate data using length attribute before inserting/updating a row. Unfortunately it seems to be invalid assumption. So question is if NHibernate is using length attribute for anything? Does it make sense to set it for each property?

答:
Yes, setting the Length property makes a different where you have string columns with a length that exceeds the default maximum length.

We have a column of type NVARCHAR(MAX). If we didn't set the length property, NHibernate would fail to set the string value if the value had a length greater than 4096 characters.

(This example uses Mapping-By-Code, because we're in 2017 :-)

```<code>classMapper.Property(
                        tickerFeed => tickerFeed.StaticTickerText,
                        propertyMapper =>
                        {
                             propertyMapper.Column("StaticTickerText");
                             propertyMapper.Length(int.MaxValue);
                        }
                    );
</code>```

However, we found we could achieve the same result using IPropertyMapper.Type to stipulate that it was a large string.

```<code>classMapper.Property(
                        tickerFeed => tickerFeed.StaticTickerText,
                        propertyMapper =>
                        {
                             propertyMapper.Column("StaticTickerText");
                             propertyMapper.Type(NHibernateUtil.StringClob);
                        }
                    );
</code>```

We ended up going with the propertyMapper.Type option, as it is more explicit.

OwnerDisplayName: Marek Blotny

Body:
typically definition of property/column looks like this:

<property name="DocumentSummary" column="DocumentSummary" length="100" type="String">
   <column name="DocumentSummary" />
</property>

I was assuming that NHibernate will validate data using length attribute before inserting/updating a row. Unfortunately it seems to be invalid assumption. So question is if NHibernate is using length attribute for anything? Does it make sense to set it for each property?

LastEditorDisplayName: Marek Blotny

Body:
Yes, setting the Length property makes a different where you have string columns with a length that exceeds the default maximum length.

We have a column of type NVARCHAR(MAX). If we didn't set the length property, NHibernate would fail to set the string value if the value had a length greater than 4096 characters.

(This example uses Mapping-By-Code, because we're in 2017 :-)

classMapper.Property(
                        tickerFeed => tickerFeed.StaticTickerText,
                        propertyMapper =>
                        {
                             propertyMapper.Column("StaticTickerText");
                             propertyMapper.Length(int.MaxValue);
                        }
                    );

However, we found we could achieve the same result using IPropertyMapper.Type to stipulate that it was a large string.

classMapper.Property(
                        tickerFeed => tickerFeed.StaticTickerText,
                        propertyMapper =>
                        {
                             propertyMapper.Column("StaticTickerText");
                             propertyMapper.Type(NHibernateUtil.StringClob);
                        }
                    );

We ended up going with the propertyMapper.Type option, as it is more explicit.


问:
How to grab a value in string?
How can I extract the STOP_DATE value from this long string in Python?

```<code>GROUP                  = TEMPORALINFORMATION

OBJECT                 = PRODUCTIONDATETIME
  NUM_VAL              = 1
  VALUE                = "2015-07-19T18:29:43Z"
END_OBJECT             = PRODUCTIONDATETIME

OBJECT                 = START_DATE
  NUM_VAL              = 1
  VALUE                = "2015-07-11T20:17:22Z"
END_OBJECT             = START_DATE

OBJECT                 = STOP_DATE
  NUM_VAL              = 1
  VALUE                = "2015-07-11T21:03:52Z"
END_OBJECT             = STOP_DATE

END_GROUP              = TEMPORALINFORMATION
</code>```

答:
Sven's answer is not as refined as it could be, my pattern will run 5x faster and the DOTALL flag can be omitted: STOP_DATE[^"]+"([^"]+)

```<code>import re

test_str = '''GROUP                  = TEMPORALINFORMATION

    OBJECT                 = PRODUCTIONDATETIME
      NUM_VAL              = 1
      VALUE                = "2015-07-19T18:29:43Z"
    END_OBJECT             = PRODUCTIONDATETIME

    OBJECT                 = START_DATE
      NUM_VAL              = 1
      VALUE                = "2015-07-11T20:17:22Z"
    END_OBJECT             = START_DATE

    OBJECT                 = STOP_DATE
      NUM_VAL              = 1
      VALUE                = "2015-07-11T21:03:52Z"
    END_OBJECT             = STOP_DATE

    END_GROUP              = TEMPORALINFORMATION'''

print re.search( r'STOP_DATE[^"]+"([^"]+)', test_str).group(1)
# 2015-07-11T21:03:52Z
</code>```

The performance boost comes from using two greedy "negated capture classes" instead of dots.

Since the desired substring is the only double-quoted value to follow STOP_DATE, the double quotes are the only characters that need to be identified.

If your actual data has other values that are double-quoted, and you need to specify VALUE, then you can use: STOP_DATE[^"]+VALUE[^"]+"([^"]+) but the required steps balloon to 2.5 times my previous pattern (but still 2x faster than Sven's).

Title: How to grab a value in string?

Body:
How can I extract the STOP_DATE value from this long string in Python?

GROUP                  = TEMPORALINFORMATION

OBJECT                 = PRODUCTIONDATETIME
  NUM_VAL              = 1
  VALUE                = "2015-07-19T18:29:43Z"
END_OBJECT             = PRODUCTIONDATETIME

OBJECT                 = START_DATE
  NUM_VAL              = 1
  VALUE                = "2015-07-11T20:17:22Z"
END_OBJECT             = START_DATE

OBJECT                 = STOP_DATE
  NUM_VAL              = 1
  VALUE                = "2015-07-11T21:03:52Z"
END_OBJECT             = STOP_DATE

END_GROUP              = TEMPORALINFORMATION

Body:
Sven's answer is not as refined as it could be, my pattern will run 5x faster and the DOTALL flag can be omitted: STOP_DATE[^"]+"([^"]+)

import re

test_str = '''GROUP                  = TEMPORALINFORMATION

    OBJECT                 = PRODUCTIONDATETIME
      NUM_VAL              = 1
      VALUE                = "2015-07-19T18:29:43Z"
    END_OBJECT             = PRODUCTIONDATETIME

    OBJECT                 = START_DATE
      NUM_VAL              = 1
      VALUE                = "2015-07-11T20:17:22Z"
    END_OBJECT             = START_DATE

    OBJECT                 = STOP_DATE
      NUM_VAL              = 1
      VALUE                = "2015-07-11T21:03:52Z"
    END_OBJECT             = STOP_DATE

    END_GROUP              = TEMPORALINFORMATION'''

print re.search( r'STOP_DATE[^"]+"([^"]+)', test_str).group(1)
# 2015-07-11T21:03:52Z

The performance boost comes from using two greedy "negated capture classes" instead of dots.

Since the desired substring is the only double-quoted value to follow STOP_DATE, the double quotes are the only characters that need to be identified.

If your actual data has other values that are double-quoted, and you need to specify VALUE, then you can use: STOP_DATE[^"]+VALUE[^"]+"([^"]+) but the required steps balloon to 2.5 times my previous pattern (but still 2x faster than Sven's).


问:
Difference between SRC and HREF
The SRC and HREF attributes are used to include some external entities like an image, a CSS file, a HTML file, any other web page or a JavaScript file.

Is there a clear differentiation between SRC and HREF? Where or when to use SRC or HREF?  I think they can't be used interchangeably.

I'm giving below few examples where these attributes are used:

To refer a CSS file: href="cssfile.css" inside the link tag.

To refer a JS file: src="myscript.js" inside the script tag.

To refer an image file: src="mypic.jpg" inside an image tag.

To refer another webpage: href="http://www.webpage.com" inside an anchor tag.

答:
after going through the HTML 5.1 ducumentation (1 November 2016):

part 4 (The elements of HTML)

chapter 2 (Document metadata)

section 4 (The link element) states that:

The destination of the link(s) is given by the href attribute, which must be present and must contain a valid non-empty URL potentially surrounded by spaces. If the href attribute is absent, then the element does not define a link.

does not contain the src attribute ...

witch is logical because it is a link .

chapter 12 (Scripting)

section 1 (The script element) states that:

Classic scripts may either be embedded inline or may be imported from an external file using the src attribute, which if specified gives the URL of the external script resource to use. If src is specified, it must be a valid non-empty URL potentially surrounded by spaces. The contents of inline script elements, or the external script resource, must conform with the requirements of the JavaScript specification’s Script production for classic scripts.

it doesn't even mention the href attribute ...

this indicates that while using script tags always use the src attribute !!!

chapter 7 (Embedded content)

section 5 (The img element)

The image given by the src and srcset attributes, and any previous sibling source element's srcset attributes if the parent is a picture element, is the embedded content.

also doesn't mention the href attribute ...

this indicates that when using img tags the src attribute should be used aswell ...

Reference link to the W3C Recommendation

Title: Difference between SRC and HREF


问:
Delete image after upload new one
I'm working with laravel 5.4 I have a form which I can upload my logoimage and in update function I have this code:

```<code>//Save logo
         if ($request->hasFile('logo')) {
           $avatar = $request->file('logo');
           $filename = time() . '.' . $avatar->getClientOriginalExtension();
           $location = public_path('avatars/logos/');
           $request->file('logo')->move($location, $filename);
           $oldFilename = $general_Settings->logo;

           $general_Settings->logo = $filename;
           Storage::delete($oldFilename);
         }

         $general_Settings->save();
</code>```

for updating my image which is work but as you see I have Storage::delete($oldFilename); this part doesn't work and just keep the old image.

what do you think is issue of that?

答:
Solved:

The issue was Filesystem.php I made my local root set to 'root' => public_path('avatars/'), and changed all my functions in my app because no way to save images in sub-folders and delete them just can save in sub-folders.

then my update function become like this:

```<code> if ($request->hasFile('logo')) {
        $avatar = $request->file('logo');
        $filename = 'sitelogo' . '-' . time() . '.' . $avatar->getClientOriginalExtension();
        $location = public_path('avatars/');
        $request->file('logo')->move($location, $filename);

        $general_Settings->logo = $filename;
      }

      $general_Settings->save();
</code>```

I hope this help someone.

Title: Delete image after upload new one

Body:
I'm working with laravel 5.4 I have a form which I can upload my logoimage and in update function I have this code:

//Save logo
         if ($request->hasFile('logo')) {
           $avatar = $request->file('logo');
           $filename = time() . '.' . $avatar->getClientOriginalExtension();
           $location = public_path('avatars/logos/');
           $request->file('logo')->move($location, $filename);
           $oldFilename = $general_Settings->logo;

           $general_Settings->logo = $filename;
           Storage::delete($oldFilename);
         }

         $general_Settings->save();

for updating my image which is work but as you see I have Storage::delete($oldFilename); this part doesn't work and just keep the old image.

what do you think is issue of that?

Body:
Solved:

The issue was Filesystem.php I made my local root set to 'root' => public_path('avatars/'), and changed all my functions in my app because no way to save images in sub-folders and delete them just can save in sub-folders.

then my update function become like this:

 if ($request->hasFile('logo')) {
        $avatar = $request->file('logo');
        $filename = 'sitelogo' . '-' . time() . '.' . $avatar->getClientOriginalExtension();
        $location = public_path('avatars/');
        $request->file('logo')->move($location, $filename);

        $general_Settings->logo = $filename;
      }

      $general_Settings->save();

I hope this help someone.


问:
print elements using stream.foreach() does not work
I have the following code and want to print the list elements after multiplying them my 10 but it says void is not allowed. How to solve it?</p>

```<code>List<Integer> integerList = Arrays.asList(10,22,30);

   long muliplied = integerList.stream()
                                .map(e -> e*10)
                                .forEach(System.out::println);
</code>```

答:
You cannot save the result of the method, as its return type is void.

Try the following code

```<code>package eu.webfarmr;

import java.util.Arrays;
import java.util.List;

public class StreamExample {
    public static void main(String[] args) {
        List<Integer> integerList = Arrays.asList(10, 22, 30);

        integerList.stream().map(e -> e * 10).forEach(System.out::println);

    }
}
</code>```

The printed result is

```<code>100
220
300
</code>```

Body:
I have the following code and want to print the list elements after multiplying them my 10 but it says void is not allowed. How to solve it?

List<Integer> integerList = Arrays.asList(10,22,30);

   long muliplied = integerList.stream()
                                .map(e -> e*10)
                                .forEach(System.out::println);

Body:
You cannot save the result of the method, as its return type is void.

Try the following code

package eu.webfarmr;

import java.util.Arrays;
import java.util.List;

public class StreamExample {
    public static void main(String[] args) {
        List<Integer> integerList = Arrays.asList(10, 22, 30);

        integerList.stream().map(e -> e * 10).forEach(System.out::println);

    }
}

The printed result is

100
220
300


问:
Do the Groovy every and any methods short-circuit?
Suppose the every or any method is being evaluated on a long list, and the value of the closure on the first element is enough to determine the final result (true for any, false for every).  Do these methods continue processing the rest of the elements of the list or do they immediately return?</p>

```<code>def lst = [1,2,3,4]
//Do either of these functions evaluate the 2nd, 3rd and 4th element of lst?
boolean value1 = lst.any{element -> element == 1}
boolean value2 = lst.every {element -> element == 2}
</code>```

答:
any() and every() short-circuit and return as soon as possible.

You can see this in the source for any() and every(). These methods each iterate over each object evaluating the closure and return if the condition is (for any())/is not (for every()) met.

Body:
Suppose the every or any method is being evaluated on a long list, and the value of the closure on the first element is enough to determine the final result (true for any, false for every).  Do these methods continue processing the rest of the elements of the list or do they immediately return?

def lst = [1,2,3,4]
//Do either of these functions evaluate the 2nd, 3rd and 4th element of lst?
boolean value1 = lst.any{element -> element == 1}
boolean value2 = lst.every {element -> element == 2}


问:
Get/set variable inside if statement
I have a small example to define and assign to arr array.

```<code>var arr;

if (arr = [1]) { // arr is an array here, it contains 1 element
    console.log(arr.length); // 1
}
</code>```

Then, I want to get length of the array

```<code>var arr;

// arr is an array here, but why cannot I assign to length property?
if (arr = [1] && arr.length) {
    console.log(arr.length);
}
</code>```

Uncaught TypeError: Cannot read property 'length' of undefined

答:
Assigning variable inside IF is a code smell.

```<code>var arr;
var x = 1;

if (arr = [1] && arr.length && x == 1) {
    console.log(arr.length);
}
</code>```

How does the if condition above look like? Most people may not aware your are assigning value to arr but think you are check if arr == [1].

A better example:

```<code>var arr = [1];

if (arr.length > 0) {
    console.log(arr.length);
}
</code>```

Title: Get/set variable inside if statement

Body:
I have a small example to define and assign to arr array.

var arr;

if (arr = [1]) { // arr is an array here, it contains 1 element
    console.log(arr.length); // 1
}

Then, I want to get length of the array

var arr;

// arr is an array here, but why cannot I assign to length property?
if (arr = [1] && arr.length) {
    console.log(arr.length);
}

Uncaught TypeError: Cannot read property 'length' of undefined

Body:
Assigning variable inside IF is a code smell.

var arr;
var x = 1;

if (arr = [1] && arr.length && x == 1) {
    console.log(arr.length);
}

How does the if condition above look like? Most people may not aware your are assigning value to arr but think you are check if arr == [1].

A better example:

var arr = [1];

if (arr.length > 0) {
    console.log(arr.length);
}


问:
Oracle ORDS on Tomcat 8 hide schema name in url
I don't want users being able to see the context or schema name in the ORDS URL.

As in the Oracle documentation my URL is something like this:

```<code>https://server:port/ords/workspace/hr/employees/7369
</code>```

note the schema name, HR is present.  My goal is to hide ORDS, workspace and hr.  So my URL should be:

```<code>https://server:port/redirect_name/employees/7369
</code>```

What I do not want is a HTTP 301 redirect which updates the browser bar.

Things tried

1) UrlRewriteFilter in ROOT but with type="redirect" it only redirects and leaks the context.  Without type="redirect" yields "The requested resource is not available." from Tomcat so apparently doesn't even get to ORDS.

2) JSP redirection

```<code><% response.sendRedirect("/some/where"); %>
</code>```

which successfully redirected, but leaks context.

3) Tomcat "rewrite Valve" again same result successful 301 type redirect.

Not tried

1)  Front Tomcat with an Apache httpd instance.

答:
Answer applies to ORDS 3.0.9 only.  The README describes:

BUG:25072243 - Fix regression preventing url mapping of ORDS enabled schemas iff the PL/SQL Gateway pool does not exist

without which I do not believe this will work (not tested).   Note if upgrade from ORDS 3.0.6 or earlier there have been changes to the DB schema and you need to upgrade.

This is not a full answer but it is the closest I managed to get.  First rename the ords.war file to the desired redirect_name.war  This will automatically create a new configuration directory for the database connection but will not yet be set up.  Options are to either install redirect_name.war using:

```<code>java -jar redirect_name.war install simple
</code>```

or by manually editing the configuration files to match the ORDS settings you already have.  There are two ways to find the configuration directory either

```<code>java -jar redirect_name.war configdir
</code>```

will give you the configuration directory or you can check it in:

```<code>.\webapps\redirect_name\WEB-INF\web.xml
</code>```

with the param name  assuming Tomcat is configured to unpack WARs otherwise look in the compressed WAR archive itself.

At this point the URL has changed from this:

```<code>https://server:port/ords/workspace/hr/employees/7369
</code>```

to this:

```<code>https://server:port/redirect_name/workspace/hr/employees/7369
</code>```

The next step is to set up a map-url which can either be done using:

```<code>java -jar redirect_name.war mapurl --type base-path --workspace-id hr / apex
</code>```

or by manually creating a url-mapping.xml file in the  found above.  If you manually create the file it should look like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<pool-config xmlns="http://xmlns.oracle.com/apex/pool-config">
   <pool name="apex" base-path="/" workspace-id="hr" updated="2017-01-01T01:01:01.012Z"/>
</pool-config>
</code>```

The pool name "apex" is the default installed database name.  You can check which database names have been set up in ORDS by checking the /conf/ subdirectory where in a default install you will find a file named apex_pu.xml describing the database connection.  If you wish to connect to a different database (more here) that can be done with:

```<code>java -jar redirect_name.war setup --database ords_db_name
</code>```

which will lead you through a series of prompts to enter either a service name or a SID.  Note that you must chose 1 when prompted here:

```<code>Enter 1 if you want to verify/install Oracle REST Data Services schema or 2 to skip this step [1]
</code>```

or the database connection won't be created.  To verify success check the /conf location and look for ords_db_name_pu.xml  Note that ords_db_name is just a database connection name alias used by ORDS it doesn't have to be an actual SID or service name.

These steps will bring the URL down from the intermediate step:

```<code>https://server:port/redirect_name/workspace/hr/employees/7369
</code>```

to this:

```<code>java -jar redirect_name.war configdir
</code>```0

the url-mapping.xml/mapurl option with / removed the need for any name.  Alternately this command could have been used:

```<code>java -jar redirect_name.war configdir
</code>```1

yielding this URL:

```<code>java -jar redirect_name.war configdir
</code>```2

Not tested

Rename ords.war to ROOT.war in theory removes the need for "redirect_name" to be in the URL but I wasn't prepared to have ORDS in the ROOT location.

Body:
I don't want users being able to see the context or schema name in the ORDS URL.

As in the Oracle documentation my URL is something like this:

https://server:port/ords/workspace/hr/employees/7369

note the schema name, HR is present.  My goal is to hide ORDS, workspace and hr.  So my URL should be:

https://server:port/redirect_name/employees/7369

What I do not want is a HTTP 301 redirect which updates the browser bar.

Things tried

1) UrlRewriteFilter in ROOT but with type="redirect" it only redirects and leaks the context.  Without type="redirect" yields "The requested resource is not available." from Tomcat so apparently doesn't even get to ORDS.

2) JSP redirection

<% response.sendRedirect("/some/where"); %>

which successfully redirected, but leaks context.

3) Tomcat "rewrite Valve" again same result successful 301 type redirect.

Not tried

1)  Front Tomcat with an Apache httpd instance.

Body:
Answer applies to ORDS 3.0.9 only.  The README describes:

BUG:25072243 - Fix regression preventing url mapping of ORDS enabled schemas iff the PL/SQL Gateway pool does not exist

without which I do not believe this will work (not tested).   Note if upgrade from ORDS 3.0.6 or earlier there have been changes to the DB schema and you need to upgrade.

This is not a full answer but it is the closest I managed to get.  First rename the ords.war file to the desired redirect_name.war  This will automatically create a new configuration directory for the database connection but will not yet be set up.  Options are to either install redirect_name.war using:

java -jar redirect_name.war install simple

or by manually editing the configuration files to match the ORDS settings you already have.  There are two ways to find the configuration directory either

java -jar redirect_name.war configdir

will give you the configuration directory or you can check it in:

.\webapps\redirect_name\WEB-INF\web.xml

with the param name  assuming Tomcat is configured to unpack WARs otherwise look in the compressed WAR archive itself.

At this point the URL has changed from this:

https://server:port/ords/workspace/hr/employees/7369

to this:

https://server:port/redirect_name/workspace/hr/employees/7369

The next step is to set up a map-url which can either be done using:

java -jar redirect_name.war mapurl --type base-path --workspace-id hr / apex

or by manually creating a url-mapping.xml file in the  found above.  If you manually create the file it should look like this:

<?xml version="1.0" encoding="UTF-8"?>
<pool-config xmlns="http://xmlns.oracle.com/apex/pool-config">
   <pool name="apex" base-path="/" workspace-id="hr" updated="2017-01-01T01:01:01.012Z"/>
</pool-config>

The pool name "apex" is the default installed database name.  You can check which database names have been set up in ORDS by checking the /conf/ subdirectory where in a default install you will find a file named apex_pu.xml describing the database connection.  If you wish to connect to a different database (more here) that can be done with:

java -jar redirect_name.war setup --database ords_db_name

which will lead you through a series of prompts to enter either a service name or a SID.  Note that you must chose 1 when prompted here:

Enter 1 if you want to verify/install Oracle REST Data Services schema or 2 to skip this step [1]

or the database connection won't be created.  To verify success check the /conf location and look for ords_db_name_pu.xml  Note that ords_db_name is just a database connection name alias used by ORDS it doesn't have to be an actual SID or service name.

These steps will bring the URL down from the intermediate step:

https://server:port/redirect_name/workspace/hr/employees/7369

to this:

https://server:port/redirect_name/workspace/employees/7369

the url-mapping.xml/mapurl option with / removed the need for any name.  Alternately this command could have been used:

java -jar redirect_name.war mapurl --type base-path --workspace-id hr /something_here apex

yielding this URL:

https://server:port/redirect_name/workspace/something_here/employees/7369

Not tested

Rename ords.war to ROOT.war in theory removes the need for "redirect_name" to be in the URL but I wasn't prepared to have ORDS in the ROOT location.


问:
Child position absolute parent relative doesn't work
I’m trying to implement something like a web page navbar. I have code like this:

nav {
  position: relative;
  display: inline-block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  right: 0px;
  list-style: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <h2>My First Website</h2>
  <ul class="nav-right">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav></code>```

I have known that an absolute element is positioned to its first positioned (not static) ancestor element. I have set position property of element nav as absolute, but it looks like the
 run out of the  range.  In other word  i'm confused about why nav'height  is  less than  ul's   Thanks a  lot.

答:
Absolute position elements are removed from the document flow. So the parent's height will hold only the other elements. Not the absolute position elements.

If you want your parent to cover your absolute position element then you have to set a fixed height to the parent element. You can set top: 0; like other's have answered. But still your parent's height wont be determined by the absolute positioned element, that's the reason the ul is outside the nav.

Body:
I’m trying to implement something like a web page navbar. I have code like this:

nav {
  position: relative;
  display: inline-block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  right: 0px;
  list-style: none;
}

My First Website

Home

About

Contact

I have known that an absolute element is positioned to its first positioned (not static) ancestor element. I have set position property of element nav as absolute, but it looks like the
 run out of the  range.  In other word  i'm confused about why nav'height  is  less than  ul's   Thanks a  lot.


问:
How to sort a column in one table based on the rank in another table
I have a table Table 1 that has User_ID and Item_List where items are arranged randomly

```<code>Customer_id   Item_List
22              1,4,3,2
24              6,3,2,1
23              4,5,7,8
</code>```

Table 2 has the ranks of the item according to the highest value

```<code>Item_Id   Item_Rank
  1          8
  2          5
  3          3
  4          4
  5          2
  6          7
  7          1
  8          6
</code>```

I want to produce a Table that has Customer_id with the corresponding Item List ranked according to the Item Rank in Table 2

```<code>Customer_id     Ranked_Item_List
   22             3,4,2,1
   24             3,2,6,1
   23             7,5,4,8
</code>```

I don't know any efficient method to do it in hive. Any suggestions?

答:
I can think in 2 different ways, create your UDF to avoid the explode or </p>

```<code>select customer_id, collect_list(item_id) from (

select customer_id, item_id, item_rank from
table1 lateral view inline(item_list) item_id join
table2 on table1.item_id = table2.item_id --this should be done as mapjoin if your rank table is not big
)  distributed by customer_id, sort by item_rank;
</code>```

<p>Like I said before, depending on the size of your data, you could create an UDF to apply the sort at mapper level based on your lookup table </p>

Body:
I have a table Table 1 that has User_ID and Item_List where items are arranged randomly

Customer_id   Item_List
22              1,4,3,2
24              6,3,2,1
23              4,5,7,8

Table 2 has the ranks of the item according to the highest value

Item_Id   Item_Rank
  1          8
  2          5
  3          3
  4          4
  5          2
  6          7
  7          1
  8          6

I want to produce a Table that has Customer_id with the corresponding Item List ranked according to the Item Rank in Table 2

Customer_id     Ranked_Item_List
   22             3,4,2,1
   24             3,2,6,1
   23             7,5,4,8

I don't know any efficient method to do it in hive. Any suggestions?

Body:
I can think in 2 different ways, create your UDF to avoid the explode or

select customer_id, collect_list(item_id) from (

select customer_id, item_id, item_rank from
table1 lateral view inline(item_list) item_id join
table2 on table1.item_id = table2.item_id --this should be done as mapjoin if your rank table is not big
)  distributed by customer_id, sort by item_rank;

Like I said before, depending on the size of your data, you could create an UDF to apply the sort at mapper level based on your lookup table


答:
Use display: block; in parent and add top:0; in child to align in right side of parent

nav {
  position: relative;
  display: block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  right: 0px;
  top:0;
  list-style: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <h2>My First Website</h2>
  <ul class="nav-right">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav></code>```

Title: Child position absolute parent relative doesn't work

Body:
Use display: block; in parent and add top:0; in child to align in right side of parent

nav {
  position: relative;
  display: block;
}

.nav-right {
  display: inline-block;
  position: absolute;
  right: 0px;
  top:0;
  list-style: none;
}

<nav>
  <h2>My First Website</h2>
  <ul class="nav-right">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav>


问:
Extract bluetooth low energy advertisement data in c++
I am trying to analyze the data contained in a bluetooth low energy advertisement, this is my code so far.

```<code>HRESULT BLEWatcher::OnAdvertisementReceived(IBluetoothLEAdvertisementWatcher* watcher, IBluetoothLEAdvertisementReceivedEventArgs* args)
{

    IBluetoothLEAdvertisement** advertisement;
    args->get_Advertisement(advertisement);

    __FIVector_1_Windows__CDevices__CBluetooth__CAdvertisement__CBluetoothLEAdvertisementDataSection** dataSections;
    (*advertisement)->get_DataSections(dataSections);
    IBluetoothLEAdvertisementDataSection** dataSection;
    (*dataSections)->GetAt(2, dataSection);
    ABI::Windows::Storage::Streams::IBuffer** buffer;
    (*dataSection)->get_Data(buffer);
    ComPtr<ABI::Windows::Storage::Streams::IDataReader> reader;
    UINT32 *length;
    (*buffer)->get_Length(length);

    return S_OK;
}
</code>```

I cannot find how to extract the data from the IBuffer, preferably as byte array. If there is a better way to extract the data, or anyone knows how to convert the IBuffer to byte array your help would be greatly appreciated.

Also, I have no way of checking that my code thus far is correct, so if any mistakes were made please feel free to let me know.

答:
I have found the answer. Mostly it's just a mess of comptrs the extra casting used by others to convert the buffer is unnecessary here because the buffer is already a comptr object.</p>

```<code>HRESULT BLEWatcher::OnAdvertisementReceived(IBluetoothLEAdvertisementWatcher* watcher, IBluetoothLEAdvertisementReceivedEventArgs* args)
{

    ComPtr<IBluetoothLEAdvertisement> advertisement;
    args->get_Advertisement(&advertisement);
    ComPtr<__FIVector_1_Windows__CDevices__CBluetooth__CAdvertisement__CBluetoothLEAdvertisementDataSection> dataSections;
    advertisement->get_DataSections(&dataSections);
    ComPtr<IBluetoothLEAdvertisementDataSection> dataSection;
    //Get appropriate data section
    dataSections->GetAt(2, &dataSection);
    ComPtr<IBuffer> buffer;
    dataSection->get_Data(&buffer);
    ComPtr<IBufferByteAccess> bufferByteAccess;
    buffer.As(&bufferByteAccess);
    byte* bytes = nullptr;
    bufferByteAccess->Buffer(&bytes);

    //Handle bytes here

    return S_OK;
}
</code>```

Body:
I am trying to analyze the data contained in a bluetooth low energy advertisement, this is my code so far.

HRESULT BLEWatcher::OnAdvertisementReceived(IBluetoothLEAdvertisementWatcher* watcher, IBluetoothLEAdvertisementReceivedEventArgs* args)
{

    IBluetoothLEAdvertisement** advertisement;
    args->get_Advertisement(advertisement);

    __FIVector_1_Windows__CDevices__CBluetooth__CAdvertisement__CBluetoothLEAdvertisementDataSection** dataSections;
    (*advertisement)->get_DataSections(dataSections);
    IBluetoothLEAdvertisementDataSection** dataSection;
    (*dataSections)->GetAt(2, dataSection);
    ABI::Windows::Storage::Streams::IBuffer** buffer;
    (*dataSection)->get_Data(buffer);
    ComPtr<ABI::Windows::Storage::Streams::IDataReader> reader;
    UINT32 *length;
    (*buffer)->get_Length(length);

    return S_OK;
}

I cannot find how to extract the data from the IBuffer, preferably as byte array. If there is a better way to extract the data, or anyone knows how to convert the IBuffer to byte array your help would be greatly appreciated.

Also, I have no way of checking that my code thus far is correct, so if any mistakes were made please feel free to let me know.

Body:
I have found the answer. Mostly it's just a mess of comptrs the extra casting used by others to convert the buffer is unnecessary here because the buffer is already a comptr object.

HRESULT BLEWatcher::OnAdvertisementReceived(IBluetoothLEAdvertisementWatcher* watcher, IBluetoothLEAdvertisementReceivedEventArgs* args)
{

    ComPtr<IBluetoothLEAdvertisement> advertisement;
    args->get_Advertisement(&advertisement);
    ComPtr<__FIVector_1_Windows__CDevices__CBluetooth__CAdvertisement__CBluetoothLEAdvertisementDataSection> dataSections;
    advertisement->get_DataSections(&dataSections);
    ComPtr<IBluetoothLEAdvertisementDataSection> dataSection;
    //Get appropriate data section
    dataSections->GetAt(2, &dataSection);
    ComPtr<IBuffer> buffer;
    dataSection->get_Data(&buffer);
    ComPtr<IBufferByteAccess> bufferByteAccess;
    buffer.As(&bufferByteAccess);
    byte* bytes = nullptr;
    bufferByteAccess->Buffer(&bytes);

    //Handle bytes here

    return S_OK;
}


问:
When and Why would a Child class declare a static instance member of the parent class?
This is another design pattern in some legacy code that I couldn't find much about on google. In this case a child class extends its abstract parent, but then turns right around and declares a static instance of the parent:

```<code>public abstract class MessageBase {
    protected DAOFactory factory;
    // method declarations
}

public class EDWMessage extends MessageBase {
    private static MessageBase instance;

    public static MessageBase getInstance(Properties properties) {
        if (instance == null) {
            instance = new EDWMessageTransaction(properties, null);
        }
        return instance;
    }
//more code
}
</code>```

I'm not sure I understand what would drive this design pattern (if it is a known pattern). Is this a sort of convenience pattern to avoid declaring each member variable of the parent as static? Or is it meant to allow multiple children classes to each have one instance of the parent. But if that's the case, why the excessive use of inheritance over just plain composition?

The rest of the code gives no indication as to why it would be done this way. Any thoughts or ideas would be much appreciated. Thanks!

P.S. I seem to be running in to a lot of interesting design patterns in this legacy code that I don't know how to handle. Thanks to everyone who has helped me out already.

Edit: Expanding the code sample. Will edit again as I discover someplace that actually uses this code. Yay for no documentation.

答:
The original intent probably was that for each subclass of MessageBase there should only be 1 instance and that you can access that instance with a commom method in the base class

so you could iterate over all message types and get the instance of each

my 2cents

Body:
This is another design pattern in some legacy code that I couldn't find much about on google. In this case a child class extends its abstract parent, but then turns right around and declares a static instance of the parent:

public abstract class MessageBase {
    protected DAOFactory factory;
    // method declarations
}

public class EDWMessage extends MessageBase {
    private static MessageBase instance;

    public static MessageBase getInstance(Properties properties) {
        if (instance == null) {
            instance = new EDWMessageTransaction(properties, null);
        }
        return instance;
    }
//more code
}

I'm not sure I understand what would drive this design pattern (if it is a known pattern). Is this a sort of convenience pattern to avoid declaring each member variable of the parent as static? Or is it meant to allow multiple children classes to each have one instance of the parent. But if that's the case, why the excessive use of inheritance over just plain composition?

The rest of the code gives no indication as to why it would be done this way. Any thoughts or ideas would be much appreciated. Thanks!

P.S. I seem to be running in to a lot of interesting design patterns in this legacy code that I don't know how to handle. Thanks to everyone who has helped me out already.

Edit: Expanding the code sample. Will edit again as I discover someplace that actually uses this code. Yay for no documentation.


问:
Remove nodes which are single or have 2nd degree visjs
I've a network graph

Now I've some connected nodes and as you can see most of the nodes only have one connected node that is their degree is 1. Now I'd like to remove such nodes to clear the clutter. Unable to find how to since last 2 days. No such helper functions available in visjs documentation. Would appreciate help.

答:
This might work:

```<code>var DEGREES_HIDDEN = 1;

for ( var node of nodes ) {
    node.cantLinks = 0;

    for ( var link of links ) {
        if ( link.from == node.id || link.to == node.id ) {
            node.cantLinks++;
        }
    }
}
for ( var node of nodes ) {
   if ( node.cantLinks <= DEGREES_HIDDEN ) {
       node.hidden = true;
   }
}
</code>```

Nodes and links are arrays not vis.DataSet, I create the latter after doing that.

Doesn't look very nice perfomance wise but it does get the job done. Hope you find it useful.

Body:
This might work:

var DEGREES_HIDDEN = 1;

for ( var node of nodes ) {
    node.cantLinks = 0;

    for ( var link of links ) {
        if ( link.from == node.id || link.to == node.id ) {
            node.cantLinks++;
        }
    }
}
for ( var node of nodes ) {
   if ( node.cantLinks <= DEGREES_HIDDEN ) {
       node.hidden = true;
   }
}

Nodes and links are arrays not vis.DataSet, I create the latter after doing that.

Doesn't look very nice perfomance wise but it does get the job done. Hope you find it useful.


答:
The forEach method of the Stream class takes a Consumer as an argument. A Consumer is one which accepts a parameter , but returns void. Now lets see one by one what each step returns:

integerList.stream()  returns a Stream

.map(e -> e*10) again returns a Stream

.forEach(System.out::println); returns a void

You are trying to assign this void to a long, so the compiler complains.

Title: print elements using stream.foreach() does not work


问:
REST API: Design API to let user submit POST something and GET some value other than created Id in response
It's bit lengthy but simple to understand so please read it.

We have a feedback form where the user fills the complaint/suggestions. To fill a complaint, the user needs to fill his/her {Name, Mobile Number, ZipCode}. As a response to this complaint, we show our nearest call center number based on user's pin code.

Once the user submits the feedback [name, mobile, zip code], the complete process is:

The user sees nearest customer care contact number upfront on the screen.

New Complaint is registered in the database.

This process needs to be integrated across platforms (Mobile, Desktop, Apps) and we need to design Restful APIs for this. Few choices:

GET /api/complaint/?mobile={mobile}&name={name}&zip={zipcode}. This API would send back nearest call center number in response, save record in complaint table. But this does not look restful as we are adding database records with GET request.

POST /api/complaint/ with {mobile},{name},{zipcode} in the request body. This too can do all above things but the problem here is that as per rest where we send back new created object in POST response, here we would send back nearest customer call center number which has nothing to do with complaint record creation in the database.

Create two separate APIs, first POST /api/complaint/ with {mobile},{name} that would insert a record in the complaint table. And second, create GET /api/callcenter/?zip={zipcode} which returns back the customer care number of that zipcode. There are few problems here like two APIs are decoupled so what if POST is unsuccessful while GET is executed OR vice versa? Also, hitting these two sequentially would be slow?

Which of these 3 is correct OR is there any 4th way to solve this problem?

答:
Teach a man to fish: almost every question in of the form "what is the REST way to do X?" has the answer "figure out how to do it with html links and forms, and match that pattern as closely as you can."

the problem here is that as per rest where we send back new created object in POST response

If that wasn't true, would it make your life easier?  If so, good news....

REST doesn't say anything about "create"; it says that resources should conform to the uniform interface.

If you are communicating with your API via http(s), the uniform interface is defined by RFC 7231 (not REST; REST is an architectural style, the Web is a reference application built using that style).

HTTP does not say that POST must equal create.

The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics.

The HTTP specification doesn't say you have to return the created object.  In fact, it says 200 OK means that you return something different:

a representation of the status of, or results obtained from the action

In your case, the status of your action is "congratulations, our attempt to find the closest care center to you succeeded.  here it is...."  Yes, this has nothing to do with the fact that you created a complaint record in the database.  From the point of view of the web client, there is no database.  Just the resources and the uniform interface.


答:
I think you can rely on "their relative order" as Spark goes over rows one by one in order (and usually does not re-order rows if not explicitly needed).

If you are concerned with the order, merge these two columns using struct function before doing groupBy.

struct(colName: String, colNames: String*): Column Creates a new struct column that composes multiple input columns.

You could also use monotonically_increasing_id function to number records and use it to pair with the other columns (perhaps using struct):

monotonically_increasing_id(): Column A column expression that generates monotonically increasing 64-bit integers.

The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive.

Title: Does collect_list() maintain relative ordering of rows?

Body:
Imagine that I have the following DataFrame df:

+---+-----------+------------+
| id|featureName|featureValue|
+---+-----------+------------+
|id1|          a|           3|
|id1|          b|           4|
|id2|          a|           2|
|id2|          c|           5|
|id3|          d|           9|
+---+-----------+------------+

Imagine that I run:

df.groupBy("id")
  .agg(collect_list($"featureIndex").as("idx"),
       collect_list($"featureValue").as("val"))

Am I GUARANTEED that "idx" and "val" will be aggregated and keep their relative order? i.e.

GOOD                   GOOD                   BAD
+---+------+------+    +---+------+------+    +---+------+------+
| id|   idx|   val|    | id|   idx|   val|    | id|   idx|   val|
+---+------+------+    +---+------+------+    +---+------+------+
|id3|   [d]|   [9]|    |id3|   [d]|   [9]|    |id3|   [d]|   [9]|
|id1|[a, b]|[3, 4]|    |id1|[b, a]|[4, 3]|    |id1|[a, b]|[4, 3]|
|id2|[a, c]|[2, 5]|    |id2|[c, a]|[5, 2]|    |id2|[a, c]|[5, 2]|
+---+------+------+    +---+------+------+    +---+------+------+

NOTE: e.g. It's BAD because for id1 [a, b] should have been associated with [3, 4] (and not [4, 3]). Same for id2


问:
Oauth Authorization issue while integrating web app with Quickbooks
I am trying to integrate my web app with QuickBooks I implemented Connect to QuickBooks button and the intuit also grants the permission to the application.

However, I get We encountered a problem processing your request issue.

What might be the issue? I don't get any response in my call_back url too.

I used the code from Intuit Sample app.

```<code>public static String REQUEST_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_request_token";
public static String ACCESS_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_access_token";
public static String AUTHORIZE_URL = "https://appcenter.intuit.com/Connect/Begin";
public static String OAUTH_CONSUMER_KEY = "qyprdFHGmJjBj1jDH05Jen95Tu3PyW";
public static String OAUTH_CONSUMER_SECRET = "OMFkKCPRBQKrMoyaLg9mFYTM26kpJg8LPthbNzTB";
public static String OAUTH_CALLBACK_URL = "http://office.technology.com:8081/delegate/intuit/";

public Map<String, String> getRequestTokenSignPost() {

    String authURL = null;

    OAuthProvider provider = createProvider();

    String consumerkey = OAUTH_CONSUMER_KEY;
    String consumersecret = OAUTH_CONSUMER_SECRET;

    LOG.info("Inside getRequestToken, Consumer Key and Secret: " + consumerkey + " " + consumersecret);
    String callback_url = OAUTH_CALLBACK_URL;
    LOG.info("callback URL: " + callback_url);

    OAuthConsumer ouathconsumer = new DefaultOAuthConsumer(consumerkey, consumersecret);

    try {
        HttpParameters additionalParams = new HttpParameters();
        additionalParams.put("oauth_callback", URLEncoder.encode(callback_url, "UTF-8"));
        ouathconsumer.setAdditionalParameters(additionalParams);
    } catch (UnsupportedEncodingException e) {
        LOG.error(e.getLocalizedMessage());
    }

    String requestret = "";
    String requestToken = "";
    String requestTokenSecret = "";

    try {
        String signedRequestTokenUrl = ouathconsumer.sign(REQUEST_TOKEN_URL);
        LOG.info("signedRequestTokenUrl: " + signedRequestTokenUrl);

        URL url;

        url = new URL(signedRequestTokenUrl);

        HttpURLConnection httpconnection = (HttpURLConnection) url.openConnection();
        httpconnection.setRequestMethod("GET");
        httpconnection.setRequestProperty("Content-type", "application/xml");
        httpconnection.setRequestProperty("Content-Length", "0");
        if (httpconnection != null) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(httpconnection.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);

            }
            rd.close();
            requestret = sb.toString();
        }
        String[] requestTokenSections = requestret.split("&");

        for (int i = 0; i < requestTokenSections.length; i++) {
            String[] currentElements = requestTokenSections[i].split("=");

            if (currentElements[0].equalsIgnoreCase("oauth_token")) {
                requestToken = currentElements[1];
            } else if (currentElements[0].equalsIgnoreCase("oauth_token_secret")) {
                requestTokenSecret = currentElements[1];
            }
        }

        Map<String, String> requesttokenmap = new HashMap<String, String>();

        try {
            authURL = provider.retrieveRequestToken(ouathconsumer, callback_url);
        } catch (OAuthNotAuthorizedException e) {
            LOG.error(e.getLocalizedMessage());
        }
        ouathconsumer.setTokenWithSecret(ouathconsumer.getToken(), ouathconsumer.getTokenSecret());

        requesttokenmap.put("requestToken", requestToken);
        requesttokenmap.put("requestTokenSecret", requestTokenSecret);
        requesttokenmap.put("authURL", authURL);
        return requesttokenmap;

    } catch (OAuthMessageSignerException e) {
        LOG.error(e.getLocalizedMessage());
    } catch (OAuthExpectationFailedException e) {
        LOG.error(e.getLocalizedMessage());
    } catch (OAuthCommunicationException e) {
        LOG.error(e.getLocalizedMessage());
    } catch (MalformedURLException e) {
        LOG.error(e.getLocalizedMessage());
    } catch (IOException e) {
        LOG.error(e.getLocalizedMessage());
    }
    LOG.info("Error: Failed to get request token.");
    return null;

}

public static OAuthProvider createProvider() {
    OAuthProvider provider =
            new DefaultOAuthProvider(OauthHelper.REQUEST_TOKEN_URL, OauthHelper.ACCESS_TOKEN_URL, OauthHelper.AUTHORIZE_URL);

    return provider;
}

public String getAuthorizeURL(String requestToken, String requestTokenSecret) {

    String authorizeURL = "";
    try {
        authorizeURL = AUTHORIZE_URL + "?oauth_token=" + requestToken;
    } catch (Exception e) {
        LOG.error(e.getLocalizedMessage());
    }
    LOG.info("Authorize URL: " + authorizeURL);
    return authorizeURL;
}
</code>```

I even get the Request token:

```<code>signedRequestTokenUrl: https://oauth.intuit.com/oauth/v1/get_request_token?oauth_signature=EHKmrR%2BV%2ByF4WRcBmpkdBeYEfuE%3D&oauth_callback=http%253Aoffice.technology.com%253A8081%252Fdelegate%252Fintuit&oauth_consumer_key=qyprdFHGaJjBj1jDH05Jen95Tu3PyW&oauth_version=1.0&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1390538706&oauth_nonce=-4612911034475731539
requestret: oauth_token_secret=XkXjGlS6bnFvOWYthCoew54W4ILcdMWQ3jaOMCQQ&oauth_callback_confirmed=true&oauth_token=qyprdRyUiXzU0QLLavn3L3TtdqvYts5CZyomkSk8miZDfB8Y
</code>```

答: I was able to fix the issue using an incognito window without any cookies for my quickbooks developer account.</p>

Body:
I am trying to integrate my web app with QuickBooks I implemented Connect to QuickBooks button and the intuit also grants the permission to the application.

However, I get We encountered a problem processing your request issue.

What might be the issue? I don't get any response in my call_back url too.

I used the code from Intuit Sample app.

public static String REQUEST_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_request_token";
public static String ACCESS_TOKEN_URL = "https://oauth.intuit.com/oauth/v1/get_access_token";
public static String AUTHORIZE_URL = "https://appcenter.intuit.com/Connect/Begin";
public static String OAUTH_CONSUMER_KEY = "qyprdFHGmJjBj1jDH05Jen95Tu3PyW";
public static String OAUTH_CONSUMER_SECRET = "OMFkKCPRBQKrMoyaLg9mFYTM26kpJg8LPthbNzTB";
public static String OAUTH_CALLBACK_URL = "http://office.technology.com:8081/delegate/intuit/";

public Map<String, String> getRequestTokenSignPost() {

    String authURL = null;

    OAuthProvider provider = createProvider();

    String consumerkey = OAUTH_CONSUMER_KEY;
    String consumersecret = OAUTH_CONSUMER_SECRET;

    LOG.info("Inside getRequestToken, Consumer Key and Secret: " + consumerkey + " " + consumersecret);
    String callback_url = OAUTH_CALLBACK_URL;
    LOG.info("callback URL: " + callback_url);

    OAuthConsumer ouathconsumer = new DefaultOAuthConsumer(consumerkey, consumersecret);

    try {
        HttpParameters additionalParams = new HttpParameters();
        additionalParams.put("oauth_callback", URLEncoder.encode(callback_url, "UTF-8"));
        ouathconsumer.setAdditionalParameters(additionalParams);
    } catch (UnsupportedEncodingException e) {
        LOG.error(e.getLocalizedMessage());
    }

    String requestret = "";
    String requestToken = "";
    String requestTokenSecret = "";

    try {
        String signedRequestTokenUrl = ouathconsumer.sign(REQUEST_TOKEN_URL);
        LOG.info("signedRequestTokenUrl: " + signedRequestTokenUrl);

        URL url;

        url = new URL(signedRequestTokenUrl);

        HttpURLConnection httpconnection = (HttpURLConnection) url.openConnection();
        httpconnection.setRequestMethod("GET");
        httpconnection.setRequestProperty("Content-type", "application/xml");
        httpconnection.setRequestProperty("Content-Length", "0");
        if (httpconnection != null) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(httpconnection.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);

            }
            rd.close();
            requestret = sb.toString();
        }
        String[] requestTokenSections = requestret.split("&");

        for (int i = 0; i < requestTokenSections.length; i++) {
            String[] currentElements = requestTokenSections[i].split("=");

            if (currentElements[0].equalsIgnoreCase("oauth_token")) {
                requestToken = currentElements[1];
            } else if (currentElements[0].equalsIgnoreCase("oauth_token_secret")) {
                requestTokenSecret = currentElements[1];
            }
        }

        Map<String, String> requesttokenmap = new HashMap<String, String>();

        try {
            authURL = provider.retrieveRequestToken(ouathconsumer, callback_url);
        } catch (OAuthNotAuthorizedException e) {
            LOG.error(e.getLocalizedMessage());
        }
        ouathconsumer.setTokenWithSecret(ouathconsumer.getToken(), ouathconsumer.getTokenSecret());

        requesttokenmap.put("requestToken", requestToken);
        requesttokenmap.put("requestTokenSecret", requestTokenSecret);
        requesttokenmap.put("authURL", authURL);
        return requesttokenmap;

    } catch (OAuthMessageSignerException e) {
        LOG.error(e.getLocalizedMessage());
    } catch (OAuthExpectationFailedException e) {
        LOG.error(e.getLocalizedMessage());
    } catch (OAuthCommunicationException e) {
        LOG.error(e.getLocalizedMessage());
    } catch (MalformedURLException e) {
        LOG.error(e.getLocalizedMessage());
    } catch (IOException e) {
        LOG.error(e.getLocalizedMessage());
    }
    LOG.info("Error: Failed to get request token.");
    return null;

}

public static OAuthProvider createProvider() {
    OAuthProvider provider =
            new DefaultOAuthProvider(OauthHelper.REQUEST_TOKEN_URL, OauthHelper.ACCESS_TOKEN_URL, OauthHelper.AUTHORIZE_URL);

    return provider;
}

public String getAuthorizeURL(String requestToken, String requestTokenSecret) {

    String authorizeURL = "";
    try {
        authorizeURL = AUTHORIZE_URL + "?oauth_token=" + requestToken;
    } catch (Exception e) {
        LOG.error(e.getLocalizedMessage());
    }
    LOG.info("Authorize URL: " + authorizeURL);
    return authorizeURL;
}

I even get the Request token:

signedRequestTokenUrl: https://oauth.intuit.com/oauth/v1/get_request_token?oauth_signature=EHKmrR%2BV%2ByF4WRcBmpkdBeYEfuE%3D&oauth_callback=http%253Aoffice.technology.com%253A8081%252Fdelegate%252Fintuit&oauth_consumer_key=qyprdFHGaJjBj1jDH05Jen95Tu3PyW&oauth_version=1.0&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1390538706&oauth_nonce=-4612911034475731539
requestret: oauth_token_secret=XkXjGlS6bnFvOWYthCoew54W4ILcdMWQ3jaOMCQQ&oauth_callback_confirmed=true&oauth_token=qyprdRyUiXzU0QLLavn3L3TtdqvYts5CZyomkSk8miZDfB8Y


问:
How to load a simplexmlobject file into a variable
I am going crazy here...

I already have a SimpleXMLElement Object so it is not an XML file...
I got it stored in a file object.txt

Now i want to put this object into a variable, but i can't get it to work...?

the SimpleXMLElement Object looks like this:

SimpleXMLElement Object
(
    [PubmedArticle] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [MedlineCitation] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [Owner] => NLM
                                    [Status] => In-Process
                                )

```<code>                        [PMID] => 20538400
                        [DateCreated] => SimpleXMLElement Object
                            (
                                [Year] => 2010
                                [Month] => 07
                                [Day] => 08
                            )

                        [Article] => SimpleXMLElement Object
                            (
                                [@attributes] => Array
                                    (
                                        [PubModel] => Print-Electronic
                                    )
</code>```

.....etc etc....

how do i put this into a variable??

i tried this:
$simplexml = file_get_contents('object.xml');

$simplexml should be an array

答:
Loading simplexml from file: simplexml_load_file: $a = simplexml_load_file('object.xml');
If you need something else, please explain.

Body:
I am going crazy here...

I already have a SimpleXMLElement Object so it is not an XML file...
I got it stored in a file object.txt

Now i want to put this object into a variable, but i can't get it to work...?

the SimpleXMLElement Object looks like this:

SimpleXMLElement Object
(
    [PubmedArticle] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [MedlineCitation] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [Owner] => NLM
                                    [Status] => In-Process
                                )

                        [PMID] => 20538400
                        [DateCreated] => SimpleXMLElement Object
                            (
                                [Year] => 2010
                                [Month] => 07
                                [Day] => 08
                            )

                        [Article] => SimpleXMLElement Object
                            (
                                [@attributes] => Array
                                    (
                                        [PubModel] => Print-Electronic
                                    )

.....etc etc....

how do i put this into a variable??

i tried this:
$simplexml = file_get_contents('object.xml');

$simplexml should be an array


问:
Positioning within a HTML form
I realize this is a very basic issue.

I am currently trying to create a website http://theviewbeyond.co.uk/.

I am currently adding a contact form to which I have created a picture to use as the background of the form, the issue is I cannot move the objects within the form such as text boxes to within the picture.

I have tried absolute positioning which doesn't seem to work either.

How can I do this ?

```<code>form {
margin: 0 auto;
width: 60%;
background-image: url("../IMG/contactpage1[2742].jpg");
background-size: cover;
</code>```

答:
I've used a fieldset as a supplimental container and positioned your from elements in this using padding. Change the padding values asrequired

fieldset {
  border: 0;
  padding-top: 400px;
  padding-left: 175px;
}

form {
  margin: 0 auto;
  width: 60%;
  background-image: url("http://theviewbeyond.co.uk/IMG/contactpage1[2742].jpg");
  background-size: cover;
  height: 900px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="Contact">
  <form>
    <fieldset>
      <input type="text" id="name" placeholder="NAME">
      <input type="text" id="email" placeholder="EMAIL">
      <input type="number" id="number" placeholder="PHONE">
      <input type="text" id="Event" placeholder="Type Of Event">
      <textarea name="message" placeholder="MESSAGE"></textarea>
    </fieldset>
  </form>
</div></code>```

Arnolds answer also has valid point regarding image size and media queries

Title: Positioning within a HTML form

Body:
I realize this is a very basic issue.

I am currently trying to create a website http://theviewbeyond.co.uk/.

I am currently adding a contact form to which I have created a picture to use as the background of the form, the issue is I cannot move the objects within the form such as text boxes to within the picture.

I have tried absolute positioning which doesn't seem to work either.

How can I do this ?

form {
margin: 0 auto;
width: 60%;
background-image: url("../IMG/contactpage1[2742].jpg");
background-size: cover;

Body:
I've used a fieldset as a supplimental container and positioned your from elements in this using padding. Change the padding values asrequired

fieldset {
  border: 0;
  padding-top: 400px;
  padding-left: 175px;
}

form {
  margin: 0 auto;
  width: 60%;
  background-image: url("http://theviewbeyond.co.uk/IMG/contactpage1[2742].jpg");
  background-size: cover;
  height: 900px;
}

<div id="Contact">
  <form>
    <fieldset>
      <input type="text" id="name" placeholder="NAME">
      <input type="text" id="email" placeholder="EMAIL">
      <input type="number" id="number" placeholder="PHONE">
      <input type="text" id="Event" placeholder="Type Of Event">
      <textarea name="message" placeholder="MESSAGE"></textarea>
    </fieldset>
  </form>
</div>

Arnolds answer also has valid point regarding image size and media queries


问:
Search for exact phrase with Elasticsearch
I am currently starting out with Elasticsearch. I've indexed a few EDIFACT messages (a pre-historic data format;-)
The content looks something like this:

```<code>UNB+UNOA:2+SENDER+RECEIVER+170509:0050+152538'
UNH+66304+CODECO:D:95B:UN:ITG12'
BGM+34+INGATE OF UCN ABCD+9'
</code>```

When I do a search for the phrase UNH+66304+CODECO:D:95B it should only return one hit but it seems it is returning all files that contain any of these words (and UNH is in every single one of the documents).
My Query is this:

```<code>curl -XGET --netrc-file ~/curl_user  'localhost:9200/edi/message/_search?pretty' -H 'Content-Type: application/json' -d'
{
    "query":{
        "match":{"MESSAGE":"UNH+66304+CODECO:D:95B"}
    }
}'
</code>```

I've tried to add the "and" operator like this:

```<code>"match":{
              "MESSAGE":{
                "query":"UNH+66304+CODECO",
                "operator": "and"

              }
            }
</code>```

But then no results are returned.
I've read the suggestion here: Searching for exact phrase
that I need to use double quotes. I've tried both "query":"'UNH+66304+CODECO'" and "query":"\"UNH+66304+CODECO\"" but it doesn't make a difference.

I have also tried match_phrase

```<code>"match_phrase":{
              "MESSAGE":{
                "query":"UNH+66304+CODECO"

              }
            }
</code>```

does not return a result while

```<code>"match_phrase":{
              "MESSAGE":{
                "query":"UNH+66304"

              }
            }
</code>```

does.
With normal text it seems to work but somehow Elasticsearch doesn't like it with the +: etc in the search string (that is unfortunately part of EDIFACT).

How to make query_string search exact phrase in ElasticSearch talks about using a different analyser if you want exact matches?

Update: abhishek mishra confirmed that the Analyser is probably the way to go. I am using Elasticsearch 5.4 and there are a lot of Analysers to chose from: https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-analyzers.html

The Keyword Analyser would probably map to what abhishek suggested as the 'not analysed' as it is a noop Analyser. However I am a bit worried about using this as the messages can be quite long. What are the performance impacts for the search? If I use the Keyword Analyser will I still be able to search for parts of the whole message?

I am wondering whether the Pattern Analyser would be a good fit?
EDIFACT messages consist of segments starting with 3 Upper Case Characters and are terminated by ' (but you can escape ' by prefixing it with ?)

```<code>FTX+AAA++It?'s a strange data format'
FTX+AAA++Yes it is'
</code>```

So the example above would be two segments. If I would use a pattern that separates splits these segments, would that be a good match?

Only problem is that currently the MESSAGE field can contain EDIFACT messages and XML messages. Using the same Pattern Analyser would not work I guess so I would have to create two different types depending on the content of the MESSAGE field (all the rest is the same).

2nd Update:
I have followed the advice to look into analysers. I thought the keyword analyser is probably not a good idea as the text can be quite long. I've found that the pattern analyser (without any custom pattern) works quite nicely. It splits up everything on : and +. Searches like

```<code>{
    "query":{
        "match_phrase":{"MESSAGE":"RFF+ABT:ATB150538080520172452"}
    }
}
</code>```

or

```<code>{
        "query":{
            "match_phrase":{"MESSAGE":"RFF+ABT:ATB150538080520172452"}
        }
    }
</code>```

work now. The problem before was that e.g. was split up into [rff,abt:atb150538080520172452].

答:
You were on the right track about the analyzer. If you look into your type mapping, the property MESSAGE is probably marked as analyzed. This is why when indexing it's getting rid of the special characters. You need to mark it as not_analyzed.

If you let us know what your type mapping looks like I can help you with the correct setting.

One of the examples -

If your ES version is < 5.0 and your type mapping looks similar to this -

```<code>{

  "MESSAGE": {
    "type" "string",
    "index": "analyzed"
  }
}
</code>```

change it to

```<code>{
  "MESSAGE": {
    "type" "string",
    "index": "not_analyzed"
  }
}
</code>```

Body:
I am currently starting out with Elasticsearch. I've indexed a few EDIFACT messages (a pre-historic data format;-)
The content looks something like this:

UNB+UNOA:2+SENDER+RECEIVER+170509:0050+152538'
UNH+66304+CODECO:D:95B:UN:ITG12'
BGM+34+INGATE OF UCN ABCD+9'

When I do a search for the phrase UNH+66304+CODECO:D:95B it should only return one hit but it seems it is returning all files that contain any of these words (and UNH is in every single one of the documents).
My Query is this:

curl -XGET --netrc-file ~/curl_user  'localhost:9200/edi/message/_search?pretty' -H 'Content-Type: application/json' -d'
{
    "query":{
        "match":{"MESSAGE":"UNH+66304+CODECO:D:95B"}
    }
}'

I've tried to add the "and" operator like this:

"match":{
              "MESSAGE":{
                "query":"UNH+66304+CODECO",
                "operator": "and"

              }
            }

But then no results are returned.
I've read the suggestion here: Searching for exact phrase
that I need to use double quotes. I've tried both "query":"'UNH+66304+CODECO'" and "query":"\"UNH+66304+CODECO\"" but it doesn't make a difference.

I have also tried match_phrase

"match_phrase":{
              "MESSAGE":{
                "query":"UNH+66304+CODECO"

              }
            }

does not return a result while

"match_phrase":{
              "MESSAGE":{
                "query":"UNH+66304"

              }
            }

does.
With normal text it seems to work but somehow Elasticsearch doesn't like it with the +: etc in the search string (that is unfortunately part of EDIFACT).

How to make query_string search exact phrase in ElasticSearch talks about using a different analyser if you want exact matches?

Update: abhishek mishra confirmed that the Analyser is probably the way to go. I am using Elasticsearch 5.4 and there are a lot of Analysers to chose from: https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-analyzers.html

The Keyword Analyser would probably map to what abhishek suggested as the 'not analysed' as it is a noop Analyser. However I am a bit worried about using this as the messages can be quite long. What are the performance impacts for the search? If I use the Keyword Analyser will I still be able to search for parts of the whole message?

I am wondering whether the Pattern Analyser would be a good fit?
EDIFACT messages consist of segments starting with 3 Upper Case Characters and are terminated by ' (but you can escape ' by prefixing it with ?)

FTX+AAA++It?'s a strange data format'
FTX+AAA++Yes it is'

So the example above would be two segments. If I would use a pattern that separates splits these segments, would that be a good match?

Only problem is that currently the MESSAGE field can contain EDIFACT messages and XML messages. Using the same Pattern Analyser would not work I guess so I would have to create two different types depending on the content of the MESSAGE field (all the rest is the same).

2nd Update:
I have followed the advice to look into analysers. I thought the keyword analyser is probably not a good idea as the text can be quite long. I've found that the pattern analyser (without any custom pattern) works quite nicely. It splits up everything on : and +. Searches like

{
    "query":{
        "match_phrase":{"MESSAGE":"RFF+ABT:ATB150538080520172452"}
    }
}

or

{
        "query":{
            "match_phrase":{"MESSAGE":"RFF+ABT:ATB150538080520172452"}
        }
    }

work now. The problem before was that e.g. was split up into [rff,abt:atb150538080520172452].

Body:
You were on the right track about the analyzer. If you look into your type mapping, the property MESSAGE is probably marked as analyzed. This is why when indexing it's getting rid of the special characters. You need to mark it as not_analyzed.

If you let us know what your type mapping looks like I can help you with the correct setting.

One of the examples -

If your ES version is < 5.0 and your type mapping looks similar to this -

{

  "MESSAGE": {
    "type" "string",
    "index": "analyzed"
  }
}

change it to

{
  "MESSAGE": {
    "type" "string",
    "index": "not_analyzed"
  }
}