text:
Q: Localization Font I am very new to localization, I am trying to localize a small software which has 19 folders 'en', 'jp, 'tw' as names for example. Inside each one is a text file saved as utf-8 with language data.
The problem is when I try and copy and paste from a chinese site I get strange glyphs like this [][][][] I presume its because my system font is not chinese and it does not support that.
As a developer should I somehow change my entire system font to have all of these languages supported? Is there such a font? I am unsure how software companies handle these things.

A:
As a developer should I somehow change my entire system font to have
  all of these languages supported?

No, you should not. Consider localization string as data.

The problem is when I try and copy and paste from a chinese site I get
  strange glyphs like this [][][][] I presume its because my system font
  is not chinese and it does not support that.

But you should be provided with such data and you should know it's encoding.
Also, I've suggest you to check internationalization libraries (like gettext) to prevent reinventing the wheel.


text:
Q: Javascript global variable not working properly? My jQuery code:
$(document).ready(function() {
    chrome.extension.sendRequest({get: "height"}, function(response) {
        height = response.value;
    });

    $("#id").css("height", height+"px");
});

You don't have to be concerned about the chrome.extension.sendRequest(), basically it communicates with a background page to fetch the value for "height" from localStorage and stores the value in global variable height.
The problem lies in $("#id") not being assigned the height value. However if I were to modify it such that it is now:
$(document).click(function() {
    $("#id").css("height", height+"px");
});

it works. Any idea why?

A: The reason is that when you defer the assignment to document click, that means the request has time to finish, and set the height value.
In your first example, height doesn't have a value at the time of assignment. The reason is that the function body passed to sendRequest is not executed immediately, but it is saved until the request is finished. After that, the function is called. But before that, javascript will continue to execute your $("#id")... statement. To make sure that it is not assigned a value until there is one, change it to the following:
$(document).ready(function() {
    chrome.extension.sendRequest({get: "height"}, function(response) {
        height = response.value;
        $("#id").css("height", height+"px");
    });
});

Now, if the callback function passed to sendRequest is executed in a context where that code cannot be executed, as may well be the case with browser extensions, you might have to pass a reference to the object instead:
$(document).ready(function() {
    var myObj = $("#id");
    chrome.extension.sendRequest({get: "height"}, function(response) {
        height = response.value;
        myObj.css("height", height+"px");
    });
});

But I'd go with the first version if that works.
When you've applied this, investigate whether you still need to keep the height variable global...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Enum with generic base class passed as contructor parameter I'm attempting to create an enum whose constructor accepts an object whose base class is a generic class.
I seem to be unable to fetch the underlying generic type from within the enum however, Object gets returned instead of T.
Is there a way to do this?
abstract public class Field<T> {
    abstract public T get();
}

public class IntegerField extends Field<Integer> {
    public Integer get() {
        return 5;
    }
}

public class StringField extends Field<String> {
    public String get() {
        return "5";
    }
}

public enum Fields {
    INTEGER (new IntegerField()),
    STRING  (new StringField());

    private final Field<?> field; // <<--- I can't have Field<T>, enum's can't be generic. :(

    <T> Fields(Field<T> field) {
        this.field = field;
    }

    public <T> T get() {
        return field.get(); // <<--- Returns Object, not T
    }
}

A: The issue is that enums can't be generically typed so even if you cast that get call ((T) field.get()) you won't have type safety because it will agree with any assignment (you could compile this successfully for instance: boolean b = Fields.INTEGER.get()).
Just use constants instead:
public final class Fields {
   public static final Field<Integer> INTEGER = new IntegerField();
   public static final Field<String> STRING = new StringField();
}

A: Why do you think an enum is preferable to this?
public final class Fields {
    public static final Field<Integer> INTEGER = new IntegerField();
    public static final Field<String> STRING = new StringField();

    //private ctor
}

or if you prefer
public final class Fields {
    public static Field<Integer> integerField() {
        return new IntegerField();
    }

    public static Field<String> stringField() {
        return new StringField();
    }

    //private ctor
}

Why would I want to call Fields.INTEGER.get() when I can just use Fields.INTEGER?


text:
Q: Injectivity of $-2p(x)+xp′(x)$ over cubic polynomials
Consider the transformation $T:P_3(\mathbb R)\to P_3(\mathbb R)$, $T(p(x))=-2p(x)+xp'(x)$. Is this linear transformation mentioned injective?

I would appreciate your help for this question above.
I understand to find whether it is injective or not, I have to find $T(v) = 0$ for which $v\ne0$ exists.
I have expanded the RHS and to me, it seems to be non-injective.
However, I need more confirmation for this as to me it's quite tough.

A: To prove $T$ is not injective, we have to prove that $\operatorname{Ker}T\neq \{0\}$, i.e. find a non-zero polynomial $p\in \mathbf{R}[X]_{\leqslant 3}$ for which $T(p)\neq 0$.
Note that $T(X^2)=-2\cdot X^2+X\cdot 2X=0$, hence $T$ is not injective.

A: Treating polynomials as vectors with the first coefficient representing the constant term, we have
$$T=\begin{bmatrix}
-2+0&0&0&0\\
0&-2+1&0&0\\
0&0&-2+2&0\\
0&0&0&-2+3\end{bmatrix}=
\begin{bmatrix}
-2&0&0&0\\
0&-1&0&0\\
0&0&0&0\\
0&0&0&1\end{bmatrix}$$
The determinant is zero, so $T$ is not injective. A non-trivial vector in the nullspace of $T$ is $(0,0,1,0)^T$, which corresponds to $p(x)=x^2$; we may verify that applying $T$ to this polynomial returns $0$.


text:
Q: Loop for each subfolder R This is my code:
setwd("folder/subfolder1")
Data <- ReadAffy()
eset<-rma(Data)
write.expres(eset, file="subfolder1.txt")

I have a number of subfolders in my folder and and I want to make a script that will handle all of the subfolders in the loop and create text files named as subfolders.
How can I do this?

A: How about this:
# get into the parent directory
setwd("folder")
# loop through the sub directories (use [-1] to lop off the current directory: ".")
for (dir in list.dirs()[-1]) {
    # get into the sub directory
    setwd(dir)
    # do the do
    Data <- ReadAffy()
    eset<-rma(Data)
    # build the file name by pasting ".txt" on the end of the directory name
    write.expres(eset, file=paste(dir, "txt", sep="."))
    # pop back up to the parent directory
    setwd("../")
}


text:
Q: Numpy: Quick setting of array elements I just came across a showstopper for a part of my code and I am not sure what I am doing wrong...
I simply have a large data cube and want to change the maximum values along the z axis to some other number:
import numpy as np
from time import time

x, y, z = 100, 100, 10
a = np.arange(x*y*z).reshape((z, y, x))

t = time()
a[np.argmax(a, axis=0)] = 1
print(time() - t)

This takes about 0.02s which is a bit slow for such a small array, but ok. My problem is that I need to do this with arrays as large as (32, 4096, 4096) and I have not had the patience to let this finish with the above code...it's just too inefficient, but it should actually be very fast! Am I doing something wrong with setting the array elements?

A: You are basically indexing your numpy array with a numpy array containing numbers. I think that is the reason why it is so slow (and I'm not sure if it really does what you want it to do).
If you create a boolean numpy array and use this as slice it's orders of magnitudes faster.
For example:
pos_max = np.expand_dims(np.argmax(a, axis=0), axis=0)
pos_max_indices = np.arange(a.shape[0]).reshape(10,1,1) == pos_max
a[pos_max_indices] = 1

is 20 times faster than the original and does the same.

A: I don't think it is the indexing with numbers that's slowing it down.  Usually indexing a single dimension with a boolean vector is slower than indexing with the corresponding np.where.
Something else is going on here.  Look at these shapes:
In [14]: a.shape
Out[14]: (10, 100, 100)
In [15]: np.argmax(a,axis=0).shape
Out[15]: (100, 100)
In [16]: a[np.argmax(a,axis=0)].shape
Out[16]: (100, 100, 100, 100)

The indexed a is much larger than the original, 1000x.
@MSeifert's solution is faster, but I can't help feeling it is more complex than needed.
In [35]: %%timeit
   ....: a=np.arange(x*y*z).reshape((z,y,x))
   ....: pos_max = np.expand_dims(np.argmax(a, axis=0), axis=0)
   ....: pos_max_indices = np.arange(a.shape[0]).reshape(10,1,1) == pos_max
   ....: a[pos_max_indices]=1
   ....:
1000 loops, best of 3: 1.28 ms per loop

I'm still working on an improvement.
The sample array isn't a good one - it's too big to display, and all the max values on the last z plane:
In [46]: x,y,z=4,2,3
In [47]: a=np.arange(x*y*z).reshape((z,y,x))
In [48]: a
Out[48]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]],

       [[16, 17, 18, 19],
        [20, 21, 22, 23]]])

In [49]: a[np.argmax(a,axis=0)]=1
In [50]: a
Out[50]:
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]],

       [[ 1,  1,  1,  1],
        [ 1,  1,  1,  1]]])

I could access those same argmax values with:
In [51]: a[-1,...]
Out[51]:
array([[1, 1, 1, 1],
       [1, 1, 1, 1]])

Let's try a random array, where the argmax can be in any plane:
In [57]: a=np.random.randint(2,10,(z,y,x))
In [58]: a
Out[58]:
array([[[9, 7, 6, 5],
        [6, 3, 5, 2]],

       [[5, 6, 2, 3],
        [7, 9, 6, 9]],

       [[7, 7, 8, 9],
        [2, 4, 9, 7]]])
In [59]: a[np.argmax(a,axis=0)]=0
In [60]: a
Out[60]:
array([[[0, 0, 0, 0],
        [0, 0, 0, 0]],

       [[0, 0, 0, 0],
        [0, 0, 0, 0]],

       [[0, 0, 0, 0],
        [0, 0, 0, 0]]])

Oops - I turned everything to 0.  Is that what you want?
Let's try the pos_max method:
In [61]: a=np.random.randint(0,10,(z,y,x))
In [62]: a
Out[62]:
array([[[9, 3, 9, 0],
        [6, 6, 2, 4]],

       [[9, 9, 4, 9],
        [5, 9, 7, 9]],

       [[1, 8, 1, 7],
        [1, 0, 2, 3]]])
In [63]: pos_max = np.expand_dims(np.argmax(a, axis=0), axis=0)
In [64]: pos_max
Out[64]:
array([[[0, 1, 0, 1],
        [0, 1, 1, 1]]], dtype=int32)
In [66]: pos_max_indices = np.arange(a.shape[0]).reshape(z,1,1) == pos_max
In [67]: pos_max_indices
Out[67]:
array([[[ True, False,  True, False],
        [ True, False, False, False]],

       [[False,  True, False,  True],
        [False,  True,  True,  True]],

       [[False, False, False, False],
        [False, False, False, False]]], dtype=bool)
In [68]: a[pos_max_indices]=0
In [69]: a
Out[69]:
array([[[0, 3, 0, 0],
        [0, 6, 2, 4]],

       [[9, 0, 4, 0],
        [5, 0, 0, 0]],

       [[1, 8, 1, 7],
        [1, 0, 2, 3]]])

