问:
How could I encode a long number using uppercase letters and numbers to make it shorter to type?
Is there a way I could encode a long number (e.g. 12349874529768521) as lower-case letters AND numbers for the purposes of reducing its length?  The idea is that a user might have a long number on a piece of paper.

It seems to me that if there are more symbols available, that the resulting number could be made shorter. So I'm looking for something like hexadecimal but using the larger symbol space of A-Z instead of just A-F.

This would be in C# (if it matters)

答:
Base32 encoding is designed to produce an unambiguous, compact, human-readable (and non-obscene!) representation. From Wikipedia:

Base32 has a number of advantages over Base64:

The resulting character set is all one case, which can often be beneficial when using a case-insensitive filesystem, spoken language, or human memory.

The
  result can be used as a file name because it can not possibly contain the '/' symbol, which is the Unix path separator.

The alphabet can be selected to avoid similar-looking pairs of different symbols, so the strings can be accurately transcribed by hand. (For example, the RFC 4648 symbol set omits the digits for one, eight and zero, since they could be confused with the letters 'I', 'B', and 'O'.)

A result excluding padding can be included in a URL without encoding any characters.

Base32 also has advantages over hexadecimal/Base16: Base32
  representation takes roughly 20% less space. (1000 bits takes 200
  characters, compared to 250 for Base16)

Douglas Crockford's original article on Base32 encoding is also well worth a read.

EDIT: here's a bit of C# that'll do base-N encoding of integers:

```<code>class Program {
    private const string BINARY = "01";
    private const string DECIMAL = "0123456789";
    private const string HEX = "0123456789abcdef";
    private const string BASE32 = "0123456789abcdefghjkmnpqrstvwxyz";

    static string EncodeInt32(string alphabet, int value) {
        var sb = new StringBuilder();
        while (value > 0) {
            sb.Insert(0, alphabet[value % alphabet.Length]);
            value = value / alphabet.Length;
        }
        return sb.ToString();
    }

    static int DecodeInt32(string alphabet, string value) {
        int result = 0;
        int b = alphabet.Length;
        int pow = 0;
        for (var i = value.Length-1; i >= 0; i--) {
            result += (int)(Math.Pow(b, pow++)) * alphabet.IndexOf(value[i]);
        }
        return (result);
    }

    static void Main(string[] args) {
        for (var i = 0; i < 1234567890; i += 1234567) {
            Console.WriteLine("{0} {1} {2}", i, EncodeInt32(BASE32, i), DecodeInt32(BASE32, EncodeInt32(BASE32, i)));
        }
        Console.ReadKey(false);
    }
}
</code>```

Example output showing typical reduction in string length:

```<code>1227159598 14j9y1e 1227159598
1228394165 14kfknn 1228394165
1229628732 14mn99w 1229628732
1230863299 14ntyy3 1230863299
1232097866 14q0mja 1232097866
1233332433 14r6a6h 1233332433
1234567000 14sbztr 1234567000
</code>```

Body:
Base32 encoding is designed to produce an unambiguous, compact, human-readable (and non-obscene!) representation. From Wikipedia:

Base32 has a number of advantages over Base64:

The resulting character set is all one case, which can often be beneficial when using a case-insensitive filesystem, spoken language, or human memory.

The
  result can be used as a file name because it can not possibly contain the '/' symbol, which is the Unix path separator.

The alphabet can be selected to avoid similar-looking pairs of different symbols, so the strings can be accurately transcribed by hand. (For example, the RFC 4648 symbol set omits the digits for one, eight and zero, since they could be confused with the letters 'I', 'B', and 'O'.)

A result excluding padding can be included in a URL without encoding any characters.

Base32 also has advantages over hexadecimal/Base16: Base32
  representation takes roughly 20% less space. (1000 bits takes 200
  characters, compared to 250 for Base16)

Douglas Crockford's original article on Base32 encoding is also well worth a read.

EDIT: here's a bit of C# that'll do base-N encoding of integers:

class Program {
    private const string BINARY = "01";
    private const string DECIMAL = "0123456789";
    private const string HEX = "0123456789abcdef";
    private const string BASE32 = "0123456789abcdefghjkmnpqrstvwxyz";

    static string EncodeInt32(string alphabet, int value) {
        var sb = new StringBuilder();
        while (value > 0) {
            sb.Insert(0, alphabet[value % alphabet.Length]);
            value = value / alphabet.Length;
        }
        return sb.ToString();
    }

    static int DecodeInt32(string alphabet, string value) {
        int result = 0;
        int b = alphabet.Length;
        int pow = 0;
        for (var i = value.Length-1; i >= 0; i--) {
            result += (int)(Math.Pow(b, pow++)) * alphabet.IndexOf(value[i]);
        }
        return (result);
    }

    static void Main(string[] args) {
        for (var i = 0; i < 1234567890; i += 1234567) {
            Console.WriteLine("{0} {1} {2}", i, EncodeInt32(BASE32, i), DecodeInt32(BASE32, EncodeInt32(BASE32, i)));
        }
        Console.ReadKey(false);
    }
}

Example output showing typical reduction in string length:

1227159598 14j9y1e 1227159598
1228394165 14kfknn 1228394165
1229628732 14mn99w 1229628732
1230863299 14ntyy3 1230863299
1232097866 14q0mja 1232097866
1233332433 14r6a6h 1233332433
1234567000 14sbztr 1234567000


来源: stackexchange

问:
check if .click() function is available in browser
I am building an application that uses .click() method in couple of places. It was reported that it causes errors in safari (windows version) because its not available in the browser.

I made some research and i found good alternative, i created a polyfill solution for it, but i am struggling to find how can i check if browser supports .click() method.

I tried following:

Element.prototype.click returns undefined in all browsers

Element.click returns undefined in all browsers

document.prototype.click returns undefined in all browsers

document.click returns undefined in all browsers

This is the polyfill i made:

```<code>Element.prototype.click = function() {
    var click_ev = document.createEvent("MouseEvents");
    click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
    this.dispatchEvent(click_ev);
};
</code>```

Now i just need to check it and apply only if .click() is unavailable.

答:
You can validate yourElment.click

```<code>if(!(yourElment.click)){
    // click doent exist
    Element.prototype.click = function() {
    var click_ev = document.createEvent("MouseEvents");
    click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
    this.dispatchEvent(click_ev);
 };
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am building an application that uses .click() method in couple of places. It was reported that it causes errors in safari (windows version) because its not available in the browser.

I made some research and i found good alternative, i created a polyfill solution for it, but i am struggling to find how can i check if browser supports .click() method.

I tried following:

Element.prototype.click returns undefined in all browsers

Element.click returns undefined in all browsers

document.prototype.click returns undefined in all browsers

document.click returns undefined in all browsers

This is the polyfill i made:

Element.prototype.click = function() {
    var click_ev = document.createEvent("MouseEvents");
    click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
    this.dispatchEvent(click_ev);
};

Now i just need to check it and apply only if .click() is unavailable.

Body:
You can validate yourElment.click

if(!(yourElment.click)){
    // click doent exist
    Element.prototype.click = function() {
    var click_ev = document.createEvent("MouseEvents");
    click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
    this.dispatchEvent(click_ev);
 };
}


答:
How about a BaseN Method to encode/decode your long into a string with characters you defined on your own

```<code>public static class BaseN
{
    private const string CharList = "0123456789abcdefghijklmnopqrstuvwxyz";
    public static String Encode(long input)
    {
        if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
        var result = new System.Collections.Generic.Stack<char>();
        while (input != 0)
        {
            result.Push(CharList[(int)(input % CharList.Length)]);
            input /= CharList.Length;
        }
        return new string(result.ToArray());
    }

    public static long Decode(string input)
    {
        long result = 0, pos = 0;
        foreach (char c in input.Reverse())
        {
            result += CharList.IndexOf(c) * (long)Math.Pow(CharList.Length, pos);
            pos++;
        }
        return result;
    }
}
</code>```

Usage:

```<code>long number = 12349874529768521;
string result = BaseN.Encode(number);
</code>```

Sample:

https://dotnetfiddle.net/odwFlk

Title: How could I encode a long number using uppercase letters and numbers to make it shorter to type?

Body:
Is there a way I could encode a long number (e.g. 12349874529768521) as lower-case letters AND numbers for the purposes of reducing its length?  The idea is that a user might have a long number on a piece of paper.

It seems to me that if there are more symbols available, that the resulting number could be made shorter. So I'm looking for something like hexadecimal but using the larger symbol space of A-Z instead of just A-F.

This would be in C# (if it matters)

Body:
How about a BaseN Method to encode/decode your long into a string with characters you defined on your own

public static class BaseN
{
    private const string CharList = "0123456789abcdefghijklmnopqrstuvwxyz";
    public static String Encode(long input)
    {
        if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
        var result = new System.Collections.Generic.Stack<char>();
        while (input != 0)
        {
            result.Push(CharList[(int)(input % CharList.Length)]);
            input /= CharList.Length;
        }
        return new string(result.ToArray());
    }

    public static long Decode(string input)
    {
        long result = 0, pos = 0;
        foreach (char c in input.Reverse())
        {
            result += CharList.IndexOf(c) * (long)Math.Pow(CharList.Length, pos);
            pos++;
        }
        return result;
    }
}

Usage:

long number = 12349874529768521;
string result = BaseN.Encode(number);

Sample:

https://dotnetfiddle.net/odwFlk


问:
Logging events in Kubernetes cluster
Iam new to Kubernetes , i have to create a logging mechanism which logs various pod lifecycle events happening in Kubernetes Cluster . Can any one tell how shall i proceed ?</p>

答:
You are looking for the ELK stack: Elasticsearch, Logstash, Kibana (or EFK if using Fluentd). There is a tutorial here:
https://kubernetes.io/docs/tasks/debug-application-cluster/logging-elasticsearch-kibana/

Unfortunately this is not a trivial. Google the terms above, experiment and learn. Good luck :)

Title: Logging events in Kubernetes cluster


问:
MVP - hide view methods from client code
While using the Model-View-Presenter pattern I often find myself in the following scenario:

```<code>// PACKAGE A
// pacakge private
interface View
{
    void methodForPresenter();
}

public class ViewImpl implements View
{
    @Override
    public void methodForPresenter() {}

    public void methodForClient() {}
}

