问:
Creating A List of Possible String Combination

Possible Duplicate:

Generate list of all possible permutations of a string

I need to work on a small algorithm project where I need to be able to list and write to a text file the possible combination of a given set of characters based on a given limit.

For example, if I enter the characters "a", "b", and "c" and set the limit to 3 the possible output would be:

```<code>a
b
c
aa
bb
cc
ab
ac
ba
bc
ca
cb
...
    aaa
    bbb
    ccc
    ...
    ...
    abc
    acb
    bac
    bca
    cab
    cba
</code>```

Until all possible combinations have been devised.

Writing this to a text file is no problem with me. Having an algorithm that would write the combination is something that I am quite not good at.

Appreciate in .NET (C# or VB) codes.

Thanks.

PS

On a side note, I wonder how long it would take for an application to create a string combination of all possible keyboard characters and how big the file would get to be.

Updated:
I should also show character combination from n characters to the implied limit..

答:
You can enumerate all the permutations in a string using a recursive implementation. A quick but functional implementation might look like the following:

Edit: You changed the OP to include strings with length less than the input character set. The following code has been modified. It gives exactly the output in your question.

```<code>static void BuildPermutations(string input, char[] current, int index, int depth, List<string> perms)
{
    if (index == depth)
    {
        perms.Add(new string(current, 0, depth));
        return;
    }
    for (int n = 0; n < input.Length; ++n)
    {
        current[index] = input[n];
        BuildPermutations(input, current, index + 1, depth, perms);
    }
}

static void Main(string[] args)
{
    string input = "abc";
    char[] current = new char[input.Length];
    List<string> perms = new List<string>();
    for (int n = 1; n <= 3; ++n )
        BuildPermutations(input, current, 0, n, perms);
    foreach (string s in perms)
        System.Console.WriteLine(s.ToString());
}
</code>```

Body:
Possible Duplicate:

Generate list of all possible permutations of a string

I need to work on a small algorithm project where I need to be able to list and write to a text file the possible combination of a given set of characters based on a given limit.

For example, if I enter the characters "a", "b", and "c" and set the limit to 3 the possible output would be:

a
b
c
aa
bb
cc
ab
ac
ba
bc
ca
cb
...
    aaa
    bbb
    ccc
    ...
    ...
    abc
    acb
    bac
    bca
    cab
    cba

Until all possible combinations have been devised.

Writing this to a text file is no problem with me. Having an algorithm that would write the combination is something that I am quite not good at.

Appreciate in .NET (C# or VB) codes.

Thanks.

PS

On a side note, I wonder how long it would take for an application to create a string combination of all possible keyboard characters and how big the file would get to be.

Updated:
I should also show character combination from n characters to the implied limit..

Body:
You can enumerate all the permutations in a string using a recursive implementation. A quick but functional implementation might look like the following:

Edit: You changed the OP to include strings with length less than the input character set. The following code has been modified. It gives exactly the output in your question.

static void BuildPermutations(string input, char[] current, int index, int depth, List<string> perms)
{
    if (index == depth)
    {
        perms.Add(new string(current, 0, depth));
        return;
    }
    for (int n = 0; n < input.Length; ++n)
    {
        current[index] = input[n];
        BuildPermutations(input, current, index + 1, depth, perms);
    }
}

static void Main(string[] args)
{
    string input = "abc";
    char[] current = new char[input.Length];
    List<string> perms = new List<string>();
    for (int n = 1; n <= 3; ++n )
        BuildPermutations(input, current, 0, n, perms);
    foreach (string s in perms)
        System.Console.WriteLine(s.ToString());
}


来源: stackexchange

问:
Price not updating in the navigation (front end)
I have copied the code from http://demo.woothemes.com/boutique/product/woo-ninja-3/

```<code><ul id="site-header-cart" class="site-header-cart menu">
            <li class="">
                                                    <a class="cart-contents" href="http://demo.woothemes.com/boutique/cart/" title="View your shopping cart">
                <span class="amount">£168.00</span> <span class="count">12 items</span>
            </a>

                    </li>
            <li>
                <div class="widget woocommerce widget_shopping_cart" style="opacity: 1;"><div class="widget_shopping_cart_content">

<ul class="cart_list product_list_widget ">

                            <li class="mini_cart_item">
                        <a href="http://demo.woothemes.com/boutique/cart/?remove_item=fbd7939d674997cdb4692d34de8633c4&_wpnonce=ab5f6b26c4" class="remove" title="Remove this item" data-product_id="76" data-product_sku="">×</a>                                                  <a href="http://demo.woothemes.com/boutique/product/woo-ninja-3/">
                                <img width="150" height="150" src="//demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771456709_fc540cc175_b.jpg?w=150&h=150&crop=1" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" srcset="//demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771456709_fc540cc175_b-150x150.jpg 150w, //demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771456709_fc540cc175_b-500x500.jpg 500w, //demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771456709_fc540cc175_b-800x800.jpg 800w" sizes="(max-width: 150px) 100vw, 150px">Woo Ninja                          </a>

                        <span class="quantity">6 × <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">£</span>15.00</span></span>                 </li>
                                        <li class="mini_cart_item">
                        <a href="http://demo.woothemes.com/boutique/cart/?remove_item=7cbbc409ec990f19c78c75bd1e06f215&_wpnonce=ab5f6b26c4" class="remove" title="Remove this item" data-product_id="70" data-product_sku="">×</a>                                                  <a href="http://demo.woothemes.com/boutique/product/flying-ninja/">
                                <img width="150" height="150" src="//demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771457369_92e02576a8_o.jpg?w=150&h=150&crop=1" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" srcset="//demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771457369_92e02576a8_o-150x150.jpg 150w, //demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771457369_92e02576a8_o-500x500.jpg 500w" sizes="(max-width: 150px) 100vw, 150px">Flying Ninja                           </a>

                        <span class="quantity">4 × <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">£</span>12.00</span></span>                 </li>
                                        <li class="mini_cart_item">
                        <a href="http://demo.woothemes.com/boutique/cart/?remove_item=735b90b4568125ed6c3f678819b6e058&_wpnonce=ab5f6b26c4" class="remove" title="Remove this item" data-product_id="67" data-product_sku="">×</a>                                                  <a href="http://demo.woothemes.com/boutique/product/ship-your-idea-3/">
                                <img width="150" height="150" src="//demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771457549_3838523969_b.jpg?w=150&h=150&crop=1" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" srcset="//demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771457549_3838523969_b-150x150.jpg 150w, //demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771457549_3838523969_b-500x500.jpg 500w" sizes="(max-width: 150px) 100vw, 150px">Ship Your Idea Silver Plated Ring                          </a>

                        <span class="quantity">2 × <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">£</span>15.00</span></span>                 </li>

</ul><!-- end product list -->

    <p class="total"><strong>Subtotal:</strong> <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">£</span>168.00</span></p>

    <p class="buttons">
        <a href="http://demo.woothemes.com/boutique/cart/" class="button wc-forward">View Cart</a>
        <a href="http://demo.woothemes.com/boutique/checkout/" class="button checkout wc-forward">Checkout</a>
    </p>

</div></div>            </li>
        </ul>
</code>```

Into my own template; but while widget is updating data just fine for some reason the "cart contents" area, shown below, doesn't update the amount and item count.

```<code><li class="">
    <a class="cart-contents" href="http://demo.woothemes.com/boutique/cart/" title="View your shopping cart">
        <span class="amount">£168.00</span> <span class="count">12 items</span>
    </a>
</li>
</code>```

How can my problem be resolved? I assume some js is missing?

答:
WooCommerce requires you to add cart area to its method.

More about it can be found below:
https://docs.woocommerce.com/document/show-cart-contents-total/

ContentLicense: CC BY-SA 3.0

Body:
I have copied the code from http://demo.woothemes.com/boutique/product/woo-ninja-3/

                £168.00 12 items

                        ×
                                <img width="150" height="150" src="//demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771456709_fc540cc175_b.jpg?w=150&h=150&crop=1" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" srcset="//demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771456709_fc540cc175_b-150x150.jpg 150w, //demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771456709_fc540cc175_b-500x500.jpg 500w, //demo.woothemes.com/boutique/wp-content/uploads/sites/79/2013/06/6771456709_fc540cc175_b-800x800.jpg 800w" sizes="(max-width: 150px) 100vw, 150px">Woo Ninja

                        6 × £15.00

                        ×
                                Flying Ninja

                        4 × £12.00

                        ×
                                Ship Your Idea Silver Plated Ring

                        2 × £15.00

Subtotal: £168.00

        View Cart
        Checkout

Into my own template; but while widget is updating data just fine for some reason the "cart contents" area, shown below, doesn't update the amount and item count.

        £168.00 12 items

How can my problem be resolved? I assume some js is missing?


问:
How to use a filter in a controller?
I have written a filter function which will return data based on the argument you are passing. I want the same functionality in my controller. Is it possible to reuse the filter function in a controller?

This is what I've tried so far:

```<code>function myCtrl($scope,filter1)
{
    // i simply used the filter function name, it is not working.
}
</code>```

答:
It seems nobody has mentioned that you can use a function as arg2 in $filter('filtername')(arg1,arg2);

For example:

```<code>$scope.filteredItems = $filter('filter')(items, function(item){return item.Price>50;});
</code>```

Title: How to use a filter in a controller?

Body:
I have written a filter function which will return data based on the argument you are passing. I want the same functionality in my controller. Is it possible to reuse the filter function in a controller?

This is what I've tried so far:

function myCtrl($scope,filter1)
{
    // i simply used the filter function name, it is not working.
}

Body:
It seems nobody has mentioned that you can use a function as arg2 in $filter('filtername')(arg1,arg2);

For example:

$scope.filteredItems = $filter('filter')(items, function(item){return item.Price>50;});


问:
How do i improve my code to load images from remote server more effiecintly without UI lag?
The adapter provides data for a listview. But when you scroll up and down, it shows old images and takes a couple of seconds to finish loading the images. This is true when you open the view for the first time.</p>

```<code>public class BooksAdapter extends ArrayAdapter<Books> {

    public BooksAdapter(Activity context, ArrayList<Books> word) {
        super(context, 0, word);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        Books currentbook = getItem(position);

        TextView bookView = (TextView) listItemView.findViewById(R.id.bookTittle);
        String booktitle = currentbook.getBookName();
        bookView.setText(booktitle);

        TextView authorView = (TextView) listItemView.findViewById(R.id.authorname);
        String authorname = currentbook.getAuthorName();
        authorView.setText(authorname);

        ImageView imageurl = (ImageView) listItemView.findViewById(R.id.imageView);
        String imagelink = currentbook.getImageLink();

        ImageAsyncTask task = new ImageAsyncTask(imageurl);
        task.execute(imagelink);

        return listItemView;

    }

    private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        private ImageView img;

        ImageAsyncTask(ImageView img) {
            this.img = img;
        }

        @Override
        protected Bitmap doInBackground(String... urls) {

            URL url = null;
            Bitmap bmp = null;

            try {
                url = new URL(urls[0]);
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error with creating URL ", e);
            }
            try {
                bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
            }

            return bmp;

        }

        @Override
        protected void onPostExecute(Bitmap data) {
            this.img.setImageBitmap(data);

        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

    }

}
</code>```

答:
Glide with default image if actual image not loaded from the server.
Place this in app.gradle

```<code>compile 'com.github.bumptech.glide:glide:3.7.0'
</code>```

Use it like,

```<code>Glide.with(this)
                .load("your_image_url")
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        e.printStackTrace();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        Log.d("d", "onResourceReady");

                        return false;
                    }
                })
                .error("your_default_image")// placed in drawable
                .into("your_target_view");
</code>```

Hope this helps.

Body:
The adapter provides data for a listview. But when you scroll up and down, it shows old images and takes a couple of seconds to finish loading the images. This is true when you open the view for the first time.

public class BooksAdapter extends ArrayAdapter<Books> {

    public BooksAdapter(Activity context, ArrayList<Books> word) {
        super(context, 0, word);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        Books currentbook = getItem(position);

        TextView bookView = (TextView) listItemView.findViewById(R.id.bookTittle);
        String booktitle = currentbook.getBookName();
        bookView.setText(booktitle);

        TextView authorView = (TextView) listItemView.findViewById(R.id.authorname);
        String authorname = currentbook.getAuthorName();
        authorView.setText(authorname);

        ImageView imageurl = (ImageView) listItemView.findViewById(R.id.imageView);
        String imagelink = currentbook.getImageLink();

        ImageAsyncTask task = new ImageAsyncTask(imageurl);
        task.execute(imagelink);

        return listItemView;

    }

    private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        private ImageView img;

        ImageAsyncTask(ImageView img) {
            this.img = img;
        }

        @Override
        protected Bitmap doInBackground(String... urls) {

            URL url = null;
            Bitmap bmp = null;

            try {
                url = new URL(urls[0]);
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error with creating URL ", e);
            }
            try {
                bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
            }

            return bmp;

        }

        @Override
        protected void onPostExecute(Bitmap data) {
            this.img.setImageBitmap(data);

        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

    }

}

Body:
Glide with default image if actual image not loaded from the server.
Place this in app.gradle

compile 'com.github.bumptech.glide:glide:3.7.0'

Use it like,

Glide.with(this)
                .load("your_image_url")
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        e.printStackTrace();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        Log.d("d", "onResourceReady");

                        return false;
                    }
                })
                .error("your_default_image")// placed in drawable
                .into("your_target_view");