That looks more reasonable.  There still is a 9 in the 2nd plane, but that's because there was also a 9 in the 1st.

This still needs to be cleaned up, but here's a non-boolean mask solution:
In [98]: a=np.random.randint(0,10,(z,y,x))
In [99]: a1=a.reshape(z,-1)   # it's easier to work with a 2d view
In [100]: ind=np.argmax(a1,axis=0)
In [101]: ind
Out[101]: array([2, 2, 1, 0, 2, 0, 1, 2], dtype=int32)
In [102]: a1[ind,np.arange(a1.shape[1])]  # the largest values
Out[102]: array([9, 8, 7, 4, 9, 7, 9, 6])
In [104]: a1
Out[104]:
array([[3, 1, 5, 4, 2, 7, 4, 5],
       [4, 4, 7, 1, 3, 7, 9, 4],
       [9, 8, 3, 3, 9, 1, 2, 6]])

In [105]: a1[ind,np.arange(a1.shape[1])]=0
In [106]: a
Out[106]:
array([[[3, 1, 5, 0],
        [2, 0, 4, 5]],

       [[4, 4, 0, 1],
        [3, 7, 0, 4]],

       [[0, 0, 3, 3],
        [0, 1, 2, 0]]])

Working with a1 the 2d view is easier; the exact shape of the x,y dimensions is not important to this problem.  We are changing individual values, not columns or planes.  Still I'd like to do get it working without `a1.

Here are two functions that replace the maximum value (in the 1st plane).  I use copy since it makes repeated time testing easier.
def setmax0(a, value=-1):
    # @MSeifert's
    a = a.copy()
    z = a.shape[0]
    # a=np.arange(x*y*z).reshape((z,y,x))
    pos_max = np.expand_dims(np.argmax(a, axis=0), axis=0)
    pos_max_indices = np.arange(z).reshape(z,1,1) == pos_max
    a[pos_max_indices]=value
    return a

def setmax1(a, value=-2):
    a = a.copy()
    z = a.shape[0]
    a1 = a.reshape(z, -1)
    ind = np.argmax(a1, axis=0)
    a1[ind, np.arange(a1.shape[1])] = value
    return a

They produce the same result in a test like:
ab = np.random.randint(0,100,(20,1000,1000))
test = np.allclose(setmax1(ab,-1),setmax0(ab,-1))

Timings (using ipython timeit) are basically the same.
They do assign values in different orders, so setmax0(ab,-np.arange(...)) will be different.


text:
Q: How to validate api request signature based on timestamp I'm developing API, and 1 of the requirements is similarity to https://developer.hotelbeds.com/docs/read/Home
Their authentication system is
Api-Key         Your registered API key
X-Signature     SHA256 encoding signature

Signature is generated with this code:
$this->signature = hash("sha256", $apiKey.trim($sharedSecret).time());

The question is: How on server side I can validate this signature?
I've searched their SDK for anything, but time() not being sended to server.
UPDATE:
Tested API with delay before sending request (signature generated 120 seconds before request), and it still works. Seems like it's using some other algorithms, then cycle for 30 last seconds.
Here is link for gist with test: https://gist.github.com/ineersa/756bcbe70f339afafd7e
UPDATE 2:
Tested up a bit further, and it seems that it works in range of 5 minutes. So it must be 600 hashes generation.

A: First you got to know the api key on the server side somehow.
Then you have to create a loop incrementing a date with seconds starting from some defined period before, like 30 seconds before and each loop you create the hash and compare to the hash you got from client.
limit your loop to the amount of time you want to give in seconds.
for example, if you want to have 60 seconds
for($i=-60;$i<=0;$i++){
    $token_validate = hash("sha256", $apiKey.trim($sharedSecret).strtotime(date("YmdHis",strtotime("now {$i} seconds"))));
    if($token_validate==$token_sent){
        break;
        $somevalidationvar=true;
    }
}

All the point is that you got to know that when the key is generated time is gonna be X and when key is validated time is gonna be X+Y. So this way presuming for example that the request can not last longer than 60 seconds you can create the hash assuming each second from 60 seconds before now till now and see if any of the hashes match the one you sent.
If it does you got it.


text:
Q: background color change on hover with background-size I have the following code:
CSS:

HTML:

    aa

'down.png' is an image with a transparent background. What I wanted to do was have the color of the background change while still keeping the image in front of the color.
The previous code does almost everything right, except that when I hover the mouse over the div, nothing happens.
QUESTION: Why might it be that the hovering and the background color change are not working?
Here is a jsfiddle link with the problem happening:
https://jsfiddle.net/sdsze2fv/

A: The problem is that you are using background: for the "background image". Differentiate background image and background color by using background-color and background-image respectively.

div.testy {
        border:1px solid black;
    }

    div.testy:hover {
        background-color:red;

    }

    aa

A: This happens because you already defined your background inline in your html.
Inline styles always override styles set in a css file unless you have added !important to the style.
I recommend that you only set background-image in your inline style and then background-color in your rule in the CSS-file.

div.testy {
  border:1px solid black;
}

div.testy:hover {
  background-color:red;
}

    aa

A: The background you are setting inline is overriding the one in the css rule. Inline styles always override anything (except stuff with !important). If you remove the inline and put it in a rule, it will work. Or another method is included in this
JSFIDDLE
in this we are saying 'hey, i want the bkgrnd image to be this'...not the background...because background includes everything from image, color, repeat etc. Its the shorthand. So you are technically setting the bkgrnd color there too...which is why its over riding your hover.
Here is the other option...remove from inline and put it into the rule...as is....then it also works
JSFIDDLE2
div.testy {
   border:1px solid black;
   height: 100px;
   font-size: 25px;
   color: orange;
   background:  url('https://upload.wikimedia.org/wikipedia/commons/3/3a/Gluecksklee_(transparent_background)2.png') no-repeat;
   background-size: contain;
}

div.testy:hover {
   background-color:red;
}


text:
Q: Change specifc plot height apex chart react I need to set specific heights to different plots in a timeline chart in a react app using apexcharts.
I want the yellow one to be shorter (found in the picture below)
The docs are not that explicit about any modification to the chart
I could change the height of all of them but not one particular one

I went through the documentation without result.


text:
Q: Matlab optimisation Apologies if this is too much like a 'do my homework' question.  I am a bit stuck and this is my go to place.  This is not code I wrote, but I am now maintaining it.
I have a tool that runs for around 8 hours on a bad day.  I profiled it today.  91.4% of runtime is in one subfunction, and within that 70% of the time is spent on this one line of code. This is getting called effectively 60000 times in the profiled run due to being inside 3-4 nested for loops (unavoidable)
    testincrease = ones(183,3021)*.02;
    cRange = (0:177)'; %fix broken syntax highlighting --> '
    pRate = ones(183,3021)*.02;
    lengthA = 0;
    lengthP = 178;
    nSim = 3021;

    tic
    for i  = 1:100
    v_F = @(adj_N,adj_I) (((1+ adj_I+ testincrease(cRange+1,:))./(1 + adj_N + pRate(cRange+1,:))).^...
                repmat([cRange+0.5],[1 nSim]))...
                ./ ...
                (repmat(((1+adj_I+testincrease(lengthA+1,:))./(1 + adj_N+ pRate(lengthA+1,:))), [lengthP 1]).^...
                repmat([repmat(cRange(1), [lengthP 1])], [1 nSim]));
    v=v_F(0,0);
    end
    toc

Current Ideas:
I think that perhaps I could use bsxfun in place of repmat (and am trying that at the moment)
When cRange(1) = 0 (as it did in one part of my test data - the part I have put here) the second half is simply dividing by 1 - an expensive and meaningless calculation.  So I want to use 'if' clauses around this to avoid unnecessary calculation.
Calling another language - this would be entirely new for me.  Probably going to try it.  There is apparently easy access to java, and also creating mex files.  In the latter case I think the overhead of passing data will be to expensive unless I rewrite huge swathes of code rather than just this one line.
If you have any other thoughts I would be grateful to hear them.  If not I'll keep doing some more research.
Edit:  Just noticed that the final line of the function repmats are completely unnecessary, since you can .^ by a scalar value without needing to change it to a matrix
Secondary edit:  This is what it looks like so far. 30% savings.
tic
for i  = 1:100
    if cRange(1) == 0

        v_F = @(adj_N,adj_I) bsxfun(@power,((1+ adj_I+ testincrease(cRange+1,:))./(1 + adj_N + pRate(cRange+1,:))),cRange+0.5);

    else
        v_F = @(adj_N,adj_I) bsxfun(@power,((1+ adj_I+ testincrease(cRange+1,:))./(1 + adj_N + pRate(cRange+1,:))),cRange+0.5)...
            ./ ...
            (repmat(((1+adj_I+testincrease(lengthA+1,:))./(1 + adj_N+ pRate(lengthA+1,:))).^cRange(1), [lengthP 1]));

    end
    v=v_F(0,0);
end
AllChange = toc;

But for some reason the bsxfun change that speeds it up in 2011a slows it down in 2008 where we compile. Bugger.

A: Suggestion 1 - try rewriting code without repmat:
repmat makes tons of memory allocations and memory copies... so if you were to rewrite the code to be the same functionality but don't use repmat it might have huge speed increase. (FYI... that one line of code has 4 repmat function calls... one of the repmat calls has repmat INSIDE of it... that would be horribly slow.)
Suggestion 2 - try rewriting the one-liner:
rewrite this MASSIVE one-liner into multiple lines. then re-run your profiler. you will then be able to more clearly see exactly what is causing the slow down! then you can fix that bit of code. (pro tip: massive one liners are sometimes not the best thing to have in your code because of various reasons (readability, debugging, performance, etc)) – Trevor Boyd Smith 17 secs ago edit
Suggestion 3 - take advantage of parallelization:
I think most of the operations in your one line of code can be parallelized. So I suggest first trying Matlab's parallel toolboo. Then if that still isn't fast enough... try using GPU acceleration via an external third-party Matlab GPU acceleration software package like Jacket.