// PACKAGE B
// client code example
void main()
{
    ViewImpl view = new ViewImpl();
    view.methodForClient(); // ok
    view.methodForPresenter(); // not ok - should not be used
}
</code>```

Is there a way how to keep methods meant for presenter hidden inside the package? The view interface is package private for a reason, but since all overriden interface methods in java have to be public, I don't know how to hide the methodForPresenter() from the client code.

答:
I found one solution using an anonymous inner class and composition:

```<code>// PACKAGE A
// pacakge private
interface View
{
    void methodForPresenter();
}

public class ViewImpl
{
    private m_view = new View()
    {
        @Override
        public void methodForPresenter() {}
    }

    public void methodForClient() {}
}

// PACKAGE B
// client code example
void main()
{
    ViewImpl view = new ViewImpl();
    view.methodForClient(); // ok
    view.methodForPresenter(); // now an error
}
</code>```

Now I pass m_view to Presenter instead of this.

Body:
While using the Model-View-Presenter pattern I often find myself in the following scenario:

// PACKAGE A
// pacakge private
interface View
{
    void methodForPresenter();
}

public class ViewImpl implements View
{
    @Override
    public void methodForPresenter() {}

    public void methodForClient() {}
}

// PACKAGE B
// client code example
void main()
{
    ViewImpl view = new ViewImpl();
    view.methodForClient(); // ok
    view.methodForPresenter(); // not ok - should not be used
}

Is there a way how to keep methods meant for presenter hidden inside the package? The view interface is package private for a reason, but since all overriden interface methods in java have to be public, I don't know how to hide the methodForPresenter() from the client code.

Body:
I found one solution using an anonymous inner class and composition:

// PACKAGE A
// pacakge private
interface View
{
    void methodForPresenter();
}

public class ViewImpl
{
    private m_view = new View()
    {
        @Override
        public void methodForPresenter() {}
    }

    public void methodForClient() {}
}

// PACKAGE B
// client code example
void main()
{
    ViewImpl view = new ViewImpl();
    view.methodForClient(); // ok
    view.methodForPresenter(); // now an error
}

Now I pass m_view to Presenter instead of this.


问:
Android SPP Bluetooth: Implement a Background connection attempt
I would like to minimize the need for user involvement in working with SPP medical devices. The user should only have to pair the device and then connections happen automatically when the device becomes connectable. HDP classic devices are like this and so are BTLE devices (the latter takes work on Android).

So the obvious solution is after pairing, create the RFCOMM Socket and invoke the connect() method (and perhaps all the workarounds to handle the various bugs).

However, this blocking method times out after 12 or so seconds according to the documentation so if I really want to continuously be ready for the device when it 'comes on-line', I need to do this in a while-loop until the connection succeeds.

So the question is if I do this, will this continuous 'pinging' for the device overload the system and drain the battery? Given that something like this happens for HDP implementations on Android, they must also do something like this but maybe they reduce the frequency of pinging so it isn't so resource demanding.

Does anyone have any experience with attempting to do continuous monitoring for SPP devices?  Thanks!

答:
I have used Bluetooth SPP connection for industrial devices and had a similar problem. It does not seem a good idea to have a service trying to connect all the time, as it will need to always run on the background and drain more battery.

My solution would be if possible to have the SPP medical device to ask for connection once powered to the paired device(your android), or when you try to connect to the medical device, automate the connection procedure which should take about 1-2 seconds (if you can filter the devices by their MAC address(preferably) or name in your app)

Based on the bluetooth chip in your medical device, you should have plenty of connectivity options from this end, but if not you can try to connect on demand.


问:
what is worng with that code? Only ($content = 'europe') is executing successfully... Remaining conditions are not executing
In that code only first condition is executing even if values are changed instead of ($content = 'europe') to ($content = 'asia') . Remaining conditions are not working.

```<code>function test(){

    if($content = 'europe'){
        $multi_tlds = $titan->getOption('wdc_europe');
    } elseif($content = 'asia'){
        $multi_tlds = $titan->getOption('wdc_asia');
    } elseif($content = 'africa'){
        $multi_tlds = $titan->getOption('wdc_africa');
    }

}
</code>```

please check below code:

I have just mentioned my name like(pradeep). That is the exact place of code

```<code><?php

    function wdc_display_func($content){
        check_ajax_referer( 'wdc_nonce', 'security' );
        $titan = TitanFramework::getInstance( 'wdc-options' );
        $whois = $titan->getOption( 'whois_option' );
        $integration = $titan->getOption( 'integration' );
        $extensions = $titan->getOption( 'extensions' );
        //$multi_tlds = $titan->getOption('wdc_multi_tlds');

    /*start - This is actual code (Pradeep)*/

        if($content == 'europe'){
            $multi_tlds = $titan->getOption('wdc_europe');
        } elseif($content == 'asia'){
            $multi_tlds = $titan->getOption('wdc_asia');
        } elseif($content == 'africa'){
            $multi_tlds = $titan->getOption('wdc_africa');
        }
        /* End - This is actual code (Pradeep)*/

        $ext_message = $titan->getOption( 'ext_message' );
        $additional_button_name = $titan->getOption( 'additional_button_name' );
        $additional_button_link = $titan->getOption( 'additional_button_link' );
        $custom_found_result_texts = $titan->getOption( 'custom_found_result_text' );
        if($custom_found_result_texts == '') $custom_found_result_texts = __('Congratulations! {domain} is available!', 'wdc');
        $custom_not_found_result_texts = $titan->getOption( 'custom_not_found_result_text' );
        if($custom_not_found_result_texts == '') $custom_not_found_result_texts = __('Sorry! {domain} is already taken!', 'wdc');
        if($ext_message == '') $ext_message = __('Sorry, we currently do not handle that particular tld.', 'wdc');

    if(isset($_POST['domain']))
    {
        if($integration == 'woocommerce' OR $integration == 'custom'){

            if($_POST['item_id'] != ''){
            $additional_button_link = $_POST['item_id'];
            }

        }
        $domain = str_replace(array('www.', 'http://'), NULL, $_POST['domain']);
        if (strpos($domain,'.') == false) {

   /*start - code (pradeep)*/
            if($multi_tlds == ''){
                $multi_tlds = array('com');
            }else{
                $multi_tlds = explode(',', $multi_tlds);
            }

        }else{
            list($sp, $split) = explode('.', $domain,2);
            $multi_tlds = array($split);
        }
    /*End - code (pradeep)*/

        if (function_exists('idn_to_ascii')) {
            $punny_domain = idn_to_ascii($domain);
        }else{
            $punny_domain = $domain;
            $punny_domain = preg_replace("/[^-a-zA-Z0-9.]+/", "", $punny_domain);
            $domain = $punny_domain;
        }
        $punny_domain = preg_replace("/[^-a-zA-Z0-9.]+/", "", $punny_domain);
        if(strlen($punny_domain) > 0)
        {

            include ('lib/DomainAvailability.php');
            $Domains = new DomainAvailability();
            list($dom, $ext) = explode('.', $punny_domain, 2);

            foreach($multi_tlds as $ex)
            {
            $domain = $dom.'.'.$ex;
            if($extensions != ''){
            $tlds = explode(',', $extensions);
            if (!in_array($ex, $tlds)) {
                $result = array('status'=>2,
                                'domain'=>$domain,
                                'text'=>    '<div class="callout callout-warning alert-warning clearfix">
                                            <div class="col-xs-10" style="padding-left:1px;text-align:left;">
                                            <i class="glyphicon glyphicon-exclamation-sign" style="margin-right:1px;"></i> '.$ext_message.'
                                            </div>
                                            </div>
                                            ');
                echo $result['text'];
                wp_die();
            }
            }

            $available = json_decode($Domains->is_available($domain));
            $custom_found_result_text = str_replace( '{domain}', $domain, $custom_found_result_texts );
            if($whois > 1) {
                    $whois_link = "<a href='".get_permalink($whois)."?&domain=$domain' target='_blank'><button id='whois' class='btn btn-danger btn-xs pull-right whois-btn'>WHOIS</button></a>";
                }else{
                    $whois_link = '';
                }

            if($integration == 'whmcs'){
    $check_ex = explode('.',$ex);

    if(count($check_ex) == 2){
        $ex_name = $check_ex[0]."_".$check_ex[1];
    }else{
        $ex_name = $check_ex[0];
    }
                $additional_button = "<a href='javascript:void(0)' onclick='submitform_$dom_$ex_name()'><button class='btn btn-success btn-xs pull-right order-btn'>$additional_button_name</button></a>";
            }elseif($integration == 'woocommerce'){
                //$additional_button = "<a href='?&add-to-cart=$additional_button_link&domain=$domain' target='_blank' class='btn btn-success btn-xs pull-right order-btn' >$additional_button_name</a>";
                $additional_button = "<a href='http://staging1.lowcostwebagency.com/domain-contact-form/' target='_blank' class='btn btn-primary btn-xs pull-right order-btn' >Ask for</a>";
                }elseif($integration == 'custom'){
                if(!$additional_button_name == '' AND !$additional_button_link == ''){
                    $additional_button_link = str_replace( '{domain}', $domain, $additional_button_link );
                    $additional_button = "<a class='btn btn-success btn-xs pull-right order-btn' href='$additional_button_link'>$additional_button_name</a>";
                }else{
                    $additional_button = '';
                }
            }else{
                $additional_button = '';
            }

            $custom_not_found_result_text = str_replace( '{domain}', $domain, $custom_not_found_result_texts );
            $whmcs = "<script type='text/javascript'>
                    function submitform_$dom_$ex_name()
                    {
                      document.whmcs_$dom_$ex_name.submit();
                    }
                    </script>
                    <form method='post' name='whmcs_$dom_$ex_name' id='whmcs' action='$additional_button_link/cart.php?a=add&domain=register'>
                    <input type='hidden' name='domains[]' value='$domain' >
                    <input type='hidden' name='domainsregperiod[$domain]' value='1'>
                    </form>";
            if ($available->status == 1) {
                    $result = array('status'=>1,
                                    'domain'=>$domain,
                                    'text'=>    '<div class="callout callout-success alert-success clearfix available">
                                                <div class="col-xs-10" style="padding-left:1px;text-align:left;">
                                                <i class="glyphicon glyphicon-ok" style="margin-right:1px;"></i> '.$custom_found_result_text.'
                                                </div>
                                                <div class="col-xs-2" style="padding-right:1px">'.$additional_button.' '.$whmcs.'</div>
                                                </div>
                                                ');
                    echo $result['text'];

            } elseif($available->status == 0) {
                    $result = array('status'=>0,
                                    'domain'=>$domain,
                                    'text'=>    '<div class="callout callout-danger alert-danger clearfix not-available">
                                                <div class="col-xs-10" style="padding-left:1px;text-align:left;">
                                                <i class="glyphicon glyphicon-remove" style="margin-right:1px;"></i> '.$custom_not_found_result_text.'
                                                </div>
                                                <div class="col-xs-2" style="padding-right:1px">'.$whois_link.'</div>
                                                </div>
                                                ');
                    echo $result['text'];
            }elseif ($available->status == 2) {
                    $result = array('status'=>2,
                                    'domain'=>$domain,
                                    'text'=>    '<div class="callout callout-warning alert-warning clearfix notfound">
                                                <div class="col-xs-10" style="padding-left:1px;text-align:left;">
                                                <i class="glyphicon glyphicon-exclamation-sign" style="margin-right:1px;"></i> WHOIS server not found for that TLD
                                                </div>
                                                </div>
                                                ');
                    echo $result['text'];

            }
        }
        }
        else
        {
            echo 'Please enter the domain name';
        }
    }
    wp_die();
    }

    add_action('wp_ajax_wdc_display','wdc_display_func');
    add_action('wp_ajax_nopriv_wdc_display','wdc_display_func');

    function wdc_display_dashboard(){
        echo do_shortcode('[wpdomainchecker]');
    }

    function wdc_add_dashboard_widgets() {

        wp_add_dashboard_widget(
                     'wdc_dashboard_widget',
                     'WP Domain Checker',
                     'wdc_display_dashboard'

            );
    }
    add_action( 'wp_dashboard_setup', 'wdc_add_dashboard_widgets' );

    function wdc_whois_shortcode(){

        if(isset($_GET['domain'])){

            echo '<h3>Whois record for <b>'.htmlspecialchars($_GET['domain']).'</b></h3>';

            require("lib/whoisClass.php");
            $whois=new Whois;
            echo "```";
            if (function_exists('idn_to_ascii')) {
            echo $whois->whoislookup(idn_to_ascii($_GET['domain']));
            }else{
            echo $whois->whoislookup($_GET['domain']);
            }
            echo "```";
        }

    }
    add_shortcode( 'wpdomainwhois', 'wdc_whois_shortcode' );

    function wdc_display_shortcode($atts){

        $titan = TitanFramework::getInstance( 'wdc-options' );
        $item_id = $titan->getOption( 'additional_button_link' );
        $image = $titan->getOption( 'loading_image' );
        $recaptcha_enable = $titan->getOption( 'recaptcha' );
        $placeholder = $titan->getOption( 'input_placeholder' );
        $image = wp_get_attachment_image_src($image);
        if($image == '') {
            $image = plugins_url( '/images/load.gif', __FILE__ );
        }else{
            $image = $image[0];
        }
            $atts = shortcode_atts(
            array(
                'width' => '900',
                'button' => 'Check',
                'recaptcha' => 'no',
                'item_id' => $item_id,
                'tld' => ''
            ), $atts );
        if($atts['recaptcha'] == 'yes'){
            $show_recaptcha = "<p> <div id='wdc-recaptcha' class='wdc' ></div></p>";
        }else{
            $show_recaptcha = "";
        }
    $content = "<div id='domain-form'>
        <div id='wdc-style'>
            <form method='post' action='./' id='form' class='pure-form'>
                <input type='hidden' name='item_id' value='{$atts['item_id']}'>
                <input type='hidden' name='tld' value='{$atts['tld']}'>
                <div class='input-group' style='max-width:{$atts["width"]}px;'>
                    <input type='text' class='form-control' autocomplete='off' id='Search' name='domain' placeholder='$placeholder'>
                        <span class='input-group-btn'>
                        <button type='submit' id='Submit' class='btn btn-default btn-info'>{$atts["button"]}</button>
                        </span>
                </div>
            {$show_recaptcha}
            <div id='loading'><img src='$image'></img></div>

 <!--start - code (pradeep) -->

    <div class='container'>
      <div class='row'>
        <div class='col-sm-3'>
    <fieldset>
    <input type='radio' name='asia' value='asia'> Asia<br>
    <input type='radio' name='europe' value='europe'> Europe<br>
    </fieldset>
    </div>
    <div class='col-sm-3'>
    <fieldset>
      <input type='radio' name='africa' value='africa'> Africa<br>
    </fieldset>
    </div>
    </div></div>

    <!-- end - code (pradeep) -->

    </form>
    <div style='max-width:{$atts["width"]}px;'>
            <div id='results' title='API' class='result'></div>
    </div>
        </div>
    </div>";

    return $content;

    }
</code>```

?>

Remaing code (continue from above code)... If you want you can go through...I hope you may find solution:

```<code>     <?php

    add_shortcode( 'wpdomainchecker', 'wdc_display_shortcode' );

    /* Woocommerce Function */
    function custom_add_to_cart_redirect() {
        if($_REQUEST['domain']){
        return WC()->cart->get_cart_url();
        }
    }
    add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect' );

    function save_name_on_wdc_field( $cart_item_key, $product_id = null, $quantity= null, $variation_id= null, $variation= null ) {

        WC()->session->set( $cart_item_key.'_domain', $_GET['domain'] );
        WC()->session->set( $cart_item_key.'_price', $_GET['price'] );

    }
    add_action( 'woocommerce_add_to_cart', 'save_name_on_wdc_field', 1, 5 );

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price');

    function add_custom_price( $cart_object ) {
        $titan = TitanFramework::getInstance( 'wdc-options' );

        global $woocommerce;
        $tld = array();
        $extensions = $titan->getOption( 'wdc_custom_price' );
        $extensions = preg_replace('/\s+/', '', $extensions);
        $tlds = explode(',', $extensions);

        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
        if(WC()->session->get( $cart_item_key.'_domain')){
        $domain = WC()->session->get( $cart_item_key.'_domain');
        list($domain, $ext) = explode('.', $domain, 2);

         foreach ($tlds as $key => $value) {
            $tld = explode('|', $value);
            if($ext == $tld[0]){
                $price = $tld[1];
                $cart_item['data']->price = $price;
            }
        }
        }
        }
     }

    function render_meta_on_cart_item( $title = null, $cart_item = null, $cart_item_key = null ) {
        global $product_id;
        if( $cart_item_key && is_cart() ) {

            if(WC()->session->get( $cart_item_key.'_domain')){
            echo $title. '<dl class="">
                     <dt class="">Domain : </dt>
                     <dd class=""><p>'. WC()->session->get( $cart_item_key.'_domain') .'</p></dd>
                  </dl>';
            }else{
                echo $title;
            }
        }else {
            echo $title;
        }
    }
    add_filter( 'woocommerce_cart_item_name', 'render_meta_on_cart_item', 1, 3 );

    function render_meta_on_checkout_order_review_item( $quantity = null, $cart_item = null, $cart_item_key = null ) {
        if( $cart_item_key ) {
            if(WC()->session->get( $cart_item_key.'_domain')){
            echo $quantity. '<dl class="">
                     <dt class="">Domain : </dt>
                     <dd class=""><p>'. WC()->session->get( $cart_item_key.'_domain') .'</p></dd>
                  </dl>';
            }else{
                echo $quantity;
            }
        }
    }
    add_filter( 'woocommerce_checkout_cart_item_quantity', 'render_meta_on_checkout_order_review_item', 1, 3 );

    function wdc_order_meta_handler( $item_id, $values, $cart_item_key ) {
        if(WC()->session->get( $cart_item_key.'_domain')){
        wc_add_order_item_meta( $item_id, "Domain", WC()->session->get( $cart_item_key.'_domain') );
        }

    }
    add_action( 'woocommerce_add_order_item_meta', 'wdc_order_meta_handler', 1, 3 );

    function wdc_force_individual_cart_items($cart_item_data, $product_id)
    {
        $titan = TitanFramework::getInstance( 'wdc-options' );
        $id = $titan->getOption( 'additional_button_link' );
        $unique_cart_item_key = md5( microtime().rand() );
        $cart_item_data['unique_key'] = $unique_cart_item_key;

        return $cart_item_data;

    }
    add_filter( 'woocommerce_add_cart_item_data','wdc_force_individual_cart_items', 10, 2 );

    add_filter('woocommerce_loop_add_to_cart_link','wdc_replace_add_to_cart');
    function wdc_replace_add_to_cart() {
    global $product;
     $link = sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button product_type_%s">%s</a>',
            esc_url( $product->add_to_cart_url() ),
            esc_attr( $product->id ),
            esc_attr( $product->get_sku() ),
            esc_attr( isset( $quantity ) ? $quantity : 1 ),
            esc_attr( $product->product_type ),
            esc_html( $product->add_to_cart_text() )
        );
      $links = sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button product_type_%s">%s</a>',
            esc_url( get_permalink($product->id) ),
            esc_attr( $product->id ),
            esc_attr( $product->get_sku() ),
            esc_attr( isset( $quantity ) ? $quantity : 1 ),
            esc_attr( $product->product_type ),
            esc_html( $product->add_to_cart_text() )
        );

       if(get_post_meta( $product->id, 'wdc_hide_addtocart', true ) == 'yes'){
        return $links;
       }else{
        return $link;
       }
    }

    function wdc_remove_cart_button(){
    $product_id = get_the_ID();
        if(get_post_meta( $product_id, 'wdc_hide_addtocart', true ) == 'yes'){
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
        }
    }
    add_action('wp','wdc_remove_cart_button');

    function wdc_woo_add_custom_general_fields() {

      global $woocommerce, $post;

      echo '<div class="options_group">';

        woocommerce_wp_checkbox(
        array(
        'id'            => 'wdc_hide_addtocart',
        'wrapper_class' => 'wdc_item_edit_class',
        'label'         => __('WDC?', 'wdc' ),
        'description'   => __( 'Check me if you want to hide Add to Cart button on single product page.', 'wdc' )
        )
    );

      echo '</div>';

    }

    function wdc_woo_add_custom_general_fields_save( $post_id ){
        $woocommerce_checkbox = isset( $_POST['wdc_hide_addtocart'] ) ? 'yes' : 'no';
        update_post_meta( $post_id, 'wdc_hide_addtocart', $woocommerce_checkbox );
    }

    // Display Fields
    add_action( 'woocommerce_product_options_general_product_data', 'wdc_woo_add_custom_general_fields' );

    // Save Fields
    add_action( 'woocommerce_process_product_meta', 'wdc_woo_add_custom_general_fields_save' );
    /* Woocommerce End Function */

    function wdc_recaptcha_func() {
        check_ajax_referer( 'wdc_nonce', 'security' );

        if(isset($_POST['response']))
        {
            $titan = TitanFramework::getInstance( 'wdc-options' );
            $captcha = $_POST['response'];
            $secret_key = $titan->getOption( 'recaptcha_secretkey' );
            $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret_key."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
            echo $response;

        }
    wp_die();
    }
    add_action('wp_ajax_wdc_recaptcha','wdc_recaptcha_func');
    add_action('wp_ajax_nopriv_wdc_recaptcha','wdc_recaptcha_func');

    function wdc_recaptcha_dis_func() {
        check_ajax_referer( 'wdc_nonce', 'security' );

            echo json_encode(array('success' => 'true'));

    wp_die();
    }
    add_action('wp_ajax_wdc_recaptcha_dis','wdc_recaptcha_dis_func');
    add_action('wp_ajax_nopriv_wdc_recaptcha_dis','wdc_recaptcha_dis_func');

    function wdc_options() {
        $titan = TitanFramework::getInstance( 'wdc-options' );
        global $panel;

        $panel = $titan->createAdminPanel( array(
        'name' => 'WP Domain Checker',
        'parent' => 'options-general.php',
        ) );

        $generaltab = $panel->createTab( array(
        'name' => 'General',
        ) );

        $generaltab->createOption( array(
        'name' => 'Custom Available Result Text',
        'id' => 'custom_found_result_text',
        'type' => 'textarea',
        'desc' => 'This is custom available result text. Use {domain} to replace domain name.'
        ) );

        $generaltab->createOption( array(
        'name' => 'Custom Not Available Result Text',
        'id' => 'custom_not_found_result_text',
        'type' => 'textarea',
        'desc' => 'This is custom not available result text. Use template tag {domain} to replace domain name.'
        ) );

        $generaltab->createOption( array(
        'name' => 'Input Placeholder',
        'id' => 'input_placeholder',
        'type' => 'text',
        'desc' => 'Placeholder for domain input.'
        ) );

        $generaltab->createOption( array(
        'name' => 'Loading Image',
        'id' => 'loading_image',
        'type' => 'upload',
        'desc' => 'Upload your image'
        ) );
        $pages=get_pages( array('post_type' => 'page','post_status' => 'publish') );
        foreach ($pages as $page) {
            $whois_page['disable'] = 'Disable';
            $whois_page[$page->ID] = $page->post_title;
        }
        $generaltab->createOption( array(
        'name' => 'Whois Page',
        'id' => 'whois_option',
        'type' => 'select',
        'options' => $whois_page,
        'desc' => 'Enable or disable whois link if domain not available',
        'default' => 'disable',
        ) );

        $generaltab->createOption( array(
        'name' => 'Integration With',
        'id' => 'integration',
        'type' => 'select',
        'options' => array(
            'disable' => 'Disable',
            'whmcs' => 'WHMCS',
            'woocommerce' => 'Woocommerce',
            'custom' => 'Custom Link',
        ),
        'desc' => 'Enable or disable integration.',
        'default' => 'disable',
        ) );

        $generaltab->createOption( array(
        'name' => 'Integration Button Text',
        'id' => 'additional_button_name',
        'type' => 'text',
        'desc' => 'Integration Button Text. (e.g.: "ORDER NOW")'
        ) );

        $generaltab->createOption( array(
        'name' => 'Integration Button Link',
        'id' => 'additional_button_link',
        'type' => 'text',
        'desc' => 'Integration button link. (e.g. for WHMCS: "http://billing.host.com"). <a href="http://asdqwe.net/wordpress-plugins/wp-domain-checker-docs/" target="_blank">Documentation</a><br>
                    For custom link, you can use template tag {domain} to include domain in the link. <br>e.g: http://godaddy.com/?aff=12345&domain={domain}'
        ) );

        $generaltab->createOption( array(
        'name' => 'Supported TLD Extensions',
        'id' => 'extensions',
        'type' => 'textarea',
        'desc' => 'Allow only specific extensions to check. separate by comma for each extension. (e.g: com,net,org,co.uk,co.id)<br>Leave it blank to allow all extensions.'
        ) );

        $generaltab->createOption( array(
        'name' => 'Not Supported TLD Extensions Messages',
        'id' => 'ext_message',
        'type' => 'text',
        'desc' => 'Not Supported TLD Extensions Messages. (e.g.: "Sorry, we currently do not handle that particular tld.")'
        ) );

        $generaltab->createOption( array(
        'name' => 'WooCommerce Custom Price',
        'id' => 'wdc_custom_price',
        'type' => 'textarea',
        'desc' => 'Allow custom price for specific tld. (e.g: com|9,net|10,org|11,co.uk|12,co.id|13)'
        ) );

        $generaltab->createOption( array(
        'name' => 'Multiple TLDs Check',
        'id' => 'wdc_multi_tlds',
        'type' => 'textarea',
        'desc' => 'Multiple TLDs check if user not define tld on the domain. (e.g: com,net,org,info)'
        ) );

 /*Start- code (Pradeep)*/

        $generaltab->createOption( array(
        'name' => 'Asia TLDs Check',
        'id' => 'wdc_asia',
        'type' => 'textarea',
        'desc' => 'Asia TLDs check if user not define tld on the domain. (e.g: in,ch,rocks,club)'
        ) );

        $generaltab->createOption( array(
        'name' => 'Europe TLDs Check',
        'id' => 'wdc_europe',
        'type' => 'textarea',
        'desc' => 'Europe TLDs check if user not define tld on the domain. (e.g: fr,it,pro)'
        ) );

        $generaltab->createOption( array(
        'name' => 'Africa TLDs Check',
        'id' => 'wdc_africa',
        'type' => 'textarea',
        'desc' => 'Africa TLDs check if user not define tld on the domain. (e.g: link,af,host,me)'
        ) );

         /*End- code (Pradeep)*/

        $recaptchaTab = $panel->createTab( array(
        'name' => 'reCaptcha',
        ) );

        $panel->createOption( array(
            'type' => 'save'
        ) );

    }
    add_action( 'tf_create_options', 'wdc_options' );

    class wdc_widget extends WP_Widget {
        function __construct() {
            parent::__construct(false, $name = __('WP Domain Checker Widget'));
        }
        function form($instance) {
                if (isset($instance['title'])) {
                    $title = $instance['title'];
                    $width = $instance['width'];
                    $button = $instance['button'];
                    $recaptcha = $instance['recaptcha'];
                }else{
                    $title = "Domain Availability Check";
                    $width = "";
                    $button = "";
                    $recaptcha = "no";
                }
        ?>

        <?php
        }

    }

    function register_wdc_widget()
    {
        register_widget( 'wdc_widget' );
    }
    add_action( 'widgets_init', 'register_wdc_widget');

        ?>
</code>```

答:
this is declaring a variable

```<code>$content = 'europe'
</code>```

should be ==

```<code>$content='asia';
function test(){

    if($content == 'europe'){
        $multi_tlds = $titan->getOption('wdc_europe');
    } elseif($content == 'asia'){
        $multi_tlds = $titan->getOption('wdc_asia');
    } elseif($content == 'africa'){
        $multi_tlds = $titan->getOption('wdc_africa');
    }

}

<input type='radio' name='asia' value='asia'> Asia<br>
    <input type='radio' name='europe' value='europe'> Europe<br>
    </fieldset>
    </div>
    <div class='col-sm-3'>
    <fieldset>
      <input type='radio' name='africa' value='africa'> Africa<br>
</code>```

this piece of code is wrong they should all have the same name

```<code>name='myregionchoice'
</code>```

then you process it as post

```<code>$regionchoice=$_POST['item_id'];
</code>```

then in the if statements

```<code>if($mygreionchoice == 'europe'){
        $multi_tlds = $titan->getOption('wdc_europe');
    } elseif($myregionchoice == 'asia'){
        $multi_tlds = $titan->getOption('wdc_asia');
    } elseif($myregionchoice == 'africa'){
        $multi_tlds = $titan->getOption('wdc_africa');
    }

}
</code>```

to use a radio button choosing options  the name has to be the same for all
check the code below for the format of how to do this and where you should process data before and after the page reloads and check the function format and how i get the output from the function and how the if statement must look like you can test this code it works

```<code><html>
    <head>
    </head>
    <body>
        <form name="anyname" action="" method="post">
            <input type="radio" name="choice" value="asia"/>asia
            <input type="radio" name="choice" value="africa"/>africa
            <input type="submit" name="submit" value="my radio choice">
        </form>
