text:
Q: Output of getSystemClipboard().getString() is not right... (javafx) I highlight text by mouse and press Shift to show a form containing a string from clipboard.
My event pressing shift sends virtual keys (Ctr+C), then I call the function windowsclickandsee() to get highlighted text from clipboard.
But it's wrong.
For example:
In my clipboard already has a string - ("1234").
Step 1: i choose a text - ("hello") and highlight it.
Step 2: i press shift
Result :
Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor) is "1234" and pressing ctr V, i see "hello".
I dont understand. Can anyone help me?
Here's my code
    private void windowsclickandsee()
    {
      Platform.runLater(() -> {
          try {
              root = new StackPane();
              text= new TextArea();
              String temp = (String) Toolkit.getDefaultToolkit()
                      .getSystemClipboard().getData(DataFlavor.stringFlavor);
              root.getChildren().add(text);
              text.appendText("1 "+temp);
              Point p= MouseInfo.getPointerInfo().getLocation();
              Scene scene = new Scene(root,400, 350);
              primaryStage.setScene(scene);
              primaryStage.setX(p.x);
              primaryStage.setY(p.y);
              primaryStage.setAlwaysOnTop(true);
              primaryStage.show();
          } catch (UnsupportedFlavorException ex) {
              Logger.getLogger(Jnativehook.class.getName()).log(Level.SEVERE, null, ex);
          } catch (IOException ex) {
              Logger.getLogger(Jnativehook.class.getName()).log(Level.SEVERE, null, ex);
          }
      });
    }


text:
Q: Find the duplicate in my list, and use it later in the code Hi i am trying to write a code that checks for duplicates in my list. i want to use this duplicate later in the program (its for a puzzle, the one there is two of is the right answer to the puzzle).
I want the "duplicate" to be stored in "i" - that way i can do something like
if i = RGB_orange - do this or that. just an example
I have tried alot of diffrent things. this is the closest i got. Any help is appreciated.
BTW - the contents of that list is diffrent RGB values. coordiantes is another list, its where my program gets its RGB values.
    for x in coordinates:
            rgbvalue = Tappair.getpixel(x)

#            rgblist = [(94, 197, 189), ## just an example
#                   (127, 176, 254),
#                   (233, 131, 78),
#                   (239, 106, 253),
#                   (233, 131, 78),
#                   (225, 81, 99),
#                   (126, 230, 129),
#                   (139, 33, 200)]

            rgblist = []

            rgblist.append(rgbvalue)
            print(rgblist)
            for i in rgblist:
                if rgblist.count(i) == 2:
                    print(i)
                    print("Counted")
                    print(rgblist)
                    break

EDIT: this works:
def tap_the_pair():
if pyautogui.locateCenterOnScreen('TapPair.png', confidence=0.9, region=(689, 250, 640, 1000)) != None:
    Tappair = pyautogui.screenshot(region=(734, 429, 540, 540))
    Tappair.save(r"C:\Users\Andreas\Desktop\pythonProject\WholeTapPair.png")
    print("tap pair game found")

    rgblist = []

   # rgblist.append(rgbvalue)

    rgb_dict = {}

    for x in coordinates:
        rgbvalue = Tappair.getpixel(x)
        if rgbvalue in rgb_dict:
            print(rgbvalue)
            return rgbvalue
        else:
            rgb_dict[rgbvalue] = True

A: You can find the duplicates in your list with:
import collections

rgblist = [(94, 197, 189), (127, 176, 254), (233, 131, 78), (239, 106, 253), (233, 131, 78), (225, 81, 99), (126, 230, 129), (139, 33, 200)]

duplicates = [item for item, count in collections.Counter(rgblist).items() if count > 1]

print(duplicates)

for i in duplicates:
    # Do something with each duplicate

Output:
[(233, 131, 78)]

A: The solution provided in the question also works, but it has a time complexity of O(n^2). A better approach with better time complexity can be to use dictionaries:
rgb_dict = {}

for rgb in rgblist:
    if rgb in rgb_dict:
        print(rgb)
        break
    else:
        rgb_dict[rgb] = True

After the loop ends, rgb will contain the duplicate. This solution has a time complexity of O(n).
Edit: try this code specific to your example. It can be done using a single for loop
rgb_dict = {}

for x in coordinates:
    rgbvalue = Tappair.getpixel(x)
    if rgbvalue in rgb_dict:
        print(rgbvalue)
        return rgbvalue
    else:
         rgb_dict[rgbvalue] = True

redpajama_set_name: RedPajamaStackExchange


text:
Q: Summing over the elements of a group $G$. Can someone explain how are these two expressions equal? Say $\rho$ and $\pi$ are two group homomorphism, $G$ is a non-abelian group and $x$ a fixed element of $G$.
It is written without explanation that $$\sum_{g\in G} \rho(xg)\pi(g^{-1})$$ can be equivalently formulated as $$\sum_{gx\in G}\rho(gx)\pi((xg)^{-1}x).$$ I realize that the index can be changed from $g$ to $gx$ because all the elments of $G$ are covered this way as well. Moreover, I can see that $(xg)^{-1}x = g^{-1}$. What I don't get is how come $xg$ inside of $\rho$ is now changed to $gx$?
Edit: I have run into a similar problem before and I couldn't find the solution there as well. The problem is that $$\sum_{g\in G} \rho(gx) \pi(g)=\sum_{g\in G}\rho(g)\pi(x^{-1}g).$$ This time, the index remains $g\in G$ in both the sums but the rest I don't follow. It is mentioned that we are using the bijection that sends $g$ to $gx$.

A: $g$ is a dummy variable. In particular, if you call
$$h=xgx^{-1}$$
so that $g=x^{-1}hx$.
Then, substituting $g=x^{-1}hx$ you get
$$\sum_{g \in G} \rho (xg) \pi (g^{-1}) = \sum_{h \in G} \rho (x(x^{-1}hx)) \pi ((x^{-1}hx)^{-1})$$
which is equal to
$$\sum_{h \in G} \rho (hx) \pi (x^{-1}h^{-1}x)$$
Now, $h$ is a dummy variable, so you can write again $g$ instead of $h$.

A: In general, this is not true.
Let $G=S_3$, $x=(1\,2)$, and $\rho(g)=1$ if $g=(2\,3)$ and $=0$ otherwise, and $\pi$ any function with $\pi\bigl((1\,3\,2)\bigr)\ne\pi\bigl((1\,2\,3)\bigr)$.
Then the first sum is
$$\sum_{g\in G} \rho(xg)\pi(g^{-1})=\sum_{g=(1\,2\,3)} \rho(xg)\pi(g^{-1})=\rho\bigl((2\,3)\bigr)\pi\bigl((1\,3\,2)\bigr)=\pi\bigl((1\,3\,2)\bigr)$$
whereas the second sum is
$$\sum_{gx\in G}\rho(gx)\pi((xg)^{-1}x)=\sum_{gx=(2\,3)}\rho(gx)\pi((xg)^{-1}x)
=\sum_{g=(1\,3\,2)}\rho(gx)\pi((xg)^{-1}x)=\pi\bigl((1\,2\,3)\bigr). $$


text:
Q: Split by regex on multiple line I have a file document who contains my messages.
I would like to make a split for each message but the format is terrible.

Date: Nov 27 2019 08:35am
From: dsad (123)
Message-Id: 1231
Subject: Hi
Hello1
Date: Nov 27 2019 08:35am
From: dsad (123)
Message-Id: 1232
Subject: Hi
Hello2
Date: Nov 27 2019 08:35am
From: dsad (123)
Message-Id: 1233
Subject: Hi
Hello3

How I can extract the data ?
Something like
private Message {
    DateTime date;
    int fromID;
    int messageID;
    string fromUsername;
    string subject;
    string message;
}

foreach (Message message in messages.Split([...]))
{
    Console.WriteLine(message.messageID);
}

What is the best way to achieve that?
I would like to split on the regex
Date: DATETIME
From: STRING (INT)
Message-Id: INT
Subject: STRING ONE ROW
MESSAGES ON MULTIPLE ROW UNTIL NEXT DATE TIME ROW
Thanks!

A: You could try a regex pattern that encompasses an entire message (tested at https://www.myregextester.com/index.php):
var regex = new Regex(@"
  Date:\s+(?<date>[^\r\n]*)[\r\n]+
  From:\s+(?<fromUsername>.*?)\s+\((?<fromID>\d+)\)[\r\n]+
  Message-Id:\s+(?<messageID>\d+)[\r\n]+
  Subject:\s+(?<subject>[^\r\n]*)[\r\n]+
  (?<message>[^\r\n]*)
", RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);
var messages = regex.Matches(...);

The named capture groups can then help you extract the details you need.


text:
Q: how to use both shadow and opacity for the same div in ie8 I have the following code where I put a link for blocking click events in an iframe.

and the  CSS
  #iframeBlocker {
    background:none transparent ;
    background-color:White;
    bottom: 0px;
    color: White;
    filter:alpha(opacity=10);
    opacity: 0.1;
    display: block;
    left: 0px;
    position: absolute;
    right: 0px;
    top: 0px;
    z-index: 1040;
     -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";
    }

My problem is. I cant use both opacity and shadow for my div. If i use the css ie code for enabling shadow, it doesnt take the opacity.
any workaround for using both shadow and opacity for a div in IE ?

A: Maybe try instead of opacity using rgba() if that fits your needs.
#iframeBlocker {
   background:rgba(255, 255, 255, 0.1);
}

A: IE8 does not have good support for either opacity or shadows.
Both features are sort-of supported via the -ms-filter/filter style, as you've already got in your code, but it's not standards-compliant, and it's not particularly good; filer has lots of bugs and quirks that can make them difficult to use.
In theory, if you want to use more than one filter style, you need to combine them into a single declaration:
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=10)
            progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";

(see also: Multiple CSS filters in IE)
@insertusernamehere's answer was nearly right, but he missed the quotes around the style, and it doesn't require a comma between them; just a space.
If that works for you, then good news. However, you still need to be careful, because the various filter styles that IE supports do have a lot of known issues, and are known to have some strange results when used in combination. You need to test carefully if you're going to go down this route.
It's worth also pointing out the popular CSS3Pie library which polyfills various CSS3 features, including box-shadow. It's worth noting that they do not currently support opacity, and the reason for that is largely because of difficulties they've had getting it to work in conjunction with the other features they support.
So after all that, my final suggestion is to drop the requirement for a drop shadow in IE8. Ultimately, it's just eye-candy so it won't affect the usability of your site if its missing, and it will cause you a lot of trouble trying to get it working.