(Disclaimer: These are general tips... I haven't tried any of these yet myself... but I will when I get the time.)


text:
Q: How to unwrap a promise in a JSDoc type with ReturnType? I have the following code:
const foo = async () => {
  return 1
}

I want to add a type to a variable with the ReturnType of the function, but the type after resolving the promise.
If I try:
/** @type {ReturnType<foo>} */
let bar

I get Promise<number>, but I want to get number.
Is it possible to achieve this result in JSDoc? How?

A: I am not able to understand the core issue and why you want to implement like this. As you are using async before a function then it will create a promise. If you will call this method it will return a promise (Promise<number>).
METHOD-1
You can easily add return type of this function like I did below:
/**
 * Return a promise
 * @return {Promise<number>} A promise of type number.
 */
const foo = async () => {
  return 1
}

And same way you can with your variable like below:
/** @type {Promise<number>} */
let bar = foo();

METHOD-2 - If you want to convert this to data type of number then their is no direct way but we can definitely do it using an extra function here. Just listen to promise using then method and pass the resolved value for assignment in the new function.
In this your function will stay as is as it will always returns a promise.
/**
 * Return a promise
 * @return {Promise<number>} A promise of type number.
 */
const foo = async () => {
  return 1
}

/** @type {number} */
let x = -Infinity;
function assignVariable(myValue) {
  x = myValue;
  console.log(x);
}

foo().then(value => {
  assignVariable(value);
});

Please find working snippit here:

const foo = async () => {
  return 10;
};

let x = -1;
function assignVariable(myValue) {
  x = myValue;
  console.log(x)
}

foo().then(value => {
  assignVariable(value);
});

A: Use the type Awaited<T>
/** @type {Awaited<ReturnType<foo>>} */
let bar


text:
Q: iOS FCM Notifications working from Google Console but not from server iOS FCM Notifications working from Google Console but not from server
Here is my Appdelegate.m
#import "AppDelegate.h"
#import <UserNotifications/UserNotifications.h>

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@import UserNotifications;
#endif

// Implement UNUserNotificationCenterDelegate to receive display notification via APNS for devices
// running iOS 10 and above.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
@end
#endif

// Copied from Apple's header in case it is missing in some cases (e.g. pre-Xcode 8 builds).
#ifndef NSFoundationVersionNumber_iOS_9_x_Max
#define NSFoundationVersionNumber_iOS_9_x_Max 1299
#endif

@implementation AppDelegate

NSString *const kGCMMessageIDKey = @"gcm.message_id";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [NSThread sleepForTimeInterval:3.0];
    self.defaults = [NSUserDefaults standardUserDefaults];
    self.selectedIndexArray = [[NSMutableArray alloc]init];

    // [START configure_firebase]
    [FIRApp configure];
    // [END configure_firebase]

    // [START set_messaging_delegate]
    [FIRMessaging messaging].delegate = self;
    // [END set_messaging_delegate]
       // Register for remote notifications. This shows a permission dialog on first run, to
    // show the dialog at a more appropriate time move this registration accordingly.
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        // iOS 7.1 or earlier. Disable the deprecation warnings.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        UIRemoteNotificationType allNotificationTypes =
        (UIRemoteNotificationTypeSound |
         UIRemoteNotificationTypeAlert |
         UIRemoteNotificationTypeBadge);
        [application registerForRemoteNotificationTypes:allNotificationTypes];
#pragma clang diagnostic pop
    } else {
        // iOS 8 or later
        // [START register_for_notifications]
        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
            UIUserNotificationType allNotificationTypes =
            (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
            UIUserNotificationSettings *settings =
            [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        } else {
            // iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
            // For iOS 10 display notification (sent via APNS)
            [UNUserNotificationCenter currentNotificationCenter].delegate = self;
            UNAuthorizationOptions authOptions =
            UNAuthorizationOptionAlert
            | UNAuthorizationOptionSound
            | UNAuthorizationOptionBadge;
            [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
            }];
            // For iOS 10 display notification (sent via APNS)
            [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
            // For iOS 10 data message (sent via FCM)
            [[FIRMessaging messaging] setDelegate:self];
#endif
        }
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        // [END register_for_notifications]
    }

     return YES;
}
// [START receive_message]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // With swizzling disabled you must let Messaging know about the message, for Analytics
     [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

    // Print message ID.
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"%@", userInfo);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // With swizzling disabled you must let Messaging know about the message, for Analytics
     [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

    // Print message ID.
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"%@", userInfo);

    completionHandler(UIBackgroundFetchResultNewData);
}

// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSDictionary *userInfo = notification.request.content.userInfo;

    // With swizzling disabled you must let Messaging know about the message, for Analytics
     [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

    // Print message ID.
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"%@", userInfo);
    NSString *notResStr = notification.request.content.body;
    self.notificationArray = [notResStr componentsSeparatedByString:@","];

    // Change this to your preferred presentation option
    completionHandler(UNNotificationPresentationOptionAlert);
}
// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler {
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"userInfo : %@", userInfo);

    completionHandler(UNNotificationPresentationOptionAlert);
}
#endif
// [END ios_10_message_handling]

// [START refresh_token]
- (void)messaging:(nonnull FIRMessaging *)messaging didRefreshRegistrationToken:(nonnull NSString *)fcmToken {
    // Note that this callback will be fired everytime a new token is generated, including the first
    // time. So if you need to retrieve the token as soon as it is available this is where that
    // should be done.
    NSLog(@"FCM registration token: %@", fcmToken);
    [self.defaults setObject:fcmToken forKey:@"deviceToken"];

    // TODO: If necessary send token to application server.
}
// [END refresh_token]

// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set [Messaging messaging].shouldEstablishDirectChannel to YES.
- (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemoteMessage *)remoteMessage {
    NSLog(@"Received data message: %@", remoteMessage.appData);
}
// [END ios_10_data_message]

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Unable to register for remote notifications: %@", error);
}

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs device token can be paired to
// the FCM registration token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"APNs device token retrieved: %@", deviceToken);

    // With swizzling disabled you must set the APNs device token here.
     [FIRMessaging messaging].APNSToken = deviceToken;
}

/*- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // [[Messaging messaging] appDidReceiveMessage:userInfo];

    // Print message ID.
    if (userInfo[kGCMMessageIDKey]) {
        NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
    }

    // Print full message.
    NSLog(@"%@", userInfo);

    completionHandler(UIBackgroundFetchResultNewData);
}*/
#pragma mark -
#pragma mark Shared Instance

+ (AppDelegate*) sharedInstance{

    return (AppDelegate*)[[UIApplication sharedApplication] delegate];

}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
}
- (void)applicationWillTerminate:(UIApplication *)application {
    [self.defaults synchronize];

}

@end

The response from server is in this format
Array
(
    [to] => .....
    [aps] => Array
        (
            [data] => Test silent background push
            [moredata] => Do more stuff
        )

    [priority] => high
    [notification] => Array
        (
            [body] => Test Body
            [title] => Test Title
        )

    [data] => Array
        (
            [Nick] => Mario
            [Room] => PortugalVSDenmark
        )

)

Notification key is there and priority is also set to high but the methods itself not calling irrespective of foreground and background.
Do I need to make any changes in code to capture the FCM notifications?
Tried in different devices as well
set firebaseproxyenabled in info.plist to NO
$url = 'https://fcm.googleapis.com/fcm/send';
        $headers = array(
            'Authorization: key=' . FIREBASE_API_KEY,
            'Content-Type: application/json'
        );
             $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        // Execute post
        $result = curl_exec($ch);

for android receiving the response even in fore ground and back ground
data = {image:\"\/logo.png\",
        notification:{\"themeicon\":\"public\\/upload_files\\/theme\\/events.png\",
                        "notification_type\":\"Mee\",
                        \"mob_number\ ":\"99999999999\",
                        \"shoutouttitle\ ":\"test\",
                        \"themecolor\ ":\"#6f95f5\",
                        \"theme_Id\ ":\"3\",
                        \"student_Id\ ":\"9\",
                        \"shoutoutuploadpath\ ":\"\",\"notification_Id\ ":\"107\",
                        \"shoutoutmessage\ ":\"test msg\",
                        \"shoutouttimeslot\ ":\"\"
                    },
    \"is_background\ ":false,
    \"payload\ ":{\"score\":\"5.6\",
                    \"team\ ":\"India\"
                },
    \"title\":\Events\",
    \"message\":\"test\",
    \"timestamp\":\"2017-06-09 8:59:45\"
}";from = 608855029366;
}

but in iOS not receiving any thing irrespective of app state
but when notification is triggered from google console receiving the notifications

A: The issue must be because of payload format which you are getting.
It should be like below format:-
{
    "aps" : {
      "alert" : {
        "body" : "great match!",
        "title" : "Portugal vs. Denmark",
      },
      "badge" : 1,
    },
    "customKey" : "customValue"
  }


text:
Q: Webpack Encore with Babel I'm getting the following error in my browser console:

Uncaught ReferenceError: regeneratorRuntime is not defined

I found a question and answer here that said to install Babel to get this working, so I set out to do just that. Now for context, I've never used Webpack Encore nor Babel before now. I've never needed to. I added the below lines to my Webpack Encore file and got another error.
Encore.configureBabel(() => {}, {
    useBuiltIns: 'usage',
})

[ encore ] Module build failed (from ./node_modules/babel-loader/lib/index.js):
RangeError: [BABEL] \resources\js\app.ts: Invalid Option: The version passed to `corejs` is invalid. Currently, only core-js@2 and core-js@3 are supported. (While processing: "\\node_modules\\@babel\\preset-env\\lib\\index.js")
    at normalizeCoreJSOption (\node_modules\@babel\preset-env\lib\normalize-options.js:114:11)
    at normalizeOptions (\node_modules\@babel\preset-env\lib\normalize-options.js:126:18)
    at \node_modules\@babel\preset-env\lib\index.js:271:37
    at \node_modules\@babel\helper-plugin-utils\lib\index.js:22:12
    at async (\node_modules\@babel\core\lib\gensync-utils\async.js:43:33)
    at async (\node_modules\gensync\index.js:186:15)
    at \node_modules\gensync\index.js:216:13
    at Generator.next (<anonymous>)
    at \node_modules\@babel\core\lib\config\full.js:217:21
    at Generator.next (<anonymous>)

With that error, I add corejs: '3.0.0', below the useBuiltIns and I'm getting more errors. Another question I found suggested that corejs would just render useBuiltIns: 'usage' obsolete.
This is all getting to be a little too much for async/await functionality. Functionality that works in my browser.


text:
Q: Path navigation in javascript? So i've been working on a website for a while using the Yelp API. And everytime i ant to import a component-class i stuggle at getting the correct filepath and it makes me insane. Can someone give me an easy explanation how navigating around in the folders with ease? I always have to fiddle until i get it and its time for me to learn this once in for all bc. it would save me so much time and energy.
This is what i usually use:
import logo from './logo.svg';
import '../Business/Business';
there is also other ways? like /root/components/Business/Business
pls be nice im still new to java , thank you :D

A: I'm not sure if there is any easy way around this. However there are few things that can be used to help.
Depending on text editor you use, this can be auto completed by the text editor itself. Visual studio code, for example has this plugin which is designed to help..
https://marketplace.visualstudio.com/items?itemName=ionutvmi.path-autocomplete
If this is no good then focus on the file to you are working on and where it is in the file system.
If the file you are linking is in the same folder the the name of the file is fine.
If the folder is at a higher level just add ../ for every level it is higher.
I hope this helps.

A: You can make use of resolve.modules in webpack config
According to the documentation

resolve.modules tells webpack what directories should be searched when resolving
  modules.
Absolute and relative paths can both be used, but be aware that they
  will behave a bit differently.
A relative path will be scanned similarly to how Node scans for
  node_modules, by looking through the current directory as well as it's
  ancestors (i.e. ./node_modules, ../node_modules, and on).
With an absolute path, it will only search in the given directory.

So you would write
const path = require('path');

...
resolve: {
    modules: [
        path.resolve(__dirname, 'app/jsx'),
        'node_modules'
    ]
}

If you wish to resolve your files from dirname/app/jsx and node_modules
so essentially
import MyComponent from '/components/MyComponent.js'

will search MyComponent in dirname/app/jsx/components/MyComponent.js'