<?php

    function choose(){
        //declare it is a global variable from outside the function
        global $choice;

        if ($choice =='africa') {
        $test='you choose africa';
        }
        elseif ($choice =='asia'){
        $test='you choose asia';
        }
        //returning the output of the function
        return $test;
        }

    //here you proccess the data after the page reloads

    if (!empty($_POST['choice'])){
        $choice=$_POST["choice"];
        //running the function
        choose();
        //getting the output from the function
        $test=choose();
        echo 'this is the data after the page reloads :',$test;
        }

    //here you process the data before the page reloads
    if ((isset($_POST["submit"])) && ($_POST["submit"]!="")){
        $choice=$_POST["choice"];
        //running the function
        choose();
        //getting the output from the function
        $test=choose();

        }
?>

    <body>
</html>
</code>```

Body:
In that code only first condition is executing even if values are changed instead of ($content = 'europe') to ($content = 'asia') . Remaining conditions are not working.

function test(){

    if($content = 'europe'){
        $multi_tlds = $titan->getOption('wdc_europe');
    } elseif($content = 'asia'){
        $multi_tlds = $titan->getOption('wdc_asia');
    } elseif($content = 'africa'){
        $multi_tlds = $titan->getOption('wdc_africa');
    }

}

please check below code:

I have just mentioned my name like(pradeep). That is the exact place of code

<?php

    function wdc_display_func($content){
        check_ajax_referer( 'wdc_nonce', 'security' );
        $titan = TitanFramework::getInstance( 'wdc-options' );
        $whois = $titan->getOption( 'whois_option' );
        $integration = $titan->getOption( 'integration' );
        $extensions = $titan->getOption( 'extensions' );
        //$multi_tlds = $titan->getOption('wdc_multi_tlds');

    /*start - This is actual code (Pradeep)*/

        if($content == 'europe'){
            $multi_tlds = $titan->getOption('wdc_europe');
        } elseif($content == 'asia'){
            $multi_tlds = $titan->getOption('wdc_asia');
        } elseif($content == 'africa'){
            $multi_tlds = $titan->getOption('wdc_africa');
        }
        /* End - This is actual code (Pradeep)*/

        $ext_message = $titan->getOption( 'ext_message' );
        $additional_button_name = $titan->getOption( 'additional_button_name' );
        $additional_button_link = $titan->getOption( 'additional_button_link' );
        $custom_found_result_texts = $titan->getOption( 'custom_found_result_text' );
        if($custom_found_result_texts == '') $custom_found_result_texts = __('Congratulations! {domain} is available!', 'wdc');
        $custom_not_found_result_texts = $titan->getOption( 'custom_not_found_result_text' );
        if($custom_not_found_result_texts == '') $custom_not_found_result_texts = __('Sorry! {domain} is already taken!', 'wdc');
        if($ext_message == '') $ext_message = __('Sorry, we currently do not handle that particular tld.', 'wdc');

    if(isset($_POST['domain']))
    {
        if($integration == 'woocommerce' OR $integration == 'custom'){

            if($_POST['item_id'] != ''){
            $additional_button_link = $_POST['item_id'];
            }

        }
        $domain = str_replace(array('www.', 'http://'), NULL, $_POST['domain']);
        if (strpos($domain,'.') == false) {

   /*start - code (pradeep)*/
            if($multi_tlds == ''){
                $multi_tlds = array('com');
            }else{
                $multi_tlds = explode(',', $multi_tlds);
            }

        }else{
            list($sp, $split) = explode('.', $domain,2);
            $multi_tlds = array($split);
        }
    /*End - code (pradeep)*/

        if (function_exists('idn_to_ascii')) {
            $punny_domain = idn_to_ascii($domain);
        }else{
            $punny_domain = $domain;
            $punny_domain = preg_replace("/[^-a-zA-Z0-9.]+/", "", $punny_domain);
            $domain = $punny_domain;
        }
        $punny_domain = preg_replace("/[^-a-zA-Z0-9.]+/", "", $punny_domain);
        if(strlen($punny_domain) > 0)
        {

            include ('lib/DomainAvailability.php');
            $Domains = new DomainAvailability();
            list($dom, $ext) = explode('.', $punny_domain, 2);

            foreach($multi_tlds as $ex)
            {
            $domain = $dom.'.'.$ex;
            if($extensions != ''){
            $tlds = explode(',', $extensions);
            if (!in_array($ex, $tlds)) {
                $result = array('status'=>2,
                                'domain'=>$domain,
                                'text'=>    '

                                             '.$ext_message.'

                                            ');
                echo $result['text'];
                wp_die();
            }
            }

            $available = json_decode($Domains->is_available($domain));
            $custom_found_result_text = str_replace( '{domain}', $domain, $custom_found_result_texts );
            if($whois > 1) {
                    $whois_link = "<button id='whois' class='btn btn-danger btn-xs pull-right whois-btn'>WHOIS</button>";
                }else{
                    $whois_link = '';
                }

            if($integration == 'whmcs'){
    $check_ex = explode('.',$ex);

    if(count($check_ex) == 2){
        $ex_name = $check_ex[0]."_".$check_ex[1];
    }else{
        $ex_name = $check_ex[0];
    }
                $additional_button = "<button class='btn btn-success btn-xs pull-right order-btn'>$additional_button_name</button>";
            }elseif($integration == 'woocommerce'){
                //$additional_button = "$additional_button_name";
                $additional_button = "Ask for";
                }elseif($integration == 'custom'){
                if(!$additional_button_name == '' AND !$additional_button_link == ''){
                    $additional_button_link = str_replace( '{domain}', $domain, $additional_button_link );
                    $additional_button = "$additional_button_name";
                }else{
                    $additional_button = '';
                }
            }else{
                $additional_button = '';
            }

            $custom_not_found_result_text = str_replace( '{domain}', $domain, $custom_not_found_result_texts );
            $whmcs = "
                    <form method='post' name='whmcs_$dom_$ex_name' id='whmcs' action='$additional_button_link/cart.php?a=add&domain=register'>
                    <input type='hidden' name='domains[]' value='$domain' >
                    <input type='hidden' name='domainsregperiod[$domain]' value='1'>
                    </form>";
            if ($available->status == 1) {
                    $result = array('status'=>1,
                                    'domain'=>$domain,
                                    'text'=>    '

                                                 '.$custom_found_result_text.'

'.$additional_button.' '.$whmcs.'

                                                ');
                    echo $result['text'];

            } elseif($available->status == 0) {
                    $result = array('status'=>0,
                                    'domain'=>$domain,
                                    'text'=>    '

                                                 '.$custom_not_found_result_text.'

'.$whois_link.'

                                                ');
                    echo $result['text'];
            }elseif ($available->status == 2) {
                    $result = array('status'=>2,
                                    'domain'=>$domain,
                                    'text'=>    '

                                                 WHOIS server not found for that TLD

                                                ');
                    echo $result['text'];

            }
        }
        }
        else
        {
            echo 'Please enter the domain name';
        }
    }
    wp_die();
    }

    add_action('wp_ajax_wdc_display','wdc_display_func');
    add_action('wp_ajax_nopriv_wdc_display','wdc_display_func');

    function wdc_display_dashboard(){
        echo do_shortcode('[wpdomainchecker]');
    }

    function wdc_add_dashboard_widgets() {

        wp_add_dashboard_widget(
                     'wdc_dashboard_widget',
                     'WP Domain Checker',
                     'wdc_display_dashboard'

            );
    }
    add_action( 'wp_dashboard_setup', 'wdc_add_dashboard_widgets' );

    function wdc_whois_shortcode(){

        if(isset($_GET['domain'])){

            echo '
Whois record for '.htmlspecialchars($_GET['domain']).'
';

            require("lib/whoisClass.php");
            $whois=new Whois;
            echo "
";
            if (function_exists('idn_to_ascii')) {
            echo $whois->whoislookup(idn_to_ascii($_GET['domain']));
            }else{
            echo $whois->whoislookup($_GET['domain']);
            }
            echo "
";
        }

    }
    add_shortcode( 'wpdomainwhois', 'wdc_whois_shortcode' );

    function wdc_display_shortcode($atts){

        $titan = TitanFramework::getInstance( 'wdc-options' );
        $item_id = $titan->getOption( 'additional_button_link' );
        $image = $titan->getOption( 'loading_image' );
        $recaptcha_enable = $titan->getOption( 'recaptcha' );
        $placeholder = $titan->getOption( 'input_placeholder' );
        $image = wp_get_attachment_image_src($image);
        if($image == '') {
            $image = plugins_url( '/images/load.gif', __FILE__ );
        }else{
            $image = $image[0];
        }
            $atts = shortcode_atts(
            array(
                'width' => '900',
                'button' => 'Check',
                'recaptcha' => 'no',
                'item_id' => $item_id,
                'tld' => ''
            ), $atts );
        if($atts['recaptcha'] == 'yes'){
            $show_recaptcha = "

";
        }else{
            $show_recaptcha = "";
        }
    $content = "

            <form method='post' action='./' id='form' class='pure-form'>
                <input type='hidden' name='item_id' value='{$atts['item_id']}'>
                <input type='hidden' name='tld' value='{$atts['tld']}'>

                    <input type='text' class='form-control' autocomplete='off' id='Search' name='domain' placeholder='$placeholder'>

                        <button type='submit' id='Submit' class='btn btn-default btn-info'>{$atts["button"]}</button>

            {$show_recaptcha}

    <fieldset>
    <input type='radio' name='asia' value='asia'> Asia

    <input type='radio' name='europe' value='europe'> Europe

    </fieldset>

    <fieldset>
      <input type='radio' name='africa' value='africa'> Africa

    </fieldset>

    </form>

";

    return $content;

    }

?>

Remaing code (continue from above code)... If you want you can go through...I hope you may find solution:

     <?php

    add_shortcode( 'wpdomainchecker', 'wdc_display_shortcode' );

    /* Woocommerce Function */
    function custom_add_to_cart_redirect() {
        if($_REQUEST['domain']){
        return WC()->cart->get_cart_url();
        }
    }
    add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect' );

    function save_name_on_wdc_field( $cart_item_key, $product_id = null, $quantity= null, $variation_id= null, $variation= null ) {

        WC()->session->set( $cart_item_key.'_domain', $_GET['domain'] );
        WC()->session->set( $cart_item_key.'_price', $_GET['price'] );

    }
    add_action( 'woocommerce_add_to_cart', 'save_name_on_wdc_field', 1, 5 );

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price');

    function add_custom_price( $cart_object ) {
        $titan = TitanFramework::getInstance( 'wdc-options' );

        global $woocommerce;
        $tld = array();
        $extensions = $titan->getOption( 'wdc_custom_price' );
        $extensions = preg_replace('/\s+/', '', $extensions);
        $tlds = explode(',', $extensions);

        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
        if(WC()->session->get( $cart_item_key.'_domain')){
        $domain = WC()->session->get( $cart_item_key.'_domain');
        list($domain, $ext) = explode('.', $domain, 2);

         foreach ($tlds as $key => $value) {
            $tld = explode('|', $value);
            if($ext == $tld[0]){
                $price = $tld[1];
                $cart_item['data']->price = $price;
            }
        }
        }
        }
     }

    function render_meta_on_cart_item( $title = null, $cart_item = null, $cart_item_key = null ) {
        global $product_id;
        if( $cart_item_key && is_cart() ) {

            if(WC()->session->get( $cart_item_key.'_domain')){
            echo $title. '

Domain :

'. WC()->session->get( $cart_item_key.'_domain') .'

';
            }else{
                echo $title;
            }
        }else {
            echo $title;
        }
    }
    add_filter( 'woocommerce_cart_item_name', 'render_meta_on_cart_item', 1, 3 );

    function render_meta_on_checkout_order_review_item( $quantity = null, $cart_item = null, $cart_item_key = null ) {
        if( $cart_item_key ) {
            if(WC()->session->get( $cart_item_key.'_domain')){
            echo $quantity. '

Domain :

'. WC()->session->get( $cart_item_key.'_domain') .'

';
            }else{
                echo $quantity;
            }
        }
    }
    add_filter( 'woocommerce_checkout_cart_item_quantity', 'render_meta_on_checkout_order_review_item', 1, 3 );

    function wdc_order_meta_handler( $item_id, $values, $cart_item_key ) {
        if(WC()->session->get( $cart_item_key.'_domain')){
        wc_add_order_item_meta( $item_id, "Domain", WC()->session->get( $cart_item_key.'_domain') );
        }

    }
    add_action( 'woocommerce_add_order_item_meta', 'wdc_order_meta_handler', 1, 3 );

    function wdc_force_individual_cart_items($cart_item_data, $product_id)
    {
        $titan = TitanFramework::getInstance( 'wdc-options' );
        $id = $titan->getOption( 'additional_button_link' );
        $unique_cart_item_key = md5( microtime().rand() );
        $cart_item_data['unique_key'] = $unique_cart_item_key;

        return $cart_item_data;

    }
    add_filter( 'woocommerce_add_cart_item_data','wdc_force_individual_cart_items', 10, 2 );

    add_filter('woocommerce_loop_add_to_cart_link','wdc_replace_add_to_cart');
    function wdc_replace_add_to_cart() {
    global $product;
     $link = sprintf( '%s',
            esc_url( $product->add_to_cart_url() ),
            esc_attr( $product->id ),
            esc_attr( $product->get_sku() ),
            esc_attr( isset( $quantity ) ? $quantity : 1 ),
            esc_attr( $product->product_type ),
            esc_html( $product->add_to_cart_text() )
        );
      $links = sprintf( '%s',
            esc_url( get_permalink($product->id) ),
            esc_attr( $product->id ),
            esc_attr( $product->get_sku() ),
            esc_attr( isset( $quantity ) ? $quantity : 1 ),
            esc_attr( $product->product_type ),
            esc_html( $product->add_to_cart_text() )
        );

       if(get_post_meta( $product->id, 'wdc_hide_addtocart', true ) == 'yes'){
        return $links;
       }else{
        return $link;
       }
    }

    function wdc_remove_cart_button(){
    $product_id = get_the_ID();
        if(get_post_meta( $product_id, 'wdc_hide_addtocart', true ) == 'yes'){
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
        }
    }
    add_action('wp','wdc_remove_cart_button');

    function wdc_woo_add_custom_general_fields() {

      global $woocommerce, $post;

      echo '
';

        woocommerce_wp_checkbox(
        array(
        'id'            => 'wdc_hide_addtocart',
        'wrapper_class' => 'wdc_item_edit_class',
        'label'         => __('WDC?', 'wdc' ),
        'description'   => __( 'Check me if you want to hide Add to Cart button on single product page.', 'wdc' )
        )
    );

      echo '
';

    }

    function wdc_woo_add_custom_general_fields_save( $post_id ){
        $woocommerce_checkbox = isset( $_POST['wdc_hide_addtocart'] ) ? 'yes' : 'no';
        update_post_meta( $post_id, 'wdc_hide_addtocart', $woocommerce_checkbox );
    }

    // Display Fields
    add_action( 'woocommerce_product_options_general_product_data', 'wdc_woo_add_custom_general_fields' );

    // Save Fields
    add_action( 'woocommerce_process_product_meta', 'wdc_woo_add_custom_general_fields_save' );
    /* Woocommerce End Function */

    function wdc_recaptcha_func() {
        check_ajax_referer( 'wdc_nonce', 'security' );

        if(isset($_POST['response']))
        {
            $titan = TitanFramework::getInstance( 'wdc-options' );
            $captcha = $_POST['response'];
            $secret_key = $titan->getOption( 'recaptcha_secretkey' );
            $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret_key."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
            echo $response;

        }
    wp_die();
    }
    add_action('wp_ajax_wdc_recaptcha','wdc_recaptcha_func');
    add_action('wp_ajax_nopriv_wdc_recaptcha','wdc_recaptcha_func');

    function wdc_recaptcha_dis_func() {
        check_ajax_referer( 'wdc_nonce', 'security' );

            echo json_encode(array('success' => 'true'));

    wp_die();
    }
    add_action('wp_ajax_wdc_recaptcha_dis','wdc_recaptcha_dis_func');
    add_action('wp_ajax_nopriv_wdc_recaptcha_dis','wdc_recaptcha_dis_func');

    function wdc_options() {
        $titan = TitanFramework::getInstance( 'wdc-options' );
        global $panel;

        $panel = $titan->createAdminPanel( array(
        'name' => 'WP Domain Checker',
        'parent' => 'options-general.php',
        ) );

        $generaltab = $panel->createTab( array(
        'name' => 'General',
        ) );

        $generaltab->createOption( array(
        'name' => 'Custom Available Result Text',
        'id' => 'custom_found_result_text',
        'type' => 'textarea',
        'desc' => 'This is custom available result text. Use {domain} to replace domain name.'
        ) );

        $generaltab->createOption( array(
        'name' => 'Custom Not Available Result Text',
        'id' => 'custom_not_found_result_text',
        'type' => 'textarea',
        'desc' => 'This is custom not available result text. Use template tag {domain} to replace domain name.'
        ) );

        $generaltab->createOption( array(
        'name' => 'Input Placeholder',
        'id' => 'input_placeholder',
        'type' => 'text',
        'desc' => 'Placeholder for domain input.'
        ) );

        $generaltab->createOption( array(
        'name' => 'Loading Image',
        'id' => 'loading_image',
        'type' => 'upload',
        'desc' => 'Upload your image'
        ) );
        $pages=get_pages( array('post_type' => 'page','post_status' => 'publish') );
        foreach ($pages as $page) {
            $whois_page['disable'] = 'Disable';
            $whois_page[$page->ID] = $page->post_title;
        }
        $generaltab->createOption( array(
        'name' => 'Whois Page',
        'id' => 'whois_option',
        'type' => 'select',
        'options' => $whois_page,
        'desc' => 'Enable or disable whois link if domain not available',
        'default' => 'disable',
        ) );

        $generaltab->createOption( array(
        'name' => 'Integration With',
        'id' => 'integration',
        'type' => 'select',
        'options' => array(
            'disable' => 'Disable',
            'whmcs' => 'WHMCS',
            'woocommerce' => 'Woocommerce',
            'custom' => 'Custom Link',
        ),
        'desc' => 'Enable or disable integration.',
        'default' => 'disable',
        ) );

        $generaltab->createOption( array(
        'name' => 'Integration Button Text',
        'id' => 'additional_button_name',
        'type' => 'text',
        'desc' => 'Integration Button Text. (e.g.: "ORDER NOW")'
        ) );

        $generaltab->createOption( array(
        'name' => 'Integration Button Link',
        'id' => 'additional_button_link',
        'type' => 'text',
        'desc' => 'Integration button link. (e.g. for WHMCS: "http://billing.host.com"). Documentation

                    For custom link, you can use template tag {domain} to include domain in the link.
e.g: http://godaddy.com/?aff=12345&domain={domain}'
        ) );

        $generaltab->createOption( array(
        'name' => 'Supported TLD Extensions',
        'id' => 'extensions',
        'type' => 'textarea',
        'desc' => 'Allow only specific extensions to check. separate by comma for each extension. (e.g: com,net,org,co.uk,co.id)
Leave it blank to allow all extensions.'
        ) );

        $generaltab->createOption( array(
        'name' => 'Not Supported TLD Extensions Messages',
        'id' => 'ext_message',
        'type' => 'text',
        'desc' => 'Not Supported TLD Extensions Messages. (e.g.: "Sorry, we currently do not handle that particular tld.")'
        ) );

        $generaltab->createOption( array(
        'name' => 'WooCommerce Custom Price',
        'id' => 'wdc_custom_price',
        'type' => 'textarea',
        'desc' => 'Allow custom price for specific tld. (e.g: com|9,net|10,org|11,co.uk|12,co.id|13)'
        ) );

        $generaltab->createOption( array(
        'name' => 'Multiple TLDs Check',
        'id' => 'wdc_multi_tlds',
        'type' => 'textarea',
        'desc' => 'Multiple TLDs check if user not define tld on the domain. (e.g: com,net,org,info)'
        ) );

 /*Start- code (Pradeep)*/

        $generaltab->createOption( array(
        'name' => 'Asia TLDs Check',
        'id' => 'wdc_asia',
        'type' => 'textarea',
        'desc' => 'Asia TLDs check if user not define tld on the domain. (e.g: in,ch,rocks,club)'
        ) );

        $generaltab->createOption( array(
        'name' => 'Europe TLDs Check',
        'id' => 'wdc_europe',
        'type' => 'textarea',
        'desc' => 'Europe TLDs check if user not define tld on the domain. (e.g: fr,it,pro)'
        ) );

        $generaltab->createOption( array(
        'name' => 'Africa TLDs Check',
        'id' => 'wdc_africa',
        'type' => 'textarea',
        'desc' => 'Africa TLDs check if user not define tld on the domain. (e.g: link,af,host,me)'
        ) );

         /*End- code (Pradeep)*/

        $recaptchaTab = $panel->createTab( array(
        'name' => 'reCaptcha',
        ) );

        $panel->createOption( array(
            'type' => 'save'
        ) );

    }
    add_action( 'tf_create_options', 'wdc_options' );

    class wdc_widget extends WP_Widget {
        function __construct() {
            parent::__construct(false, $name = __('WP Domain Checker Widget'));
        }
        function form($instance) {
                if (isset($instance['title'])) {
                    $title = $instance['title'];
                    $width = $instance['width'];
                    $button = $instance['button'];
                    $recaptcha = $instance['recaptcha'];
                }else{
                    $title = "Domain Availability Check";
                    $width = "";
                    $button = "";
                    $recaptcha = "no";
                }
        ?>

        <?php
        }

    }

    function register_wdc_widget()
    {
        register_widget( 'wdc_widget' );
    }
    add_action( 'widgets_init', 'register_wdc_widget');

        ?>

Body:
this is declaring a variable

$content = 'europe'

should be ==

$content='asia';
function test(){

    if($content == 'europe'){
        $multi_tlds = $titan->getOption('wdc_europe');
    } elseif($content == 'asia'){
        $multi_tlds = $titan->getOption('wdc_asia');
    } elseif($content == 'africa'){
        $multi_tlds = $titan->getOption('wdc_africa');
    }

}

<input type='radio' name='asia' value='asia'> Asia<br>
    <input type='radio' name='europe' value='europe'> Europe<br>
    </fieldset>
    </div>
    <div class='col-sm-3'>
    <fieldset>
      <input type='radio' name='africa' value='africa'> Africa<br>

this piece of code is wrong they should all have the same name

name='myregionchoice'

then you process it as post

$regionchoice=$_POST['item_id'];

then in the if statements

if($mygreionchoice == 'europe'){
        $multi_tlds = $titan->getOption('wdc_europe');
    } elseif($myregionchoice == 'asia'){
        $multi_tlds = $titan->getOption('wdc_asia');
    } elseif($myregionchoice == 'africa'){
        $multi_tlds = $titan->getOption('wdc_africa');
    }

}

to use a radio button choosing options  the name has to be the same for all
check the code below for the format of how to do this and where you should process data before and after the page reloads and check the function format and how i get the output from the function and how the if statement must look like you can test this code it works

<html>
    <head>
    </head>
    <body>
        <form name="anyname" action="" method="post">
            <input type="radio" name="choice" value="asia"/>asia
            <input type="radio" name="choice" value="africa"/>africa
            <input type="submit" name="submit" value="my radio choice">
        </form>
<?php

    function choose(){
        //declare it is a global variable from outside the function
        global $choice;

        if ($choice =='africa') {
        $test='you choose africa';
        }
        elseif ($choice =='asia'){
        $test='you choose asia';
        }
        //returning the output of the function
        return $test;
        }

    //here you proccess the data after the page reloads

    if (!empty($_POST['choice'])){
        $choice=$_POST["choice"];
        //running the function
        choose();
        //getting the output from the function
        $test=choose();
        echo 'this is the data after the page reloads :',$test;
        }

    //here you process the data before the page reloads
    if ((isset($_POST["submit"])) && ($_POST["submit"]!="")){
        $choice=$_POST["choice"];
        //running the function
        choose();
        //getting the output from the function
        $test=choose();

        }
?>

    <body>
</html>


答: == is for comparison and = equates the variable with the value. You need to compare inside if instead of equating.

Title: what is worng with that code? Only ($content = 'europe') is executing successfully... Remaining conditions are not executing


答:
$content = 'europe' is an assignment sentence, which always returns true and therefore the code unther that condition is always executed.

I think what you are looking for is a comparison statement, that woul be $content == 'europe' (and the same of all the other values).

Also, you should then pass the $content variable to your function, otherwise is undefined:

```<code>function test($content) {...}
</code>```

Body:
$content = 'europe' is an assignment sentence, which always returns true and therefore the code unther that condition is always executed.

I think what you are looking for is a comparison statement, that woul be $content == 'europe' (and the same of all the other values).

Also, you should then pass the $content variable to your function, otherwise is undefined:

function test($content) {...}


问:
How to trigger onchange event via Browser Javascript Console
It's HTML Code:

```<code><tr>
<td class="caption">Amount</td>
<td><input type="text" name="Amount" value="" size="30" id="Amount"
onkeypress="return isNumberKey(event);" onchange="this.value =
changeAmount(this.value);" maxlength="18"></td>
</tr>
<tr>
<td>Amount Word</td>
<td><textarea name="AmountWord" cols="" rows="" wrap="soft"
class="text_sotien" id="AmountWord" readonly=""></textarea></td>
</tr>
</code>```

My website will have 2 field as above. changeAmount() function is a script on my server. Now, I wanna create a Javascript script for my customer. When they pasted it on your browser console (Ctrl + Shilf + I on Chrome or F12 on Firefog), it will fill new value of Amount field then call function changeAmount() to change value of AmountWord. It's my code but it only can change value of Amount field, not call changeAmount() function to change value of AmountWord field :(

```<code>javascript:document.getElementById("Amount").value='111000';document.getElementById("AmountWord").focus; document.getElementById("AmountWord").click();
</code>```

Please help me

答:
With modern browser methods:

```<code>const input = document.querySelector("input[name='Amount']")
input.dispatchEvent(new CustomEvent("change"))
</code>```

Better to just avoid inline JS calls like that though.

Body:
It's HTML Code:

Amount
<input type="text" name="Amount" value="" size="30" id="Amount"
onkeypress="return isNumberKey(event);" onchange="this.value =
changeAmount(this.value);" maxlength="18">

Amount Word
<textarea name="AmountWord" cols="" rows="" wrap="soft"
class="text_sotien" id="AmountWord" readonly=""></textarea>

My website will have 2 field as above. changeAmount() function is a script on my server. Now, I wanna create a Javascript script for my customer. When they pasted it on your browser console (Ctrl + Shilf + I on Chrome or F12 on Firefog), it will fill new value of Amount field then call function changeAmount() to change value of AmountWord. It's my code but it only can change value of Amount field, not call changeAmount() function to change value of AmountWord field :(

javascript:document.getElementById("Amount").value='111000';document.getElementById("AmountWord").focus; document.getElementById("AmountWord").click();

Please help me

Body:
With modern browser methods:

const input = document.querySelector("input[name='Amount']")
input.dispatchEvent(new CustomEvent("change"))

Better to just avoid inline JS calls like that though.


问:
Can't compile runnable that calls itself?
I'm trying to make a Runnable that calls itself:

```<code>class A {
  public void f() {
    final Runnable r = new Runnable() {
      public void run() {
        // do stuff, return if it worked.
        r.run(); // otherwise try again
      }
    };
  }
}
</code>```

It gets this error:

```<code>$ javac A.java
A.java:6: error: variable r might not have been initialized
        r.run(); // otherwise try again
        ^