Hope this helps.


问:
sp_OACreate Error Creating COM Component in SQL Server 2014/2012
The following script was extracted from https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-oacreate-transact-sql

```<code>DECLARE @object int;
DECLARE @hr int;
DECLARE @src varchar(255), @desc varchar(255);
EXEC @hr = sp_OACreate 'SQLDMO.SQLServer', @object OUT;
IF @hr <> 0
BEGIN
   EXEC sp_OAGetErrorInfo @object, @src OUT, @desc OUT
   raiserror('Error Creating COM Component 0x%x, %s, %s',16,1, @hr, @src, @desc)
    RETURN
END;
GO
</code>```

When running it I get the following error:
Msg 50000, Level 16, State 1, Line 82
Error Creating COM Component 0x800401f3, ODSOLE Extended Procedure,  Invalid class string

Could you please advice?

答:
Good. Using sp_OACreate and co is almost always a bad idea these days and you should be thinking CLR integration instead.

The fact that their sample uses COM Objects that we're discontinued with the 2008 R2 version of the product just means that you can't do too much damage by attempting to use the sample without modifying it.

If you are to use these procedures, you ought to be substituting in appropriate values rather than using the sample without modifying it.

Body:
The following script was extracted from https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-oacreate-transact-sql

DECLARE @object int;
DECLARE @hr int;
DECLARE @src varchar(255), @desc varchar(255);
EXEC @hr = sp_OACreate 'SQLDMO.SQLServer', @object OUT;
IF @hr <> 0
BEGIN
   EXEC sp_OAGetErrorInfo @object, @src OUT, @desc OUT
   raiserror('Error Creating COM Component 0x%x, %s, %s',16,1, @hr, @src, @desc)
    RETURN
END;
GO

When running it I get the following error:
Msg 50000, Level 16, State 1, Line 82
Error Creating COM Component 0x800401f3, ODSOLE Extended Procedure,  Invalid class string

Could you please advice?


问:
Text-align isn't working for form element
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

```<code><header>
  <nav>
    <ul>
      <li><a href="">One</a></li>
      <li><a href="">Two</a></li>
      <li><a href="">Three</a></li>
      <li><a href="">Four</a></li>
    </ul>
    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>
  </nav>
</header>
</code>```

My css:

```<code>ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}
</code>```

Jsfiddle: https://jsfiddle.net/dsotpsq4/

答:
you should add position:absolute and a right margin value to the form tag in the  css ...

```<code>form{
display: inline;
position: absolute;
right: 10px;
}
</code>```

Note that Absolutely positioned elements are removed from the normal flow, and can overlap other elements ...

W3Schools Explanation

Body:
Why text-align isn't working for form? I want my form to be aligned to the right. Please help me. Can I do it WITHOUT floats?

One

Two

Three

Four

    <form action="">
      <input type="text">
      <button>Submit</button>
    </form>

My css:

ul{
  display: inline;
  text-align: left;
}

ul li{
  display: inline;
  margin-right: 20px;
}

header form{
  display: inline;
  text-align: right;
}

Jsfiddle: https://jsfiddle.net/dsotpsq4/

Body:
you should add position:absolute and a right margin value to the form tag in the  css ...

form{
display: inline;
position: absolute;
right: 10px;
}

Note that Absolutely positioned elements are removed from the normal flow, and can overlap other elements ...

W3Schools Explanation


问:
Python tabula-py won't read pdf
I am trying to extract tables from a series of PDF files but cannot make tabula-py work. I’ve been trying to use it through a Jupyter Notebook on a Windows OS. Unfortunately, I’m getting the same

‘FileNotFoundError’

every time I try to use the read_PDF().

From what I’ve found online so far, the error seems to be originated when trying to run the Tabula java file. I've got java properly installed.

Any help with this will be greatly appreciated.

This is the code I'm trying to run:

```<code>    from tabula import read_pdf
    df = read_pdf("https://github.com/tabulapdf/tabula-java/raw/master/src/test/resources/technology/tabula/arabic.pdf")
</code>```

Error message:

```<code>    FileNotFoundError                         Traceback (most recent call last)
    <ipython-input-78-956ad4697ff7> in <module>()
          1 from tabula import read_pdf
    ----> 2 df = read_pdf("https://github.com/tabulapdf/tabula-java/raw/master/src/test/resources/technology/tabula/arabic.pdf")

    C:\Program Files\Anaconda3\lib\site-packages\tabula\wrapper.py in read_pdf(input_path, **kwargs)
         64
         65     try:
    ---> 66         output = subprocess.check_output(args)
         67     finally:
         68         if is_url:

    C:\Program Files\Anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
        624
        625     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
    --> 626                **kwargs).stdout
        627
        628

    C:\Program Files\Anaconda3\lib\subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
        691         kwargs['stdin'] = PIPE
        692
    --> 693     with Popen(*popenargs, **kwargs) as process:
        694         try:
        695             stdout, stderr = process.communicate(input, timeout=timeout)

    C:\Program Files\Anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds)
        945                                 c2pread, c2pwrite,
        946                                 errread, errwrite,
    --> 947                                 restore_signals, start_new_session)
        948         except:
        949             # Cleanup if the child failed starting.

    C:\Program Files\Anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
       1222                                          env,
       1223                                          cwd,
    -> 1224                                          startupinfo)
       1225             finally:
       1226                 # Child is launched. Close the parent's copy of those pipe
</code>```