text:
Q: Accordion Collapses Immediately After I Expand a Row I am creating a drop down table with Accordion on my SharePoint site. I referenced this page (P.S. I hate W3Schools) https://www.w3schools.com/w3css/w3css_accordions.asp#:~:text=An%20accordion%20is%20used%20to%20show%20%28and%20hide%29,of%20button%20to%20open%20and%20close%20the%20content%3A
Everytime I expand a row on SharePoint, the page refreshes and immediately collapses the row. When I do it in JSFiddle or this snippet, it works fine. Why is that.
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}

.accordion {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
  transition: 0.5s;
}

.active, .accordion:hover {
  background-color: #ccc;
}

.panel {
  padding: 0 18px;
  display: none;
  background-color: white;
  overflow: hidden;
}
h2{
    text-align: center;
    font-size: 20px;
    font-weight: bold;

}
.previous {
  background-color: #104723;
  color: #b3ab7d;
}
a {
  text-decoration: none;
  display: inline-block;
  padding: 8px 16px;
}
a:link, a:visited, a:hover {
    color: #b3ab7d;
}

.backbtn{
text-align: left;
}

System and Information Integrity (SI)

<button class="accordion">SI.1.210 Identify, report, and correct information and information system flaws in a timely manner.</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="accordion">SI.1.211 Provide protection from malicious code at appropriate locations within organizational information systems.</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="accordion">S1.1.212 Update malicious code protection mechanisms when new releases are available.</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="accordion">SI.1.213 Perform periodic scans of the information system and real-time scans of files from external sources as files are downloaded, opened, or executed</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

« Go Back

A: You need to add the attribute type="button" to your buttons, to prevent them from behaving as "submit" buttons and submitting the form data to the server (which is what is causing your page refresh).
<button type="button" class="accordion">Description</button>

From the MDN page on the button element (emphasis mine):

type
The default behavior of the button. Possible values are:

*

*submit: The button submits the form data to the server. This is the default if the attribute is not specified for buttons associated with
a <form>, or if the attribute is an empty or invalid value.

*reset: The button resets all the controls to their initial values, like <input type="reset">. (This behavior tends to annoy users.)

*button: The button has no default behavior, and does nothing when pressed by default. It can have client-side scripts listen to the
element's events, which are triggered when the events occur.

If you inspect your HTML, you will see almost undoubtedly that what you have added to SharePoint exists inside a <form> element that is just part of SP pages, which is why the submit behavior happens if you don't specify your button type as something other.


text:
Q: ¿Agregar palabras claves imágenes ayuda a mejorar el SEO de una página web? Estoy trabajando en un proyecto, realizando una página web, la cual recibí una recomendación de cambiar los nombres de mis imágenes por nombres largos con palabras claves, ejemplo:
televisores_chile_sony_valpariso_<nombre-de-imagen>
Realizando esto:

*

*¿Conseguiré aumentar mi SEO o solo conseguiré que Google me penalice por repetir muchas veces las palabras claves?

Son alrededor de 100 imágenes

A: Como todo excesivo uso de las herramientas que nos da google para posicionar nuestros sitios, puede ser penalizado si se usa abusivamente.
Según Google

El uso de palabras clave para los atributos "alt" ("aglomeración de palabras clave") genera una experiencia negativa para el usuario y puede hacer que su sitio se considere spam. Concéntrese en crear contenidos útiles con mucha información y que utilicen las palabras clave de manera apropiada y en contexto. Le recomendamos que pruebe el contenido de su sitio con un navegador de solo texto como Lynx.

Fuente: Google Webmaster
Acá tengo un documento que realice hace poco sobre algunos tips de SEO que quizá te pueden ayudar: Bases de posicionamiento
Muchos Saludos

A: Mi experiencia me dice que indicar un nombre que describa la imagen como nombre de fichero siempre es una buena practica. No digo usar la palabra clave en todas las imágenes para conseguir posicionar una palabra. Lo que digo es que, usando el sentido común, un nombre de imagen que describa su contenido siempre es útil, ya sea una maquina o una persona quien lo lea.
Si la foto es un chico columpiándose, llamar a la imagen "chico-columpio.jpg" siempre va a ser positivo. Si alguien busca "chico columpio" en imágenes de google, la imagen saldrá en los resultados.
Poner en todas las imágenes la palabra clave que quieres posicionar, es una mala practica. Poner nombres que describan la imagen no.
Es preferible que llames a la imagen con el modelo exacto del producto, ya que una persona verdaderamente interesada en ese producto, acabará en tu web.
Un saludo.

A: Puede ayuda pero si es excesivo lo que haces te va a penalizar.
El motor de seo tiene en cuenta el contexto y ese tipo de fraude es detectable desde hace muchos años.
Mejor aprende de SEO, hay muchos cursos en linea al respecto.

A: Por mi experiencia te puedo contar que pongas a las imágenes y a los alt de las mismas lo que describa únicamente a esa imagen. Si es una televisión led 55 pulgadas llámala tv-led-55-p, y en el alt "televisión LED 55 pulgadas sony" por ejemplo. Nada de ponerle a todas las imágenes las keywords que quieras posicionar en tu página, y mucho menos solo las principales...
Google ya sabe que tu ciudad es Chile, no hace falta que se lo recalques en todos los lugares, de hecho no es una buena práctica sobrecargarlo por la fuerza, tal vez alguna keyword de la sección en la que están esas imágenes, pero ay te digo que sin sobrecargarlo. Céntrate en describir a la imagen


text:
Q: Finding the overlapping locations for a 5 mile and 10 mile radius for a list of location data with latittude and longitude I have a 10,000 observation dataset with a list of location information looking like this:
 ADDRESS                 |    CITY        |  STATE | ZIP   |LATITUDE   |LONGITUDE

1189 Beall Ave           |  Wooster       | OH  | 44691 | 40.8110501   |-81.93361870000001

580 West 113th Street    |  New York City | NY  | 10025 | 40.8059768   | -73.96506139999997

268 West Putnam Avenue   |  Greenwich     | CT  | 06830 | 40.81776801  |-73.96324589997

1 University Drive       |   Orange       | CA  | 92866 | 40.843766801 |-73.9447589997

200 South Pointe Drive   |  Miami Beach   | FL  | 33139 | 40.1234801   |-73.966427997

I need to find the overlapping locations within a 5 mile and 10 mile radius. I heard that their is a function called geodist which may allow me to do that, although I have never used it. The problem is that for geodist to work I may need all the combinations of the latitudes and longitudes to be side by side, which may make the file really really large and hard to use. I also, do not know how I would be able to get the lat/longs for every combination to be side by side.
Does anyone know of a way I could get the final output that I am looking for ?

A: Here is a broad outline of one possible approach to this problem:

*

*Allocate each address into a latitude and longitude 'grid' by rounding the co-ordinates to the nearest 0.01 degrees or something like that.

*Within each cell, number all the addresses 1 to n so that each has a unique id.

*Write a datastep taking your address dataset as input via a set statement, and also load it into a hash object. Your dataset is fairly small, so you should have no problems fitting the relevant bits in memory.

*For each address, calculate distances only to other addresses in the same cell, or other cells within a certain radius, i.e.

*

*Decide which cell to look up

*Iterate through all the addresses in that cell using the unique id you created earlier, looking up the co-ordinates of each from the hash object

*Use geodist to calculate the distance for each one and output a record if it's a keeper.

This is a bit more work to program, but it is much more efficient than an O(n^2) brute force search. I once used a similar algorithm with a dataset of 1.8m UK postcodes and about 60m points of co-ordinate data.


text:
Q: A sum related to binomial theorem
If $\dfrac{x^2+x+1}{1-x} = a_0+a_1x+a_2x^2+\cdots$
then $\displaystyle\sum_{\gamma = 1}^{50}a_{\gamma} = ??$

Original Image
This is a sum related to evaluating a series, from the chapter binomial theorem.
This is how I tried to solve the question

I took the $(1-x)$ from the denominator to the numerator making it a $$(1-x)^{-1}$$
and then expanded it binomially, and I tried to find the sum of the coefficients of $$x,x^2,x^3,....,x^{50}$$
However my answer isn't matching. I got $1325$ but the answer is $149$.
update:i do get my mistake, but
how do i go about solving it?

A: Your first few terms are correct.  But you only have three terms in the numerator, so the series is $1+2x+3x^2+3x^4+3x^5+...$

A: By considering,
$\begin{array}{rcccccc}
   \frac{1}{1-x}   & =  & 1 & + & x & + & x^{2}+\ldots + x^{50} + \ldots \\
   \frac{x}{1-x}   & =  &   &   & x & + & x^{2}+\ldots + x^{50} + \ldots \\
   \frac{x^2}{1-x} & =  &   &   &   &   & x^{2}+\ldots + x^{50} + \ldots \\
 \end{array}$
Hence the sum is $50+50+49=149$.

A: The general expansion is $(1-x)^{-1}=1+x+x^2...\infty$ so now we need sum of coefficients upto $50$. If we see the pattern we see that $(x^2+x+2)(1)=3$ sum of coeeficients. For $(1+x)(1+x+x^2)$ its 6 so its an AP. So we need sum upto $50$ which is $49\times 3=147$ but 1 term will be $x^{51}$ which we dont need so we get only $+2$ for last term so its $147+2=149$ . Hope its clear.


text:
Q: Javascript data-attribute isArray returns true So as im building a small plugin I can across a small issue, when filtering the selectors I check if the selector is an Array, which in most cases works but when using a attribute(dataset in this case) it sees the selector as an array.
Is there a way to fix this?
    var Constructor = function (selector) {
        if (!selector) return;
        if (selector === 'document') {
            this.nodes = [document];
        } else if (selector === 'window') {
            this.nodes = [window];
        } else if(typeof selector === 'string') {
            this.nodes = document.querySelectorAll(selector);
        }else{
            this.nodes = Array.isArray ? selector : [selector];// it will return as an array
        }
    };

partofanplugin.find('[data-id="12"]')// will be seen as an array instead of a string.

A: You need to actually call the function, right now you are just checking if the function exists
Array.isArray(selector) ? selector : [selector];

instead of
Array.isArray ? selector : [selector];


text:
Q: HTTP headers problem I'me getting the following error:
Response object error 'ASP 0156 : 80004005'

Header Error

/includes/page_language.asp, line 3

The HTTP headers are already written to the client browser. Any HTTP header modifications must be made before writing page content.

But, the 1st line of the page is the doctype:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

The next line is:
<!-- #include file = "includes/page_language.asp" -->

The 1st 4 lines in the page_language.asp file are:
<%
response.codePage = 65001
response.charset = "utf-8"
%>

So it doesn't like response.charset = "utf-8" - but there is no HTML before these lines to cause the problem...
This error only happens the 1st time you load a page - press refresh when this has happened and the page loads fine. The site was working properly, but we noticed this yesterday.
UPDATE:
I've now changed index.asp to read:
<%
response.codePage = 65001
response.charset = "utf-8"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

But I'm still getting the error at the response.charset line....
I'm stumped - any suggestions would be greatly appreciated!

A: Try to use firebug and test response.charset. Look's like it is
not HTTP Content-Type charset but <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