1 error
</code>```

Why? Is there something special in the standard library definition of Runnable which removes the guarantee that the interface implementation is fully defined before it is used (perhaps for example, it has some code that gets run whenever you make an implementation of it)?

答:
You could save this pointer and call Run method in a new Runnable :</p>

```<code>    Runnable r = new Runnable() {
        @Override public void run() {
            // if condition met and need to run more
            final Runnable that = this;
            executor.execute(new Runnable() { @Override public void run() { that.run(); } });
        }
    };
</code>```

Body:
I'm trying to make a Runnable that calls itself:

class A {
  public void f() {
    final Runnable r = new Runnable() {
      public void run() {
        // do stuff, return if it worked.
        r.run(); // otherwise try again
      }
    };
  }
}

It gets this error:

$ javac A.java
A.java:6: error: variable r might not have been initialized
        r.run(); // otherwise try again
        ^
1 error

Why? Is there something special in the standard library definition of Runnable which removes the guarantee that the interface implementation is fully defined before it is used (perhaps for example, it has some code that gets run whenever you make an implementation of it)?

Body:
You could save this pointer and call Run method in a new Runnable :

    Runnable r = new Runnable() {
        @Override public void run() {
            // if condition met and need to run more
            final Runnable that = this;
            executor.execute(new Runnable() { @Override public void run() { that.run(); } });
        }
    };


问:
how to setup the assets folder in CodeIgniter like in Laravel
like the public folder given by laravel default i tried to create something like that for easy make up of my css, js, picture and so on. I tried configuring it like this. In my application/helpers/utility_helpers.php

```<code>    <?php
    function asset_url()
    {
  return base_url().'assets/';
    }
     ?>