答:
I reproduce this problem without setting PATH environment for java.exe. Make sure to set PATH for Java. See also:
https://www.java.com/en/download/help/path.xml</p>

Title: Python tabula-py won't read pdf

Body:
I am trying to extract tables from a series of PDF files but cannot make tabula-py work. I’ve been trying to use it through a Jupyter Notebook on a Windows OS. Unfortunately, I’m getting the same

‘FileNotFoundError’

every time I try to use the read_PDF().

From what I’ve found online so far, the error seems to be originated when trying to run the Tabula java file. I've got java properly installed.

Any help with this will be greatly appreciated.

This is the code I'm trying to run:

    from tabula import read_pdf
    df = read_pdf("https://github.com/tabulapdf/tabula-java/raw/master/src/test/resources/technology/tabula/arabic.pdf")

Error message:

    FileNotFoundError                         Traceback (most recent call last)
    <ipython-input-78-956ad4697ff7> in <module>()
          1 from tabula import read_pdf
    ----> 2 df = read_pdf("https://github.com/tabulapdf/tabula-java/raw/master/src/test/resources/technology/tabula/arabic.pdf")

    C:\Program Files\Anaconda3\lib\site-packages\tabula\wrapper.py in read_pdf(input_path, **kwargs)
         64
         65     try:
    ---> 66         output = subprocess.check_output(args)
         67     finally:
         68         if is_url:

    C:\Program Files\Anaconda3\lib\subprocess.py in check_output(timeout, *popenargs, **kwargs)
        624
        625     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
    --> 626                **kwargs).stdout
        627
        628

    C:\Program Files\Anaconda3\lib\subprocess.py in run(input, timeout, check, *popenargs, **kwargs)
        691         kwargs['stdin'] = PIPE
        692
    --> 693     with Popen(*popenargs, **kwargs) as process:
        694         try:
        695             stdout, stderr = process.communicate(input, timeout=timeout)

    C:\Program Files\Anaconda3\lib\subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds)
        945                                 c2pread, c2pwrite,
        946                                 errread, errwrite,
    --> 947                                 restore_signals, start_new_session)
        948         except:
        949             # Cleanup if the child failed starting.

    C:\Program Files\Anaconda3\lib\subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, unused_restore_signals, unused_start_new_session)
       1222                                          env,
       1223                                          cwd,
    -> 1224                                          startupinfo)
       1225             finally:
       1226                 # Child is launched. Close the parent's copy of those pipe


问:
Sum up vector values till threshold, then start again
I have a vector a = [1 3 4 2 1 5 6 3 2]. Now I want to create a new vector 'b' with the cumsum of a, but after reaching a threshold, let's say 5, cumsum should reset and start again till it reaches the threshold again, so the new vector should look like this:

```<code>b = [1 4 4 2 3 5 6 3 5]
</code>```

Any ideas?

答:
You could build a sparse matrix that, when multiplied by the original vector, returns the cumulative sums. I haven't timed this solution versus others, but I strongly suspect this will be the fastest for large arrays of a. </p>

```<code>% Original data
a = [1 3 4 2 1 5 6 3 2];
% Threshold
th = 5;
% Cumulative sum corrected by threshold
b = cumsum(a)/th;
% Group indices to be summed by checking for equality,
% rounded down, between each cumsum value and its next value. We add one to
% prevent NaNs from occuring in the next step.
c = cumsum(floor(b) ~= floor([0,b(1:end-1)]))+1;
% Build the sparse matrix, remove all values that are in the upper
% triangle.
S = tril(sparse(c.'./c == 1));
% In case you use matlab 2016a or older:
% S = tril(sparse(bsxfun(@rdivide,c.',c) == 1));
% Matrix multiplication to create o.
o = S*a.';
</code>```

Body:
I have a vector a = [1 3 4 2 1 5 6 3 2]. Now I want to create a new vector 'b' with the cumsum of a, but after reaching a threshold, let's say 5, cumsum should reset and start again till it reaches the threshold again, so the new vector should look like this:

b = [1 4 4 2 3 5 6 3 5]

Any ideas?

Body:
You could build a sparse matrix that, when multiplied by the original vector, returns the cumulative sums. I haven't timed this solution versus others, but I strongly suspect this will be the fastest for large arrays of a.