A: Finally fixed by removing the response.charset="utf-8" and adding
<meta http-equiv="content-type" content="text/html;charset=utf-8">


text:
Q: Scheduled task running batch but not exe within the batch I know there are similar questions already out there, but none of the other solutions seem to help.
Using Windows 7, I have an executable (for this explanation, I am calling it test.exe) that takes a parameter of the current date.
Example when using the run command:
c:\test.exe 12/26/2014
The executable needs to be ran on a daily schedule.
I have the following batch file set up to run the exe with the required parameters:
@echo off
::This batch will be ran daily to start the exe program
set dateFormat=%DATE:~4,2%/%DATE:~7,2%/%DATE:~10,4%
echo Batch started %dateFormat% %Time%>> BatchLogfile.txt
set testfile=C:\test.exe
start %testfile% %dateFormat%
pause

I can run the batch successfully by double-clicking on it in explorer, but when I add it as a scheduled task it does not actually start the exe.
The batch does run and I can see the processes for the cmd and the exe, but the exe "interface" does not pop up. The echo line in the batch writes out to the log file successfully.
On the scheduled task, I am currently using cmd for the program/script and the following params:
/k "C:\test.bat"

I have also tried the following arguments unsuccessfully in the task scheduler:
C:\Windows\System32\cmd.exe

/c start "" "C:\test.bat"

/k start "C:\test.bat"

Is there anything else I should try so that the exe "interface" shows on the screen? Perhaps there is a better way to run the exe other than task scheduler?

A: If you want to see the GUI for test.exe, then you will need to configure the respective Windows Scheduled Task to "Run only when user is logged on". Of course then the process would only run for the configured user account.
This is available to select in the Security Options section in the General tab of the respective scheduled task.


text:
Q: how to accept gdpr cookies when fetching json? I am trying to get the forbes list using a query in R:
billionaires <- jsonlite::fromJSON("https://www.forbes.com/forbesapi/person/billionaires/2020/position/true.json")

I get this strange error:
Error in parse_con(txt, bigint_as_char) :
  lexical error: invalid char in json text.
                                       <!doctype html> <html lang="en"
                     (right here) ------^

This is not working because instead of the json, I get an html page asking for the gdpr consent (I am in spain)
req <- GET("https://www.forbes.com/forbesapi/person/billionaires/2020/position/true.json")
stop_for_status(req)
json <- content(req, "text")

"\n<!doctype html>\n<html lang="en">\n\t\n\t\t<meta http-equiv="Content-Language" content="en_US">\n\n\t\t<script type="text/javascript">\n\t\t\t(function () {\n\t\t\t\tfunction isValidUrl(toURL) {\n\t\t\t\t\t// Regex taken from welcome ad.\n\t\t\t\t\treturn (toURL || '').match(/^(?:https?:?\/\/)?(?:[^.(){}\\\/])?\.?forbes\.com(?:\/|\?|$)/i);\n\t\t\t\t}\n\n\t\t\t\tfunction getUrlParameter(name) {\n\t\t\t\t\tname = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');\n\t\t\t\t\tvar regex = new RegExp('[\\?&]' + name + '=([^&#])');\n\t\t\t\t\tvar results = regex.exec(location.search);\n\t\t\t\t\treturn results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));\n\t\t\t\t};\n\n\t\t\t\tfunction consentIsSet(message) {\n\t\t\t\t\tconsole.log(message);\n\t\t\t\t\tvar result = JSON.parse(message.data);\n\t\t\t\t\tif(result.message == "submit_preferences"){\n\t\t\t\t\t\tvar toURL = getUrlParameter("toURL");\n\t\t\t\t\t\tif(!isValidUrl(toURL)){\n\t\t\t\t\t\t\ttoURL = "https://www.forbes.com/";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlocation.href=toURL;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar apiObject = {\n\t\t\t\t\tPrivacyManagerAPI:\n\t\t\t\t\t{\n\t\t\t\t\t\taction: "getConsent",\n\t\t\t\t\t\ttimestamp: new Date().getTime(),\n\t\t\t\t\t\tself: "forbes.com"\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tvar json = JSON.stringify(apiObject);\n\t\t\t\twindow.top.postMessage(json,"");\n\t\t\t\twindow.addEventListener("message", consentIsSet, false);\n\t\t\t})();\n\t\t\n\n\t\t\n\t\t\t(function () {\n\t\t\t\tvar makeStub = function () {\n\t\t\t\t\tvar TCF_LOCATOR_NAME = '__tcfapiLocator';\n\t\t\t\t\tvar TCF_LOCATOR_ID = '__tcfapiTrustarc';\n\t\t\t\t\tvar win = window;\n\t\t\t\t\tvar queue = [];\n\t\t\t\t\tvar cmpFrame;\n\t\t\t\t\tfunction addFrame() {\n\t\t\t\t\t\tvar doc = win.document;\n\t\t\t\t\t\tvar otherCMP = !!(win.frames[TCF_LOCATOR_NAME]);\n\t\t\t\t\t\tif (!otherCMP) {\n\t\t\t\t\t\t\tif (doc.body) {\n\t\t\t\t\t\t\t\tvar iframe = doc.createElement('iframe');\n\t\t\t\t\t\t\t\tiframe.name = TCF_LOCATOR_NAME;\n\t\t\t\t\t\t\t\tiframe.style.display = 'none';\n\t\t\t\t\t\t\t\tiframe.id = TCF_LOCATOR_ID;\n\t\t\t\t\t\t\t\tiframe.src = 'https://trustarc.mgr.consensu.org/asset/cmpcookie.v2.html';\n\t\t\t\t\t\t\t\tdoc.body.appendChild(iframe);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsetTimeout(addFrame, 5);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn !otherCMP;\n\t\t\t\t\t}\n\t\t\t\t\tfunction tcfAPIHandler() {\n\t\t\t\t\t\tvar args = arguments;\n\t\t\t\t\t\tvar gdprApplies;\n\t\t\t\t\t\tif (!args.length) {\n\t\t\t\t\t\t\t/**\n\t\t\t\t\t\t\t shortcut to get the queue when the full CMP\n\t\t\t\t\t\t\t* implementation loads; it can call tcfapiHandler()\n\t\t\t\t\t\t\t* with no arguments to get the queued arguments\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\treturn queue;\n\t\t\t\t\t\t} else if (args[0] === 'setGdprApplies') {\n\t\t\t\t\t\t\t/\n\t\t\t\t\t\t\t* shortcut to set gdprApplies if the publisher\n\t\t\t\t\t\t\t* knows that they apply GDPR rules to all\n\t\t\t\t\t\t\t* traffic (see the section on "What does the\n\t\t\t\t\t\t\t* gdprApplies value mean" for more\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tif (args.length > 3 && parseInt(args[1], 10) === 2 && typeof args[3] === 'boolean') {\n\t\t\t\t\t\t\t\tgdprApplies = args[3];\n\t\t\t\t\t\t\t\tif (typeof args[2] === 'function') {\n\t\t\t\t\t\t\t\t\targs[2]('set', true);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (args[0] === 'ping') {\n\t\t\t\t\t\t\t/\n\t\t\t\t\t\t\t* Only supported method; give PingReturn\n\t\t\t\t\t\t\t* object as response\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tvar retr = {\n\t\t\t\t\t\t\t\tgdprApplies: gdprApplies,\n\t\t\t\t\t\t\t\tcmpLoaded: false,\n\t\t\t\t\t\t\t\tcmpStatus: 'stubCMP',\n\t\t\t\t\t\t\t\tapiVersion: '2.0'\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tif (typeof args[2] === 'function') {\n\t\t\t\t\t\t\t\targs[2](retr, true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t/\n\t\t\t\t\t\t\t* some other method, just queue it for the\n\t\t\t\t\t\t\t* full CMP implementation to deal with\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tqueue.push(args);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfunction postMessageEventHandler(event) {\n\t\t\t\t\t\tvar msgIsString = typeof event.data === 'string';\n\t\t\t\t\t\tvar json = {};\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t/\n\t\t\t\t\t\t\t* Try to parse the data from the event.  This is important\n\t\t\t\t\t\t\t* to have in a try/catch because often messages may come\n\t\t\t\t\t\t\t* through that are not JSON\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tif (msgIsString) {\n\t\t\t\t\t\t\t\tjson = JSON.parse(event.data);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tjson = event.data;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (ignore) {}\n\t\t\t\t\t\tvar payload = json.__tcfapiCall;\n\t\t\t\t\t\tif (payload) {\n\t\t\t\t\t\t\twindow.__tcfapi(\n\t\t\t\t\t\t\t\tpayload.command,\n\t\t\t\t\t\t\t\tpayload.version,\n\t\t\t\t\t\t\t\tfunction (retValue, success) {\n\t\t\t\t\t\t\t\t\tvar returnMsg = {\n\t\t\t\t\t\t\t\t\t\t__tcfapiReturn: {\n\t\t\t\t\t\t\t\t\t\t\treturnValue: retValue,\n\t\t\t\t\t\t\t\t\t\t\tsuccess: success,\n\t\t\t\t\t\t\t\t\t\t\tcallId: payload.callId,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\tif (msgIsString) {\n\t\t\t\t\t\t\t\t\t\treturnMsg = JSON.stringify(returnMsg);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tevent.source.postMessage(returnMsg, '');\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tpayload.parameter\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t/**\n\t\t\t\t\t Iterate up to the top window checking for an already-created\n\t\t\t\t\t* "__tcfapilLocator" frame on every level. If one exists already then we are\n\t\t\t\t\t* not the master CMP and will not queue commands.\n\t\t\t\t\t*/\n\t\t\t\t\twhile (win) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (win.frames[TCF_LOCATOR_NAME]) {\n\t\t\t\t\t\t\t\tcmpFrame = win;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (ignore) {}\n\t\t\t\t\t\t// if we're at the top and no cmpFrame\n\t\t\t\t\t\tif (win === window.top) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Move up\n\t\t\t\t\t\twin = win.parent;\n\t\t\t\t\t}\n\t\t\t\t\tif (!cmpFrame) {\n\t\t\t\t\t\t// we have recur'd up the windows and have found no __tcfapiLocator frame\n\t\t\t\t\t\taddFrame();\n\t\t\t\t\t\twin.__tcfapi = tcfAPIHandler;\n\t\t\t\t\t\twin.addEventListener('message', postMessageEventHandler, false);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\tmakeStub();\n\t\t\t}());\n\t\t\n\t\n\t\n\t\n\t\t<script async="async" type="text/javascript" crossorigin src='//consent.trustarc.com/notice?domain=forbes_iab2.com&c=teconsent&js=nj&noticeType=bb&gtm=1'>\n\t\n\t\n\t\n\n"

I should I do to deal with it?

A: It seems you just need to specify the notice_gdpr_prefs cookie field. The original value is 0,1,2::implied,eu;, but even if the value is empty, it returns the data. It seems to only check that the cookie field is present:
library(httr)
library(jsonlite)

result <- GET("https://www.forbes.com/forbesapi/person/billionaires/2020/position/true.json",
  add_headers(cookie = "notice_gdpr_prefs=")
)
billionaires = fromJSON(content(result, "text"))

print(billionaires)