</code>```

I have my assests folder along with application, system, user_guide etc.
i confugured the autoload function of application/config as :

```<code>    $autoload['helper'] = array('url','utility');
</code>```

when i hit any url in browser now, it says

```<code>    An Error Was Encountered

    Unable to load the requested file: helpers/utility_helper.php
</code>```

how can i make it and can you explain me if i need to specify root for that helpers also.And if not can i simply access the assets like this:

```<code>    <img src="assets/base_components/build/banner.png">
</code>```

in my view

答:
Your code looks ok, it should work.
According to the error

```<code>Unable to load the requested file: helpers/utility_helper.php
</code>```

there is no utility_helper.php file in application/helpers/ folder. Check if the file exists in that folder or if you don't have a typo in the file name.

Body:
like the public folder given by laravel default i tried to create something like that for easy make up of my css, js, picture and so on. I tried configuring it like this. In my application/helpers/utility_helpers.php

    <?php
    function asset_url()
    {
  return base_url().'assets/';
    }
     ?>

I have my assests folder along with application, system, user_guide etc.
i confugured the autoload function of application/config as :

    $autoload['helper'] = array('url','utility');

when i hit any url in browser now, it says

    An Error Was Encountered

    Unable to load the requested file: helpers/utility_helper.php

how can i make it and can you explain me if i need to specify root for that helpers also.And if not can i simply access the assets like this:

in my view

Body:
Your code looks ok, it should work.
According to the error

Unable to load the requested file: helpers/utility_helper.php

there is no utility_helper.php file in application/helpers/ folder. Check if the file exists in that folder or if you don't have a typo in the file name.


问:
Specify the AWS credentials in hadoop
I want to specify the AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID at run-time.

I already tried using

```<code>hadoop -Dfs.s3a.access.key=${AWS_ACESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY} fs -ls s3a://my_bucket/
</code>```

and

```<code>export HADOOP_CLIENT_OPTS="-Dfs.s3a.access.key=${AWS_ACCESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY}"
</code>```

and

```<code>export HADOOP_OPTS="-Dfs.s3a.access.key=${AWS_ACCESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY}"
</code>```

In the last two examples, I tried to run with:

```<code>hadoop fs -ls s3a://my-bucket/
</code>```

In all the cases I got:

```<code>-ls: Fatal internal error
com.amazonaws.AmazonClientException: Unable to load AWS credentials from any provider in the chain
        at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:117)
        at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3521)
        at com.amazonaws.services.s3.AmazonS3Client.headBucket(AmazonS3Client.java:1031)
        at com.amazonaws.services.s3.AmazonS3Client.doesBucketExist(AmazonS3Client.java:994)
        at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:297)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94)
        at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373)
        at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
        at org.apache.hadoop.fs.shell.PathData.expandAsGlob(PathData.java:325)
        at org.apache.hadoop.fs.shell.Command.expandArgument(Command.java:235)
        at org.apache.hadoop.fs.shell.Command.expandArguments(Command.java:218)
        at org.apache.hadoop.fs.shell.Command.processRawArguments(Command.java:201)
        at org.apache.hadoop.fs.shell.Command.run(Command.java:165)
        at org.apache.hadoop.fs.FsShell.run(FsShell.java:287)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
        at org.apache.hadoop.fs.FsShell.main(FsShell.java:340)