A: You can't have multiple CSS filter rules but you can list multiple filters within a single rule:
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=10)
            progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";

Read more on the MSDN: Creating Multimedia Effects with Visual Filters and Transitions.

A: I finally found the way. Was rather simple.
just added the css for adding shadow to IE8 to the enclosing div "Iframewrapper"
  #IframeWrapper {

        -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";
    }

So instead of adding both the css for opacity and shadow in same div, it works if they are in differnt div's.


text:
Q: What's the use of second parameter of std::enable_if? I am confused about the second parameter of std::enable_if.
In using of a return type of int, we can make it using:
template <class T>
typename std::enable_if<mpi::is_builtin<T>::value, int>::type
foo() { return 1; }

But how can I use enable_if in paramter or template? In this case, what's the difference of too functions below:
template<class T ,
       class = typename std::enable_if<std::is_integral<T>::value>::type >
T too(T t) { std::cout << "here" << std::endl; return t; }

int too(int t) { std::cout << "there" << std::endl; return t; }

Thanks.

A: It means that in case of
template<class T ,
   class = typename std::enable_if<std::is_integral<T>::value>::type >

it becomes
template<class T ,
   class = void >

if the condition std::is_integral<T>::value is true, hence the function is allowed for the type T and therefore participates in overload resolution.
If the condition is not met, it becomes illegal and the typename std::enable_if<...>::type invalidates the function for the type T. In your example, the first method allows all integral types (int, unsigned, long, ...) but no classes, etc.
The second, int-only version in your example would loose some information and convert values from unsigned to signed or narrow some values, which is why the first version can be really helpful in some cases.
Note that void is actually the default for the second parameter of std::enable_if, which is often sufficient to enable or disable templates, etc. as you don't really need a specific type. All you need to know/detect is, whether or not it is valid (void) or invalid, in which case there is no valid substitution for the ::type part.

A:
what's the difference of too functions below:

One is a template that can be called for any CopyConstructible type, the enable_if only constrains it when the default template argument is used:
#include <iostream>

template<class T ,
       class = typename std::enable_if<std::is_integral<T>::value>::type >
T too(T t) { std::cout << "here" << std::endl; return t; }

int too(int t) { std::cout << "there" << std::endl; return t; }

int main()
{
    too<double, void>(1.0);
}


text:
Q: Local int vs Global int in C I read that:

in C, local variables start with unknown value

and I decided to check it, that's what I did:
Three results of the same program: 1, 2, 3.
Question 1: Why unknown value in 1, or why global int was 0 and local int was 1?
Question 2: Why local unsigned int with each new start was different?
Question 3: Is global/local char ' '? char ch = ' '; // something like that
Question 4: Why global and local start with different values (if they are not initialised)? For what?
Source code: (I used clang (v10.0.0) for compiling)
#include <stdio.h>

int global_int;
unsigned int global_unsint;
char global_char;

int main()
{
  int local_int;
  unsigned int local_unsint;
  char local_char;

  printf ("Global int: %d \t unsigned_int: %u \t char: %c\n", global_int, global_unsint, global_char);
  printf ("Local int: %d \t unsigned_int: %u \t char: %c\n", local_int, local_unsint, local_char);
}

A:
local variables start with unknown value

Not entirely true. Local variables with automatic storage duration do; static variables are initialized at zero. As it happens, all the local variables in main() in your code snippet have automatic storage duration.

Why unknown value it's 1, or why global int was 0 and local int was 1?

Global variables have static storage duration. This means they are implicitly initialized at zero on program startup.  Local variables with automatic storage duration have undefined values until they are explicitly initialized.

Why local unsigned_int with each new start was different?

That's undefined behavior for you. All bets are off.

Is global/local char was ' ' ?

No. The global char is implicitly initialized as '\0' on program startup; the local char has an undefined value.

Why global and local start with different values (if they are not initialised)? For what?

Because of rules for initialization of objects with static storage duration and automatic storage duration.

A: Accessing uninitialized (or previously unassigned) variable invokes Undefined Behavior.
Anything can happen; for example

*

*your compiler may produce an executable

*your executable may "run"

*running your executable may appear to work as expected

*the values printed may be reasoned for

or none of the above, depending on the phase of the moon, the compiler flags, what other programs are running on your computer at the same time, ..., ..., ...

A: To better understand what is going on you should know that most architectures use a stack on which the local, automatic variables are allocated. With each function called ("invoked"), some storage of the stack is used and upon each function return that storage is available again.
That means that the automatic variables of a function use stack space that has been used before (by another function) and because these variables are not initialized by the compiler or run-time system, they contain values from earlier function invocations. So for your function, their values are undefined.