kaggle link


text:
Q: SQL Server 2005 into Excel with OPENROWSET MSG 7399/7303 My patience is at an end with this issue. I run jobs via SSMS or the agent that have been working perfectly fine up until last week that insert data from tables/views into various Excel files.
Most recently, the jobs/code just keep running while never finishing...these jobs use to only take up-to 15-25 seconds to complete but now never end. I've tested the code below on a new sheet and it goes instantaneously! The error I'm getting also doesn't help, the solutions I've found in Google were no help or were already set.
Any ideas what would cause a openrowset export to just bomb out and not do its job?
Code I generally run that works:
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;HDR=YES;Database=C:\Automation\DYNAMIC\Output\File.xlsx;',
'SELECT * FROM [Data$]')

SELECT *
FROM [REPORTING].[dbo].[tbl_table]

The current error message:

Msg 7399, Level 16, State 1, Line 1
  The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information
  about the error.
  Msg 7303, Level 16, State 1, Line 1
  Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".

System:

*

*SQL Server 2005 32-Bit on Windows XP 32-Bit

Updated/Edited information:

*

*Excel sheets contain either functions on a separate tab or Charts extrapolating the data from the [Data$] tab (if any of this helps)

*I have created a brand new worksheet and tested my insert query and it worked perfectly

*The source file was not originally created on the server, but instead transferred via Share Drive (I don't think this would matter though)
Any help is appreciated!!
Thanks

A: I have had this same issue and what seemed to correct it was restarting SQLServer Service


text:
Q: WPF weird behaviour: The SelectedValue is set right BUT then ist reset to NULL I am binding a ListBox to a List in the ViewModel named FilmeSerienListe. SelectedItem is set when ismouseover = True. The SelectedItem of the ListBox is bound to a Property in the ViewModel named SelectedFilmSerie.
This means when the mouse is over a particular ListBoxItem, this ListBoxItem is selected and its value bound to SelectedFilmSerie. BUT this does not seem to work very well, because the SelectedFilmSerie Property is for some reason always NULL. So, I debugged the App to see what did go wrong – Now the weird behaviour – SelectedFilmSerie is in fact NOT the WHOLE time NULL.
At first – when the mouse is over a ListBoxItem – the value parameter is set to the right Object, and it is NOT NULL, BUT then when I go further with my debugging this SelectedFilmSerie Property is recalled and NOW the value parameter is NULL, which make the SelectedFilmSerie Property also NULL.
WPF:
<ListBox ItemsSource="{Binding FilmeSerienListe}"
         SelectedItem="{Binding SelectedFilmSerie}">

   <ListBox.ItemContainerStyle>
      <Style TargetType="{x:Type ListBoxItem}">

         <Setter Property="Template">
            <Setter.Value>
               <ControlTemplate TargetType="ListBoxItem">
                  <ContentPresenter />
               </ControlTemplate>
            </Setter.Value>
         </Setter>

         <Style.Triggers>
            <Trigger Property="IsMouseOver"
                     Value="True">

               <Setter Property="IsSelected"
                        Value="true" />

                  </Setter.Value>
               </Setter>
            </Trigger>
         </Style.Triggers>
      </Style>
   </ListBox.ItemContainerStyle>

C#
private IEnumerable<FilmeSerien> _filmeSerienListe;
public IEnumerable<FilmeSerien> FilmeSerienListe
{
    get => _filmeSerienListe;
    set
    {
        _filmeSerienListe = value;
        NotifyPropertyChanged();
    }
}

private FilmeSerien _selectedFilmSerie;
public FilmeSerien SelectedFilmSerie
{
    get => _selectedFilmSerie;
    set
    {
        Trace.WriteLine(value != null ? "Value is NOT null" : "Value is NULL");
        _selectedFilmSerie = value;
        NotifyPropertyChanged();
    }
}

Debugger:
ismouseover = True:

4xStep Over:

1xStep Over:

4xStep Over:

Output:
The sec the mouse entered the ListBoxItem, I get Value is NOT null and the sec the mouse leaves the ListBoxItem, I get Value is NULL

More details:
The ListBox is a list of cards bound to FilmeSerienListe with the datatype IEnumerable<FilmeSerien> each ListBoxItem is a card which is a representation of a FilmeSerien.
A card contains several Properties that are in a Property with the datatype FilmeSerien. Like: Titel, Img, Vote and other. Vote is an int datatype Property.
Looks something like this:

Problem:
Every Time I hit a star to vote a movie. I get a NullReferenceException because the SelectedFilmSerie is null.
WPF For star:
<Viewbox>
   <materialDesign:RatingBar Value="{Binding Vote}"
                              Orientation="Horizontal"
                              Foreground="SkyBlue"/>
</Viewbox>

A: If I understand you correctly, you need to select the ListBox element not by clicking, but by hovering the mouse over it.
To be honest, it does not even occur to my head for what this might be needed.
I asked in the comments to clarify the purpose of such an implementation, but you didn't answer.
But if, I understood your question correctly, then it is implemented like this:
    <Window.Resources>
        <Style x:Key="listBoxItemStyle" TargetType="ListBoxItem">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Trigger.EnterActions>
                        <BeginStoryboard>
                            <Storyboard>
                                <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsSelected">
                                    <DiscreteBooleanKeyFrame KeyTime="0" Value="True"/>
                                </BooleanAnimationUsingKeyFrames>
                            </Storyboard>
                        </BeginStoryboard>
                    </Trigger.EnterActions>
                </Trigger>
            </Style.Triggers>
        </Style>
  </Window.Resources>
    <Grid VerticalAlignment="Center" >
        <ListBox ItemsSource="{Binding FilmeSerienListe}"
                 SelectedItem="{Binding SelectedFilmSerie}"
                 ItemContainerStyle="{DynamicResource listBoxItemStyle}">
        </ListBox>
    </Grid>


text:
Q: Groovy ClassNotFoundException: groovy.swing.factory.groovy$lang$Closure In Eclipse I have for some reason since last week a weird error while using Groovy. I never seen this error before and a search shows that I seems to be the only one.
Caused by: java.lang.NoClassDefFoundError: groovy/swing/factory/groovy$lang$Closure
    at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3402)
    at java.base/java.lang.Class.privateGetPublicMethods(Class.java:3427)
    at java.base/java.lang.Class.getMethods(Class.java:2019)
    at org.junit.platform.commons.util.ReflectionUtils.getDefaultMethods(ReflectionUtils.java:1518)
    at org.junit.platform.commons.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:1491)
    at org.junit.platform.commons.util.ReflectionUtils.findMethod(ReflectionUtils.java:1341)
    at org.junit.platform.commons.util.ReflectionUtils.isMethodPresent(ReflectionUtils.java:1242)

I have no clue why I get this. I'm not using Swing or Groovy Swing anywhere. It's not JUnit 5 related because I got this also from Guice.
This should be related with Eclipse because if I compile it in Maven it runs fine. Currently I need to do a mvn clean install so that it runs again in Eclipse.
Eclipse Version: 2022-06 (4.24.0)
Build id: 20220609-1112

Groovy 3.0.14

Run in Eclipse. Groovy is added as dependency. It should run without errors.


text:
Q: How to sort a Python dict's keys by value I have a dict that looks like this
{ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }
And I would like to convert it DESC and create a list of just the keywords. Eg, this would return
["keyword3" , "keyword1" , "keyword4" , "keyword2"]
All examples I found use lambda and I'm not very strong with that. Is there a way I could loop through this, and sort them as I go? Thanks for any suggestions.
PS: I could create the initial dict differently if it would help.

A: You could use
res = list(sorted(theDict, key=theDict.__getitem__, reverse=True))