</code>```

What am doing wrong?

答:
I think part of the problem is that, confusingly, unlike the JVM -D opts, the Hadoop -D command expects a space between the -D and the key, e.g:

```<code>hadoop fs -ls -D fs.s3a.access.key=AAIIED s3a://landsat-pds/
</code>```

I would still avoid doing that on the command line though, as anyone who can do a ps command can see your secrets.

Generally we stick them into core-site.xml when running outside EC2; in EC2 it's handled magically

Title: Specify the AWS credentials in hadoop

Body:
I want to specify the AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID at run-time.

I already tried using

hadoop -Dfs.s3a.access.key=${AWS_ACESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY} fs -ls s3a://my_bucket/

and

export HADOOP_CLIENT_OPTS="-Dfs.s3a.access.key=${AWS_ACCESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY}"

and

export HADOOP_OPTS="-Dfs.s3a.access.key=${AWS_ACCESS_KEY_ID} -Dfs.s3a.secret.key=${AWS_SECRET_ACCESS_KEY}"

In the last two examples, I tried to run with:

hadoop fs -ls s3a://my-bucket/

In all the cases I got:

-ls: Fatal internal error
com.amazonaws.AmazonClientException: Unable to load AWS credentials from any provider in the chain
        at com.amazonaws.auth.AWSCredentialsProviderChain.getCredentials(AWSCredentialsProviderChain.java:117)
        at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3521)
        at com.amazonaws.services.s3.AmazonS3Client.headBucket(AmazonS3Client.java:1031)
        at com.amazonaws.services.s3.AmazonS3Client.doesBucketExist(AmazonS3Client.java:994)
        at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:297)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94)
        at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373)
        at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
        at org.apache.hadoop.fs.shell.PathData.expandAsGlob(PathData.java:325)
        at org.apache.hadoop.fs.shell.Command.expandArgument(Command.java:235)
        at org.apache.hadoop.fs.shell.Command.expandArguments(Command.java:218)
        at org.apache.hadoop.fs.shell.Command.processRawArguments(Command.java:201)
        at org.apache.hadoop.fs.shell.Command.run(Command.java:165)
        at org.apache.hadoop.fs.FsShell.run(FsShell.java:287)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
        at org.apache.hadoop.fs.FsShell.main(FsShell.java:340)

What am doing wrong?

Body:
I think part of the problem is that, confusingly, unlike the JVM -D opts, the Hadoop -D command expects a space between the -D and the key, e.g:

hadoop fs -ls -D fs.s3a.access.key=AAIIED s3a://landsat-pds/

I would still avoid doing that on the command line though, as anyone who can do a ps command can see your secrets.

Generally we stick them into core-site.xml when running outside EC2; in EC2 it's handled magically


问:
How to change the primary key value in sql server?
I am using SQL server 2014.

In my table, I set primary key for the column.The primary key value starts from 1. I want to change it to start from 0. How can I achieve this?

答:
If the table is empty, the easiest thing to do would be to drop the table and recreate it with an identity seed of 0 like GuidoG did.  If the table has data, changing the primary key to a 0 (like Intern87 mentions) would be a bad idea because after it inserts a row with a key of 0 the next key would be 1 which would probably already be in the table and therefore would cause further inserts to fail with a primary key duplication error.

So if you have existing data but you MUST have data with a key of 0, I would probably just do an identity insert with row 0.  Do this with the following

```<code>SET IDENTITY_INSERT mytable ON;