% Original data
a = [1 3 4 2 1 5 6 3 2];
% Threshold
th = 5;
% Cumulative sum corrected by threshold
b = cumsum(a)/th;
% Group indices to be summed by checking for equality,
% rounded down, between each cumsum value and its next value. We add one to
% prevent NaNs from occuring in the next step.
c = cumsum(floor(b) ~= floor([0,b(1:end-1)]))+1;
% Build the sparse matrix, remove all values that are in the upper
% triangle.
S = tril(sparse(c.'./c == 1));
% In case you use matlab 2016a or older:
% S = tril(sparse(bsxfun(@rdivide,c.',c) == 1));
% Matrix multiplication to create o.
o = S*a.';


问:
Add email recipient to all new Trac tickets
Is there a configuration change that can be made to Trac to send a notification to an email address only upon the creation of all new tickets? If it can't be done through config, a plugin would be the second best option, with source code modification as a last resort.

NOTE: The setting smtp_always_cc in the notification section of TracIni will send messages on all updates. I'm in need of email notifications only on the creation of a new ticket.

答: You could write your own ticket listener plugin (or rather, override the default one and tweak it), or write a email filter (procmail?) to remove  non-creation mails.</p>

ContentLicense: CC BY-SA 2.5


问:
How to set AppBar to autohide C# WinForm
I know that there is a way how to set my application desktop toolbar to autohide, but unfortunately I don't know how to use it properly. Can you someone give me an example, please? I'm programming AppBar in C# WinForm.

Thank you very much

There is a code, which I'm using for registering the AppBar.

```<code>    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct APPBARDATA
    {
        public int cbSize;
        public IntPtr hWnd;
        public int uCallbackMessage;
        public int uEdge;
        public RECT rc;
        public IntPtr lParam;
    }

    private enum ABMsg : int
    {
        ABM_NEW = 0,
        ABM_REMOVE,
        ABM_QUERYPOS,
        ABM_SETPOS,
        ABM_GETSTATE,
        ABM_GETTASKBARPOS,
        ABM_ACTIVATE,
        ABM_GETAUTOHIDEBAR,
        ABM_SETAUTOHIDEBAR,
        ABM_WINDOWPOSCHANGED,
        ABM_SETSTATE
    }

    private enum ABNotify : int
    {
        ABN_STATECHANGE = 0,
        ABN_POSCHANGED,
        ABN_FULLSCREENAPP,
        ABN_WINDOWARRANGE
    }

    private enum ABEdge : int
    {
        ABE_LEFT = 0,
        ABE_TOP,
        ABE_RIGHT,
        ABE_BOTTOM
    }

    private bool isBarRegistered = false;
    private int uCallBack;

    [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
    private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);

    [DllImport("USER32")]
    private static extern int GetSystemMetrics(int Index);

    [DllImport("User32.dll", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int cx, int cy, bool repaint);

    [DllImport("User32.dll", CharSet = CharSet.Auto)]
    private static extern int RegisterWindowMessage(string msg);

    private void RegisterBar(bool dvojty)
    {
        APPBARDATA abd = new APPBARDATA();
        abd.cbSize = Marshal.SizeOf(abd);
        abd.hWnd = this.Handle;
        if (!isBarRegistered)
        {
            if (Properties.Settings.Default.Strana.ToLower() == "ano")
            {
                this.Width = minSirka;
                this.Height = Screen.FromPoint(this.Location).WorkingArea.Height;
            }
            else
            {
                this.Width = Screen.FromPoint(this.Location).WorkingArea.Width;
                this.Height = minVyska;
            }
            uCallBack = RegisterWindowMessage("AppBarMessage");
            abd.uCallbackMessage = uCallBack;

            uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
            isBarRegistered = true;

            ABSetPos(hrana);
        }
        else
        {
            toolBar = new Rectangle(0, 0, 0, 0);
            SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);
            isBarRegistered = false;
            //this.TopMost = true;

            if (dvojty)
            {
                if (Properties.Settings.Default.Strana.ToLower() == "ano")
                {
                    this.Width = minSirka;
                    this.Height = Screen.FromPoint(this.Location).WorkingArea.Height;
                }
                else
                {
                    this.Width = Screen.FromPoint(this.Location).WorkingArea.Width;
                    this.Height = minVyska;
                }
                uCallBack = RegisterWindowMessage("AppBarMessage");
                abd.uCallbackMessage = uCallBack;

                uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
                isBarRegistered = true;

                ABSetPos(hrana);
            }
        }
    }

    private void ABSetPos(string edge)
    {
        APPBARDATA abd = new APPBARDATA();
        //SHAppBarMessage((int)ABMsg.ABM_SETAUTOHIDEBAR, ref abd);
        abd.cbSize = Marshal.SizeOf(abd);
        abd.hWnd = this.Handle;

        if (edge == "" || edge == "top")
        {
            abd.uEdge = (int)ABEdge.ABE_TOP;
        }
        else if (edge == "right")
        {
            abd.uEdge = (int)ABEdge.ABE_RIGHT;
        }
        else if (edge == "left")
        {
            abd.uEdge = (int)ABEdge.ABE_LEFT;
        }
        else if (edge == "bottom")
        {
            abd.uEdge = (int)ABEdge.ABE_BOTTOM;
        }
        else
        {
            abd.uEdge = (int)ABEdge.ABE_TOP;
        }

        if (abd.uEdge == (int)ABEdge.ABE_LEFT || abd.uEdge == (int)ABEdge.ABE_RIGHT)
        {
            abd.rc.top = 0;
            abd.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;

            if (abd.uEdge == (int)ABEdge.ABE_LEFT)
            {
                abd.rc.left = 0;
                abd.rc.right = Size.Width;
                okraj = "left";
            }
            else
            {
                abd.rc.right = SystemInformation.PrimaryMonitorSize.Width;
                abd.rc.left = abd.rc.right - Size.Width;
                okraj = "right";
            }

        }
        else
        {
            abd.rc.left = Screen.FromControl(this).WorkingArea.Left;
            abd.rc.right = Screen.FromControl(this).WorkingArea.Right;
            if (abd.uEdge == (int)ABEdge.ABE_TOP)
            {
                abd.rc.top = Screen.FromControl(this).WorkingArea.Top;
                abd.rc.bottom = Size.Height;
                okraj = "top";
            }
            else
            {
                abd.rc.bottom = Screen.FromControl(this).WorkingArea.Bottom;
                abd.rc.top = abd.rc.bottom - Size.Height;
                okraj = "bottom";
            }
        }

        SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref abd);

        switch (abd.uEdge)
        {
            case (int)ABEdge.ABE_LEFT:
                abd.rc.right = abd.rc.left + Size.Width;
                break;
            case (int)ABEdge.ABE_RIGHT:
                abd.rc.left = abd.rc.right - Size.Width;
                break;
            case (int)ABEdge.ABE_TOP:
                abd.rc.bottom = abd.rc.top + Size.Height;
                break;
            case (int)ABEdge.ABE_BOTTOM:
                abd.rc.top = abd.rc.bottom - Size.Height;
                break;
        }

        this.Top -= 1;
        SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref abd);
        MoveWindow(abd.hWnd, abd.rc.left, abd.rc.top, Size.Width, Size.Height, true);
        toolBar = new Rectangle(abd.rc.left, abd.rc.top, Size.Width, Size.Height);
        left = this.Left;
        top = this.Top;
    }
</code>```

答:
Untested

First, your SHAppBarMessage() declaration should be returning IntPtr:

```<code>[DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr SHAppBarMessage(int dwMessage, ref APPBARDATA pData);
</code>```

Then, as per the documentation for ABM_GETAUTOHIDEBAR and ABM_SETAUTOHIDEBAR, there can only be one AppBar with AutoHide per edge of the screen.  So after filling out your APPBARDATA structure in your ABSetPos() method (specifying what edge you are going to use), you can query the system to see if there is already an auto-hiding bar on that edge.  If none is returned, then you can register your appbar...something like:

```<code>IntPtr curAutoHide = SHAppBarMessage((int)ABMsg.ABM_GETAUTOHIDEBAR, ref abd);
if (curAutoHide.Equals(IntPtr.Zero)) // if there is no current appbar with autohide set for that edge...
{
    abd.lParam = new IntPtr(1); // true
    SHAppBarMessage((int)ABMsg.ABM_SETAUTOHIDEBAR, ref abd);
}
</code>```

Body:
I know that there is a way how to set my application desktop toolbar to autohide, but unfortunately I don't know how to use it properly. Can you someone give me an example, please? I'm programming AppBar in C# WinForm.

Thank you very much

There is a code, which I'm using for registering the AppBar.

    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct APPBARDATA
    {
        public int cbSize;
        public IntPtr hWnd;
        public int uCallbackMessage;
        public int uEdge;
        public RECT rc;
        public IntPtr lParam;
    }

    private enum ABMsg : int
    {
        ABM_NEW = 0,
        ABM_REMOVE,
        ABM_QUERYPOS,
        ABM_SETPOS,
        ABM_GETSTATE,
        ABM_GETTASKBARPOS,
        ABM_ACTIVATE,
        ABM_GETAUTOHIDEBAR,
        ABM_SETAUTOHIDEBAR,
        ABM_WINDOWPOSCHANGED,
        ABM_SETSTATE
    }

    private enum ABNotify : int
    {
        ABN_STATECHANGE = 0,
        ABN_POSCHANGED,
        ABN_FULLSCREENAPP,
        ABN_WINDOWARRANGE
    }

    private enum ABEdge : int
    {
        ABE_LEFT = 0,
        ABE_TOP,
        ABE_RIGHT,
        ABE_BOTTOM
    }

    private bool isBarRegistered = false;
    private int uCallBack;

    [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
    private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);

    [DllImport("USER32")]
    private static extern int GetSystemMetrics(int Index);

    [DllImport("User32.dll", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int cx, int cy, bool repaint);

    [DllImport("User32.dll", CharSet = CharSet.Auto)]
    private static extern int RegisterWindowMessage(string msg);

    private void RegisterBar(bool dvojty)
    {
        APPBARDATA abd = new APPBARDATA();
        abd.cbSize = Marshal.SizeOf(abd);
        abd.hWnd = this.Handle;
        if (!isBarRegistered)
        {
            if (Properties.Settings.Default.Strana.ToLower() == "ano")
            {
                this.Width = minSirka;
                this.Height = Screen.FromPoint(this.Location).WorkingArea.Height;
            }
            else
            {
                this.Width = Screen.FromPoint(this.Location).WorkingArea.Width;
                this.Height = minVyska;
            }
            uCallBack = RegisterWindowMessage("AppBarMessage");
            abd.uCallbackMessage = uCallBack;

            uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
            isBarRegistered = true;

            ABSetPos(hrana);
        }
        else
        {
            toolBar = new Rectangle(0, 0, 0, 0);
            SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);
            isBarRegistered = false;
            //this.TopMost = true;

            if (dvojty)
            {
                if (Properties.Settings.Default.Strana.ToLower() == "ano")
                {
                    this.Width = minSirka;
                    this.Height = Screen.FromPoint(this.Location).WorkingArea.Height;
                }
                else
                {
                    this.Width = Screen.FromPoint(this.Location).WorkingArea.Width;
                    this.Height = minVyska;
                }
                uCallBack = RegisterWindowMessage("AppBarMessage");
                abd.uCallbackMessage = uCallBack;

                uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);
                isBarRegistered = true;

                ABSetPos(hrana);
            }
        }
    }

    private void ABSetPos(string edge)
    {
        APPBARDATA abd = new APPBARDATA();
        //SHAppBarMessage((int)ABMsg.ABM_SETAUTOHIDEBAR, ref abd);
        abd.cbSize = Marshal.SizeOf(abd);
        abd.hWnd = this.Handle;

        if (edge == "" || edge == "top")
        {
            abd.uEdge = (int)ABEdge.ABE_TOP;
        }
        else if (edge == "right")
        {
            abd.uEdge = (int)ABEdge.ABE_RIGHT;
        }
        else if (edge == "left")
        {
            abd.uEdge = (int)ABEdge.ABE_LEFT;
        }
        else if (edge == "bottom")
        {
            abd.uEdge = (int)ABEdge.ABE_BOTTOM;
        }
        else
        {
            abd.uEdge = (int)ABEdge.ABE_TOP;
        }

        if (abd.uEdge == (int)ABEdge.ABE_LEFT || abd.uEdge == (int)ABEdge.ABE_RIGHT)
        {
            abd.rc.top = 0;
            abd.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;

            if (abd.uEdge == (int)ABEdge.ABE_LEFT)
            {
                abd.rc.left = 0;
                abd.rc.right = Size.Width;
                okraj = "left";
            }
            else
            {
                abd.rc.right = SystemInformation.PrimaryMonitorSize.Width;
                abd.rc.left = abd.rc.right - Size.Width;
                okraj = "right";
            }

        }
        else
        {
            abd.rc.left = Screen.FromControl(this).WorkingArea.Left;
            abd.rc.right = Screen.FromControl(this).WorkingArea.Right;
            if (abd.uEdge == (int)ABEdge.ABE_TOP)
            {
                abd.rc.top = Screen.FromControl(this).WorkingArea.Top;
                abd.rc.bottom = Size.Height;
                okraj = "top";
            }
            else
            {
                abd.rc.bottom = Screen.FromControl(this).WorkingArea.Bottom;
                abd.rc.top = abd.rc.bottom - Size.Height;
                okraj = "bottom";
            }
        }

        SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref abd);

        switch (abd.uEdge)
        {
            case (int)ABEdge.ABE_LEFT:
                abd.rc.right = abd.rc.left + Size.Width;
                break;
            case (int)ABEdge.ABE_RIGHT:
                abd.rc.left = abd.rc.right - Size.Width;
                break;
            case (int)ABEdge.ABE_TOP:
                abd.rc.bottom = abd.rc.top + Size.Height;
                break;
            case (int)ABEdge.ABE_BOTTOM:
                abd.rc.top = abd.rc.bottom - Size.Height;
                break;
        }

        this.Top -= 1;
        SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref abd);
        MoveWindow(abd.hWnd, abd.rc.left, abd.rc.top, Size.Width, Size.Height, true);
        toolBar = new Rectangle(abd.rc.left, abd.rc.top, Size.Width, Size.Height);
        left = this.Left;
        top = this.Top;
    }

Body:
Untested

First, your SHAppBarMessage() declaration should be returning IntPtr:

[DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr SHAppBarMessage(int dwMessage, ref APPBARDATA pData);

Then, as per the documentation for ABM_GETAUTOHIDEBAR and ABM_SETAUTOHIDEBAR, there can only be one AppBar with AutoHide per edge of the screen.  So after filling out your APPBARDATA structure in your ABSetPos() method (specifying what edge you are going to use), you can query the system to see if there is already an auto-hiding bar on that edge.  If none is returned, then you can register your appbar...something like:

IntPtr curAutoHide = SHAppBarMessage((int)ABMsg.ABM_GETAUTOHIDEBAR, ref abd);
if (curAutoHide.Equals(IntPtr.Zero)) // if there is no current appbar with autohide set for that edge...
{
    abd.lParam = new IntPtr(1); // true
    SHAppBarMessage((int)ABMsg.ABM_SETAUTOHIDEBAR, ref abd);
}


问:
Retrieve, only the contents from media wiki API
I would like to retrieve only the events in a hash from February 14 wiki page

For that I am trying this JSON API call but it does not give clear information. How can I imrovise my api call to get all events list in a proper way. I would like to store this info in db as object like key, value pair.

答:
Use parameters prop=revisions, rvprop=content and set rvsection ID to the API call. In your case, the section ID for Events is 1, so the API call will be:

https://en.wikipedia.org/w/api.php?action=query&titles=February_14&prop=revisions&rvprop=content&format=json&rvsection=1


问:
SQL function for returning multiple XPath hits
I have a huge table with a column which contains large XML documents. I want to get all the values of a particular attribute name (Surname), occurring at any point in any of the XML values.

Currently I have this query...

```<code>select distinct XmlCol.value('(//@Surname)[1]','varchar(200)') from (
    select * from MyTable
)
</code>```

...it grabs the first occurrence of my desired attribute in each entry of the XML column, however as it only grabs the first, there may be any number of attributes appearing after that occurrence, in the same XML value.

The value() function only works with a single result, hence why I need to provide the [1] specifying return the first hit.

Is there a way to repeat this function to get all the hits in a piece of XML, or is there another function which takes an XPath and can return multiple values?

Illustrated example

In case above is not clear, a simple example would be if MyTable had a single XmlCol column, with just 2 rows.

Row 1

```<code><SimpleXML>
   <ArbitraryElement Surname="Smith"/>
   <ArbitraryElement>
        <ArbitraryInnerElement Surname="Bauer"/>
   </ArbitraryElement>
</SimpleXML>
</code>```

Row 2

```<code><SimpleXML Surname="Bond">
</SimpleXML>
</code>```

Note the attribute appears at different locations and in different elements, I want it to work with any amount of nested elements.

Currently my method only hits the first element per XML entry, so gives the output:

```<code>Smith, Bond
</code>```

I'd like it to return an arbitrary amount per entry, meaning the result should be:

```<code>Smith, Bauer, Bond
</code>```

答:
You would want to use a CROSS APPLY to achieve this.

```<code>select distinct XmlCol.value('.', 'varchar(max)') as [Value]
from MyTable
CROSS APPLY MyTable.XmlCol.nodes('(//@Surname)') as [Table]([Column])
</code>```

Body:
I have a huge table with a column which contains large XML documents. I want to get all the values of a particular attribute name (Surname), occurring at any point in any of the XML values.

Currently I have this query...

select distinct XmlCol.value('(//@Surname)[1]','varchar(200)') from (
    select * from MyTable
)

...it grabs the first occurrence of my desired attribute in each entry of the XML column, however as it only grabs the first, there may be any number of attributes appearing after that occurrence, in the same XML value.

The value() function only works with a single result, hence why I need to provide the [1] specifying return the first hit.

Is there a way to repeat this function to get all the hits in a piece of XML, or is there another function which takes an XPath and can return multiple values?

Illustrated example

In case above is not clear, a simple example would be if MyTable had a single XmlCol column, with just 2 rows.

Row 1

<SimpleXML>
   <ArbitraryElement Surname="Smith"/>
   <ArbitraryElement>
        <ArbitraryInnerElement Surname="Bauer"/>
   </ArbitraryElement>
</SimpleXML>

Row 2

<SimpleXML Surname="Bond">
</SimpleXML>

Note the attribute appears at different locations and in different elements, I want it to work with any amount of nested elements.

Currently my method only hits the first element per XML entry, so gives the output:

Smith, Bond

I'd like it to return an arbitrary amount per entry, meaning the result should be:

Smith, Bauer, Bond

Body:
You would want to use a CROSS APPLY to achieve this.

select distinct XmlCol.value('.', 'varchar(max)') as [Value]
from MyTable
CROSS APPLY MyTable.XmlCol.nodes('(//@Surname)') as [Table]([Column])


问:
Accessing same variables in different python scripts preserving values
I have below scripts

script1:

```<code>var1 = 10
var2 = []
</code>```

script2:

```<code>import script1
script1.var1 = script1.var1 + 10
script1.var2 = script1.var2.append['1']
</code>```

script3:

```<code>import script1
script1.var1 = script1.var1 + 10
script1.var2 = script1.var2.append['2']
print script1.var1
print script1.var2
</code>```

script2 will execute first then script3

In script3,  script1 is importing so all values update as per script 1

I am expecting var1 to print 30 and var2  print ['1', '2']

So what is the best way to use variables in this case.

答:
As I understand the question, script2 and script3 are ran independently of each other, i.e.

```<code>$ python script2.py
$ python script3.py
</code>```

Then, no, changes you make to variables of script1 in script2 will not be persisted after the program has finished. However, if you have another script, call it script4.py, that executes both ofscript2 and script3 within the same program...

```<code>import script2
import script3
</code>```

... then the changes will be persisted (im memory) and script3 should print 30 and ['1', '2'] as you expected.

If you want to store variables between program execution, I suggest you have a look at json, or some other persistence module for Python, for storing data on disk or in a data base.

Body:
I have below scripts

script1:

var1 = 10
var2 = []

script2:

import script1
script1.var1 = script1.var1 + 10
script1.var2 = script1.var2.append['1']

script3:

import script1
script1.var1 = script1.var1 + 10
script1.var2 = script1.var2.append['2']
print script1.var1
print script1.var2

script2 will execute first then script3

In script3,  script1 is importing so all values update as per script 1

I am expecting var1 to print 30 and var2  print ['1', '2']

So what is the best way to use variables in this case.

Body:
As I understand the question, script2 and script3 are ran independently of each other, i.e.

$ python script2.py
$ python script3.py

Then, no, changes you make to variables of script1 in script2 will not be persisted after the program has finished. However, if you have another script, call it script4.py, that executes both ofscript2 and script3 within the same program...

import script2
import script3

... then the changes will be persisted (im memory) and script3 should print 30 and ['1', '2'] as you expected.

If you want to store variables between program execution, I suggest you have a look at json, or some other persistence module for Python, for storing data on disk or in a data base.


问:
Watson generic word from utterance
Trying to create a set of entities & intents for things of the ilk "describe <something>" or "tell me about <something>" or "list instances of <something>".  The <something>s are not known in advance.  Consequently, I cannot exhaustively list the possible values for the entity.

My impression from (albeit very little) use and from the documentation is that the conversation API isn't good at this type of thing.  Experience thus far says that it will recognize things that match the examples given for some entity, but I haven't seen that it can generalize to something like

describe @target

show me instances of @target

without knowing the set of values for @target.

What am I missing?

答:
Based on your example, you can combine the Intents and Entities for your purpose.

It's a good practice, I think.

Like Daniel said, you can create one intent with examples for asking about something, like these examples within your #describeAbout:

Describe about

Can you please describe

Can you please explain about

List instances of

etc...

And create one entity like @typesDescribe, with yours values. Like this values:

Paper

Love

Fruits

After Watson training your examples, with your Dialog, create one flow with the condition

```<code>if #describeAbout AND @typesDescribe:Paper
</code>```

Response:

@typesDescribe (Will show the value: Paper) is a thin material produced by pressing together moist fibres of cellulose pulp derived from wood, rags or grasses, and drying them into flexible sheets.

And, usually, if your confidence about Intent and Entity are small, you can add one more condition for your Intent with the confidence level that you want. Check.

Obs.: You can create one Intent alone, with condition #describeAbout, and the response will ask for your user "You can know what?", and create one flow with various @typesDescribe:value, for example.

Title: Watson generic word from utterance

Body:
Based on your example, you can combine the Intents and Entities for your purpose.

It's a good practice, I think.

Like Daniel said, you can create one intent with examples for asking about something, like these examples within your #describeAbout:

Describe about

Can you please describe

Can you please explain about

List instances of

etc...

And create one entity like @typesDescribe, with yours values. Like this values:

Paper

Love

Fruits

After Watson training your examples, with your Dialog, create one flow with the condition

if #describeAbout AND @typesDescribe:Paper

Response:

@typesDescribe (Will show the value: Paper) is a thin material produced by pressing together moist fibres of cellulose pulp derived from wood, rags or grasses, and drying them into flexible sheets.

And, usually, if your confidence about Intent and Entity are small, you can add one more condition for your Intent with the confidence level that you want. Check.

Obs.: You can create one Intent alone, with condition #describeAbout, and the response will ask for your user "You can know what?", and create one flow with various @typesDescribe:value, for example.


问:
how to display wordpress tags and users who used them
Im using $terms = get_terms( 'ad_tags'); to display tags from custom postype ,  It works well. Now I want to display the users who used them on the post. I'm coding a small plugin. e.g

```<code>foreach ( $terms as $term ){

    $term->name  // tag and users who used them
}
</code>```

How do you go about this?

答:
Yes, you can get user details who created the post by particular post id.

First of all, you can get user id of particular post by using $author_id=$post->post_author;

Then you can get other information of the user by using author_id with this function: get_the_author_meta( string $field = '', int $user_id = false )

You can pass first_name, last_name, email as a $field to get user information.

That's the way of getting user information of particular post.

I hope this will helpful for you.

Thanks.

Body:
Im using $terms = get_terms( 'ad_tags'); to display tags from custom postype ,  It works well. Now I want to display the users who used them on the post. I'm coding a small plugin. e.g

foreach ( $terms as $term ){

    $term->name  // tag and users who used them
}

How do you go about this?


问:
c++ How could I properly predefined array of char*?
I am doing it that way:

```<code>int argc = 9;
char* argv[argc];

argv[0] = "c:/prog.exe";
</code>```

but I get notice, that it is deprecated. What is better way?

答:
You have to either make it const:

```<code>const char *argv[] = { "Arg1", "Arg2", "..." };
</code>```

... or not use the constant string literals:

```<code>int argc = 9;
char* argv[argc];
char prog_name[] = "c:/prog.exe";
argv[0] = prog_name;
</code>```

Body:
I am doing it that way:

int argc = 9;
char* argv[argc];

argv[0] = "c:/prog.exe";

but I get notice, that it is deprecated. What is better way?

Body:
You have to either make it const:

const char *argv[] = { "Arg1", "Arg2", "..." };

... or not use the constant string literals:

int argc = 9;
char* argv[argc];
char prog_name[] = "c:/prog.exe";
argv[0] = prog_name;


问:
How to set properties on a class to a list of method groups matching on type?
What we had before was a OracleCommand we were adding parameters to, then we'd run ExecuteReaderAsync on it to get a OracleDataReader. Then we filled lists of different objects by calling a "GetList" method that would take the reader and a method group that returns an object of the same type as the list.

```<code>// These parameters need to be in the same order as returned by the procedure.
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("ProcedureTable1", OracleDbType.RefCursor, ParameterDirection.Output);
command.Parameters.Add("ProcedureTable2", OracleDbType.RefCursor, ParameterDirection.Output);
command.Parameters.Add("ProcedureTable3", OracleDbType.RefCursor, ParameterDirection.Output);

OracleDataReader reader = await command.ExecuteReaderAsync() as OracleDataReader;

// These methods need to be called in the same order as the parameters above.
List<Type1> type1s = await GetList(reader, CreateType1, false); // The first item is called with an overload that takes wht
List<Type2> type2s = await GetList(reader, CreateType2);
List<Type3> type3s = await GetList(reader, CreateType3);
</code>```

The problem, as the commends suggest, is that if the parameters are put out of order we get a database exception instead of data. If the calls to the method groups are placed out of order the list simply fill with empty versions of the class they should contain.

It was suggested to use an ordered list, so I set up a Dictionary to hold DataPackage object with a string name of the procedure in the database package and the method group.

I was easily able to add them all in the right order once, and set up the command parameters.

```<code>// These parameter/method pairs need to be in the same order as returned by the procedure.
List<DataPackage> orderedList = new List<DataPackage>
{
  new DataPackage<Type1>("Type1ProcedureName", CreateType1MethodGroup, type1List),
  new DataPackage<Type2>("Type2ProcedureName", CreateType2MethodGroup, type2List),
  new DataPackage<Type3>("Type3ProcedureName", CreateType3MethodGroup, type1List),
};

command.CommandType = CommandType.StoredProcedure;
orderedList.ForEach(p => command.Parameters.Add(p.ProcedureName, OracleDbType.RefCursor, ParameterDirection.Output));
</code>```

With the classes

```<code>public class DataPackage
{
    public string ProcedureName { get; protected set; }

    public Func<OracleDataReader, object> MethodGroup { get; protected set; }

    public virtual void Add(object list)
    {
    }
}
</code>```

and

```<code>public class DataPackage<T> : DataPackage
{
  public DataPackage(string procedureName, Func<OracleDataReader, object> methodGroup, List<T> returnedData)
  {
      this.ProcedureName = procedureName;
      this.MethodGroup = methodGroup;
      this.ReturnedData = returnedData;
  }

  public List<T> ReturnedData { get; set; }

  public override void Add (object list)
  {
      List<T> castList = list as List<T>;

      if (castList != null)
      {
            this.ReturnedData.AddRange(castList);
      }
  }
}
</code>```

At least it only needs to be added in order once, and that part works. The part where I haven't been able to figure out is calling the GetList with each method group to fill the data.

```<code>orderedList.ForEach(async v =>
{
  v.Add(await GetList(reader, v.MethodGroup, false));
});
</code>```

The problem is when I debug the Add method on DataPackage the list comes in as an object, and it tries to be cast to List but that fails, even though the list parameter is obviously a list and is filled with data.
Is there a better way to do this?

答:
I was searching and found the question Cast Object to Generic List and changed the code in the Add method of the typed DataPackage to

```<code>    public override void Add (object list)
    {
        IEnumerable castList = list as IEnumerable;

        if (castList != null)
        {
            IEnumerable<T> typedList = castList.OfType<T>();
            this.ReturnedData.AddRange(typedList);
        }
    }
</code>```

And it works fine.

Body:
What we had before was a OracleCommand we were adding parameters to, then we'd run ExecuteReaderAsync on it to get a OracleDataReader. Then we filled lists of different objects by calling a "GetList" method that would take the reader and a method group that returns an object of the same type as the list.

// These parameters need to be in the same order as returned by the procedure.
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("ProcedureTable1", OracleDbType.RefCursor, ParameterDirection.Output);
command.Parameters.Add("ProcedureTable2", OracleDbType.RefCursor, ParameterDirection.Output);
command.Parameters.Add("ProcedureTable3", OracleDbType.RefCursor, ParameterDirection.Output);

OracleDataReader reader = await command.ExecuteReaderAsync() as OracleDataReader;

// These methods need to be called in the same order as the parameters above.
List<Type1> type1s = await GetList(reader, CreateType1, false); // The first item is called with an overload that takes wht
List<Type2> type2s = await GetList(reader, CreateType2);
List<Type3> type3s = await GetList(reader, CreateType3);

The problem, as the commends suggest, is that if the parameters are put out of order we get a database exception instead of data. If the calls to the method groups are placed out of order the list simply fill with empty versions of the class they should contain.

It was suggested to use an ordered list, so I set up a Dictionary to hold DataPackage object with a string name of the procedure in the database package and the method group.

I was easily able to add them all in the right order once, and set up the command parameters.

// These parameter/method pairs need to be in the same order as returned by the procedure.
List<DataPackage> orderedList = new List<DataPackage>
{
  new DataPackage<Type1>("Type1ProcedureName", CreateType1MethodGroup, type1List),
  new DataPackage<Type2>("Type2ProcedureName", CreateType2MethodGroup, type2List),
  new DataPackage<Type3>("Type3ProcedureName", CreateType3MethodGroup, type1List),
};

command.CommandType = CommandType.StoredProcedure;
orderedList.ForEach(p => command.Parameters.Add(p.ProcedureName, OracleDbType.RefCursor, ParameterDirection.Output));

With the classes

public class DataPackage
{
    public string ProcedureName { get; protected set; }

    public Func<OracleDataReader, object> MethodGroup { get; protected set; }

    public virtual void Add(object list)
    {
    }
}

and

public class DataPackage<T> : DataPackage
{
  public DataPackage(string procedureName, Func<OracleDataReader, object> methodGroup, List<T> returnedData)
  {
      this.ProcedureName = procedureName;
      this.MethodGroup = methodGroup;
      this.ReturnedData = returnedData;
  }

  public List<T> ReturnedData { get; set; }

  public override void Add (object list)
  {
      List<T> castList = list as List<T>;

      if (castList != null)
      {
            this.ReturnedData.AddRange(castList);
      }
  }
}

At least it only needs to be added in order once, and that part works. The part where I haven't been able to figure out is calling the GetList with each method group to fill the data.

orderedList.ForEach(async v =>
{
  v.Add(await GetList(reader, v.MethodGroup, false));
});

The problem is when I debug the Add method on DataPackage the list comes in as an object, and it tries to be cast to List but that fails, even though the list parameter is obviously a list and is filled with data.
Is there a better way to do this?

Body:
I was searching and found the question Cast Object to Generic List and changed the code in the Add method of the typed DataPackage to

    public override void Add (object list)
    {
        IEnumerable castList = list as IEnumerable;

        if (castList != null)
        {
            IEnumerable<T> typedList = castList.OfType<T>();
            this.ReturnedData.AddRange(typedList);
        }
    }

And it works fine.


问:
Comparing a list against a tuple
I am trying to compare a list of values against a list of tuples. For example:

```<code>list = [1.0, 2.0]

list_of_tuples = [(3, 1.0, 'a'), (4, 2.0, 'b'), (5, 3.0, 'c')]
</code>```

Ideally what I am trying to do is take the list of tuples and check to see if all the values in that list are present in the other one. In the case of the example lists I provided above 1.0 and 2.0 are present but 3.0 is not. Another problem with this is that the location of the values in the list of tuples is going to be unknown when the comprehension takes place (which isn't the case in the example I provided above) so I'm not actually sure if it is possible to do what I am trying to do.

Any help with this would be appreciated, or an alternative solution would be helpful as well.

答:
If just one value of the tuple must be in the list, then this should give you the list of tuples which are invalid.

```<code>filter(lambda values: not any(value in list for value in values), list_of_tuples)
</code>```

Otherwise, if all values must be in the list

```<code>filter(lambda values: not all(value in list for value in values), list_of_tuples)
</code>```

Title: Comparing a list against a tuple

Body:
I am trying to compare a list of values against a list of tuples. For example:

list = [1.0, 2.0]

list_of_tuples = [(3, 1.0, 'a'), (4, 2.0, 'b'), (5, 3.0, 'c')]

Ideally what I am trying to do is take the list of tuples and check to see if all the values in that list are present in the other one. In the case of the example lists I provided above 1.0 and 2.0 are present but 3.0 is not. Another problem with this is that the location of the values in the list of tuples is going to be unknown when the comprehension takes place (which isn't the case in the example I provided above) so I'm not actually sure if it is possible to do what I am trying to do.

Any help with this would be appreciated, or an alternative solution would be helpful as well.

Body:
If just one value of the tuple must be in the list, then this should give you the list of tuples which are invalid.

filter(lambda values: not any(value in list for value in values), list_of_tuples)

Otherwise, if all values must be in the list

filter(lambda values: not all(value in list for value in values), list_of_tuples)


问:
Spring Boot: Determining what autoconfiguration are applied to jersey?
Following the online docs for adding jersey to Sring boot, it appears I just need to include the following package

```<code>spring-boot-starter-jersey
</code>```

Actually, it states that Spring Boot provides automatic configuration by including this package.

Where can I find out what exactly is happening?

If I don't add this package then what is NOT configured?

I tried searching for the package in google but got no specific explanation only saying that it automatically configures, but configures what?

I would like to know a little more of what is happening behind the scenes.

答:
I would recommend learning a little more about how Spring Boot works to provide the automatic configuration in general.

A good reference is the spring boot reference guide. http://docs.spring.io/spring-boot/docs/1.5.3.RELEASE/reference/htmlsingle/#common-application-properties

You can look at the common application properties in appendix A to see what all spring allows you to configure out of the box.

The Reference guide also gives a high level of what "spring-boot-starter-jersey" if you search for it on the page.

They also have a few samples that you can go through and debug to follow along if that is a way for you to learn.

Hope that gives you a starting point for learning!

Body:
Following the online docs for adding jersey to Sring boot, it appears I just need to include the following package

spring-boot-starter-jersey

Actually, it states that Spring Boot provides automatic configuration by including this package.

Where can I find out what exactly is happening?

If I don't add this package then what is NOT configured?

I tried searching for the package in google but got no specific explanation only saying that it automatically configures, but configures what?

I would like to know a little more of what is happening behind the scenes.


问:
How to deprecate an Array type declaration in Delphi?
I need to mark as deprecated an array type declaration (well, actually more than just one), in order to help migrate our code to the more advanced and flexible TArray<T> generic type.

I've tried this:

```<code>type
  TArrayChars = array of Char deprecated;
</code>```

but I got a compilation error: E2029 ';' expected but identifier 'deprecated' found

The same works if the declared type isn't an array, for example:

```<code>type
  TFieldChars = set of Char deprecated;
</code>```

Note that this should be feasible by design.

What am I missing?

This seems to be a bug in Delphi (at least 10.1 Berlin and 10.2 Tokyo).

My accepted answer proposes a neat workaround, that is:

```<code>type
  TArrayCharsOld = array of Char;
  TArrayChars    = TArrayCharsOld deprecated;
</code>```

I'll file a bug report to Embarcadero.

This is the Embarcadero QC issue I've submitted:
https://quality.embarcadero.com/browse/RSP-18316

答:
There's nothing much to say. Dynamic array type declarations cannot be marked as deprecated.

I would consider this to be a defect. The documentation says:

The 'hint' directives platform, deprecated, and library may be
  appended to any declaration. These directives will produce warnings at
  compile time. Hint directives can be applied to type declarations,
  variable declarations, class, interface, and structure declarations,
  field declarations within classes or records, procedure, function, and
  method declarations, and unit declarations.

Your dynamic array type declaration meets the requirements listed here since it is a type declaration.

Body:
I need to mark as deprecated an array type declaration (well, actually more than just one), in order to help migrate our code to the more advanced and flexible TArray<T> generic type.

I've tried this:

type
  TArrayChars = array of Char deprecated;

but I got a compilation error: E2029 ';' expected but identifier 'deprecated' found

The same works if the declared type isn't an array, for example:

type
  TFieldChars = set of Char deprecated;

Note that this should be feasible by design.

What am I missing?

This seems to be a bug in Delphi (at least 10.1 Berlin and 10.2 Tokyo).

My accepted answer proposes a neat workaround, that is:

type
  TArrayCharsOld = array of Char;
  TArrayChars    = TArrayCharsOld deprecated;

I'll file a bug report to Embarcadero.

This is the Embarcadero QC issue I've submitted:
https://quality.embarcadero.com/browse/RSP-18316


问:
How to get the enum type by its attribute?
I have written an enum class and I want to either get the attribute by type or get the type by attribute, but it seems impossible.

```<code>public enum AreaCode {
    area1(7927),
    area2(7928),
    area3(7929);

    private final int ac;

    AreaCode(int ac) {
        this.ac = ac;
    }

    int areaCode(){
        return ac;
    }

    AreaCode area(int n) {
        switch (n) {
            case 7927: return AreaCode.area1;
            case 7928: return AreaCode.area2;
            case 7929: return AreaCode.area3;
        }
    }
}
</code>```

The code above will not compile. How to make area(int n) work?

答:
Here is another way (using Guava and Java 8) to create a Map for a lookup:</p>

```<code>import com.google.common.collect.Maps;

public enum AreaCode {
  area1(7927),
  area2(7928),
  area3(7929);

  private final int ac;

  private final static Map<Integer, AreaCode> AREA_BY_CODE =
      Maps.uniqueIndex(EnumSet.allOf(AreaCode.class), AreaCode::areaCode);

  AreaCode(int ac) {
    this.ac = ac;
  }

  public static AreaCode area(int n) {
    return AREA_BY_CODE.get(n);
  }

  int areaCode() {
    return ac;
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have written an enum class and I want to either get the attribute by type or get the type by attribute, but it seems impossible.

public enum AreaCode {
    area1(7927),
    area2(7928),
    area3(7929);

    private final int ac;

    AreaCode(int ac) {
        this.ac = ac;
    }

    int areaCode(){
        return ac;
    }

    AreaCode area(int n) {
        switch (n) {
            case 7927: return AreaCode.area1;
            case 7928: return AreaCode.area2;
            case 7929: return AreaCode.area3;
        }
    }
}

The code above will not compile. How to make area(int n) work?

Body:
Here is another way (using Guava and Java 8) to create a Map for a lookup:

import com.google.common.collect.Maps;

public enum AreaCode {
  area1(7927),
  area2(7928),
  area3(7929);

  private final int ac;

  private final static Map<Integer, AreaCode> AREA_BY_CODE =
      Maps.uniqueIndex(EnumSet.allOf(AreaCode.class), AreaCode::areaCode);

  AreaCode(int ac) {
    this.ac = ac;
  }

  public static AreaCode area(int n) {
    return AREA_BY_CODE.get(n);
  }

  int areaCode() {
    return ac;
  }
}


问:
How to prevent Sql-Injection on User-Generated Sql Queries
I have a project (private, ASP.net website, password protected with https) where one of the requirements is that the user be able to enter Sql queries that will directly query the database. I need to be able to allow these queries, while preventing them from doing damage to the database itself, and from accessing or updating data that they shouldn't be able to access/update.

I have come up with the following rules for implementation:

Use a db user that only has permission for Select Table/View and Update Table (thus any other commands like drop/alter/truncate/insert/delete will just not run).

Verify that the statement begins with the words "Select" or "Update"

Verify (using Regex) that there are no instances of semi-colons in the statement that are not surrounded by single-quotes, white space and letters. (The thought here is that the only way that they could include a second query would be to end the first with a semi-colon that is not part of an input string).

Verify (using Regex) that the user has permission to access the tables being queried/updated, included in joins, etc. This includes any subqueries. (Part of the way that this will be accomplished is that the user will be using a set of table names that do not actually exist in the database, part of the query parsing will be to substitute in the correct corresponding table names into the query).

Am I missing anything?

The goal is that the users be able to query/update tables to which they have access in any way that they see fit, and to prevent any accidental or malicious attempts to damage the db. (And since a requirement is that the user generate the sql, I have no way to parametrize the query or sanitize it using any built-in tools that I know of).

答:
The question is, do you trust your users? If your users have had to log into the system, you are using HTTPS & taken precautions against XSS attacks then SQL Injection is a smaller issue. Running the queries under a restricted account ought to be enough if you trust the legitimate users. For years I've been running MyLittleAdmin on the web and have yet to have a problem.

If you run under a properly restricted SQL Account select convert(varchar(50),0x64726F70207461626C652061) won't get very far and you can defend against resource hogging queries by setting a short timeout on your database requests. People could still do incorrect updates, but then that just comes back to do you trust your users?

You are always taking a managed risk attaching any database to the web, but then that's what backups are for.

OwnerDisplayName: Yaakov Ellis

LastEditorDisplayName: Yaakov Ellis

OwnerDisplayName: Martin Brown


问:
How to set separate behaviours for different sets of tabs?
I am developing a functionality where I have different sets of tabs.
And I want every set of tabs to behave by itself. I mean: any of the other set of tabs have to interfere with the behaviour of the other sets.

The only error I have in the code so far is that when you click on any of the tabs of the first set, the content of the select tabs of the other sets disappear.

And I need the first tab of every set to be always selected by default.

Here is a JSFiddle I have created.

$(document).ready(function() {

  $('.tabs a:not(:first)').addClass('inactive');
  $('.container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //this is the start of our condition
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().nextAll('.container').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}</code>```

  test1
  test2
  test3
  test4

1Some content

2Some content

3Some content

4Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content
```

答:
The idea is simple:

Wrap your content with a div just like how you wrap your tabs (otherwise they are all siblings).

Now add inactive to all children of tabs except the 1st child of each tabs

```<code> $(".tabs a:not(:first-child)").addClass('inactive');
</code>```

Target each div content by .tabs + div (which will find next sibling div) then hide all child that are not 1st child of each div

```<code>$(".tabs + div > div:not(:first-child)").hide();
</code>```

When click on tabs, go to parent then go next div find all child (.container) and hide them, then show the id that clicked.

```<code> $(this).parent().next('div').find('.container').hide();
</code>```

Also fixed html you have, there are duplicated ids (make sure id are unique)

$(document).ready(function() {
  $(".tabs a:not(:first-child)").addClass('inactive');
  $(".tabs + div > div:not(:first-child)").hide();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //this is the start of our condition
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().next('div').find('.container').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}</code>```

  test1
  test2
  test3
  test4

1Some content

2Some content

3Some content

4Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content

  test1
  test2
  test3
  test4

9Some content

10Some content

11Some content

12Some content

```

Body:
I am developing a functionality where I have different sets of tabs.
And I want every set of tabs to behave by itself. I mean: any of the other set of tabs have to interfere with the behaviour of the other sets.

The only error I have in the code so far is that when you click on any of the tabs of the first set, the content of the select tabs of the other sets disappear.

And I need the first tab of every set to be always selected by default.

Here is a JSFiddle I have created.

$(document).ready(function() {

  $('.tabs a:not(:first)').addClass('inactive');
  $('.container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //this is the start of our condition
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().nextAll('.container').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});

.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}

  test1
  test2
  test3
  test4

1Some content

2Some content

3Some content

4Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content

  test1
  test2
  test3
  test4

5Some content

6Some content

7Some content

8Some content

Body:
The idea is simple:

Wrap your content with a div just like how you wrap your tabs (otherwise they are all siblings).

Now add inactive to all children of tabs except the 1st child of each tabs

 $(".tabs a:not(:first-child)").addClass('inactive');

Target each div content by .tabs + div (which will find next sibling div) then hide all child that are not 1st child of each div

$(".tabs + div > div:not(:first-child)").hide();

When click on tabs, go to parent then go next div find all child (.container) and hide them, then show the id that clicked.

 $(this).parent().next('div').find('.container').hide();

Also fixed html you have, there are duplicated ids (make sure id are unique)

$(document).ready(function() {
  $(".tabs a:not(:first-child)").addClass('inactive');
  $(".tabs + div > div:not(:first-child)").hide();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //this is the start of our condition
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().next('div').find('.container').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});

.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tabs">
  <a id="tab1">test1</a>
  <a id="tab2">test2</a>
  <a id="tab3">test3</a>
  <a id="tab4">test4</a>
</div>
<div>
  <div class="container" id="tab1C">1Some content</div>
  <div class="container" id="tab2C">2Some content</div>
  <div class="container" id="tab3C">3Some content</div>
  <div class="container" id="tab4C">4Some content</div>
</div>

<div class="tabs">
  <a id="tab5">test1</a>
  <a id="tab6">test2</a>
  <a id="tab7">test3</a>
  <a id="tab8">test4</a>
</div>
<div>
  <div class="container" id="tab5C">5Some content</div>
  <div class="container" id="tab6C">6Some content</div>
  <div class="container" id="tab7C">7Some content</div>
  <div class="container" id="tab8C">8Some content</div>
</div>

<div class="tabs">
  <a id="tab9">test1</a>
  <a id="tab10">test2</a>
  <a id="tab11">test3</a>
  <a id="tab12">test4</a>
</div>
<div>
  <div class="container" id="tab9C">9Some content</div>
  <div class="container" id="tab10C">10Some content</div>
  <div class="container" id="tab11C">11Some content</div>
  <div class="container" id="tab12C">12Some content</div>
</div>


问:
Get specific part of a URL with JavaScript
I'm new to JavaScript, I need help solving a problem.

I have the following URL:

http://localhost/solo04/index.php?route=checkout/checkout#shipping-method

I would like to just get that part of the url (route =checkout/checkout) how to do this?

答:
    var str1 = "http: //localhost/solo04/index.php? Route = checkout / checkout # shipping-method";
    var n = str1.lastIndexOf("?")+1;
    alert(str1.substr(n));```


问:
Java static method vs function
What is difference between this codes in java 8 :

This  :

```<code>public class Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}
</code>```

and this :

```<code>public interface Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}
</code>```

This is main class :

```<code>public class MainClass {
    public static void main(String[] args) {
            Hello.sayHello(); //for function
            Hello.sayHello(); //for class
    }
}
</code>```

答:
In Java 8 you are now allowed to define methods in interfaces.  So technically they are the same.  The difference with interfaces still remains you cannot instantiate them.  So you can only use the methods in them.

Here is link: https://en.wikipedia.org/wiki/Interface_(Java)

It speaks about how interfaces interact now in Java 8.

In your code, it still should call the Hello class method over the interface class method because as I said interfaces can't be instantiated.

Title: Java static method vs function

Body:
What is difference between this codes in java 8 :

This  :

public class Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}

and this :

public interface Hello {
    public static void sayHello() {
        System.out.println("ghasedak.Hello !!!");
    }
}

This is main class :

public class MainClass {
    public static void main(String[] args) {
            Hello.sayHello(); //for function
            Hello.sayHello(); //for class
    }
}


答:
You can create a hyperlink element to accomplish this, simply create it like you normally would but don't append it to the DOM:

```<code>var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"
</code>```

If you then require the query-string, you can parse it using something like:

```<code>function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}
</code>```

In order to get a specific variable.

Credit to jlong & Tarik for the excellent ideas.

Title: Get specific part of a URL with JavaScript

Body:
I'm new to JavaScript, I need help solving a problem.

I have the following URL:

http://localhost/solo04/index.php?route=checkout/checkout#shipping-method

I would like to just get that part of the url (route =checkout/checkout) how to do this?

Body:
You can create a hyperlink element to accomplish this, simply create it like you normally would but don't append it to the DOM:

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.search;   // => "?search=test"
parser.hash;     // => "#hash"
parser.host;     // => "example.com:3000"

If you then require the query-string, you can parse it using something like:

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (decodeURIComponent(pair[0]) == variable) {
            return decodeURIComponent(pair[1]);
        }
    }
    console.log('Query variable %s not found', variable);
}

In order to get a specific variable.

Credit to jlong & Tarik for the excellent ideas.


答:
The easiest way is to use a regex or split:

```<code>url = "http://localhost/solo04/index.php?Route=checkout/checkout#shipping-method";

lastPart = url.split('?')[1]; // grabs the part on the right of the ?

console.log(lastPart);
</code>```

More variants are listed How to get the value from the GET parameters?

Body:
The easiest way is to use a regex or split:

url = "http://localhost/solo04/index.php?Route=checkout/checkout#shipping-method";

lastPart = url.split('?')[1]; // grabs the part on the right of the ?

console.log(lastPart);

More variants are listed How to get the value from the GET parameters?


问:
VB.NET Cross platform app
I make a game using vb.net & wpf. But I want this run on Windows/Linux/Mac.
How can I do it?
I'm sorry my english is really bad :D I use Google translate.</p>

答:
Implementing a solution for multiple platforms is not an easy task and you need to be familiar with all the platforms you plan to support, starting with trivialities such as different path schemes and ending with checking every reference you require by your project settings for its compatibility to the target platform.

Please have a look at http://www.mono-project.com. When you install the mono package to your system, you can run your compiled .exe as it is from the shell under certain circumstances.

Obviously, you need to decide whether you try to create one application that runs on all target platforms OR if you want to create platform specific applications all referencing to the same game engine.

If you stick very close to the framework not using external references, chances are higher to achieve the former. If the main logic of your game can easily be compartmentalized into a dedicated project, the latter is the way to go.

In general, cross-plattform compatibility is more easily to achieve if your application backend consists of a console application to be accessed by a webbrowser installed on the system - using a web frontend though. But as long as you do not require accelerated graphics, this should be feasible.

Title: VB.NET Cross platform app