(You don't need the list in Python 2.x)
The theDict.__getitem__ is actually equivalent to lambda x: theDict[x].
(A lambda is just an anonymous function. For example
>>> g = lambda x: x + 5
>>> g(123)
128

This is equivalent to
>>> def h(x):
...   return x + 5
>>> h(123)
128

)

A: i always did it this way....are there advantages to using the sorted method?
keys = dict.keys()
keys.sort( lambda x,y: cmp(dict[x], dict[y]) )

whoops didnt read the part about not using lambda =(

A: I would come up with something like this:
[k for v, k in sorted(((v, k) for k, v in theDict.items()), reverse=True)]

But KennyTM's solution is much nicer :)

A: >>> d={ "keyword1":3 , "keyword2":1 , "keyword3":5 , "keyword4":2 }
>>> sorted(d, key=d.get, reverse=True)
['keyword3', 'keyword1', 'keyword4', 'keyword2']

A: It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently order less, but other types, such as lists and tuples, are not. So you need a sorted representation, which will be a list—probably a list of tuples. For instance,
'''
Sort the dictionary by score. if the score is same then sort them by name
{
 'Rahul'  : {score : 75}
 'Suhas' : {score : 95}
 'Vanita' : {score : 56}
 'Dinesh' : {score : 78}
 'Anil'  : {score : 69}
 'Anup'  : {score : 95}
}
'''
import operator

x={'Rahul' : {'score' : 75},'Suhas' : {'score' : 95},'Vanita' : {'score' : 56},
   'Dinesh' : {'score' : 78},'Anil' : {'score' : 69},'Anup' : {'score' : 95}
  }
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
print sorted_x

output:
[('Vanita', {'score': 56}), ('Anil', {'score': 69}), ('Rahul', {'score': 75}), ('Dinesh', {'score': 78}), ('Anup', {'score': 95}), ('Suhas', {'score': 95})]


text:
Q: ui-screen-shooter not running I am using ui-screen-shooter to try to take localized screen shots, but i am having issues running ./ui-screen-shooter.   I've followed all the instructions and think i have all the script files.  but i get the following error when i run ./ui-screen-shooter:
./ui-screen-shooter.sh ~/Desktop/screenshots
/Users/andyphillips404/Documents/Projects/DoggeryApps/Photo Finish/config-screenshots.sh: line 24: syntax error near unexpected token `('

I am not sure what is wrong.   Here is a copy of my config-screenshots.sh:
#!/bin/bash
# This is an example configuration file to be used with ui-screen-shooter
# It is designed to work with the Hello World International application
# Please copy to config-screenshots.sh and edit for your needs

# LOCALE
# ======
# Set the locales here in which your screenshots should be made.
# Use format like en-US zh-Hans for filenames compatible with iTMSTransporter
# Note: to get the locale names for your existing app:
#  - Download .itmsp file with iTMSTransporter
#  - Run `grep locale ~/Desktop/*.itmsp/metadata.xml  | grep name | sort -u`

export languages="en-US da de es fr it ja nl pt ru zh-Hans zh-Hant"

# SIMULATORS
# ==========
# The simulators we want to run the script against, declared as a Bash array.
# Run `instruments -s devices` to get a list of all the possible string values.

declare -xa simulators=(
"iPhone 6 (8.1 Simulator)",
"iPhone 6 Plus (8.1 Simulator)",
"iPhone 5 (8.1 Simulator)",
"iPhone 4s (8.1 Simulator)"
)

Anyone have any idea, guessing the issue is with the declare statement from the error code but can't figure out why....

A: I am an idiot, and sorry for wasting everyone's time.  I need to stop using the basic text editor on a mac.   It changes the " to " as you can see from the posting above.   The last character in the export line above the line in issue is what was causing all the problems....
changed it back to a " and we are good...   not the first time that has burned me... sorry guys....


text:
Q: How do I replace values in data column according to dictionary?
I need to replace the values in a column of my dataset with values that refer to the values with the same name in dictionary.
So my data looks like this (don't pay attention on column names):
data = data[['A?',
       'B',...,]]

And the dictionary looks like ths:
felt_index = {
  "First opt": 1,
  "Second opt": 1,
  "Third opt": 0.72
}

I want that instead of my column looks like this:

A?
...

First opt
...

Second opt
...

Third opt
...

It would have look like this:

A?
...

1
...

1
...

0.72
...

I've tried some solutions and it didn't work out.
The last thing I tried is:
for val in data[['A?']]:
        data[['A']][val] = felt_index.get(data[['A?']][val])

And I got this error:
TypeError: unhashable type: 'Series'

I can't figure t out how to solve it:( Please, help.

A: Use pandas.DataFrame.replace:
new_df = df.replace({"A?": felt_index})
print(new_df)

Output:
     A?  ...
0  1.00  ...
1  1.00  ...
2  0.72  ...

From the official doc of pandas.DataFrame.replace:

For a DataFrame, nested dictionaries, e.g.,             {'a': {'b': np.nan}}, are read as follows: look in column 'a' for the value 'b' and replace it with NaN.

If you want to replace those not in a dictionary:
# Sample
           A?  ...
0   First opt  ...
1  Second opt  ...
2   Third opt  ...
3     Non opt  ...

df["A?"] = df["A?"].map(felt_index).replace({np.nan: None})

Output:
     A?  ...
0   1.0  ...
1   1.0  ...
2  0.72  ...
3  None  ...

Note that since you want None, it requires replace with dict. If you want a specific value, use fillna instead:
df["A?"] = df["A?"].map(felt_index).fillna("NO!")

Output:
     A?  ...
0   1.0  ...
1   1.0  ...
2  0.72  ...
3   NO!  ...


text:
Q: ORA-00904 and ORA-06512 when I try to MAX all columns create or replace PROCEDURE COMPARAISON_TEST as

begin
 declare

cursor c_tab is
select table_name, column_name , data_type
from all_tab_columns;

  v_sql VARCHAR2 (32000);

        begin

            FOR r_tab in c_tab LOOP
            v_sql := 'SELECT ' ||
            r_tab.table_name || ' TABLE_NAME, ' ||
            r_tab.column_name || ' COLUMN_NAME, ' ||
            '(SELECT MAX(' || r_tab.column_name || ') FROM ' || r_tab.table_name || ') VALUE ' ||
            'FROM DUAL ';
    execute immediate v_sql;
end LOOP;
end;
end COMPARAISON_TEST;

ERRORS
   ORA-00904: "DUAL" : invalid identifier
   ORA-06512: à "ODS.COMPARAISON_TEST", line 20
   ORA-06512: à "ODS.COMPARAISON_TEST", line 20
   ORA-06512: à line 2

A: Problem is that you're doing it in the dark.
Always, before actually executing dynamic SQL, display it on the screen so that you'd see the string to be executed.
This is what you did (I added WHERE clause to a cursor, to shorten the output):
SQL>  declare
  2
  3  cursor c_tab is
  4  select table_name, column_name , data_type
  5  from all_tab_columns
  6  where owner = 'SCOTT' and table_name = 'DEPT';
  7
  8    v_sql VARCHAR2 (32000);
  9
 10          begin
 11
 12              FOR r_tab in c_tab LOOP
 13              v_sql := 'SELECT ' ||
 14              r_tab.table_name || ' TABLE_NAME, ' ||
 15              r_tab.column_name || ' COLUMN_NAME, ' ||
 16              '(SELECT MAX(' || r_tab.column_name || ') FROM ' || r_tab.table_name || ') VALUE ' ||
 17              'FROM DUAL ';
 18      dbms_output.put_line(v_sql);
 19      --execute immediate v_sql;
 20  end LOOP;
 21  end;
 22  /
SELECT DEPT TABLE_NAME, DEPTNO COLUMN_NAME, (SELECT MAX(DEPTNO) FROM DEPT) VALUE
FROM DUAL
SELECT DEPT TABLE_NAME, DNAME COLUMN_NAME, (SELECT MAX(DNAME) FROM DEPT) VALUE
FROM DUAL
SELECT DEPT TABLE_NAME, LOC COLUMN_NAME, (SELECT MAX(LOC) FROM DEPT) VALUE FROM
DUAL

PL/SQL procedure successfully completed.

SQL>

See all those invalid strings? They can't be executed. In order to make them valid, include table and column names into single quotes, e.g.
SELECT 'DEPT' TABLE_NAME, 'DEPTNO' COLUMN_NAME, (SELECT MAX(DEPTNO) FROM DEPT) VALUE
FROM DUAL;

This is what you might have wanted:
SQL> set serveroutput on
SQL>
SQL> declare
  2    cursor c_tab is
  3      select table_name, column_name , data_type
  4      from user_tab_columns
  5      where table_name = 'DEPT';
  6    v_sql VARCHAR2 (32000);
  7    v_val varchar2(200);
  8  begin
  9    FOR r_tab in c_tab LOOP
 10      v_sql := 'SELECT MAX(' || r_tab.column_name || ') FROM ' ||
 11                r_tab.table_name;
 12      execute immediate v_sql into v_val;
 13      dbms_output.put_line(r_tab.table_name||'.'||r_tab.column_name||': '|| v_val);
 14    end LOOP;
 15  end;
 16  /
DEPT.DEPTNO: 40
DEPT.DNAME: SALES
DEPT.LOC: NEW YORK

PL/SQL procedure successfully completed.

SQL>

If you want to store result into a table, then you'd do something like this:
SQL> create table maxes
  2    (table_name   varchar2(30),
  3     column_name  varchar2(30),
  4     max_value    varchar2(30)
  5    );

Table created.

SQL> declare
  2    cursor c_tab is
  3      select table_name, column_name , data_type
  4      from user_tab_columns
  5      where table_name = 'DEPT';
  6    v_sql VARCHAR2 (32000);
  7    v_val varchar2(200);
  8  begin
  9    FOR r_tab in c_tab LOOP
 10      v_sql := 'SELECT MAX(' || r_tab.column_name || ') FROM ' ||
 11                r_tab.table_name;
 12      execute immediate v_sql into v_val;
 13      insert into maxes (table_name, column_name, max_value)
 14        values
 15        (r_tab.table_name, r_tab.column_name, v_val);
 16    end LOOP;
 17  end;
 18  /

PL/SQL procedure successfully completed.

SQL> select * From maxes;

TABLE_NAME      COLUMN_NAME     MAX_VALUE
--------------- --------------- ---------------
DEPT            DEPTNO          40
DEPT            DNAME           SALES
DEPT            LOC             NEW YORK

SQL>

A: You should double single quotes that you want to appear within the string.
v_sql := 'SELECT ''' ||
            r_tab.table_name || ''' TABLE_NAME, ''' ||
            r_tab.column_name || ''' COLUMN_NAME, ' ||
            '(SELECT MAX(' || r_tab.column_name || ') FROM ' || r_tab.table_name || ') VALUE ' ||
            'FROM DUAL ';


text:
Q: re-initialize the framebuffer when program crashes I'm using SDL to display images on a monitor, without X installed.
When my program ends successfully, the monitor goes back to the login prompt (as expected). But when my program crashes, the last image stays frozen on the monitor (even if I launch the program again, the last image of the previous execution stays stuck on the monitor).
How could I kill the display in order to "use" it again ? The only solution that I found is to reboot the computer but I need to avoid that because other processes run on the computer and cannot be interrupted.


text:
Q: storing Instances of student into an array Im trying to store these instances of student inside of this array.
Student:
public Student(string Value)
    {
        FirstName = Value;
        LastName = Value;
        StudentID = Value;
    }

Here is the Array
string[] student = new string[4];
    { ElementarySchoolStudent, MiddleSchoolStudent, HighSchoolStudent, CollegeStudent }

Each constructor is like this and they use the Student method.
CollegeStudent(string value) : base(value) { }

How exactly would I go about storing these instances in the array? When I do it like that i get the error message:

college student is a type which is not valid in the given context.

What's the correct way to code it exactly?

A: From this and the last question, maybe you want something like this
Given
public class Student
{
   public string FirstName  { get; set; }
   public string LastName   { get; set; }
   public string StudentID  { get; set; }
}

Usage
var students = new Student[]
{
   new Student(){FirstName = "bob",LastName = "blerg",StudentID = "23432"},
   new Student(){FirstName = "dan",LastName = "flib",StudentID = "4564"},
   new Student(){FirstName = "jib",LastName = "jab",StudentID = "564"},
};

foreach (var student in students)
   Console.WriteLine($"{student.StudentID} : {student.FirstName}, {student.LastName}");

Output
23432 : bob, blerg
4564 : dan, flib
564 : jib, jab

Note : Add constructor or pepper and salt to taste


text:
Q: Log4j2 ouptput to File is succesful but not to Console using Ant When running Ant, Log4j2 ouput goes to File Mylog.log correctly but nothing gets displayed on the console. What am I missing from build.xml or the log4j2.xml?
Version: log4j2 2.0, Ant 4.11
But when using Eclipse's run as Junit, displays the Log4j2 output to both console and file log successfully.
In the Log4j2.xml, both Appenders to Console and File have been created.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="All">
      <Appenders>
          <Console name="STDOUT" target="SYSTEM_OUT" >
              <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
          </Console>
          <File name="FileLogger" fileName="MyLog.log" append="false">
              <PatternLayout pattern="%d %t %-5p %c{2} - %m%n"/>
          </File>
      </Appenders>
      <Loggers>
          <Logger name="com.site" level="All" />
          <Root >
              <AppenderRef ref="STDOUT" level="All"/>
              <AppenderRef ref="FileLogger" level="All"/>
          </Root>
      </Loggers>
</Configuration>

In the build.xml, I have included the path to log4j2.xml in the classpath for "junit" target
<target name="junit">
    <classpath>
        <path refid="log4j2_config"/>

In the test class, the getLogger is included.
private static final Logger log4j = LogManager.getLogger("com.site");

A: In your configuration, the Logger with  name="com.site" does not have an appender-ref. So that logger does not do anything and can be removed. Your root logger will handle all events so that is fine.
I suspect that the difference between running your JUnit tests with Ant and in Eclipse is a classpath issue. Try specifying the full absolute path in <path refid="/full/path/to/log4j2_config"/> to see if that makes any difference.
You can also use a system property to specify the location of the config file:
http://logging.apache.org/log4j/2.x/faq.html#config_location


text:
Q: How Java compares two wrapper variables? I have two variables that should be compared:
Double a = 1D;
Double b = 2D;

if (a > b) {
    System.out.print("Ok");
}

In this case java will use autoboxing or compare two object's references?

A: From section 15.20.1 of the JLS:

The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then signed integer comparison is performed; if this promoted type is float or double, then floating-point comparison is performed.

Section 5.6.2 starts with:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:

*

*If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed.

So yes, unboxing is performed. > has no meaning for references themselves.
More interesting is the == case where both options would be possible - and in that case, if either operand is a primitive and the other can be converted via numeric promotion, then that happens... but if both are reference types, the reference comparison is performed. For example:
Double d1 = new Double(1.0);
Double d2 = new Double(1.0);
System.out.println(d1 == d2); // Prints false due to reference comparison

A: It will use autoboxing. You cannot do greater than on references


text:
Q: Stirling Number of the Second Kind Identity I'm aware of the identity
\begin{align}
\sum_{i = 0}^{k} i! \binom{n+1}{i + 1} S(k,i) = H_{n,-k},
\end{align}
where $H_{n,-k}$ is a generalized Harmonic number defined by $H_{n,m} = \sum_{r = 1}^{n} r^{-m}$. I believe the following sum is related to the generalized Harmonic numbers as well,
\begin{align}
\sum_{i = 0}^{k} (-1)^{i} i! \binom{n-i}{k-i} S(j,i)
\end{align}
and should be a nice function of $n, k$ and $j$, where $0 \leq j, k \leq n$. Any hints are certainly welcome!

A: I'm not sure that you're going to be able to get a nice expression in general (although I would be happy to be proved wrong!).
The special case $j = n$ has a very simple expression in terms of the Eulerian numbers, though.  We have
$$\sum_{i=0}^k (-1)^i i! \binom{n-i}{k-i} \left\{ n \atop i\right\} = \sum_{i=0}^k (-1)^i i! \binom{n-i}{n-k} \left\{ n \atop i\right\} = (-1)^k \left\langle n \atop n-k\right\rangle,$$
where the first step follows from $\binom{n}{k} = \binom{n}{n-k}$ and the second step from a known expression for the Eulerian numbers (see Eq. 6.40, Concrete Mathematics, 2nd edition, p. 269).  The Eulerian number $\left\langle n \atop k\right\rangle$ counts the number of permutations on $n$ elements in which exactly $k$ are larger than the immediately preceding element.
Maybe the case $j = 2$ is of interest as well.  Here we have $$\sum_{i=0}^k (-1)^i i! \binom{n-i}{k-i} \left\{ 2 \atop i\right\} = 2\binom{n-2}{k-2} -\binom{n-1}{k-1} = 2\binom{n-2}{k-2} -\left[\binom{n-2}{k-1} + \binom{n-2}{k-2}\right] $$
$$= \binom{n-2}{k-2} -\binom{n-2}{k-1},$$
which is the just the triangle you get when you take differences of neighboring entries in Pascal's triangle.  This triangle can also be thought of as two copies of Catalan's triangle, one positive and one negative, although the numbers are shifted and rotated.

A: By way  of enrichment  of this discussion  we give a  purely algebraic
proof that does not use Eulerian numbers.
Suppose we seek to prove that
$$\sum_{q=0}^n q! {m+1\choose q+1} {n\brace q} = H_{m,-n}$$
with $m\ge n.$
Recall  the bivariate generating  function $G(z,  u)$ of  the Stirling
numbers of the second kind which is
$$G(z, u) = \exp(u(\exp(z)-1)).$$
This yields for the sum that
$$\sum_{q=0}^n q! {m+1\choose q+1} n! [z^n] [u^q] \exp(u(\exp(z)-1))
\\= n! [z^n] \sum_{q=0}^n q! {m+1\choose q+1} \frac{(\exp(z)-1)^q}{q!}
= n! [z^n] \sum_{q=0}^n {m+1\choose q+1} (\exp(z)-1)^q.$$
An important observation at this point is that $\exp(z)-1$ starts at
$z$, so  we may  extend the summation  to $m$ without  affecting the
coefficient of $z^n,$ getting
$$n! [z^n] \sum_{q=0}^m {m+1\choose q+1} (\exp(z)-1)^q.$$
Rewrite this as
$$(m+1) \times n! [z^n]
\sum_{q=0}^m {m\choose q} \frac{(\exp(z)-1)^q}{q+1}
\\= (m+1) \times n! [z^n] \frac{1}{\exp(z)-1}
\sum_{q=0}^m {m\choose q} \frac{(\exp(z)-1)^{q+1}}{q+1}.$$
Stop for a moment to perform a formal power series integration.
We have $$(1+x)^m = \sum_{q=0}^m {m\choose q} x^q$$
so that
$$\frac{1}{m+1}(1+x)^{m+1} - \frac{1}{m+1}
=\frac{1}{m+1}\left((1+x)^{m+1} - 1\right)
\\= \sum_{q=0}^m {m\choose q} \frac{x^{q+1}}{q+1}.$$
Apply this to the sum to obtain
$$(m+1) \times n! [z^n] \frac{1}{\exp(z)-1}
\frac{1}{m+1}\left(\exp(z(m+1)) - 1\right)$$
which is
$$n! [z^n] \frac{\exp(z(m+1)) - 1}{\exp(z)-1}
= n! [z^n] \sum_{k=0}^m \exp(zk)
\\= n! \sum_{k=0}^m \frac{k^n}{n!} = \sum_{k=0}^m k^n = H_{m, -n}.$$


text:
Q: Perl Simple Regexp I have a valid string, somestr xyztip, where xyz is optional. But if xyz does exist, it needs to be next to tip (no whitespace).
So valid strings are: somestr tip or somestr xyztip.
An invalid string would be: somestr xyz tip  (space between xyz and tip)
I've tried many combinations, but I can't get the regexp to balk at a space between 'xyz' & 'tip'.  The one below is what I would think should work:
/^.+?\s(xyz)?tip$/

The problem is the syntax before the '(xyz)?' - that is the '.+?\s' .  This is saying any char 1 or more times, not greedy followed by a single whitespace.
what am I missing here?

A: Assuming that xyz cannot be anywhere in the string except for immediately before tip, the following should work:
/^((?!xyz).)+\s(xyz)?tip$/

This changes the .+? to ((?!xyz).)+.  By putting the negative lookahead within the repeating group we can match any number of characters but stop if we encounter xyz, so ((?!xyz).)+ would match "foo" from "fooxyz".  This allows us to make sure that xyz is never matched by the first part of the regex, so that if it exists it has to be in the (xyz)?tip portion of the regex.

A: What you need is a "zero width positive look-ahead assertion"... so, your regex would look something like:
\S+\s(?:xyz)?(?=tip)

From perldoc perlre:
"(?=pattern)"
    A zero-width positive look-ahead assertion.  For example, "/\w+(?=\t)/"
    matches a word followed by a tab, without including the tab in $&.

A: You can use this:
^(?>[^ ]++| (?!xyz))+ (?:xyz)?tip$


text:
Q: A good SQL sniffer Can anyone point me to a good SQL sniffer where I can watch the SQL commands that run against my database in real time?
If it's free, that would be great.

A: Use a SQL Trace, and if you are looking for a GUI to go along with it you can use SQL Profiler.  It ships with all versions of SQL Server except SQL Server Express.  SQL Trace is utilize directly through T-SQL and is available even with SQL Server Express, though a pretty good working knowledge of SQL Trace is desirable as it can be a little daunting to set up without the GUI.
What you would do is select the events that pertain to SQL statements/batches/stored procedures executing.  You will be able to capture the actual text statement(s).
If you don't want to wrestle with selecting out of the available (and many) events, you can use a built-in template.  It sounds like you'd probably want to use the T-SQL template, but look through it before just blindly running the trace.
BOL Reference on SQL Profiler
At the botton of that linked reference, there are a handful of "tasks" (tutorials) to get you started in the right direction.
EDIT:  Aaron brings up a good point (see comments).  Utilizing SQL Server Profiler is typically used for a quick glimpse or relatively short trace to do some snap troubleshooting.  There are definitely performance impacts, and I have seen busy servers brought to their knees because of it.  If you are looking for a longer, less performance impact trace I'd look to use T-SQL to generate the server-side traces.  Another great alternative is Extended Events.
BOL Reference on Extended Events

A: Use "SQL Profiler". It comes free with SQL Server 2008.


text:
Q: Apache OFBiz integration with Cassandra and Eventual Consistency Apache OFBiz supposedly integrates with Apache Cassandra databases. But does it support the eventual consistency feature?
If yes can anyone point me in the direction of some documentation or some written content explaining how?
If no - does OFBiz integrate and support any other database with eventual consistency?
Thanks in advance,
Jakob

A: Even if the integration of OFBiz with a Cassandra database has been mentioned in a couple of occasions in the OFBiz mailing lists, I am not aware of any setup of OFBiz that can work properly without a relational database.
Even if there are JDBC drivers for Cassandra, I doubt Cassandra can provide all the relational database features required by OFBiz.
The integration of OFBiz with Cassandra or any other big data tool is achievable and it is done by pairing the relational database with another ad-hoc database for specific purposes.
Unfortunately I am not aware of any effort to implement OFBiz on a database that supports the Eventual consistency model.


text:
Q: Using DropDown_SelectedIndexChanged to bind gridview, but paging is not working I have a DropDownList which is having few list items. Every time I select any item, based on it I am binding a gridview, hence resulting gridview depends on my selection. Some results are exceeding the pagesize hence I need to navigate on 2nd page in GridView, however the GridView is disappeating when I am selecting 2nd page.
 protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
 {
    string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
    SqlConnection con = new SqlConnection(constr);

    con.Open();
    string str = string.Empty;
    str = "SELECT * FROM Table1";

    SqlDataAdapter adp = new SqlDataAdapter(str, con);

    DataSet ds = new DataSet();
    adp.Fill(ds, "myds");

    BusinessKPIGrid.DataSource = ds;
    BusinessKPIGrid.DataBind();
}

 protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
 {
    //I know I need to bind the gridview here, but how ?
    BusinessKPIGrid.PageIndex = e.NewPageIndex;
    BusinessKPIGrid.DataBind();
 }

I don't know how to bind the gridview in paging event, since I do not have any separate binding function.

A: there is a separate function for page event for grid view..create separate method for binding grid & call that method on pageindexchange event..
protected void BusinessKPIGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    BusinessKPIGrid.PageIndex = e.NewPageIndex;
     bindyourgrid();
}

A: try this
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
    string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
    SqlConnection con = new SqlConnection(constr);

    con.Open();
    string str = string.Empty;
    str = "SELECT * FROM Table1";

    SqlDataAdapter adp = new SqlDataAdapter(str, con);

    DataSet ds = new DataSet();
    adp.Fill(ds, "myds");
    ViewState["ds"]=ds;
    BusinessKPIGrid.DataSource = ds;
    BusinessKPIGrid.DataBind();

}

  protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
    {
        //I know I need to bind the gridview here, but how ?
        BusinessKPIGrid.PageIndex = e.NewPageIndex;
         BusinessKPIGrid.DataSource = (DataSet)ViewState["ds"];
        BusinessKPIGrid.DataBind();
    }

A: From DDL_SelectedIndexChanged if you are searching some thing then use 'PageIndexChanging' and set the page size for it
protected void gvworker_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvworker.PageIndex = e.NewPageIndex;
        //result got from ddl list i.e bind your data set
    }