INSERT INTO mytable (id, col1, col2, etc..)
VALUES (0, 'col1data','col2data', etc..);

SET IDENTITY_INSERT mytable OFF;
</code>```

just make sure to run all of that at once because once you turn identity insert on then other inserts may fail till you turn it off.

Body:
If the table is empty, the easiest thing to do would be to drop the table and recreate it with an identity seed of 0 like GuidoG did.  If the table has data, changing the primary key to a 0 (like Intern87 mentions) would be a bad idea because after it inserts a row with a key of 0 the next key would be 1 which would probably already be in the table and therefore would cause further inserts to fail with a primary key duplication error.

So if you have existing data but you MUST have data with a key of 0, I would probably just do an identity insert with row 0.  Do this with the following

SET IDENTITY_INSERT mytable ON;

INSERT INTO mytable (id, col1, col2, etc..)
VALUES (0, 'col1data','col2data', etc..);

SET IDENTITY_INSERT mytable OFF;

just make sure to run all of that at once because once you turn identity insert on then other inserts may fail till you turn it off.


问:
.NET Random Class picking always 0 when range is 0 or 1
I am writing a random question generator. I would like to pick one question from each section.

Random class with DateTime.Now.Milliseconds as seed value generates random numbers, if the range is greater than 2(0,2/2+). But, If I give a min of 0 and a max of 1 in the range, it always returns me 0.

Am I using it wrongly.

Please suggest if there are any other alternatives.

Thanks,
Mahesh

答:
MSDN: Random.Next Method (Int32) Returns a nonnegative random number less than the specified maximum.
Use this.</p>

```<code>Random random = new Random();