A: global_int, global_unsint, global_char are the global variable. They will be located in the bss segment. The OS kernel will simply maps them to Copy-On-Write with pages of zero values for saving the paging processing on OS-side. That's why you always see the values of them are zero.
local_int, unsigned int local_unsint, `local_charq are the automatic variable. They will be located on stack segment of the main function. The values of them is not know exactly. They depends on memory location on the stack  that they were assigned in the run-time. So we can not trust the initialized values for automatic variable.


text:
Q: How to fix product image upload in Magento 1.4.1.1? I am facing issue while uploading the product images in Magento ver. 1.4.1.1 from admin. When I try to upload the image I do not get any error but the images are not visible in the front end as well as in the admin section of Magento.
I am able to see the message like following screenshot.

I have following folder created
/media/tmp/catalog/product

Under this folder the images are visible.
The issue is happening on windows 7, xampp server.
On my Linux environment it is working fine.
Please help me to fix the issue.


text:
Q: how to bordered a single button on selected in list I have a list of buttons,
I would like to select one of them and the red bordered appear onClick.
once click again, border disappear. How can I achieved that?
As far as I did, when I click it circle all the button in list at once.
please kindly teach me.

A: First you will have to create a stateful widget for your button, that keeps track of if it should show the border or not. This is what it should look like:
class MyButton extends StatefulWidget {
  @override
  _MyButtonState createState() => _MyButtonState();

  final Widget child;
  final void Function() onPressed;
  final Key key;
  final Color buttonPrimaryColor, buttonOnPrimaryColor, borderColor;
  final double borderWidth;
  MyButton({
    @required this.child,
    this.onPressed,
    this.key,
    this.borderColor = Colors.red,
    this.buttonPrimaryColor,
    this.buttonOnPrimaryColor,
    this.borderWidth = 1.0,
  });
}

class _MyButtonState extends State<MyButton> {
  bool showBorder = false;
  void toggleShowBorder() => setState(() => showBorder = !showBorder);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      key: widget.key,
      onPressed: widget.onPressed == null
          ? null
          : () {
              toggleShowBorder();
              widget.onPressed();
            },
      child: widget.child,
      style: ButtonStyle(
        // If showBorder == true, we show a red border
        shape: MaterialStateProperty.resolveWith(
          (_) => showBorder
              ? RoundedRectangleBorder(
                  borderRadius: BorderRadius.zero,
                  side: BorderSide(
                    color: widget.borderColor,
                    width: widget.borderWidth,
                  ),
                )
              : RoundedRectangleBorder(),
        ),
      ).merge(
        ElevatedButton.styleFrom(
          primary: widget.buttonPrimaryColor ??
              Theme.of(context).buttonTheme.colorScheme.primary,
          onPrimary: widget.buttonOnPrimaryColor ??
              Theme.of(context).buttonTheme.colorScheme.onPrimary,
        ),
      ),
    );
  }
}

The usage is very simple:
MyButton(
  child: Text('Press me'),
  onPressed: () {},
),

If you want to change the button's color you can do it by passing in parameters:
MyButton(
  borderColor: Colors.amber,
  buttonPrimaryColor: Colors.white,
  buttonOnPrimaryColor: Colors.black,
  child: Text('Press me'),
  onPressed: () {},
),

Use buttonPrimaryColor for the button's background color
Use buttonOnPrimaryColor for the button's foreground color
Use borderColor for the button's border color (it is red by default)
You can also change the border width, using the borderWidth parameter, like this: (it is 1.0 by default)
MyButton(
  borderWidth: 4.0,
  child: Text('Press me'),
  onPressed: () {},
),

It would also be a good idea to pass in a key parameter since you are working
with a list of buttons, like this:
MyButton(
  key: Key('some unique key'),
  child: Text('Press me'),
  onPressed: () {},
),

The key should be a unique string.


text:
Q: Size of the screens in float Because the graphics functions (such as "drawLine") require you to type parameters in "float" and not in "int"?
Perhaps because the size of the various Android devices vary in "int" as they are always the same in "float"?

A: Ultimately, drawing is done through a GPU that does all its calculations using floating point types.  This is also what allows things like subpixel rendering to work.  Also, you are free to do a series of complex computations using floats without having to worry about whether or not it's better to round up or down for the current display type. Android will handle that for you with the float you provide.
It is true that Android is not consistent in asking for float or int, but when the measurement is for raw pixels, they are still measuring the exact same thing, so the measurement for floating point pixels of 5.0 is the same as int 5.


text:
Q: RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb I'm trying to learn Machine Learning, but I cannot resolve below error.
[My environment]

*

*Mac High Sierra 10.13.2

*Python3.4.5

*Numpy1.13.3

[Command]
$ python3 -c "import jupyter, matplotlib, numpy, pandas, scipy, sklearn"

[Error]
RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb
Traceback (most recent call last):
  File "/Users/uekyo/ml/env/lib/python3.4/site-packages/pandas/__init__.py", line 26, in <module>
    from pandas._libs import (hashtable as _hashtable,
  File "/Users/uekyo/ml/env/lib/python3.4/site-packages/pandas/_libs/__init__.py", line 4, in <module>
    from .tslib import iNaT, NaT, Timestamp, Timedelta, OutOfBoundsDatetime
  File "pandas/_libs/tslib.pyx", line 1, in init pandas._libs.tslib
ImportError: numpy.core.multiarray failed to import

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/uekyo/ml/env/lib/python3.4/site-packages/pandas/__init__.py", line 35, in <module>
    "the C extensions first.".format(module))
ImportError: C extension: numpy.core.multiarray failed to import not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace --force' to build the C extensions first.

[Things I tried]
I understood numpy is wrong. So I tried below things, but the error still appears.
~1~
sudo mv /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy_old

~2~
pip3 uninstall numpy
pip3 install numpy  -I

Thanks.

A: Most likely due to version of numpy too low; this one solved my problem:
pip3 install "numpy == 1.15.0" --user

conda install can't solve because currently it only have numpy version 1.13.1, but is may due to my mirror site choosen is not the latest

A: Base on currently installed tensorflow or sklearn packages, there might be some incompatibility. You should try different numpy version. BTW, in my case, downgrading from 1.18 to 1.15 fixed the problem.
pip install "numpy == 1.15.0"

A: Seems like this is due to pandas version higher than 0.21.0 and numpy version 1.13.3 that is pulled by TensorFlow not playing well together.
Here is how I fixed it in my end:
# ipython
Python 2.7.6 (default, Nov 23 2017, 15:49:48)
Type "copyright", "credits" or "license" for more information.

IPython 4.2.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import tensorflow as tf
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb

In [2]: !pip install pandas==0.21.0
Collecting pandas==0.21.0
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request
has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server
to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve
 this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLC
ontext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to f
ail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest
/security.html#insecureplatformwarning.
  InsecurePlatformWarning
  Downloading pandas-0.21.0-cp27-cp27mu-manylinux1_x86_64.whl (24.3MB)
    100% |################################| 24.3MB 52kB/s
Requirement already satisfied: pytz>=2011k in /usr/local/lib/python2.7/dist-packages (from pandas==0.21.0)
Requirement already satisfied: numpy>=1.9.0 in /usr/local/lib/python2.7/dist-packages (from pandas==0.21.0)
Requirement already satisfied: python-dateutil in /usr/local/lib/python2.7/dist-packages (from pandas==0.21.0)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python2.7/dist-packages (from python-dateutil->pandas==0.21.0)
Installing collected packages: pandas
  Found existing installation: pandas 0.21.1
    Uninstalling pandas-0.21.1:
      Successfully uninstalled pandas-0.21.1
Successfully installed pandas-0.21.0

In [3]: del tf

In [4]: import tensorflow as tf

A: I had same issue. If you are using anaconda simply type
conda update tensorflow
This should fix the issue.


text:
Q: Get next value in PHP In an XML file i have some attributes
<logoSize logoSizeCm2="6">
<logoSize logoSizeCm2="24">
<logoSize logoSizeCm2="60">
<logoSize logoSizeCm2="120">
<logoSize logoSizeCm2="240">

What i want is to get every logoSizeCm2 value that is lower than $prpurlNumber plus the next one.
foreach ($XMLB->logoSize as $prodar) {
   $prodb = $prodar[0];
   $pripurl = $prodb->xpath("@logoSizeCm2");
   $prpurlNumber = '65';
   if ($pripurl <= $prpurlNumber) {
      echo $prpurl;
   }
}

This outputs 6 24 60 but what i want is to also get the next one like this  6 24 60 120
Any help would be much appreciated.

A: If they will always be in ascending order
$prpurlNumber = '65';
foreach ($XMLB->logoSize as $prodar) {
    $prodb = $prodar[0];
    $pripurl = $prodb->xpath("@logoSizeCm2");

    if ($pripurl <= $prpurlNumber) {
        echo $prpurl;
    }
    if ($pripurl > $prpurlNumber) {
        echo $prpurl;
        break;  // to exit the loop
    }
}


text:
Q: .each not iterating over nested arrays For some reason, this is not iterating over the collection. Throwing a pry in there shows that only the first index is getting looked at. [0,1,2] I'm sure I'm just tired and it's something small, but I'm drawing a black here,
WIN_COMBINATIONS = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
]

def won?(board)
  WIN_COMBINATIONS.each do |combo|
    if board[combo[0]] != " " && board[combo[0]] == board[combo[1]] && board[combo[0]] == board[combo[2]]
      return combo
    else
      return false
    end
  end
end

A: def won?(board)
  WIN_COMBINATIONS.any? do |combo|
    board[combo[0]] != " " &&
      board[combo[0]] == board[combo[1]] &&
      board[combo[0]] == board[combo[2]]
  end
end

or, even more succinct with Array#values_at:
def won?(board)
  WIN_COMBINATIONS.any? do |combo|
    [%w|X| * 3, %w|O| * 3].include? board.values_at(*combo)
  end
end

A: The reason is that you return from your method on the first iteration.
Inside your iteration you always return after the first step. Just put the return false statement after your iteration and it will work.

A: Just three more solutions along with test code checking them against each other:
def won1?(board)
  WIN_COMBINATIONS.any? do |i, j, k|
    board[i] != " " && board[i] == board[j] && board[i] == board[k]
  end
end

def won2?(board)
  WIN_COMBINATIONS.any? do |combo|
    a, b = board.values_at(*combo).minmax; a != " " && a == b
  end
end

def won3?(board)
  WIN_COMBINATIONS.any? do |combo|
    [["X"], ["O"]].member?(board.values_at(*combo).uniq)
  end
end

WIN_COMBINATIONS = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
]

a = ["O", "X", " "]
a.product(*([a] * 8)).each { |board|
  w1 = won1?(board)
  w2 = won2?(board)
  w3 = won3?(board)
  p [w1, w2, w3, board] if w2 != w1 || w3 != w1
}


text:
Q: Cannot open github.com and some other websites I use Ubuntu 14.04. I cannot open github.com and many other websites since two weeks, I tried opening in my laptop and phone but nothing works.
I also tried in many browsers (Chrome, Firefox, Ubuntu's built-in browser) but nothing works. Is it a problem in my router's IP address or internet service provider? Because I use internet in phone and laptop via router.
I have a TP-Link router and service from BSNL.

A: If the ISP has only blocked the DNS in their servers then you can change your router to use one of the public DNS providers, eg: Google 8.8.8.8 / 8.8.4.4 or OpenDNS 208.67.222.222 / 208.67.220.220


text:
Q: Nesting a parent child relationship in lodash, given the parent id and children How would I be able to nest json object if the parent and its children was given as a property.
The data looks like:
   "1": {
        "id": 1,
        "name": "foo",
        "parent": null,
        "root": 1,
        "children": [2, 4, 6],
        "posts":[
            { "id": "1", "name": "item1" },
            { "id": "2", "name": "item2" },
            { "id": "3", "name": "item3" }
        ]
    },
    "2": {
        "id": 2,
        "name": "bar",
        "parent": 1,
        "root": 1,
        "children": null,
        "posts":[
            { "id": "4", "name": "item4" }
        ]
    },
    "3": {
        "id": 3,
        "name": "bazz",
        "parent": null,
        "root": 3,
        "children": [5, 7],
        "posts":[
            { "id": "5", "name": "item5" },
            { "id": "6", "name": "item6" }
        ]
    },
   ....

A simple groupby using lodash won't do it.
var group = _.groupBy(data, 'parent');

Here is a fiddle:
http://jsfiddle.net/tzugzo8a/1/
The context of question is a nested categories with subcategories, and categories can have categories and posts in them.
Basically I don't want to have a different property for children and posts, since they are all children of a parent.
Desired output
    "1": {
        "id": 1,
        "name": "foo",
        "parent": null,
        "root": 1,
        "isCategory": true,
        "children": [
             {
                 "id": 2,
                 "name": "bar",
                 "parent": 1,
                 "root": 1,
                 "isCategory": true,
                 "children": null
             },
             { "id": "1", "name": "item1", isCategory: false },
             { "id": "2", "name": "item2", isCategory: false },
             { "id": "3", "name": "item3", isCategory: false }

        ]
        ...
    }

A: This is my take on the question (fiddle):
var data = getData();

var group = getTree(data);

console.log(group);

function getTree(flat) {
    return _.reduce(flat, function (treeObj, item, prop, flatTree) {
        var children = _.map(item.children, function (childId) {
            return _.set(flatTree[childId], 'isCategory', true);
        }).concat(_.map(item.items, function(item) {
            return _.set(item, 'isCategory', false);
        }));

        item.children = !!children.length ? children : null;

        delete item.items;

        item.parent === null && (treeObj[prop] = item);

        return treeObj;
    }, {});
}

A: Take a look on the updated fiddle:
var data = getData();

_.keys(data).forEach(function(id){
    var element = data[id];
    if (element.children === null){
        element.children = [];
    }

    element.isCategory = true;
    element.items.forEach(function(item){
        item.isCategory = false;
    })
});

_.keys(data).forEach(function(id){
    var element = data[id];
    element.children = element.children.map(function(childId){
      return data[childId];
    }).concat(element.items);
});

_.keys(data).forEach(function(id){
    delete data[id].items;
});

console.log(JSON.stringify(_.findWhere(_.values(data), {'parent': null})));


text:
Q: running variable created by taking data-id So i am making a site with clickable images that link to a link for instance youtube.com.
I want to make 1 function for all links so i came up with putting the variable name inside the data-id and then trying to run the variable.
Any ideas why this won't work?
It does print $youtube but how can i use that printed variable.

     $(document).ready(function(){

    $youtube = "https://www.youtube.com/";
    $gmail = "";

    $(".linkicon").click(function(){
        $element = "$"+ $(this).data("id");
        window.open($element,"_self");
    });

    });

YouTube

A: The issue is because you cannot dynamically access variables in the manner you're attempting.
To workaround this you could store the data-id as the key of an object and have the URL as the value. Then you can use bracket notation to access the object, like this:

$(document).ready(function() {
  var links = {
    youtube: 'https://www.youtube.com/',
    gmail: ''
  }

  $(".linkicon").click(function() {
    var $element = links[$(this).data("id")];
    window.open($element, "_self");
  });
});

YouTube

You should however note that this approach is completely non-compliant in terms of accessibility guidelines, as you're using a div as an element which triggers an action.
Also note that the $ prefix on JS variables is generally used to denote that the value is a jQuery object, not a string.


text:
Q: Refreshing a page after certain delay in jquery here's my problem: i need to display a message for a while, and then reload the page.
can someone tell me how to reload a page, after certain delay?

A: You may try this without js, it cycles:
<meta http-equiv="refresh" content="5"/>

Page refersh in every 5 seconds...

You can even navigate to a different page, visiting google home page
<meta http-equiv="refresh" content="5;http://www.google.com"/>

Redirecting in 5 seconds...

A: You don't even need jQuery or HTML5 for this:
setTimeout(location.reload.bind(location), 60000);

This will wait 1 minute (60,000 milliseconds), then call the location.reload function, which is a built-in function to refresh the page.

A: setTimeout(function(){
    window.location.reload(); // you can pass true to reload function to ignore the client cache and reload from the server
},delayTime); //delayTime should be written in milliseconds e.g. 1000 which equals 1 second

Update:
One-liner using ES6:
setTimeout(() => window.location.reload(), delayTime);


text:
Q: Using addClass to show an interval I'm attempting to show an interval within a bar. Initially I was using the jQuery plugin for range, but it did not work like I wanted.
I have several different bulleted pointed within my bar. Whenever someone clicks within or near the point (in the class sliderInterval) I want the class rangeSection to be added to that area, basically showing that certain interval active. However, the rangeSection doesn't even show up, nor I am certain I am doing this correctly.
In addition, since I am doing this with intervals. I want to be able to give those intervals values, so that when one is selected I can display that value.
This is what I am trying to get it to look like:

I added a snippet to show what I have done so far. Any advise?

$(function interval() {
  $(".slideInterval").click(function() {
    $(this).addClass(".rangeSection");
  });
});
#sliderBar {
  border-radius: 15px;
  width: 90%;
  height: auto;
  margin: 25px 10%;
  background: blue;
}
.rangeSection {
  width: 100px;
  height: 100%;
  color: purple;
  position: absolute;
  z-index: 1;
}
.intervalCircle {
  border-radius: 50%;
  height: 15px;
  width: 15px;
  background: red;
  z-index: 1;
  position: absolute;
}
.sliderInterval {
  display: inline-block;
  padding: 10px 8%;
}
.sliderInterval:first-child {
  padding-left: 0;
}
.intervalCircle:first-child {
  padding-left: 0;
}

A: try this one.
You can use the .ready(); function of the jQuery library and set the .click() listener on all the .sliderInterval elements. I added the active class as well.
try it here:
https://jsfiddle.net/8cxLLts1/
$(document).ready(function(){
    $(".sliderInterval").click(function() {
       $(this).addClass("active");
    });
});

EDIT: actually, if you use toggleClass() instead of addClass(), you'll be able to turn on and off a specific section

A: Using onclick in your html attribute and then binding a click event also in js could be considered redundant and unnecessary. Try removing the onclick attribute from your html and then adjust your js like so:
$(document).ready(function(){
})
.on('click', '.sliderInterval', function(){
    $(this).addClass(".rangeSection");
});

Bind it to the document itself and this will help with your event delegation naturally. Also, take care to double check your class names - your js is missing the 'r' in '.sliderInterval'.


text:
Q: django - post form on select I made a simple django form, with a list of choices (in radio buttons):
class MyForm(forms.Form):
            choices=forms.ChoiceField( widget=forms.RadioSelect(), choices=[(k,k) for k in ['one','two','three']],label="choose one")

I would like the form to submit automatically when a user selects one of the options. In straightforward HTML I would've done it as
  <select name='myselect' onChange="FORM_NAME.submit();">
    ....
  </select>

But I do not know how to integrate this into the form class without writing a template. Specifically, I would need to know FORM_NAME so I can call FORM_NAME.submit() in the above snippet.
Can it be done without using a template?

A: I think you do not need to know the form name. This should work as well:
<select name='myselect' onChange="this.form.submit();">

A quick solution to integrate this into your form would involve adding a attribute to your widget.
widget=forms.RadioSelect(attrs={'onchange': 'this.form.submit();'})

Now one could argue if this isn't better separated from your form definition (separating definition, style and behaviour), but that should do it.


text:
Q: Rails4 and Bootstrap: responsive design doesn't work Although I tried the code below, these contents are arranged in tandem like this;
side1
.
.
.
contents from yield
.
.
.
side2

How can I display like this?
side1... contents from yield... side2

On the other hand, class="table table-striped" works, for example.
I have been tried to modify the source created by others.
It would be appreciated if you could give me where I should check.
application.html.erb

side1

<%= notice %>

<%= alert %>

        <%= yield %>

side2

Although I tried col-xs, I found the same result.
custom.css.scss
@import "bootstrap";

Gemfile
gem 'bootstrap-sass', '2.3.2.0'

application.css
 *= require_tree .
 *= require_self

A: Can you check if custom.css.scss has been added to application.css.scss and that application.css is loaded in the layout page?
EDIT:
According to this for the bootstrap version: bootstrap docs, perhaps you should use

 syntax.


text:
Q: How to modify Rad Studio Community Edition During the setup of Embarcadero Rad Studio 10.2.3 Community Edition I did not select the Interbase Express components. Now I want to install those components, but could not find a way to modify the installation to select those components.
How can I modify a RAD Studio Community Edition installation after the initial setup?

A: RAD Studio can be installed either from the web installer or from the ISO image. While the ISO installation provides a Modify option like any other MSI setup, the web installer uses a different approach.
Installations done with the web installer have an additional menu item in the IDE under Tools named Manage Platforms, which opens the setup selection dialog already seen during the initial installation. There you can select (and deselect) other platforms and components.
As the Community Edition can only be installed with the web installer, everything said about that one also holds true for a Community Edition installation.


text:
Q: Set an enum value of the class I have a class namely OrderProviderData provided below,
public class OrderProviderData {

    public enum TradingInterface {CX_CLIENT, CX_SERVER, CX_ADMIN, CX_ENGINE}

    private boolean easyTrade = false;

    private OrderPreSelect order;
    private String[] event;

    public OrderPreSelect getOrder() {
        return order;
    }

    public void setOrder(OrderPreSelect order) {
        this.order = order;
    }

    public String[] getEvent() {
        return event;
    }

    public void setEvent(String[] event) {
        this.event = event;
    }
}

I would like to set the values for the OrderProviderData instance in the
receiveEvent method based on some conditions.
public final class OrderProvider extends BlockingDatabaseOrderWorker {

    // some code to initiate here

    @Override
    public final Object receiveEvent() throws Exception {

        OrderProviderData data = null;

        // get + store the TradingInterface value "tradingIf" here
        // set the value inside the "switch" condition

        switch(tradingIf){

            data = new OrderProviderData();

            // set the TradingInterface here
            case value1:
               //set
               break;  //optional

            case value2:
              //set
              break;  //optional

            default:
               // some code
         }
    }

    // varify whether the easyTrade is true
    // set the boolean
}

How do I write it properly? I'm open to better advise too.

A: *

*Add the enum as field to your class. You are only defining the enum itself. (getter and setter are needed as well)
public class OrderProviderData {
public enum TradingInterface {CX_CLIENT, CX_SERVER, CX_ADMIN, CX_ENGINE}

private boolean easyTrade = false;

private TradingInterface tradingInterface;

private OrderPreSelect order;
private String[] event;

public OrderPreSelect getOrder() {
    return order;
}

public void setOrder(OrderPreSelect order) {
    this.order = order;
}

public String[] getEvent() {
    return event;
}

public void setEvent(String[] event) {
    this.event = event;
}

public TradingInterface getTradingInterface() {
    return tradingInterface;
}

public void setTradingInterface(TradingInterface tradingInterface) {
    this.tradingInterface = tradingInterface;
}

}
then you can switch over the cases (which are the values of the enum). You can't place code between switch and first case
@Override
public final Object receiveEvent() throws Exception {
    Server f = new Server();

    switch (f.getInf()) {
    case CX_CLIENT:
        // set
        break; // optional

    case CX_SERVER:
        // set
        break; // optional

    default:
        // some code
    }

}


text:
Q: Orangehrm:Create new menu function I am new to symfony framework. Now I am customizing orangehrm to suit certain new requirements.
For example: Similar to Admin>Qualifications>skills menu, I need to create Admin>Qualifications>Category.I have made the menu modifications by editing index.php file.
The functionality for this new page is similar to 'Skill' page.But we need to use different database table. Orangehrm uses doctrine for database related operation. I am not at all familiar with doctrine either.
Could someone please give the instructions for implementing 'Admin>Qualifications>Category' function? It is very urgent and I think the process is also very simple (not sure).

A: First you have to add your menu in database then create classes in your specific module.
Step 1: Check in which module do you want to add your menu.
        module list is in ohrm_module table.
Step 2: Check under what user roll you want to add menu.
        user roll is in ohrm_user_role.
Step 3: Add Screen on bases of module (step 1).
        insert data into ohrm_screen
step 4: Add Menu Item on bases of Screen (step 3).
        insert into ohrm_menu_item
Step 5: Assign screen to user on bases of user roll (step 2) and screen (step 3).
        insert into ohrm_user_role_screen
Step 6: Logout and login again. New menu will be there.
Step 7: Go to your plugin folder and create your controller in action folder like this
        class YourLinkNameAction extends sfAction {
        //SANI: Start all coding in execute method
        }
Step 8: Create your View in template folder like this
        YourLinkNameSuccess.php
That's all


text:
Q: How to get URL parameter using jQuery or plain JavaScript? I have seen lots of jQuery examples where parameter size and name are unknown.
My URL is only going to ever have 1 string:
http://example.com?sent=yes

I just want to detect:

*

*Does sent exist?

*Is it equal to "yes"?

A: I hope this will help.

A: Solution from 2023
We have: http://example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)

Does sent exist?
searchParams.has('sent') // true

Is it equal to "yes"?
let param = searchParams.get('sent')

and then just compare it.

A: Yet another alternative function...
function param(name) {
    return (location.search.split(name + '=')[1] || '').split('&')[0];
}

A: Try this working demo http://jsfiddle.net/xy7cX/
API:

*

*inArray : http://api.jquery.com/jQuery.inArray/
This should help :)
code
var url = "http://myurl.com?sent=yes"

var pieces = url.split("?");
alert(pieces[1] + " ===== " + $.inArray("sent=yes", pieces));

A: This will give you a nice object to work with
    function queryParameters () {
        var result = {};

        var params = window.location.search.split(/\?|\&/);

        params.forEach( function(it) {
            if (it) {
                var param = it.split("=");
                result[param[0]] = param[1];
            }
        });

        return result;
    }

And then;
    if (queryParameters().sent === 'yes') { .....

A: This might be overkill, but there is a pretty popular library now available for parsing URIs, called URI.js.
Example

var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow";
var components = URI.parse(uri);
var query = URI.parseQuery(components['query']);
document.getElementById("result").innerHTML = "URI = " + uri;
document.getElementById("result").innerHTML += "
technology = " + query['technology'];

// If you look in your console, you will see that this library generates a JS array for multi-valued queries!
console.log(query['technology']);
console.log(query['blog']);

A:

function GetRequestParam(param)
{
 var res = null;
 try{
  var qs = decodeURIComponent(window.location.search.substring(1));//get everything after then '?' in URI
  var ar = qs.split('&');
  $.each(ar, function(a, b){
   var kv = b.split('=');
   if(param === kv[0]){
    res = kv[1];
    return false;//break loop
   }
  });
 }catch(e){}
 return res;
}

A: Using URLSearchParams:
var params = new window.URLSearchParams(window.location.search);
console.log(params.get('name'));

Be careful about the compatibility (Mostly it's fine, but IE and Edge, may be different story, check this for compatible reference: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)

A: May be its too late. But this method is very easy and simple

A: Best solution here.
var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
};

And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');

A: This one is simple and worked for me
$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

so if your url is http://www.yoursite.com?city=4
try this
console.log($.urlParam('city'));

A: Perhaps you might want to give Dentist JS a look? (disclaimer: I wrote the code)
code:
document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"

with Dentist JS, you can basically call the extract() function on all strings (e.g., document.URL.extract() ) and you get back a HashMap of all parameters found. It's also customizable to deal with delimiters and all.
Minified version < 1kb

A: I always stick this as one line. Now params has the vars:
params={};location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v})

multi-lined:
var params={};
window.location.search
  .replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
    params[key] = value;
  }
);

as a function
function getSearchParams(k){
 var p={};
 location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
 return k?p[k]:p;
}

which you could use as:
getSearchParams()  //returns {key1:val1, key2:val2}

or
getSearchParams("key1")  //returns val1

A: Coffeescript version of Sameer's answer
getUrlParameter = (sParam) ->
  sPageURL = window.location.search.substring(1)
  sURLVariables = sPageURL.split('&')
  i = 0
  while i < sURLVariables.length
    sParameterName = sURLVariables[i].split('=')
    if sParameterName[0] == sParam
      return sParameterName[1]
    i++

A: A slight improvement to Sameer's answer, cache params into closure to avoid parsing and looping through all parameters each time calling
var getURLParam = (function() {
    var paramStr = decodeURIComponent(window.location.search).substring(1);
    var paramSegs = paramStr.split('&');
    var params = [];
    for(var i = 0; i < paramSegs.length; i++) {
        var paramSeg = paramSegs[i].split('=');
        params[paramSeg[0]] = paramSeg[1];
    }
    console.log(params);
    return function(key) {
        return params[key];
    }
})();

A: I use this and it works.
http://codesheet.org/codesheet/NF246Tzs
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
    });
return vars;
}

var first = getUrlVars()["id"];

A: With vanilla JavaScript, you could easily take the params (location.search), get the substring (without the ?) and turn it into an array, by splitting it by '&'.
As you iterate through urlParams, you could then split the string again with '=' and add it to the 'params' object as object[elmement[0]] = element[1].  Super simple and easy to access.
http://www.website.com/?error=userError&type=handwritten
            var urlParams = location.search.substring(1).split('&'),
                params = {};

            urlParams.forEach(function(el){
                var tmpArr = el.split('=');
                params[tmpArr[0]] = tmpArr[1];
            });

            var error = params['error'];
            var type = params['type'];

A: What if there is & in URL parameter like filename="p&g.html"&uid=66
In this case the 1st function will not work properly. So I modified the code
function getUrlParameter(sParam) {
    var sURLVariables = window.location.search.substring(1).split('&'), sParameterName, i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
}

A: Admittedly I'm adding my answer to an over-answered question, but this has the advantages of:
-- Not depending on any outside libraries, including jQuery
-- Not polluting global function namespace, by extending 'String'
-- Not creating any global data and doing unnecessary processing after match found
-- Handling encoding issues, and accepting (assuming) non-encoded parameter name
-- Avoiding explicit for loops
String.prototype.urlParamValue = function() {
    var desiredVal = null;
    var paramName = this.valueOf();
    window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
        var nameVal = currentValue.split('=');
        if ( decodeURIComponent(nameVal[0]) === paramName ) {
            desiredVal = decodeURIComponent(nameVal[1]);
            return true;
        }
        return false;
    });
    return desiredVal;
};

Then you'd use it as:
var paramVal = "paramName".urlParamValue() // null if no match

A: If you want to find a specific parameter from a specific url:
function findParam(url, param){
  var check = "" + param;
  if(url.search(check )>=0){
      return url.substring(url.search(check )).split('&')[0].split('=')[1];
  }
}

var url = "http://www.yourdomain.com/example?id=1&order_no=114&invoice_no=254";
alert(findParam(url,"order_no"));

A: Another solution that uses jQuery and JSON, so you can access the parameter values through an object.
var loc = window.location.href;
var param = {};
if(loc.indexOf('?') > -1)
{
    var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");

    var stringJson = "{";
    for(var i=0;i<params.length;i++)
    {
        var propVal = params[i].split("=");
        var paramName = propVal[0];
        var value = propVal[1];
        stringJson += "\""+paramName+"\": \""+value+"\"";
        if(i != params.length-1) stringJson += ",";
    }
    stringJson += "}";
    // parse string with jQuery parseJSON
    param = $.parseJSON(stringJson);
}

Assuming your URL is http://example.com/?search=hello+world&language=en&page=3
After that it's only a matter of using the parameters like this:
param.language

to return
en

The most useful usage of this is to run it at page load and make use of a global variable to use the parameters anywhere you might need them.
If your parameter contains numeric values then just parse the value.
parseInt(param.page)

If there are no parameters param will just be an empty object.

A: $.urlParam = function(name) {
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
}

A: use this
$.urlParam = function(name) {
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
}

A: Just wanted to show my codes:
function (name) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  results = regex.exec(location.search);
  return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

}

A:

var RequestQuerystring;
(window.onpopstate = function () {
    var match,
        pl = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query = window.location.search.substring(1);

    RequestQuerystring = {};
    while (match = search.exec(query))
        RequestQuerystring[decode(match[1])] = decode(match[2]);
})();

RequestQuerystring is now an object with all you parameters

A: Get the param from a string:
Object.defineProperty(String.prototype, 'urlParam', {

    value: function (param) {

    "use strict";

    var str = this.trim();

    var regex = "[\?&]" + param + "=([^&#]*)";

    var results = new RegExp(regex, "i").exec(str);

    return (results !== null) ? results[1] : '';

    }
});

to use:
var src = 'http://your-url.com/?param=value'

console.log(src.urlParam(param)); // returns 'value'

A: I Hope to use the full simple REG Exp
  function getQueryString1(param) {
    return decodeURIComponent(
        (location.search.match(RegExp("[?|&]"+param+'=(.+?)(&|$)'))||[,null])[1]
    );
  }


text:
Q: Checkov custom policy for checking IAM role name We have a specific policy to include region name for IAM roles
I've created custom policy for that, but It's not working:
definition:
  and:
      - cond_type: "attribute"
        resource_types:
            - "aws_iam_role"
            - "aws_s3_bucket"
        attribute: "name"
        operator: "regex_match"
        value: /(us(-gov)?|ap|ca|cn|eu|sa)-(central|(north|south)?(east|west)?)-\d/g

Does anybody know how to fix that and is that possible to check IAM role name using checkov?

A: Fixed by these regular expression:
"^.*(us(-gov)?|ap|ca|cn|eu|sa)-(central|(north|south)?(east|west)?)-\\d.*$"


text:
Q: How to stop a div from wrapping continuously? My container div keeps wrapping underneath the nav div after re-sizing the browser.
I have attempted various methods, however I'm doing something wrong and I don't know what.

nav {
  border-style: solid;
  border-color: green;
  float: left;
  padding-left: 10px;
  padding-right: 10px;
  display: inline-block;
  height: 70vh;
}

ul {
  padding: 0px;
  list-style-type: none;
}

.container {
  border-top: solid;
  border-right: solid;
  border-bottom: solid;
  border-color: green;
  display: inline-block;
  width: 80vw;
  height: 70vh;
}

home

portfolio

dsdfsdfs

NAV div on the far left and CONTAINER div underneath it:

A: Remove:
display:inline-block

from .container, so that it defaults to display:block.


text:
Q: Maven error while setting up i.lon 100 server in eclipse I'm trying to connect i.lon100 with JAVA using Programmers Reference. pom.xml and .pdf file with Programmer reference can be downloaded from page: http://home.elka.pw.edu.pl/~mkolasin/
My eclipse version is:
Eclipse Java EE IDE for Web Developers.
Version: Juno Service Release 2
Build id: 20130225-0426
Maven version: 2.2.1 (as recomended in programmers reference)
a) First of all I have a problem with page 22-6 with installing Maven Embedder and Maven Integration for Eclipse, becouse I assume that http://m2eclipse.sonatype.org/update/ page doesn't exsist. So, my first question: is there any other site I can download those software using eclipse?
B) I installed from eclipse market: Maven integration for eclipse, but i couldn't find Maven Embedder. And now i have got right click on project: RUN AS - Maven Built instead of Run AS - maven package is it still okay?
c) When i try to make another step page 22-13 "In the Project Explorer view, right-click the ilon-ws folder, point to Run As, and then click
Maven Package. This generates the java proxy classes and builds the jar." i got an error in console and i don't know how to fix it.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org...ticLoggerBinder for further details.
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.echelon.es:ilon-ws:jar:4.03-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.codehaus.mojo:jaxws-maven-plugin is missing. @ line 71, column 21
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 113, column 23
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-source-plugin is missing. @ line 124, column 23
[WARNING] 'repositories.repository.layout' for java.net uses the unsupported value 'legacy', artifact resolution might fail. @ line 36, column 21
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building ECHELON i.LON SmartServer 4.03-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.985s
[INFO] Finished at: Tue Jun 04 20:20:25 CEST 2013
[INFO] Final Memory: 4M/105M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project ilon-ws: Could not resolve dependencies for project com.echelon.es:ilon-ws:jar:4.03-SNAPSHOT: Failed to collect dependencies for [com.sun.xml.ws:jaxws-rt:jar:2.2 (compile)]: Failed to read artifact descriptor for woodstox:wstx-asl:jar:3.2.1: Could not transfer artifact woodstox:wstx-asl:pom:3.2.1 from/to java.net (http://download.java.net/maven/1/): No connector available to access repository java.net (http://download.java.net/maven/1/) of type legacy using the available factories AsyncRepositoryConnectorFactory, WagonRepositoryConnectorFactory -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache....lutionException

I tried adding slf4j-nop-1.7.5.jar file to buildpath and nothing has changed.
Please give me any suggestions or help, becouse I can't handle it since last few days, and i don't know where to find answers.
Regards,
Kolata


text:
Q: Extract unique terms from a document I am looking for an efficient way to extract terms from a document that are unique to him and don't appear in any other document.
The naive way is to index all documents in a database such as elasticsearch and search each term in the new documents in all the index. This will probably be very inefficient.
The problem is a kind of feature extraction problem.
My questions is whether elasticsearch or any other tool can provide an efficient method to solve this problem?

A: Well if you have a big amount of data I'll suggest you use the Redis database to store and fetch the data in Redis you can also pre-cache your data so that it would be easy to load again
Redis also uses Key-value pair but is very fast than python dictionary
and for making it unique you can make some key-value combination
for more details about Redis check this
https://realpython.com/python-redis/

A: **try this**

import re

# Declare a dictionary
dict = {}

# Method to check whether the word
# exists in dictionary or not
def uniqueWord(Word):

    if Word in dict:

        # If the word exists in dictionary then
        # simply increase its count
        dict[words] += 1

    else:

        # If the word does not exists in
        # dictionary update the dictionary
        # and make its count 1
        dict.update({words: 1})

# Driver code
if __name__ == '__main__':

    string = "Java is great. Grails is also great"

    # re.split() method is used to split
    # all the words in a string separated
    # by non-alphanumeric characters (\W)
    ListOfWords = re.split("[\W]+", string)

    # Extract each word from ListOfWords
    # and pass it to the method uniqueWord()
    for words in ListOfWords:
        uniqueWord(words)

    # Iterate over dictionary if the value
    # of the key is 1, then print the element
    for elements in dict:
        if dict[elements] == 1:
            print(elements)


text:
Q: Should a critical section or mutex be really member variable or when should it be? I have seen code where mutex or critical section is declared as member variable of the class to make it thread safe something like the following.
class ThreadSafeClass
{
public:
    ThreadSafeClass() { x = new int; }
    ~ThreadSafeClass() {};

    void reallocate()
    {
        std::lock_guard<std::mutex> lock(m);

        delete x;
        x = new int;
    }

    int * x;
    std::mutex m;
};

But doesn't that make it thread safe only if the same object was being shared by multiple threads? In other words, if each thread was creating its own instance of this class, they will be very much independent and its member variables will never conflict with each other and synchronization will not even be needed in that case!?
It appears to me that defining the mutex as member variable really reduces synchronization to the events when the same object is being shared by multiple threads. It doesn't really make the class any thread safer if each thread has its own copy of the class (for example if the class were to access other global objects). Is this a correct assessment?

A: If you can guarantee that any given object will only be accessed by one thread then a mutex is an unnecessary expense. It however must be well documented on the class's contract to prevent misuse.
PS: new and delete have their own synchronization mechanisms, so even without a lock they will create contention.
EDIT: The more you keep threads independent from each other the better (because it eliminates the need for locks). However, if your class will work heavily with a shared resource (e.g. database, file, socket, memory, etc ...) then having a per-thread instance is of little advantage so you might as well share an object between threads. Real independence is achieved by having different threads work with separate memory locations or resources.
If you will have potentially long waits on your locks, then it might be a good idea to have a single instance running in its own thread and take "jobs" from a synchronized queue.


text:
Q: Scan all the documents in a View So, this my code. It gets only the first document. But what I want to do is read a specific document. The view is a collection of usernames and passwords. So, for example : The username is in the 5th document, then the program will scan the view until it finds the right document. Sorry for my poor explanation. I hope you understand my problem.
On Error Goto e
    Dim db As NotesDatabase
    Dim view As NotesView
    Dim results As Variant
    Dim cmd As String
    Dim d As NotesDocument, flag As Integer, upw As String, uname As String

Set db = source.Database
uname  = Inputbox("Enter Username")

Set view = db.GetView("Registration View")
Set d = view.GetFirstDocument()

'cmd = {@DbLookup("";"48257E00:00089AF5";"RegView";1)}
'results = Evaluate(cmd)
Dim pw As String, un As String
'Forall Username In results
'   Msgbox username(1)
'End Forall
If Not d Is Nothing Then
    un = d.userfield(0)
    pw = d.passfield(0)
    If un <> uname Then
        Msgbox "Username invalid!"
    End If
    If un = uname Then
        upw  = Inputbox("Enter Password")
        If pw <> upw Then
            Msgbox "Password invalid!"
        End If
        If pw = upw Then
            Msgbox "Log In succesful!"
            flag = 1
        End If
    End If
End If

If flag <> 1 Then Call source.Close()

Exit Sub
e:
    Print Error, Erl

A: Instead of using view.getFirstDocument you should use view.getDocumentByKey(uname,true) which return the document with the key uname in the first column in the view
Make sure the first column In the view is set to sorted
If no document is found using the key then getDocumentByKey returns nothing

A: You can create a view with the first column userfield and the second column passfield. The first column has to be sorted.
In your code build an array of uname and upw
Dim strSearch (0 to 1) as String
Dim viewSearch as NotesView
Dim doc as NotesDocument

viewSearch = db.getView("YourSearchView")

strSearch(0) = uname
strSearch(1) = upw

Set doc = db.getDocumentByKey(strSearch, true)

If(Not doc is nothing)Then
    Print "Login successfull"
Else
    Print "Wrong username or password"

End if

If you want to use a two step check of username and then password you can create two search views and use the first for check if the username exists and the second for checking the given username and password.

A: Of course you could cycle through the complete view and compare each single entry, but that will be quite slow. In your code the complete "cycling" is missing. You would need to use a do - while loop to run through all entries in the view:
Set d = view.GetFirstDocument()
Do
  un = d.userfield(0)
  pw = d.passfield(0)
  '- here comes the rest of your code, if password is right - exit
  If flag = 1 then exitLoop = True

  Set d = view.GetNextDocument( d )
  if d is Nothing then exitLoop = True
Loop until exitLoop

But this is quite inefficient. If your view is sortey by username (if not, create one that is), then use getDocumentbyKey as suggested by Thomas.
Set d = view.GetDocumentByKey( uname )
If not d is Nothing then
  un = d.userfield

The question is WHY would one do something like this: Notes / Domino has a great security concept and saving all usernames and passwords in a view, where everybody can simple read the passwords by checking the document properties is -sorry to say- stupid and does not give you even one more bit of security...


text:
Q: Entity Framework Migrations seeds duplicate rows I've got two classes
public class Category
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class Item
{
  public int Id { get; set; }
  public sting Name { get; set; }
  public Category Category { get; set; }
}

I have EF Migrations and the following seed:
var instockCategory = new Category() { Name = "InStock" };
var outofStockCategory = new Category() { Name = "OutOfStock" };

context.Items.AddOrUpdate(
 d => d.Name,
 new Item() { Name = "Item1", Category = instockCategory },
 new Item() { Name = "Item2", Category = outofStockCategory },
 new Item() { Name = "Item3", Category = outofStockCategory }
);

The line "d => d.Name" makes sure that based  on the name of the item, there won't be duplicate records when I reseed the database.
However, the first time I execute this, two categories are created with id 1 and 2. But the second time I run this, 3 new categories are created!
Can I fix this without manually adding every single category first?

A: You have to use AddOrUpdate for your categories too.
var instockCategory = default(Category);
var outofStockCategory = default(Category);

context.Set<Category>().AddOrUpdate(
    c => c.Name,
    instockCategory = new Category() { Name = "InStock" },
    outofStockCategory = new Category() { Name = "OutOfStock" }
);

context.Items.AddOrUpdate(
    d => d.Name,
    new Item() { Name = "Item1", Category = instockCategory },
    new Item() { Name = "Item2", Category = outofStockCategory },
    new Item() { Name = "Item3", Category = outofStockCategory }
);

An explicit DbSet on your Context class is not necessary.
public class Context : DbContext
{
    public DbSet<Item> Items { get; set; }
}


text:
Q: Enable DataGrid sorting for first column in xaml I have a DataGrid in WPF with autogenerated columns.
How can I disable sorting functionality of all the rows except the first one which corresponds time in my Source.
I am following MVVM pattern and I know that CanUserSortColumns is disabling sorting for all the columns. I want to disable all but the first column.
Should I write trigger or interaction or something else? All the help is appreciated.
<DataGrid AutoGenerateColumns="True"
        ItemsSource="{Binding MyDataTable}"
        CanUserSortColumns="False">
</DataGrid>

A: I found this code snippet for you:
<my:DataGridTemplateColumn  SortMemberPath="CompleteDate" Header="Complete Date" CanUserSort="true">
            <my:DataGridTemplateColumn.CellTemplate >
                    <DataTemplate>
                        <TextBlock>
                            <TextBlock.Text>
                                <Binding Path="CompleteDate" ConverterCulture="en-GB" StringFormat="{}{0:MM/dd/yyyy}"/>
                            </TextBlock.Text>
                        </TextBlock>
                    </DataTemplate>
                </my:DataGridTemplateColumn.CellTemplate>
            </my:DataGridTemplateColumn>

Use the CanUserSort Property to define it's sortable-state column explicit. The SortMemberPath defines the Property you use for sorting. Hope this helps.
UPDATE:
If you are using autogenerated columns you can't access them via xaml. So you need to access them in code File.
I'm not familiar with the xaml Grid but would expect something like:
//Bound Data here so that the Grid generate the columns

int i = 0;
foreach (DataColumn column in myGrid.ColumnCollection)
{
   if (i == 0)
      column.CanSortUser = true;
   else
      column.CanSortUser = false;

   i++;
}

The original Typenames can differ but something this way should be possible.
UPDATE-2
If you don't want to hurt the MVVM you can use this. There is described how to use Interfaces to access the code and stay independet with your view and viewmodel.

A: The problem is, that DataGridColumnHeader has the CanUserSort property as a local computed property. It can been set by manually generating the columns (what you don't want).
If it was a property with setter you could create a DataTrigger looking at TabIndex == 0 and set through Setter in xaml Style.
Your only chance by using AutoGeneratedColumns is the following:
<DataGrid AutoGenerateColumns="True"
    ItemsSource="{Binding MyDataTable}"
    CanUserSortColumns="True"
    AutoGeneratedColumns="DataGrid_OnAutoGeneratedColumns">
</DataGrid>

your codebehind:
private void DataGrid_OnAutoGeneratedColumns(object sender, EventArgs e)
{
    DataGrid dg = sender as DataGrid;
    if (dg == null) return;
    dg.Columns.ToList().Select((col, indx) => new {Col = col, Indx = indx}).ToList().ForEach(obj => obj.Col.CanUserSort = obj.Indx == 0);
}

This enables the first columns UserCanSort property and disables the others. This function is independend from your viewmodel and can been placed at your view.xaml.cs code behind file.
EDIT:
If you won't have any codebehind you can just do it by using your own DataGridControl.
MyDataGrid.cs
namespace YourNamespace {
    public class MyDataGrid : DataGrid
    {
        protected override void OnAutoGeneratedColumns(EventArgs e)
        {
            DataGrid dg = sender as DataGrid;
            if (dg == null) return;
            dg.Columns.ToList().Select((col, indx) => new {Col = col, Indx = indx}).ToList().ForEach(obj => obj.Col.CanUserSort = obj.Indx == 0);

            base.OnAutoGeneratedColumns(e);
        }
    }
}

your view:
<YourNamespace:MyDataGrid AutoGenerateColumns="True"
    ItemsSource="{Binding MyDataTable}"
    CanUserSortColumns="True">
</YourNamespace:MyDataGrid>

and you are done without a single line codebehind.


text:
Q: ffmpeg not splitting into EXACT same length chunks I am trying to use ffmpeg to split a long video into exactly 20second long clips, and accomplishing that by:
inside docker as a python sub-process
subprocess.run(["/usr/sbin/ffmpeg",
        "-i", video_loc,
        "-async", "1",
        "-map", "0",
        "-segment_time", "20",
        "-f", "segment",
        "-reset_timestamps", "1",
        "n-%05d.mp4"], cwd=r'/clips')

My problem is that each are roughly 20seconds, some are as low as 10seconds, some as high as 27 seconds, i would say most are around 16-23. Is there something else that I can do to ensure the split of exactly 20 seconds? I am open to any technique possible, aside from anything manual...

A: I have another approach that you can try
Let us say you have a video called 'input.mp4' and you want to split it to "n" number of videos and each are 20 sec long.

ffmpeg -ss 00:00:00.000 -i input.mp4 -ss 00:00:19.000 -t 00:00:20.000 -c copy v1.mp4
ffmpeg -ss 00:00:20.000 -i input.mp4 -ss 00:00:39.000 -t 00:00:20.000 -c copy v2.mp4
and so on ..

A: I wish I had the reputation to leave a comment to compound upon Gyan's comment instead of leaving an answer but alas I don't, so this will have to do.
The reason you're still experiencing some degree of variation is likely because the framerate of the input source is fractional and not whole. For example - 59.94 or 29.97 as opposed to 30 or 60.
I have tested segmentation and forcing keyframes extensively and found both only work "perfectly" when the source videos FPS is a whole number. Simply force your source video to an integer framerate so frames are duplicated and you will experience much more consistency in terms of length. Of course with the obvious caveat that your output now contains duplicated frames. The reason I have perfectly in quotation marks is because there is still a degree of variation extremely infrequently, I have only noticed it twice in my case.
That being said you may rather have slight variation in segment length as opposed to duplicated frames. But if you were segmenting multiple sources at once it is basically required that all sources have integer framerates or slowly over-time, when comparing like numbered parts, you will experience desynchronization.
Long story short, if length consistency is the #1 priority utilize both -r [desired integer framerate] and expr:gte(t,n_forced*20) after the input.


text:
Q: Using pcapy or scapy to monitor self-generated (HTTP) network traffic I need to monitor how long it takes for a certain website to respond when addressed. I would like to sniff the traffic on port 80 but only when there is traffic being exchanged with the targeted site. I have searched SO and it seems like pcapy or scapy is the right tool for the job, but they seem deeper than I need. I have studying the following script:
Network traffic monitor with pcapy in python
and I think I need to change the
def __handle_packet(self, header, data):
    # method is called for each packet by dispatch call (pcapy)
    self._dispatch_bytes_sum += header.getlen() #header.getlen() #len(data)
    logger.debug("header: (len:{0}, caplen:{1}, ts:{2}), d:{3}".format(header.getlen(), header.getcaplen(), header.getts(), len(data)))
    #self.dumper.dump(header, data)

to somehow only unpack/handle packets that are destined for the target site. Note that this is for a Windows XP machine on a LAN and it is critical that the browser initiate the traffic.
Any pointers appreciated?

A: The problem with scapy is it doesn't handle reassembling TCP streams. Your HTTP that you're looking for is likely to be embedded in a TCP stream. To quote the docs:

Scapy is based on a stimulus/response model. This model does not work well for a TCP stack. On the other hand, quite often, the TCP stream is used as a tube to exchange messages that are stimulus/response-based.

Like you said scapy is more ideal for lower-layer things. You could, for instance, probably track IP packets on DHCP requests. Like many network tools, the complexities and stream-based nature of TCP means once you cross that layer it gets harder to reassemble everything and deal with all the retransmission and what not edge cases and coherently pull data out.
Could you use something like curl or urllib and see how long it takes for the response to come back?


text:
Q: jQuery won't submit a form

Find your vehicle

        <form id="vehicle" action="sales/new-motorhomes" method="post">

Manufacturer

            <select name="manufacturer" id="manufacturers">
                <option value="1">Auto-Trail</option>
                <option value="2">Adria</option>
                <option value="3">Elddis</option>
            </select>

Vehicle Type

            <select name="category" id="categoryid">
                <option value="1">New Motorhomes</option>
                <option value="2">Used Motorhomes</option>
                <option value="3">Caravans</option>
            </select>

Berths

            <input type="text" name="berth" id="berths" style="border: 0; color: #f6931f; font-weight: bold;" />

        </form>

What have I missed here..?

A: Since the submit-event is just declared but never called you have to put the submit-event outside of your click-handler and just trigger it on click:
http://fiddle.jshell.net/rvx27/
jQuery(function () {
    jQuery('form:first').submit(function (event) {
        var action = '';
        var actionid = jQuery('#categoryid').children(':selected').attr('value');

        if (actionid == 1) {
            action = 'sales/new-motorhomes';
        }
        if (actionid == 2) {
            action = 'sales/used-motorhomes';
        }
        if (actionid == 3) {
            action = 'sales/caravans';
        }
        jQuery(this).attr('action', action);

    });
    jQuery('.go').click(function (e) {
        e.preventDefault();
        jQuery('form:first').submit();
    });
});

A: The code
jQuery('form:first').submit(function (event){});

Will assign an event handler to be called when the form is submitted. It does no actually submit the form.
To submit the form you must call
jQuery('form:first').submit();

or have a submit button in the form.
Your code could be rewritted as
jQuery(document).ready(function() {
   jQuery('form:first').submit(function (event){
        var action = '';
        var actionid = jQuery('#categoryid').children(':selected').attr('value');

        if (actionid == 1) {
           action = 'sales/new-motorhomes';
        }
        if (actionid == 2) {
           action = 'sales/used-motorhomes';
        }
        if (actionid == 3) {
           action = 'sales/caravans';
        }
        jQuery(this).attr('action', action);

        return true; // Important to return okay to submit

   });

   jQuery('.go').click(function(e) {
       e.preventDefault();
       jQuery('form:first').submit(); // Trigger the submission
   });
});

This code assigns the event handler document.ready() event and then the subsequent click triggers the submit.

A: You need to use form id when you submit form using jquery.
Replace jQuery('form:first').submit(function (event){
With jQuery('#vehicle').submit(function (event){

A: why aren't you using id selector
jQuery('#vehicle').submit();

this is faster and better than :first and should submit the form..

A: Your code:
jQuery('form:first').submit(function (event){ ... });

...is binding a submit handler. To submit the form you need:
jQuery('form:first').submit();

If the only way the form can be submitted is via that link you can do that action setting stuff directly within the link's click handler before calling .submit() on the form. Or bind the submit handler separately (from outside the click handler or it'll keep binding additional handlers on each click) and then just call .submit() from within the click handler.

A: Try this:
jQuery(function() {

            jQuery('.go').click(function(e) {
                e.preventDefault();

                var action = '';
                var actionid = jQuery('#categoryid').children(':selected').attr('value');

                if (actionid == 1) {
                    action = 'sales/new-motorhomes';
                }
                if (actionid == 2) {
                    action = 'sales/used-motorhomes';
                }
                if (actionid == 3) {
                    action = 'sales/caravans';
                }
                jQuery('form:first').attr('action', action);

                jQuery('form:first').submit()

                });
            });
        });


text:
Q: How to convert interval to a timestamp in postgresql? and change its default format? ))Hi all,
In postgres I have a table with an Interval datatype coloumn,
Within a thirdapp Im SELECTing one of those Interval rows (via QUERY) cuz I need to compare its value with another "interval" value in this third app.
Well, the case is that this third app, doesn't have an "interval" timetype, so instead Im using a "DateTime" value (equivalent to postgres timestamp).
So in order to compare both (postgres "interval" and thirdapp "Datetime") I need to convert postgres "interval" to "timestamp", to do so Im using this query...
SELECT to_timestamp((to_char((SELECT timespan FROM mytable ORDER BY stmtserial DESC LIMIT 1), 'yy-mm-dd HH24:MI:SS.MS')), 'yy-mm-dd HH24:MI:SS.MS')

It works, but the result timestamp is shown in this format...
MM/DD/YYYY HH12:MI:SS AM

starting to count from year 2000, month 1 day 1, so if "interval" = 00:00:00.000 (0 seconds) this will be its "converted to timestamp" result...
1/1/2000 12:00:00 AM

Is there a way to change this behavior? cuz the thirdapp start to count from...
1/1/0001 12:00:00 AM

So, there is a gap of 1999 years, Is there a simple way to config or alter this behavior in PostgreSQL so it can start counting from year 0001, or any workaround???
Thanks Advanced.


text:
Q: For a list of list (we call it A), I want to have a different list of list. see details below? Suppose I have a list of list.
[[1,2,3,4,5,6], [2,4,6,8,9,10], [10, 11, 12, 13, 14, 15]]

Now I want to a list of list such as
[[1,2,0,0,0,0], [2,4,0,0,0,0], [10, 11, 0, 0, 0, 0]]

Is there a quick way to do it instead of using a loop to modify it. Thank you.
Edit: sorry for the confusion. I like to keep first x elements and modify rest to 0.
The size of each sublist is same.

A: You can try this.
for lst in my_list:
    lst[2:]=[0,0,0,0]
print(my_list)
#[[1, 2, 0, 0, 0, 0], [2, 4, 0, 0, 0, 0], [10, 11, 0, 0, 0, 0]]

If you have different sizes of lists in list and you want to change only last 4 items to 0 try this.
for lst in my_list:
    lst[-4:]=[0,0,0,0]

EDIT:
I want to keep the first x elements, and change the rest to 0.
Try this.
lst[x-len(lst):]=[0 for i in range(len(lst)-x)] #suggested by dcg

Or
lst[x:]=[0]*(len(lst)-x)

A: The following code is what you need:
if __name__ == "__main__":
    # list modification with zeros
    alist = [[1,2,3,4,5,6], [2,4,6,8,9,10], [10, 11, 12, 13, 14, 15]]

    for x in alist:
        x[2:] = [0]*4

    print(alist)

Output:
[[1, 2, 0, 0, 0, 0], [2, 4, 0, 0, 0, 0], [10, 11, 0, 0, 0, 0]]


text:
Q: ORA-29275: partial multibyte character I have input data coming from a flat file which has english, japanese, chinese characters in one column.
I am loading these values in a staging table column whose schema definition is VARCHAR2(250 CHAR),  the main table column has definition VARCHAR2(250) WHICH i can not change.
So, i am doing a SUBSTR on this column. After loading the table when i did a
SELECT * FROM TABLE

...I get this error :

ORA-29275: partial multibyte character

If i select other columns then no issues.

A: I think i might have found a good way to do it
if you do rtrim(substrb('中华人', 1, 8)) you get '中华' and a byte length of the expected 6
please try

A: you should use SUBSTRB when you copy your data from your 250 CHAR column to your 250 byte column. This function will only output whole characters (you won't get incomplete unicode characters):
SQL> select substrb('中华人', 1, 9) ch9,
  2         substrb('中华人', 1, 8) ch8,
  3         substrb('中华人', 1, 7) ch7,
  4         substrb('中华人', 1, 6) ch6,
  5         substrb('中华人', 1, 5) ch5
  6    FROM dual;

CH9       CH8      CH7     CH6    CH5
--------- -------- ------- ------ -----
中华人       中华       中华      中华     中

Edit:
@mwardm made an interesting comment concerning the actual length of the resulting string and whether the resulting string could contain an invalid sequence of bytes. Consider the following on an AL32UTF8 DB:
SQL> select lengthb('ÏÏÏ'),
  2         lengthb(substrb('ÏÏÏÏÏÏ', 1, 5)),
  3         dump('ÏÏÏ'),
  4         dump(substrb('ÏÏÏÏÏÏ', 1, 5))
  5    FROM dual;

LE LE DUMP('ÏÏÏ')                           DUMP(SUBSTRB('ÏÏÏÏÏÏ',1,5))
-- -- ------------------------------------- -------------------------------
 6  5 Typ=96 Len=6: 195,143,195,143,195,143 Typ=1 Len=5: 195,143,195,143,32

As you can see the last byte of the substrb string is not the truncated first byte of the special character but encodes a legit character (The first 128 characters in this character set are the same as the ASCII7US character set so this encodes the ' ' space character, using RTRIM as suggested in another answer will remove the last character).
Furthermore, I also got this interesting result using the character set AL16UTF16:
SQL> select lengthb(N'ĈĈ') le,
  2         dump(N'ĈĈ') dump,
  3         lengthb(substrb(N'Ĉ', 1, 3)) length_substr,
  4         dump(substrb(N'ĈĈ', 1, 3)) dump_substr
  5    from dual;

        LE DUMP                    LENGTH_SUBSTR DUMP_SUBSTR
---------- ----------------------- ------------- -----------------
         4 Typ=96 Len=4: 1,8,1,8               2 Typ=1 Len=2: 1,8

In this case Oracle has choosen to cut the string after the second byte because in the AL16UTF16 character set there is no legit one-byte character. The resulting string is only 2 bytes instead of 3.
This would need further testing and is by no mean a rigorous demonstration but I still stand by my first hunch that substrb will return a valid sequence of bytes that encodes a valid string of characters.

A: Using substr will behave differently depending on the database character set.  I assume from your description that your DB character set is not one of the Unicode variants, and you must truncate the varchar2(250 char) data to 250 BYTES or less.  This is dangerous because it can stop in the middle of a 2-byte character, resulting in the message you got.  You should look at the documentation for substrc(), which will calculate its length based on characters and not bytes.
It might help if you explain more why you are required to throw away part of the data.


text:
Q: is there cross platform library to call/create process in c++ Is there any cross platform library to create process's (using createProcess win32 api in windows for example).
for linux/windows/mac?

A: You could use Qt which implements many OS utilities in a platform-independent way, eg. processes, threads, networking, GUI of course,....

A: Have a look at https://github.com/eidheim/tiny-process-library, a modern C++(11) platform independent process library without external dependencies.

A: I was able to run notepad using:
std::system("notepad.exe");
I beleive in linux it also should work.

A: *

*Boost.Process will do that

*as will PoCo (Processes namespace, in Foundation)

None of these are intrusive libraries, and none of these imply UI frameworks. Both will support static linkage without major size overhead.

A: wxWidgets also contains a cross-platform process control library for spawning child processes through the wxProcess class.  If cross-platform threading is needed, it can be handled through the wxThread class as well.  Overall, wxWidgets a nice cross-platform library that's fairly light-weight and pretty straight-forward to use.  You can find some great getting-started tutorials on the main website that show you how to get an application up and running.


text:
Q: filtering content for UITableView I was looking at the TableSearch example code from Apple.  It looks like that they have a NSArray for all the content, and a NSMutableArray for filtered content.  And then if the filter is on, then they would show the NSMutableArray.  If it is off, they would show the NSArray that has all the data.
1) I was wondering if this is a common implementation for filters since I haven't done much filtering before.
2) To add to that question, if I had a filter of four different categories, would I still use one NSMutableArray that shows the filtered content when the filter is on?  Or do I create four different NSMutableArrays for each different type of filter, and then show that list depending on which filter is on.
Assuming that the common implementation is to have an NSArray for the list, I'm getting confused if creating the arrays of filtered list up front is expensive if I were to do four different NSMutableArrays, or if depending on the click from the user of what filter option they select, should I create the NSMutableArray on the fly, and then reload the [tableView reloadData];
Thanks.

A: I don't have that sample app in front of me, but you typically would filter using a predicate, so it would be helpful for you to review the docs on NSPredicate.
So when you want to change the filter, you do so by changing the predicate. You don't have to create all filtered results. You only create the one you need at any given moment.
With arrays, you can filter using code like that shown in this example. The key lines are
NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:@"length == 9"];
NSArray *myArray2 = [myArray filteredArrayUsingPredicate:predicate];

Filtering is not always done with arrays. It can be done with NSFetchedResultsControllers if using Core Data. Predicates are used there also, in very much the same way. Predicates can be used for other things, too, including regular expression filtering. It's worth looking at, if you aren't familiar with it.

A: It really depends. If your underlying data is in Core Data, use NSFetchedResultsController and give it NSPredicates. If you have an array of data, it may be easiest to traverse it and create another array of data.
In general, the filter itself is not likely to be as expensive as the overall drawing process (which includes instantiating or recycling table cells). You can do what's easy and profile with Instruments.
Keeping four different arrays is normally not a good idea in terms of memory, which is a scarce resource.
No matter what though, reloadData is going to be involved. (Depending on OS version, perhaps — see the NSFetchedResultsController docs.)


text:
Q: How do I reduce overhead of passing a matrix to a function? I am performing statistics on 2 rather large (2+ GB each) 3D arrays and I perform that computation inside a function:
double stats(vector< vector< vector< double > > > A, vector< vector< vector< double > > > B);

I believe that a large amount of the time taken by the program is simply passing A and B to my function, rather than actually performing the statistics inside the function.
Does this seem reasonable? Is there substantial overhead from passing these vectors to a function? If so, what is the best way to account for this? I know that I could simply put all of these functions inside a class and then refer to the arrays in terms of a class member, but I was hoping to keep these functions class agnostic if possible.

A: Pass the arrays by reference. Note the ampersands, &:
double stats(vector< vector< vector< double > > > & A, vector< vector< vector< double > > > & B);

Passing by value as you are will cause the vectors to be copied, incurring performance and memory overhead.
If you don't need to modify the vectors within stats, also consider using a const reference:
double stats(vector< vector< vector< double > > > const& A, vector< vector< vector< double > > > const& B);


text:
Q: A formula for weighting means by how many data points there are? I am using image recognition software to categorise images. I am returned a bunch of labels which are then assigned into a relevant category groups. I am now trying to figure out which singular group the image most likely represents.
The following is an example dataset (the list is sorted by the highest confidence within the group):
const groupings = [
  {
    name: 'hobbies',
    confidences: [
      99.50678253173828
    ],
  },
  {
    name: 'houseAndFurniture',
    confidences: [
      99.49097747802734,
      98.10116577148438,
      96.84264373779297,
      96.81708526611328
    ],
  },
  {
    name: 'art',
    confidences: [
      90.4281005881523,
      90.4281005859375
    ]
  },
  {
    name: 'travelAndLeisure',
    confidences: [
      90.4281005859375
    ]
  },
];

Each number represents 1 label (example, "Sofa") which has been placed in the relevant grouping. If I simply take the mean of each grouping I end up with the problem that hobbies (99.50678253173828) will end up with a higher mean than houseAndFurniture (97.812968063).
As a human I can look at this and realise that houseAndFurniture is most likely the correct grouping to place this in, but I don't want to just take the group with the most labels as it can sometimes be wrong. The confidence needs to count as well.
Question
How would a statistician go about solving this issue? Is there a statistical method for scaling the mean of a dataset according to how many data points are within it? Or something along those lines?