for (int i = 0; i < 10; i++)
{
  Console.WriteLine("Genereted value:{0}", random.Next(2));
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
MSDN: Random.Next Method (Int32) Returns a nonnegative random number less than the specified maximum.
Use this.

Random random = new Random();

for (int i = 0; i < 10; i++)
{
  Console.WriteLine("Genereted value:{0}", random.Next(2));
}


问:
express-jwt always sending 401 unauthorized while verifying user
I have this middle-ware function which checks if the user is logged in or not, since I have web application and android platform as well therefore I am using tokens for the android and for web I am using session which is by default manager by passport.

In my function I am checking If I have a Authorization header, I know it's my android platform and therefore verify user by verifying jwt token, but It is always sending me 401 unauthorized and not setting the req.user.

Here is the middle-ware function, if someone can please point out my mistake where I am going wrong in my logic.

```<code>var jwt_auth = require('express-jwt')

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    if (req.get("Authorization")) {
        jwt_auth({secret: 'somesecret'});
        if (req.user) {
            return next();
        }
        res.send(200, "Unauthorized access");
    }
    else {
        // if user is authenticated in the session, carry on
        if (req.isAuthenticated())
            return next();

        // if they aren't redirect them to the home page
        res.redirect('/');
    }
}
</code>```

答:
That's because jwt_auth is an async action and your res.send(200, "Unauthorized access") never wait for jwt_auth to complete.

You should take a look at express-jwt's example.

The basic one is

```<code>var jwt = require('express-jwt');

app.get('/protected',
    jwt({secret: 'shhhhhhared-secret'}),
    function(req, res) {
        if (!req.user.admin) return   res.sendStatus(401);
       res.sendStatus(200);
});
</code>```

if you want to pass a custom function to extract token from request, use the getToken option, the following example is taken from express jwt's README, you can modify the function in your needs.

```<code>app.use(jwt({
  secret: 'hello world !',
  credentialsRequired: false,
  getToken: function fromHeaderOrQuerystring (req) {
  if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
        return req.headers.authorization.split(' ')[1];
  } else if (req.query && req.query.token) {
      return req.query.token;
  }
    return null;
  }
}));
</code>```

Body:
I have this middle-ware function which checks if the user is logged in or not, since I have web application and android platform as well therefore I am using tokens for the android and for web I am using session which is by default manager by passport.

In my function I am checking If I have a Authorization header, I know it's my android platform and therefore verify user by verifying jwt token, but It is always sending me 401 unauthorized and not setting the req.user.

Here is the middle-ware function, if someone can please point out my mistake where I am going wrong in my logic.

var jwt_auth = require('express-jwt')

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    if (req.get("Authorization")) {
        jwt_auth({secret: 'somesecret'});
        if (req.user) {
            return next();
        }
        res.send(200, "Unauthorized access");
    }
    else {
        // if user is authenticated in the session, carry on
        if (req.isAuthenticated())
            return next();

        // if they aren't redirect them to the home page
        res.redirect('/');
    }
}

Body:
That's because jwt_auth is an async action and your res.send(200, "Unauthorized access") never wait for jwt_auth to complete.

You should take a look at express-jwt's example.

The basic one is

var jwt = require('express-jwt');

app.get('/protected',
    jwt({secret: 'shhhhhhared-secret'}),
    function(req, res) {
        if (!req.user.admin) return   res.sendStatus(401);
       res.sendStatus(200);
});

if you want to pass a custom function to extract token from request, use the getToken option, the following example is taken from express jwt's README, you can modify the function in your needs.

app.use(jwt({
  secret: 'hello world !',
  credentialsRequired: false,
  getToken: function fromHeaderOrQuerystring (req) {
  if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
        return req.headers.authorization.split(' ')[1];
  } else if (req.query && req.query.token) {
      return req.query.token;
  }
    return null;
  }
}));


问:
Websphere web plug-in to automatically propagate cluster node shutdown
Does the WebServer web server plug-in automatically propagate the new configuration due to a manual shutdown of a node in the application server cluster? I've been going through the documentation and it looks like the only way for the web server to act on this is by detecting the node state by itself.
Is there any workaround?</p>

答:
By default, the WAS Plug-in only detects that a JVM is down by failing to send it a request or failing to establish a new TCP connection.

If you use the "Intelligent Management for WebServers" features available in 8.5 and later, there is a control connection between the cell and the Plug-in that will proactively tell the Plugin that a server is down.

Backing up to the non-IM case, here's what happens during an unplanned shutdown of a JVM (from http://publib.boulder.ibm.com/httpserv/ihsdiag/plugin_questions.html#failover)

If an application server terminates unexpectedly, several things
unfold. This is largely WebSphere edition independent.

The application servers operating system closes all open sockets.

WebServer threads waiting for the response in the WAS Plug-in are notified of EOF or ECONNRESET.

If the error occurred on a new connection to the application server, it will be marked down in the current webserver process. This server will not be retried until a configurable interval expires (RetryInterval).

If the error occurred on a an existng connection to the application server, it will not be marked down.

Retryable requests that were in-flight are retried by the WAS Plug-in, as permitted.

If the backend servers use memory to memory session replication (ND only), the WLM component will tell the WAS Plug-in to use a specific replacement affinity server.

If the backend servers use any kind of session persistence, the failover is transparent. Session persistence is available in all websphere editions.

New requests, with or without affinity, are routed to remaining servers..

After the RetryInterval expires, the WAS plug-in will try to establish new connections to the server. If it remains down, failure will be relatively fast, and put the server back into the markd down state.


问:
CreateProcess weird behavior with files without extension
I have noticed this behavior:

There are 2 executable files in the current dir, named 'somefile' and 'somefile.abc'.

CreateProcessA(NULL, "somefile", ...) - fails with error code 2 (ERROR_FILE_NOT_FOUND)

CreateProcessA(NULL, "somefile.abc", ...) - works

CreateProcessA(NULL, ".\\somefile", ...) - works

CreateProcessA(NULL, ".\\somefile.abc", ...) - works

So, it looks like the ".\" is mandatory if and only if the file doesn't have an extension.
Is there a logic behind this behavior?

答:
From MSDN:

If the file name does not contain an extension, .exe is appended. Therefore, if the file name extension is .com, this parameter must include the .com extension. If the file name ends in a period (.) with no extension, or if the file name contains a path, .exe is not appended.

I don't know if the documented behavior should be called "weird".