text:
Q: How to implement per user .emacs style config in clojure application? I have a Clojure application which process some data in our company. So I want to obtain possibility of its customization throw .myapp.clj file or something like this.
It must be a simple script in clojure in which user can define own data processing principle. Also he must has possibility for tunning http back end and others application parts.
So, what is the best way to implement this fiche?

A: A couple ways come to mind with varying levels of sophistication. The simplest is to just have each user define a ~/.myall.clj in their home directory and then the start of the program would include a line:
(def per-user-config (load-file "~/.myall.clj"))

load-file reads a file and returns the last form read in the file. This allows you to compose config files nicely. For instance you can make a company wide template that has symbols for things like user-name and then load it from a per-user config file that defines user-name and then calls load-file on the template
config-template.clj:
{:app-name "foo"
 :user-url (str "http://server.company:8080/users/" user-name)
 :foo "bar"}

joes-config.clj:
(def user-name "joe")
(load-file "resources/global-config.clj")

this allows you to distribute most of the config through git while still allowing users to overwrite any arbitrary part of the config.


text:
Q: Proof of Kirchhoff's theorem for directed nonsimple graphs? There's a marvelous theorem in graph theory that reduces the count of spanning trees for a graph to a computation of determinant of a naturally-defined matrix (the Laplacian matrix):
http://en.wikipedia.org/wiki/Kirchhoff%27s_matrix_tree_theorem
I am looking for a book proving the theorem for the following setting: $G$ is a directed graph which allows for multiple edges (which means the Laplacian might contain values other than $-1,0$ off the diagonal). In this case, the minor obtained from removing the $i$th row and column corresponds to the number of spanning tree whose root is $i$.
My usual reference for algebraic graph theory is Godsil and Royle; however, they prove the theorem for a simpler setting (or I don't understand what they do).

A: Dave Perkinson has just what you are looking for:
http://people.reed.edu/~davidp/412/handouts/matrix-tree.pdf

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hibernate and JSP Transaction per Request Hey,
I'm building a four tier software system (Presentation - JSP, Problem Domain, Application Logic, Persistence) and I want to have my transactions in hibernate per request so that I am not making a transaction every time i want to do something and also that I can have data tracking with my objects so that only the properties that were changed are updated.
I have looked at spring as a framework for this and as much as I would love to implement this my group has vetoed it and we cannot use it.
I have also looked at JTA and I cannot see how it would be of use as I am not using beans.
I have thought about a solution such as having a method to call to close and open transactions but it seems like there could be a more elegant solution.
What would be the best way to keep my transaction per request based on my system?

A: Apache provides a SessionFilter for Hibernate, instructions after the click.

A:
Hey, I'm building a four tier software system (Presentation - JSP, Problem Domain, Application Logic, Persistence) and I want to have my transactions in hibernate per request so that I am not making a transaction every time i want to do something and ...

I am interested on how'd you make your application with 4 abstraction layer, while you are using ClickServlet to maintain the one transaction per request. AFAIK your transaction will be as many requests as your active servlet worker threads.
If you want to leverage the lazy loading capabilities of Hibernate, you either:
(1) have to maintain transaction when request is still active (so that you won't get the LazyLoadingException), or
(2) you have to segregate the layer, make layer pass DTO and VO instead of passing the Hibernate model to layers above.
IMO the latter is a cleaner approach, as the main objective of having abstraction layers is to make them easier to reuse, easier to test, and separate the concern.
I suggest you not to handle transaction in the Servlet session/request level. It will make all your layer below presentation become tightly coupled with Servlet API. Usually this is not what we want when we want to have abstraction layers. So probably Apache Click framework and its ClickServlet is not the best way to do it. Spring can handle that better. If you got vetoed, too bad then.
If you don't want to use Spring automated transaction, you still can use AspectJ (or other aspect oriented programming components) to handle your transaction transparently (create transaction when entering methods and commit/rollback when exiting methods). Of course this is more hairy than just simply adopting Spring Framework.

... also that I can have data tracking with my objects so that only the properties that were changed are updated.

This one can be handled by Hibernate Level 1 Cache + Lazy Loading transparently. You don't have to do it yourself.
Hibernate will only generate the SQL to the backend when session is being flushed, or L1 cache is full, or on transaction commit.
In general, you don't have to do anything in order to minimize Data Manipulation Language (DML) statements to backend, usually Hibernate handles this better when configured properly.

I have also looked at JTA and I cannot see how it would be of use as I am not using beans.

You can use JPA without beans. It's just simply an API that you can invoke from anywhere.

I have thought about a solution such as having a method to call to close and open transactions but it seems like there could be a more elegant solution.

Yes. Look at aspect oriented programming by Gregor Kiczales. Spring Framework support this AOP off-the-shelf. If your team vetoed it, you can still Do-It-Yourself.

What would be the best way to keep my transaction per request based on my system?

Best approach (seing that you have planned to have 4 abstraction layers), is load your data from Hibernate domain models to Data Transfer Object/Value Object at the Persistence Layer.
The layer above, Application Logic Layer has access to the Hibernate domain model, but may not pass Hibernate models into the layer above. In order to make it efficient you have to implement paginating in these layers (otherwise you will often load all data into memory, which is bad).
This way, and coupled with the aspect-ing the transaction I think is the current best practice.


text:
Q: ABAP OLE - Open excel password protected workbook I'm trying to open a password protected excel file using SAP ABAP OLE OBJECT as follows:
DATA: lt_excel_line(4096) OCCURS 10 WITH HEADER LINE.
DATA: app       TYPE ole2_object,
      workbook  TYPE ole2_object,
      worksheet TYPE ole2_object.

CREATE OBJECT app 'EXCEL.APPLICATION'.
SET PROPERTY OF app 'VISIBLE' = 0.

CALL METHOD OF app 'WORKBOOKS' = workbook.

CALL METHOD OF workbook 'OPEN'
  EXPORTING
  #1 = '<filename>'
  #5 = '<password>'.

The filename and password are definitely correct and the following VBA code opens the file as required no problem:
Dim wb1 As Workbook
Set wb1 = Workbooks.Open Filename:="<filename>", Password:="<password>")

But the ABAP code always returns sy-subrc = 2. Anyone know what could be going on? Or what else I can try? Grateful for any help.

A: I think the problem is with the parameters being positional only (just a guess), as the SAP GUI automation does not support parameter names. There are 3 parameters between Filename and Password, so you numbered them correctly, but I guess the SAP GUI automation controller does not see it that way.
I replicated your problem and got it working as follows:
CALL METHOD OF workbook 'OPEN' = document
  EXPORTING
  #1 = '<filename>'
  #2 = 0              "UpdateLinks
  #3 = 0              "ReadOnly
  #4 = 1              "Format
  #5 = '<password>'.

Here I am explicitly passing the parameters UpdateLinks, ReadOnly and Format.
I tested it first in VBA. It seems Format (#4) must be set to true. I don't know what that does.
Remember to set the document handle as a return from this call as I do here, otherwise you don't have a reference to it!


text:
Q: When using a mocking framework and MSPEC where do you set your stubs I am relatively new to using MSpec and as I write more and more tests it becomes obvious to reduce duplication you often have to use a base class for your setup as per Rob Conery's article
I am happy with using the AssertWasCalled method to verify my expectations, but where do you set up a stub's return value, I find it useful to set the context in the base class injecting my dependencies but that (I think) means that I need to set my stubs up in the Because delegate which just feels wrong.
Is there a better approach I am missing?

A: The initialization/setup of stubs belongs to the arrange phase. The arrange phase is used to get the system into a known state before you exercise it.
In MSpec, the arrange phase is performed in Establish fields. For example:
public class When_the_temperature_threshold_is_reached
{
    static ITemperatureSensor Sensor;
    static Threshold Threshold;

    Establish context = () =>
        {
            Sensor = MockRepository.GenerateStub<ITemperatureSensor>();
            Sensor
                .Stub(x => x.GetTemperature())
                .Return(42);

            Threshold = new Threshold(Sensor);
        };

    Because of = () => Reached = Threshold.IsReached(40);

    It should_report_that_the_threshold_was_reached =
        () => Reached.ShouldBeTrue();
}

When you write more tests using that kind of ITemperatureSensor, you should extract a base class that does complicated or repeated setup.
public abstract class TemperatureSpecs
{
    protected static ITemperatureSensor CreateSensorAlwaysReporting(int temperature)
    {
        var sensor = MockRepository.GenerateStub<ITemperatureSensor>();
        sensor
            .Stub(x => x.GetTemperature())
            .Return(temperature);

        return sensor;
    }
}

public class When_the_temperature_threshold_is_reached : TemperatureSpecs
{
    // Everything else cut for brevity.
    Establish context = () =>
        {
            Sensor = CreateSensorAlwaysReporting(42);

            Threshold = new Threshold(Sensor);
        };
}

This gives you the advantage that you can influence the stub's return value from the context itself: You do this by keeping as much information as possible local to the context and provide a good name for the "setup" method in the base class.
There is no need to specifiy or expect anything stub-related in Because. When Because is run, your system should be in a state where it can be exercised without further preparation.


text:
Q: Outlook calendar authentication with ADFS and a default Windows Auth zone We configured a Sharepoint portal with two zones. One (default) with windows authentication because of the search crawler, and another with and ADFS provider.
In the browser (using the ADFS zone) everything works.
Now the problem. We can sync a calendar with outlook, and it opens, but when we try to edit something (or when it tries to sync), outlook asks for authentication but on the default (windows auth) zone that only has the user for the crawler with permissions.
Does anybody know why this appends? And any solution?
Thanks

A: Apparently Outlook tries to authenticate in the first zone he can find.
An the order of the first zones is:
Intranet
Default
...
So essentially we change the ADFS zone to the intranet zone and it worked.


text:
Q: Триггер в Postgres Добрый день! Пробовал формировать триггер по автоматическому добавлению ключевого (инкрементного) поля в таблицу. Приведите верный пример, как используя последовательность сделать триггер с автоинкрементом числа.
Мой неверный (ошибочный) вариант ниже:
CREATE FUNCTION trigger_s_before_lns ()
RETURNS trigger AS
BEGIN
  NEW.ns=nvl(NEW.ns,to_char(nextval('s_seq'),'99999'))
return NEW;
END;
LANGUAGE  plpgsql;

Где s_seq - последовательность.
A: Что бы использовать последовательности в postgres вовсе не нужно создавать триггер, достаточно указать последовательность в значении по умолчанию:
CREATE TABLE some_table(
    incremented_field integer DEFAULT nextval('s_seq'),
    /* ... */
);

Триггер на PL/SQL будет выглядеть примерно так:
CREATE FUNCTION trigger_function() RETURNS trigger AS $$
    BEGIN
        NEW.ns := nextval('s_seq');
        RETURN NEW;
    END;
$$ LANGUAGE plpgsql;


text:
Q: Why is scientific notation not identical to integer in php? I just wondered why my if statement was not entered when using scientific notation, i.e. 1e2 instead of 100 and 1e6 instead of 1000000.
It turns out, those are only equal and not identical, as seen by the following code:
<?php
echo "Integer: " . 100; // prints 100
echo "\n";
echo "Scientific notation: " . 1e2; // prints 100
echo "\n";

echo "Equality: ";

if(100 == 1e2) {
    echo "as expected";
} else {
    echo "wtf php";
}
// prints "Equality: as expected"

echo "\n";
echo "Identity: ";

if(100 === 1e2) {
    echo "as expected";
} else {
    echo "wtf php";
}
// prints "Identity: wtf php"

I have run it on different php versions and it seems to at least be consistent, as this behavior is the same across: 4.3.0 - 5.0.5, 5.1.1 - 5.6.27, hhvm-3.10.0 - 3.13.2, 7.0.0 - 7.1.0RC5.
Yet: Why!?

A: === operator, in php, consider the type of the operands.
1e2 even return a float number, and 100 is an integer.
so, it's equals in values (==), but not in types (===).


text:
Q: Couchbase view using "WHERE" clause dynamically I have Json Documents in the following format
Name :
Class :
City :
Type :
Age :
Level :
Mother :
Father :

I have a map function like this
function(doc,meta)
{
    emit([doc.Name,doc.Age,doc.Type,doc.Level],null);
}

What I can do is give "name" and filter out all results but what I also want to do is give "age" only and filter out on that. For that couchbase does not provide functionality to skip "Name" key. So I have to create a new map function which has "Age" as first key, but I also have to query on only "Level" key also so like this. I would have to create many map functions for each field which obviously is not feasible so is there anything I can do apart from making new map function to achieve this type of functionality?
I can't us n1ql because I have 150 million documents so it will take a lot of time.

A: First of all - that is not a very good reduce function.

*

*it does not have any filtering

*function header should be function(doc, meta)

*if you have mixture between json and binary objects - add meta.type == "json"

Now for the things you can do:

*

*If you are using v4 and above (v4.1 in much more recommended) you can use N1QL and use it very similar to SQL language. (I didn't understand why you can't use n1ql)

*You can emit multiple items in multiple order

i.e. if I have doc in the format of
{
  "name": "Roi",
  "age": 31
}

I can emit to the index two values:
function (doc, meta) {
  if (meta.type=="json") {
    emit(doc.name, null);
    emit(doc.age, null);
  }
}

Now I can query by 2 values.
this is much better than creating 2 views.
Anyway, if you have something to filter by - it is always recommended.


text:
Q: Qubes-OS transfer files from and to HVM I can't find in the documentation how to transfer data from and to the HVM in Qubes-OS. When a normal AppVM is created, it has the Qubes Tools installed so easy copy and paste, and transferring files is possible. However, a HVM seems completely locked down.
Any idea's?

A: Yes, you can copy files between HVM⟺HVM & HVM⟺AppVM.
I didn't find any way in Qubes Documentation to do that.
I guess developers of Qubes didn't give this feature still.
But, I found way to do this.
First time what you have to do:

*

*Create a virtual disk image.

*Attach it to any VM(except dom0).

*Identify the disk image using fdisk.

*Create partition(s).

*Create filesystem in that partition.

*Detach from that VM

Every time what you have to do:

*

*Attach it to target VM(HVM or AppVM).

*Identify the disk image using fdisk.

*Mount that volume.

*Copy or Move whatever you want.

*Unmount that volume.

*Detach from that VM.

*Do same to another VM(HVM or AppVM) for Paste.

Commands to do:
Creating virtual disk image (in dom0 Terminal):
sudo dd if=/dev/zero of=/home/anaconda/storage.img bs=1M seek=20480 count=0

Replace 'anaconda' by your username; the number after seek is disk size in MB.
Attaching disk image to a VM (in dom0 Terminal):
 For Qubes-3.2
qvm-block -A VMname dom0:/home/anaconda/storage.img

For Qubes-4.0
sudo losetup -f --show /home/anaconda/storage.img

qvm-block attach VMname dom0:loop21

Identifying disk image (in VM Terminal):
sudo fdisk -l

Creating partition (in VM Terminal):
sudo fdisk /dev/xvdi

Creating filesystem in partition (in VM Terminal):
sudo mkfs.fat /dev/xvdi1

Mounting volume (in VM Terminal):
sudo mkdir /mnt/removable

sudo mount /dev/xvdi1 /mnt/removable

Unmounting volume (in VM Terminal):
sudo umount /dev/xvdi1

Detaching disk image from VM (in dom0 Terminal):
qvm-block

qvm-block -d dom0:loop21

For Qubes-4.0 replace '-d' by 'detach'.
For video tutorial go to this link
https://m.youtube.com/watch?v=qE06DWWf97E


text:
Q: Python - Image Difference Score What would be the pythonic way of scoring the differences between the two images below?
(for example, quantify that the second image is 25% different than the first)
OpenCV seems to pop up a lot in discussions about image comparison such as in this discussion -> Checking images for similarity with OpenCV
However, I do not believe doing a histogram comparison will work here because the values are primarily black and white.
How would you approach a problem like this?

A: I found an answer that worked for me so I wanted to share it in case anyone else has a similar question. The code compares the pixels of the two images and finds the differences. Identical pixels will have a value of 0. Knowing this, we can use numpy to find the non-zero pixels and use that number to calculate a difference score.
you can use this code
import cv2
import numpy as np

img1 = cv2.imread("16x16_orig.png", 0)

img2 = cv2.imread("16x16_dif.png", 0)

#--- take the absolute difference of the images ---
res = cv2.absdiff(img1, img2)
print(res)

#--- convert the result to integer type ---
res = res.astype(np.uint8)

print(np.count_nonzero(res))

#--- find percentage difference based on number of pixels that are not zero ---
percentage = (np.count_nonzero(res) * 100)/ res.size
print(percentage)

using the two images below will return a score of 50% which is what we expect.
Original Image

different

after we get the absdiff, the resulting array looks like this:
[[  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0]
 [207 207 207 207 207 207 207 207 207 207 207 207 207 207 207 207]
 [207 207 207 207 207 207 207 207 207 207 207 207 207 207 207 207]
 [207 207 207 207 207 207 207 207 207 207 207 207 207 207 207 207]
 [207 207 207 207 207 207 207 207 207 207 207 207 207 207 207 207]
 [207 207 207 207 207 207 207 207 207 207 207 207 207 207 207 207]
 [207 207 207 207 207 207 207 207 207 207 207 207 207 207 207 207]
 [207 207 207 207 207 207 207 207 207 207 207 207 207 207 207 207]
 [207 207 207 207 207 207 207 207 207 207 207 207 207 207 207 207]]

It is important to note that the images that you wish to compare will need to be the same size.
For those that are curious about the images in the original question. The result was a 2.56% difference with 1292 non zero pixels


text:
Q: Filter an array I have an array like this:
$categories_array = array(
[0] => 'category_1',
[1] => 'category_2',
[2] => 'category_3',
[3] => 'category_4'
)

I'd like to "filter" the array to get a new one. For example, I'd like to have a new array with only 'category_2' and 'category_3' like this:
$new_categories_array = array(
[1] => 'category_2',
[2] => 'category_3',
)

How can I accomplish this result?

A: unset($new_categories_array[0]);
unset($new_categories_array[3]);
..might do the trick

A: See

*

*array_diff — Computes the difference of arrays

*array_intersect — Computes the intersection of arrays

Example:
$original = array('category_1','category_2','category_3','category_4');
$new      = array_diff($original, array('category_1', 'category_4'));

print_r($new);

Output:
Array
(
    [1] => category_2
    [2] => category_3
)

When using array_intersect the returned array would contain cat 1 and 4 obviously.

A: Use preg_grep:
$new_categories_array = preg_grep('/category_[23]/', $categories_array);

A: While I agree preg_grep is a good solution in your example, if you want a more general case function, look at array_filter - http://ca.php.net/manual/en/function.array-filter.php


text:
Q: How to combine similar values into single value dataframe? I have a dataframe that includes languages of codes.
The head of dataframe;
    repo_id language
0   2519612 JavaScript
1   1519634 C
2   8534335 C++
3   6719676 LiveScript
4   1519234 C#
5   3234554 Python
6   3234554 Julia
7   3234554 Elm
8   3234554 Gosu

I want to combine similar language into single one.
For example,
"C, C++ and C#" consolidate into "C"
"LiveScript, JavaScript, .." consolidate into "JavaScript"
"Julia, Elm, Gosu" consolidate into "Other"
"Python" stay as "Python"
Desired output is;
    repo_id language
0   2519612 JavaScript
1   1519634 C
2   8534335 C
3   6719676 JavaScript
4   1519234 C
5   3234554 Python
6   3234554 Other
7   3234554 Other
8   3234554 Other

Bad Solution;
df.loc[df['language'] == 'C++', 'language'] = 'C'
df.loc[df['language'] == 'C#', 'language'] = 'C'

I don't want to change labels individually, How can I do it easier?

A: This may help you:
Use apply function with a lambda function to check the language and then update the language column as follows
   df['language'] = df['language'].apply(lambda x: 'C' if x in ['C', 'C#', 'C++'] else 'JavaScript')

Desired output is:
        repo_id     language
0   2519670     JavaScript
1   2519670     C
2   2519670     C
3   2519670     JavaScript
4   2519670     C

Modify your function as follow
dic = {'repo_id':[2519670, 2519670,2519670, 2519670, 2519670, 2519670, 2519670,2519670, 2519670, 2519670],
       'language':['JavaScript', "C++", "C", 'LiveScript', 'C#', 'Python', 'Julia', 'Elm', 'Gosu', 'Python'] }

df = pd.DataFrame(dic)
    repo_id     language
0   2519670     JavaScript
1   2519670     C++
2   2519670     C
3   2519670     LiveScript
4   2519670     C#
5   2519670     Python
6   2519670     Julia
7   2519670     Elm
8   2519670     Gosu

Then apply the following function:
df['language'] = df['language'].apply(lambda x: 'C' if x in ['C', 'C#', 'C++'] else ('JavaScript' if x in ['JavaScript', 'LiveScript'] else ('Python' if x in ['Python'] else 'Other')))
df

Desired output
repo_id     language
0   2519670     JavaScript
1   2519670     C
2   2519670     C
3   2519670     JavaScript
4   2519670     C
5   2519670     Python
6   2519670     Other
7   2519670     Other
8   2519670     Other
9   2519670     Python


text:
Q: how to move a few letters between 'a' and 'z' I have an exercise that I need to take a string, reverse it, and then I'm entering a number and each letter needs to be moved a few letters according to that number, and I need to use in all of that with pointers.
here is my code :
#include <stdio.h>

#define LEN 100
void decryptText(char* encText, int n);
int main(void)
{
    char str[LEN] = { 0 };
    int num = 0;
    printf("Please enter a string :\n");
    fgets(str, LEN, stdin);
    printf("\nPlease enter a number:\n");
    scanf("%d", &num);
    decryptText(str, num);
    getchar();
    system("PAUSE");
    return 0;
}

void decryptText(char* encText, int n)
{
    int i = 0, len = 0 , value = 0 ;
    char moved = "";

    for (i = 0; i<LEN; i++){
        if (*encText == '\0')
        {
            break;
        }
        encText++;
    }
    len = i;
    encText--;
    printf("The secret message is: \n\n");
    for (i = len; i>0; i--)
    {
        value = (int*)(encText--);
        moved = (char)(value + n);
        *encText = moved;
        printf("%c", *encText);
    }
    printf("\n\n");
}

The program does not work, and I still need to make my letters only between 'a' and 'z' and I can't change the pointer to move the letter.

A: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define LEN 100

void decryptText(char* encText, int n);

int main(void){
    char str[LEN] = { 0 };
    int num = 0;
    printf("Please enter a string :\n");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0';//remove newline
    printf("\nPlease enter a number:\n");
    scanf("%d", &num);
    num = num % 26;
    decryptText(str, num);
    //getchar();
    system("PAUSE");
    return 0;
}

void decryptText(char* encText, int n){
    int i = 0, len = 0 , value = 0 ;
    unsigned moved = '\0';

    for (i = 0; *encText; i++){
        ++encText;
    }
    len = i;
    --encText;

    printf("The secret message is: \n\n");
    for (i = len; i>0; i--){
        value = *encText;
        if(isupper(value))
            value = tolower(value);
        if(islower(value)){
            moved = value + n;
            if(moved > 'z')
                moved = 'a' -1 + moved - 'z';
            else if(moved < 'a')
                moved = 'z' +1 + moved - 'a';
            *encText = moved;
        }
        printf("%c", *encText--);
    }
    printf("\n\n");
}


text:
Q: Double column Highcharts with drilldown I am using Highcharts for generating a two column bar graph. Means for each day I am showing the number of downloads and number of signups. Now I need to have a drilldown, which shows up the hourly data. The Highcharts docs is showing an example for Signle column by specifying the y value. But as I am showing stached bar, I have two y values for the same date. The code I am using is as follows :
series: [{
 name    : 'Signups,
 color   : '#0066FF',
 data    : <?=$series_1?>, //data in JSON format from PHP
 drilldown: true
 }, {
 name    : 'Downloads',
 color   : '#E81531',
 data    : <?=$series_2?>, //data in JSON format from PHP
 drilldown: true

}],

A: Example for you for drilldown with two series, with stacking: 'normal': http://jsfiddle.net/6zYmJ/10/
$('#container').highcharts({
    chart: {
        type: 'column'
    },
    title: {
        text: 'Basic drilldown'
    },
    xAxis: {
        type: 'category'
    },

    legend: {
        enabled: false
    },

    plotOptions: {
        series: {
            stacking: 'normal',
            borderWidth: 0,
            dataLabels: {
                enabled: true,
            }
        }
    },

    series: [{
        name: 'Things',
        colorByPoint: true,
        data: [{
            name: 'Animals',
            y: 5,
            drilldown: 'animals'
        }, {
            name: 'Fruits',
            y: 2,
            drilldown: 'fruits'
        }, {
            name: 'Cars',
            y: 4,
            drilldown: 'cars'
        }]
    }, {
        name: 'Things2',
        colorByPoint: true,
        data: [{
            name: 'Animals2',
            y: 5,
            drilldown: 'animals2'
        }, {
            name: 'Fruits2',
            y: 2,
            drilldown: 'fruits2'
        }, {
            name: 'Cars2',
            y: 4,
            drilldown: 'cars2'
        }]
    }],
    drilldown: {
        series: [{
            id: 'animals',
            data: [
                ['Cats', 4],
                ['Dogs', 2],
                ['Cows', 1],
                ['Sheep', 2],
                ['Pigs', 1]
            ]
        }, {
            id: 'fruits',
            data: [
                ['Apples', 4],
                ['Oranges', 2]
            ]
        }, {
            id: 'cars',
            data: [
                ['Toyota', 4],
                ['Opel', 2],
                ['Volkswagen', 2]
            ]
        },{
            id: 'animals2',
            data: [
                ['Cats', 4],
                ['Dogs', 2],
                ['Cows', 1],
                ['Sheep', 2],
                ['Pigs', 1]
            ]
        }, {
            id: 'fruits2',
            data: [
                ['Apples', 4],
                ['Oranges', 2]
            ]
        }, {
            id: 'cars2',
            data: [
                ['Toyota', 4],
                ['Opel', 2],
                ['Volkswagen', 2]
            ]
        }]
    }
})

A: Adding to Pawel Response-
Just replace in plotOptions with this value
column: {
                pointPadding: 0.2,
                borderWidth: 0
            }
,


text:
Q: can i use same JDBC connection, statement and resultset to execute two queries in JDBC I am authenticating user like
public static boolean login(DataManager dataManager, String userName, String password) {
    boolean authenticated = false;
    Connection connection = dataManager.getConnection();
    if (connection != null) {
         try {
             Statement s = connection.createStatement();
             String sql = "query";
             try {
                 ResultSet rs = s.executeQuery(sql);
                 try {
                     while (rs.next()) {
                        String group_code = rs.getString(1);
                        String orgaunit = rs.getString(2);

                        authenticated = true;
                     } //end of while()
                 } finally {
                     rs.close();
                 }
             } finally {
                 s.close();
             }

         } catch(SQLException e) {
             //System.out.println("Could not login from dataabse:" + e.getMessage());
         } finally {
             dataManager.putConnection(connection);
         }
    } //end of if (connection != null)
    return authenticated;
} //end of login()

I am closing connection in dataManager.putConnection(connection). I want to ask once user get login then i have to update the status of user and maintain log history. Can i use something like this
try {
    Statement s = connection.createStatement();
    String sql = "query";
    try {
        ResultSet rs = s.executeQuery(sql);
        try {
            while (rs.next()) {
                String group_code = rs.getString(1);
                authenticated = true;
            } //end of while()

            if (autherntcated == true) {
                sql = "query2(update status)";
                rs = s.executeQuery(sql);

                while (rs.next()) {
                    //dos tuff
                }

                sql = "anotherQuery";
                rs = s.executeQuery(sql);
                while (rs.next()) {
                    //do stuff
                }

            }

        } finally {
            rs.close();
        }
    } finally {
        s.close();
    }
} catch(SQLException e) {
    //System.out.println("Could not login from dataabse:" + e.getMessage());
} finally {
    dataManager.putConnection(connection);
}

Means using same connection, same statement and same resultset execute other queries or is it wrong approach ?
Thank you.
Edit
--------------------------------------------------------------
if (connection != null) {
    try {
        String sql = "query";
        PreparedStatement prepStatement = connection.prepareStatement(sql);
        try {
            ResultSet rs = prepStatement.executeQuery(sql);
            try {
                while (rs.next()) {
                    String group_code = rs.getString(1);
                    authenticated = true;
                } //end of while()
            } finally {
                rs.close();
            }
        } finally {
            prepStatement.close();
        }

        /// Addition
        if (authenticated == true) {
            updateUser(connection, userName);
        }
    } catch(SQLException e) {
        //System.out.println("Could not login from dataabse:" + e.getMessage());
    } finally {
        dataManager.putConnection(connection);
    }
} //end of if (connection != null)

UPdate method:
private static void updateUser(Connection connection, String userName) {

    try {
        String sql = "UPDATE users SET status_code = 'A' WHERE login_id = '" + userName + "'";
        PreparedStatement prepStatement = connection.prepareStatement(sql);
        try {
            int numberOfRowsUpdated = prepStatement.executeUpdate(sql);
        } finally {
            prepStatement.close();
        }

        maintainHistory(connection);

    } catch(SQLException e) {
    //System.out.println("Could not login from dataabse:" + e.getMessage());
    }

} //end of updateUser()

maintainHistory:
private static void maintainHistory(Connection connection) {

    try {
        String sql = "INSERT INTO auditlog_user_logins(user_code,logintime,prstid) VALUES ();";
        PreparedStatement prepStatement = connection.prepareStatement(sql);
        try {
          int numberOfRowsUpdated = prepStatement.executeUpdate(sql);

       } finally {

        prepStatement.close();

       }

     } catch(SQLException e) {

         //System.out.println("Could not login from dataabse:" + e.getMessage());

     }

} //end of maintainHistory()

A:
can I use same JDBC connection, statement

Yes. You can reuse them prior to closing.

and resultset

No. The question doesn't make sense. The result set is the result of executing a query or update. There is no question of re-using it. I imagine you need to close the preceding result set prior to executing the next query or update.

A: I would suggest reusing connection because establishing connection every single time you're trying to query your database maybe a performace overhead.
As for statements, I would suggest switching to PreparedStatement. They are not only cached but one good way to protect yourself from SQL injections. So build up your query before-hand, execute them and finally close them when you're done. Reusing PreparedStatement would mean that you're substituting the parameter values for the the same PreparedStatement and executing the same.
So for example, if you've a PreparedStatement like:
PreparedStatement preparedStatement = connection.prepareStatement("SELECT [col_names] from [table_name] where [col_1_value] = ? and [col_2_value] = ?")

In this case, you can reuse the same PreparedStatement multiple times by just substituting new values for the parameters. Generally, for your case you'll have multiple PreparedStatements. Since these statements are cached, they wouldn't be a big hit on performance when you execute the same.
Here's a good tutorial to introduce you PreparedStatement in case you're in need of one: "Using Prepared Statements"
ResultSets - well I don't see how can you reuse it. Close it as and when you're done with them. As per the Javadoc:

A ResultSet object is automatically closed when the Statement object
  that generated it is closed, re-executed, or used to retrieve the next
  result from a sequence of multiple results.

However, make sure to close your connection once you're done using it. Re-usability is a good thing, but resource mismanagement isn't

A: Answered different Test case with same question.

Can I use same JDBC connection, Statement and ResultSet to execute two queries in JDBC

We can not reuse Connection, Statement and ResultSet parallelly or concurrent as follows:
Connection con = databaseConnector.getConnection();
PreparedStatement stmt1=con.prepareStatement("select * from emp");
ResultSet rs1=stmt.executeQuery();
while(rs1.next()){  // get SQLException in second iteration
System.out.println(rs1.getInt(1)+" "+rs1.getString(2));
    //As soon as you execute the following query, the previous Statement and ResultSet are implicitly closed.
    // to resolve we the problem, we should not use the above used Connection. We have to use new Connection.
    PreparedStatement stmt2=con.prepareStatement("select * from address");
    ResultSet rs2=stmt2.executeQuery();
    System.out.println(rs2.getString(1)+" "+rs2.getString(2));

}

*

*Closing a Connection closes a Statement, when Statement closed implicitly closes ResultSet also.

*Closing a Statement closes a ResultSet but not Connection.

*Closing a ReultSet only closes itself, not Statement.

*By default, only one ResultSet per Statement can be open at the same time.

Best Practice:

*

*Connections are not thread safe, so sharing them across requests is not a good idea.

*Opening a DB connection is an expensive, should use a ConnectionPool for sharing connections.

*Close ResultSet as soon as you finish working with ResultSet.

A: You can use the UpdatableResultSet.


text:
Q: How to build a command parser with regex I'm trying to implement a command parser to parse command parameters to a key value pair list.
For example, there is a command to output images:[name]_w[width]_h[height]_t[transparency],say"image01_w64_h128_t90",the program would output the image "image01" with specified size and transparency, and so far I'm using regex to solve it.
Code:
private static readonly Regex CommandReg = new Regex(
    @"^(?<name>[\d\w]+?)(_W(?<width>\d+))?(_H(?<height>\d+))?(_T(?<transparency>\d+))?$"
    , RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.ExplicitCapture);
public static NameValueCollection ParseCommand(string command)
{
    var match = CommandReg.Match(command);
    if (!match.Success) return null;
    var groups = match.Groups;
    var paramList = new NameValueCollection(4);
    paramList["name"] = groups["name"].Value;
    paramList["width"] = groups["width"].Value;
    paramList["height"] = groups["height"].Value;
    paramList["transparency"] = groups["transparency"].Value;
    return paramList;
}

This way worked and the code is very easy. However, a higher demand is if the order of parameters is changed, say "image01_h128_w64_t90" or "image01_t90_w64_h128", the program can also output expected result.

*

*Is it possible to solve the problem using regex?

*If regex is helpless,any other suggestions?

Thanks for any suggestion, editing, and viewing.

A: Just do string.split('_') then iterate through the array to find everything you need.
if(arr[i].startswith("w"))
{
paramList["width"] = arr[i].remove(0,1);
}

and so on.


text:
Q: How do I make large datasets load quickly in Python? I do data mining research and often have Python scripts that load large datasets from SQLite databases, CSV files, pickle files, etc. In the development process, my scripts often need to be changed and I find myself waiting 20 to 30 seconds waiting for data to load.
Loading data streams (e.g. from a SQLite database) sometimes works, but not in all situations -- if I need to go back into a dataset often, I'd rather pay the upfront time cost of loading the data.
My best solution so far is subsampling the data until I'm happy with my final script. Does anyone have a better solution/design practice?
My "ideal" solution would involve using the Python debugger (pdb) cleverly so that the data remains loaded in memory, I can edit my script, and then resume from a given point.

A: One way to do this would be to keep your loading and manipulation scripts in separate files X and Y and have X.py read
import Y
data = Y.load()
.... your code ....

When you're coding X.py, you omit this part from the file and manually run it in an interactive shell.  Then you can modify X.py and do an import X in the shell to test your code.

A: Write a script that does the selects, the object-relational conversions, then pickles the data to a local file.
Your development script will start by unpickling the data and proceeding.
If the data is significantly smaller than physical RAM, you can memory map a file shared between two processes, and write the pickled data to memory.

A: Jupyter notebook allows you to load a large data set into a memory resident data structure, such as a Pandas dataframe in one cell. Then you can operate on that data structure in subsequent cells without having to reload the data.


text:
Q: How can I update wrapperlist item How can I update the wrapperlist item with the value of the second for loop? Always the wrapper adds the whole information (see my screenshot). Also I don't know how can I display the result at a visualforce page? It is not possible with apex:repeat.
public class Radial_Analyse_Test {

    public List<ResultWrapper> resultList   {get; set;}

    public Radial_Analyse_Test(){
        Radial_Analyse_output();
    }

    public class ResultWrapper {
        public Decimal Network_2021 {get; set;}
        public Decimal Network_2022 {get; set;}
    }

    public void Radar_Analyse_output() {

        //Id AccId = ApexPages.currentPage().getParameters().get('id');
        Id AccId = '0011x00001LuukeAAB';    // for test
        Decimal Network_2021 = 0;
        Decimal Network_2022 = 0;

        Map<Id, List<ResultWrapper>> KscCatsToWrapper = new Map<Id, List<ResultWrapper>>();
        Set<String>KscCats = new Set<String>();

        for (Scorecard__c ksc1: [SELECT Id, Name, Account__c, Year__c, Network__c FROM Scorecard__c where Account__c = :AccId and Year__c = 2021]) {
            KscCats.add(AccId);
            ResultWrapper wrap  = new ResultWrapper();
            wrap.Network_2021   = ksc1.Network__c;
            KscCatsToWrapper.put(AccId, new List<ResultWrapper>());
            KscCatsToWrapper.get(AccId).add(wrap);
        }
        system.debug('KscCats 2021: ' + KscCats);
        system.debug('KscWrapper 2021: ' + KscCatsToWrapper);
        system.debug('-------------------------------------');

        for (Scorecard__c ksc2: [SELECT Id, Name, Account__c, Year__c, Network__c FROM Scorecard__c where Account__c = :AccId and Year__c = 2022]) {
            KscCats.add(AccId);
            ResultWrapper wrap  = new ResultWrapper();
            wrap.Network_2022   = ksc2.Network__c;
            if(!KscCatsToWrapper.containsKey(AccId)){
                KscCatsToWrapper.put(AccId,new List<ResultWrapper>());
                KscCatsToWrapper.get(AccId).add(wrap);
            } else {
                KscCatsToWrapper.get(AccId).add(wrap);
            }
            system.debug('KscCats 2022: ' + KscCats);
            system.debug('KscWrapper 2022: ' + KscCatsToWrapper);
            system.debug('-------------------------------------');
        }
}

<apex:page sidebar="false" Controller="Radial_Analyse_Test" showHeader="true" id="pg">
    <center>
        <apex:repeat value="{!resultlist}" var="w">
            {!w.Network_2021}
        </apex:repeat>
</apex:page>

CURRENT
At the end of the query I want to add the data to a radial chart.
Currently I do it like below, but it works not good, because I have
public Radial_Analyse() {

    Id AccId = ApexPages.currentPage().getParameters().get('id');

    data = new List<RadialData>();
    List<Scorecard__c> KSCList = new List<Scorecard__c>();
    KSCList = [SELECT Name, Year__c, Employee__c, Network__c, Sales__c FROM Scorecard__c where Account__c = :AccId];
    for(Scorecard__c KSC : KSCList) {
        data.add(new RadialData('Employee', KSC.Employee__c));
        data.add(new RadialData('Network', KSC.Network__c));
        data.add(new RadialData('Sales', KSC.Sales__c));
    }

    public class RadialData {
        String  Score_Category {get;set;}
        Decimal Score   {get;set;}

        public RadialData(String Score_Category, Decimal Score) {
            this.Score_Category= Score_Category;
            this.Score = Score;
        }
    }
}

FUTURE
I think the result should like this, but I don't know how can I split the wrapper.
public class RadialData {
    String Score_Category {get; set;}
    Decimal Score_2021   {get;set;}
    Decimal Score_2022   {get;set;}

    public RadialData(String Score_Category, Decimal Score_2021, Decimal Score_2022) {
        this.Score_Category = Score_Category;
        this.Score_2021 = Score_2021;
        this.Score_2022 = Score_2022;
    }
}

EDIT 02.08.2022
Wrapper
06:09:57:422 USER_DEBUG [75]|DEBUG|KscWrapper 2022: {2021=(ResultWrapper:[Employee=2, Network=8, Sales=5]), 2022=(ResultWrapper:[Employee=1, Network=6, Sales=5])}

split wrapper into years
06:09:57:424 USER_DEBUG [83]|DEBUG|network 2021 --> (ResultWrapper:[Employee=2, Network=8, Sales=5])
06:09:57:424 USER_DEBUG [84]|DEBUG|network 2022 --> (ResultWrapper:[Employee=1, Network=6, Sales=5])

that looks good, but now when I try to get a specific value of the year like KscCatsToWrapper.get(2021).get('Network'));
I get an error Method does not exist or incorrect signature: void get(String) from the type List<Radial_Analyse_Test.ResultWrapper>

A: If this code is for 1 account at a time anyway, why do you organize into a map of <Id,List<ResultWrapper>> where Id is the accountId? That's not needed.
And if you then want to have results per year, why not organize into a  Map<String,List<ResultWrapper>> where the String is the year? (or you could even user an integer of the year as the map key).
Then later on, when you need a list of values for 1 year, you simply do resultList = KscCatsToWrapper.get('2021')  ( or resultList = KscCatsToWrapper.get(2021) if you use integers).
Then, lastly, if you also want to split the scores into categories, it would be beneficial to include those as a map key as well. So a nested map: Map<String,Map<String,List<ResultWrapper>>>
That will require a bit more organisation but you can find enough examples online.
Eventually when you need the value you can do KscCatsToWrapper.get('Network').get('2021')


text:
Q: mysql query with multiple group by's i am trying to write an SQL query but this is a bit to complicated for me.
I have a table with these fields:
user1, user2, user1Payed, user2Payed.

user1 and user2 have emails inside.
user1Payed and user2Payed have numbers inside, representing a kind of payments.
This is a table that represents all the orders users have made.
user1 and user1Payed are bound by meaning.
user2 and user2Payed are also bound by meaning.
orders in my system are made by 2 users that do not have to be distinct. this means that an order could be made be the same user. in this case it could be that user1Payed and user2Payed would have different values.
my goal is to write a query that will calculate all distinct users that have a total of userPayed (user1Payed + user2Payed) over a certain number. this means that i need to count the amount of all user1Payed and user2Payed associated with a distinct user.
i understand that some use of GROUP BY should be made here but this is insufficient because this will not address all posibilities.
take for an example the case the in a specific row my user1 and user2 are the same username, how will i calculate user1Payed and user2Payed?
It seems that what i should do is make a table with all the rows that a certain user is user1 and then check its user1Payed.
then make another table with all the rows that the user is user2 and count user2Payed.
after this i need to sum up the 2 results and from this result i could make the final result.
but i don't have any idea how would i implement this.
thanks alot.

A: Use UNION to combine the data for each user column.
SELECT user, SUM(amount) total
FROM (
    SELECT user1 user, user1Payed amount
    FROM table
    UNION ALL
    SELECT user2 user, user2Payed amount
    FROM table
) u
GROUP BY user

I don't know what "bound by meaning" means, I hope it isn't relevant to the answer.


text:
Q: what is the difference between com.mcxiaoke.volley:library-aar and com.mcxiaoke.volley:library? When I search volley in android studio, get both com.mcxiaoke.volley:library:1.0.19 and com.mcxiaoke.volley:library-aar:1.0.1. But what is the difference? what is the aar stand for? Base on this answer, the one without a aar is a newer version, is that right?

A: You can add a library with different methods in your project.For example:
https://github.com/mcxiaoke/android-volley
This is for Maven:
<dependency>
    <groupId>com.mcxiaoke.volley</groupId>
    <artifactId>library</artifactId>
    <version>1.0.19</version>
</dependency>

Using SNAPSHOT
add this to repositories section in build.gradle
repositories {
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
    }

Or the easiest and best way:
compile 'com.mcxiaoke.volley:library:1.0.19'

And of course, The AAR file consists of a JAR file and some resource files and that comes from Maven repository.
https://stackoverflow.com/a/21485222/4409113

A: aar is just a file format (like jar).
http://tools.android.com/tech-docs/new-build-system/aar-format.
the version is what matters. 1.0.19 is newer than 1.0.1


text:
Q: HTML5 video: How to test for HLS playing capability? (video.canPlayType) I have video which is delivered over HLS. Now I'd like to test in JavaScript if the device actually can play HLS video in HTML5.
Usually in Javascript I did something like
  document.createElement('video').canPlayType('video/mp4')
However I can't figure out which 'type' is the right one for HLS.
Apple's Safari HTML5 Audio and Video Guide seems to suggest "vnd.apple.mpegURL" ("Listing 1-7  Falling back to a plug-in for IE")
<video controls>
    <source src="HttpLiveStream.m3u8" type="vnd.apple.mpegURL">
    <source src="ProgressiveDowload.mp4" type="video/mp4">
....

but canPlayType("vnd.apple.mpegURL") return an empty string even on iOS devices which can play actual HLS streams perfectly fine.
Is there any way to check for playback capabilities without 'external knowledge' (e.g. "check for iOS user agent and assume it can play hls")?
I know I can specify multiple sources in a  element and the browser will use the first playable source. However in my case I need feed a single URL to JW Player which I can't modify. So somehow I need to find the "best playable URL" from a set of video encodings. (An open source JS library which handles source selection would be a nice workaround though.)

A: I haven't tested this across the board, but it looks like you should be testing for the full HLS mimetype application/vnd.apple.mpegURL instead of just just vnd.apple.mpegURL.
application/x-mpegURL and audio/mpegurl are also suitable mimetypes for the HLS m3u8 file.  audio/x-mpegurl is also listed as an acceptable mimetype according to Apple, but it doesn't appear to be mentioned in the actual HLS draft spec.
In Safari on iOS and OS X,
document.createElement('video').canPlayType('application/vnd.apple.mpegURL')

returns maybe.  I'm not sure if there are any other browsers that support HLS -- Android doesn't seem to like this syntax (despite some assertions I've seen to the contrary), and I believe that it may be due to the fact that the actual video playback is delegated to an external application, rather than the browser itself.
References:

*

*http://developer.apple.com/library/ios/#technotes/tn2235/_index.html

*http://www.longtailvideo.com/html5/hls

*https://datatracker.ietf.org/doc/html/draft-pantos-http-live-streaming-03

*http://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Using_HTML5_Audio_Video.pdf


text:
Q: Delete a json value which is inside a set of json I have a JSON as below.
{
"key" : "Balance",
"translation" : [
    {
        "language" : "English",
        "value" : "abc"
    },
    {
        "language" : "German",
        "value" : "faq"
    }
]
}

I'm passing the language "English" and the language and its value should delete. There are many keys so I'm using for loop in my function to get that language.
this._work.forEach( ( translation ) => {
        translation.translation.forEach( data => delete data.language[ language ] );
    } );

this._work contains the above json value. Here the language and its value not deleting. What I'm missing?

A: In your solution,  delete data.language[ language ] will not work since data.language['English'] is undefined. This deletion technique is generally used when you want to remove by using key from an object, not row in an array.
You can use filter instead of using forEach.
this._work.forEach( ( row ) => {
   row.translation = row.translation.filter( translation => translation.language !== translation );
} );

A: Aside note: There is nothing called JSON en js, what you have is a js object.
Actually you're trying to delete the attribute "English" from the string language, which is wrong and doesn't make sense.
For example:
delete data.language["English"]

I recommend you to use the function Array.prototype.filter as follow:

let data = {
  "key": "Balance",
  "translation": [{
      "language": "English",
      "value": "abc"
    },
    {
      "language": "German",
      "value": "faq"
    }
  ]
},
    language = "English";

data.translation = data.translation.filter(({language: lang}) => lang !== language);
console.log(data);

A: {
   property: 'value',
   language: 'English'
}

delete instruction needs a property provided to be deleted. like delete data.property or delete data.language. In the code, you provided data.language[language] points to a value. If you want to delete the language property if the value is English, then the code you needs is
this._work.forEach( ( translation ) => {
        translation.translation.forEach( data => if (language === data.language) { delete data.language; });
    } );

as a result you would get:
{
"key" : "Balance",
"translation" : [
    {
        "value" : "abc"
    },
    {
        "language" : "German",
        "value" : "faq"
    }
]
}


text:
Q: WP Query - if there are no posts with certain tag query other ones I'm banging my head on how to achieve this. I am querying posts that have 'popular' tag. But there are going to be times when I will have no posts with that tag.
This is my query.
$featured_posts = new WP_Query(array(
    'post_type' => 'post',
    'posts_per_page' => 3,
    'post__not_in' => get_option( 'sticky_posts' ),
    'cat' => get_query_var('cat'),
    'tag' => 'popular',
    'tag__not_in' => array($tag->term_id),
));

How do I say that if there are no articles with 'popular' tag to show all other articles?

A: WP_Query doesn't have a fallback system in it. It just executes the query with the given parameters.
One option is just to check, if the first query has any posts and if not, then run another query with different parameters.
Another way is to conditionally build up the parameters. So first get the tag term and if it has any posts attached include it in the parameters.
$args = array(
  'post_type' => 'post',
  'posts_per_page' => 3,
  'post__not_in' => get_option( 'sticky_posts' ),
);

$category = get_query_var('cat');
if ( $category && is_int($category) ) {
  $args['cat'] => $category;
}

$popular_tag = get_term_by( 'slug', 'popular', 'post_tag' );
// Does the tag exist and does it have any post attached to it
if ( $popular_tag && $popular_tag->count ) {
  $args['tag_id'] => $popular_tag->term_id;
}

$query = new WP_Query($args);

From WP_Term class reference, https://developer.wordpress.org/reference/classes/wp_term/

Cached object count for this term.


text:
Q: SqlDependency.Start не работает в Unity? Я создаю простое клиент-серверное приложение и застрял на взаимодействии с SQL.
Если я в "обычной" вижуал студии запускаю код:
using System.Data;
class Program
{
    static void Main(string[] args)
    {
         SqlDependency.Start("server=111.111.111.111;database=db;Persist Security Info=false;Integrated Security=false;User Id=user;Password=password");
    }
}

То я вижу все правильно созданные службы в Service Broker'e в SQL студии.
Но стоит мне запустить нечто похожее из юнитей:
using System.Data;
public class ABC : MonoBehaviour
{
    void Start()
    {
        System.Data.SqlClient.SqlDependency.Start("server=111.111.111.111;database=db;Persist Security Info=false;Integrated Security=false;User Id=user;Password=password")
    }
}

То код просто не отрабатывает. Никаких ошибок, просто ничего. Пробовал подключать разные версии System.Data - не помогло.
bool a=System.Data.SqlClient.SqlDependency.Start("server=111.111.111.111;database=db;Persist Security Info=false;Integrated Security=false;User Id=user;Password=password")
Debug.Log(a)

возвращает True
Прошу о помощи.

A: После двух дней поисков решения я его таки нашел.
Идем в Edit > Project Settings > Player, далее меняем "Scripting Runtime Version" на".NET 4.x Equivalent" и"Api Compatibility Level" на".NET 4x", перезапускаем юнити. Идем в Unity\Editor\Data\MonoBleedingEdge\lib\mono\4.5 и копируем System.Data.dll в папку своего проекта.
И тогда она работает. Надеюсь кому-нибудь поможет.


text:
Q: Inverse laplace with fractional order enter image description here
$$
L^{-1}\left[ \frac{s^{\alpha}}{s^2\alpha+a^2}\right]\\
L^{-1}\left[ \frac{a}{s^2\alpha+a^2}\right]
$$
Can any one help me with those where alpha is fraction/rational number ... thanks in advance

A: From this PDF on page 26:
$$\mathcal{L}_s^{-1}\left[\frac{s^{\alpha }}{s^{\beta }+a^2}\right](t)=t^{-1-\alpha +\beta }
   E_{\beta ,-\alpha +\beta }\left(-a^2 t^{\beta }\right)$$
$$\mathcal{L}_s^{-1}\left[\frac{a}{s^{\beta }+a^2}\right](t)=a t^{-1+\beta } E_{\beta ,\beta
   }\left(a^2 t^{\beta }\right)$$
where: $E_{\beta ,\beta -\alpha }\left(-a^2 t^{\beta }\right)$ and $E_{\beta ,\beta }\left(a^2 t^{\beta }\right)$ is MittagLefflerE function.


text:
Q: Incrementing ArrayList elements by Random Numbers So I'm working on an assignment for my AP Computer Science Class dealing with ArrayLists. For #13 and 14 I am supposed to increment each ArrayList element by a random number between 0 and 20 (inclusive). I don't understand why I cannot use the (ArrayList.set()) method to increment my ArrayList elements. Thank you in advance!
import java.util.Collection; //Driver Class
import java.util.Random;
import java.util.ArrayList;
import java.util.Random;
public class MusicDownloads {
    public static void main(String[] args) {
        ArrayList < DownloadInfo > music = new ArrayList < DownloadInfo > ();
    music.add(new DownloadInfo("So What"));                         //2
    music.add(new DownloadInfo("Blue in Green"));
    music.add(new DownloadInfo("Night in Tunisia"));
    music.add(new DownloadInfo("Fly Me to the Moon"));
    music.add(new DownloadInfo("Come Fly With Me"));
    music.add(new DownloadInfo("This Town"));
    music.add(new DownloadInfo("Flamenco Sketches"));

        int addNum = 0;
        Random rand = new Random();
        for (int i = 0; i < music.size(); i++) {
            addNum = 0;
            addNum = (int) Math.random() * 20; //13
            music.set(i, music.get(i).addNumDL(addNum));
        }

        System.out.println("Num 13/14");
        for (int i = 0; i < music.size(); i++) {
            System.out.println(music.get(i)); //14
        }
    }
}

public class DownloadInfo //Object Class
{
    private String title = "";
    private int numDownloads = 0;

    public DownloadInfo(String t) {
        title = t;
    }

    public String getSongTitle() {
        return title;
    }

    public void addNumDL(int addNum) {
        numDownloads = addNum + numDownloads;
    }

    public int getnumDownloads() {
        return numDownloads;
    }

    public String toString() {
        return ("Song title: <" + title + "> " + " <Number of times downloaded: " + numDownloads + ">");
    }
}

A: You should add(…) the elements rather than using set(i, …).
Apart from that, a few style nitpicks:

*

*Don't use Math.random() if you want an integer. Rather create a Random (or use ThreadLocalRandom, if you're on 1.7 or later) and use its nextInt(int) method. You even instantiate a Random above.

*Java has a += operator which updates the value in place.

A: If you are simply trying to increment the counter within the DownloadInfo object as it appears in the code snippet, then you don't need to replace the element in the array.  You could simply use:
public static void main(String[] args)
{
   ArrayList<DownloadInfo> music = new ArrayList<DownloadInfo>();
   music.add(new DownloadInfo("Wasted Years"));
   music.add(new DownloadInfo("The Trooper"));
   music.add(new DownloadInfo("Can I Play with Madness"));
   music.add(new DownloadInfo("22 Acacia Avenue"));
   music.add(new DownloadInfo("Rime of the Ancient Mariner"));

   for (int i=0; i<music.size(); i++)
   {
       int addNum = (int) (Math.random() * 20);
       music.get(i).addNumDL(addNum);
   }

    System.out.println("Num 13/14");
    for (int i=0; i<music.size(); i++)
    {
        System.out.println(music.get(i));       //14
    }
}

Note the parenthesis around the (Math.random() * 20).  If you don't use these then the int cast is applied to the result of Math.random() and you end up with a lot of 0 results.
In your code above when you are using set, the result of addNumDL is not a DownloadInfo object so I am assuming you are getting a compile issue there as you are trying to set a void into the array.  At least that is what I got when I built your class locally.  If I am misunderstanding you and you are trying to move the objects around within the ArrayList as well we can go from there.


text:
Q: Azure Mobile Apps Offline Client Throws NotSupportedException on Query I have a Azure Mobile Apps Xamarin.Forms PCL client and have Offline Sync enabled. I tried to Pull data from my backend and afterwards query data from the offline storage with a Where clause. That throws the following exception and I don't know why.
Sync error: 'fahrerinfo.Imei.Equals("02032032030232")' is not supported in a 'Where' Mobile Services query expression.
    public async Task SyncAsync()
    {

        ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;

        try
        {
             await OfflineSyncStoreManager.Instance.TruckFahrerTable.PullAsync("allTruckFahrerItems",
                OfflineSyncStoreManager.Instance.TruckFahrerTable.CreateQuery());

            Debug.WriteLine("SyncAsync: PUSH/PULL completed.");

        }
        catch (MobileServicePushFailedException e)
        {
            Debug.WriteLine("SyncAsync: PUSH failed.");
            Debug.WriteLine(e.Message);
        }
        catch (Exception e)
        {
            Debug.WriteLine("SyncAsync: PUSH/PULL failed.");
            Debug.WriteLine(e.Message);
            //Debugger.Break();
        }
    }

    public async Task<ObservableCollection<TruckFahrer>> GetTruckFaherAsync(bool syncItems)
    {
        try
        {
            if (syncItems)
            {
                await OfflineSyncStoreManager.Instance.SyncAsync().ConfigureAwait(false);
            }

            var deviceInfo = DependencyService.Get<IDeviceInfo>().GetPhoneInfo();
            var imeiString = deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.ImeiKey];

            var imei = imeiString.Equals("000000000000000") ? deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.IdKey] : imeiString;

            IEnumerable<TruckFahrer> items =
                await OfflineSyncStoreManager.Instance.TruckFahrerTable
                //.Where(fahrerinfo => fahrerinfo.Imei.Equals(imei)) TODO: Why does that throw an exception???
                .ToEnumerableAsync();

            // TODO: Because above does not work
            items = items.Where(fahrer => fahrer.Imei.Equals(imei));

            return new ObservableCollection<TruckFahrer>(items);
        }
        catch (MobileServiceInvalidOperationException msioe)
        {
            Debug.WriteLine(@"Invalid sync operation: {0}", msioe.Message);
            Debugger.Break();
        }
        catch (Exception e)
        {
            Debug.WriteLine(@"Sync error: {0}", e.Message);
            Debugger.Break();
        }

        return null;
    }

Thanks for any hint,
Eric

A: Are you a Java developer too? I'm and had this issue because in Java we need to compare strings with String#equals method, haha.
For some reason MobileServices doesn't allow us to use Equals in this situation.
To fix your problem, use == instead. As you can see here C# difference between == and Equals() both have the same effect in this case.
Where(fahrerinfo => fahrerinfo.Imei == imei)


text:
Q: Unit Test with Asp.Net Web Api and customer filter I am working on the Unit Testing in Asp.Net Mvc Web Api.
I have 2 projects
1: Catalog.Api - This contains all the controllers
2: Catalog.UnitTests - This contains the Unit Test for controllers
All Controllers are Inherit with "ApiController" and every controller has custom filter [AuthenticationFilter]. Here is my values controller.
    [AuthenticationFilter]
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }

And my custom is check the authorization token. Here it is
public class AuthenticationFilter: AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)

        {
            var request = actionContext.Request;
            var authorization = request.Headers.Authorization;

            if (authorization == null || authorization.Scheme != "Bearer")
            {
                ShowAuthenticationError(actionContext, "Authorization required");
                return;
            }

            if (string.IsNullOrEmpty(authorization.Parameter))
            {
                ShowAuthenticationError(actionContext, "Missing Jwt Token");
                return;
            }

            var token = authorization.Parameter;

            var principal = AuthenticateToken(token);
            if (principal == null)
            {
                ShowAuthenticationError(actionContext, "Invalid token");
                return;
            }
            base.OnAuthorization(actionContext);
        }
        private static void ShowAuthenticationError(HttpActionContext filterContext, string message)
        {
            var responseDTO = new ResponseDTO() { Code = 401, Message = message };
            filterContext.Response =
            filterContext.Request.CreateResponse(HttpStatusCode.Unauthorized, responseDTO);
        }
    }
    public class ResponseDTO
    {
        public int Code { get; set; }
        public string Message { get; set; }
    }

Now in the Unit Test project i have a class and unit test method.
        [TestMethod]
        public void CheckFilter()
        {
            try
            {
                var controller = new ValuesController();
                var controllerContext = new HttpControllerContext();
                var request = new HttpRequestMessage();
                request.Headers.Add("Authorization", "bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InVhbGkiLCJlbWFpbCI6InVhbGlAaW5yZWFjaGNlLmNvbSIsIm5iZiI6MTU2NDY0NjIyMSwiZXhwI");

                controllerContext.Request = request;
                controller.ControllerContext = controllerContext;

                var result = controller.Get();
                Assert.IsTrue(result.Any());

            }
            catch (Exception ex)
            {
                Assert.Fail();
            }
        }

I am calling my controller by adding reference of API project into my unit test project. So all controllers are available in the unit test project.
Issue is that when i call the values controller it always return the data. And when i remove the request and header so it is also returning the data but in that case that will be unauthorized.
I think my custom filter is not calling. How should that would be called and authenticate the user.

A: I check your question and configure that issue it is basically you are calling the controller directly.
Basically controller is a class and when you are calling that it is behaving like a simple class and call the method and send back the result. It is simple and clear
But in your situation you have project for your api so can do this.
[TestMethod]
public void CheckFilter()
{
    try
    {
        var config = new HttpConfiguration();
        // This is the resgister method which is written in you Api project. That code is after this method this method because i did the same thing to call my controller.
        Catalog.Api.WebApiConfig.Register(config);
        using (var server = new HttpServer(config))
        {
            var client = new HttpClient(server);

            string url = "http://localhost:PortNumberOfProject/api/values";

            var request = new HttpRequestMessage
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get
            };
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "Your Token");

            var response = await client.SendAsync(request);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
    }
    catch (Exception ex)
    {
        Assert.Fail();
    }
}

Here is the WebApi Register method of Api project which is used to register the Api and Routes.
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Here is your controller as it is. And now debug your test and add a break point in your [AuthenticationFilter] and OnAuthorization method.
[AuthenticationFilter]
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}


text:
Q: Why does the border get cut off when using border-radius? Please see this fiddle:
jsfiddle example
notice the headers are cutting off the border-radius, any ideas why?
Thanks

A: The gradients of the .pod-headers are overlapping the round corners on the .pods because you didn't round the .pod-headers. They don't inherit the round corners from their parent elements.
To fix it, round the top corners (only) of your .pod-header elements using this CSS:
    -webkit-border-radius: 6px 6px 0 0;
    -moz-border-radius: 6px 6px 0 0;
    border-radius: 6px 6px 0 0;

A: You are giving one class the border radius and the inner class the background but no radius (so it still has a square corner).
Check out the CSS in the updated fiddle

A: You also need to set the border-radius on the inner div.
For example Use this:
#pod-container .pod .pod-header {
    background: #ffffff; /* Old browsers */
    background: -moz-linear-gradient(top, #ffffff 0%, #e5e5e5 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#e5e5e5)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #ffffff 0%,#e5e5e5 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #ffffff 0%,#e5e5e5 100%); /* Opera11.10+ */
    background: -ms-linear-gradient(top, #ffffff 0%,#e5e5e5 100%); /* IE10+ */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e5e5e5',GradientType=0 ); /* IE6-9 */
    background: linear-gradient(top, #ffffff 0%,#e5e5e5 100%); /* W3C */
    border-radius: 6px;

    border-bottom: 1px solid #CCC;
}


text:
Q: Webpack plugin parser not finding local or module function calls I'm writing a code analytics webpack plugin that wants to find all instances of a  function name in a webpack bundle.
I made a repo for this question: https://github.com/RonPenton/webpack-parser-fail-demo
So the parser is really simple, just looks like this:
    class ParsePlugin {
    apply(compiler) {
        compiler.plugin('compilation', function (compilation, data) {

            data.normalModuleFactory.plugin('parser', function (parser, options) {

                parser.plugin(`call $findme`, function (expr) {
                    console.log("found $findme!");
                });
            });
        });
    }

https://github.com/RonPenton/webpack-parser-fail-demo/blob/master/parse.js
All I want to do is find all instances of $findme() in code and record information about them. At a later time, I may even end up altering the calls, but that's for another day.
When I supply this source file, all is well: https://github.com/RonPenton/webpack-parser-fail-demo/blob/master/good.js
$findme("Testing");
$findme("Testing too...");

When I run webpack, the output shows both instances were found:
found $findme!
found $findme!
Hash: a6555af5036af17d9320
Version: webpack 3.6.0
Time: 69ms
  Asset     Size  Chunks             Chunk Names
good.js  2.52 kB       0  [emitted]  main
   [0] ./good.js 47 bytes {0} [built]

But when I use a different entry point, where the function is defined either locally (https://github.com/RonPenton/webpack-parser-fail-demo/blob/master/bad.js) or in an external module (https://github.com/RonPenton/webpack-parser-fail-demo/blob/master/bad2.js), suddenly the parser stops finding these methods.
function $findme(input) {
    console.log(input);
}
$findme("Testing");
$findme("Testing too...");

====
import { $findme } from './findme';
$findme("Testing");
$findme("Testing too...");

So what's the deal? I tried digging into the webpack source code, and as far as I can tell, this seems intentional. But there's literally no documentation about why it's done this way, and not a comment in sight.
Is this not something that can be done with plugins?
Thanks for the help in advance.

A: The webpack parser weirdly only calls those hooks when your functions are called or retrieved a certain way. That's why your hook worked when the function was invoked one way, but didn't work when it was imported from somewhere.
I was trying to find all calls to an object method and had the same issue.
This github issue made by another person goes into more detail: https://github.com/webpack/webpack/issues/9480
To resolve this you need to trick the webpack Parser into thinking that function/method calls that it doesn't want to call hooks on for some reason are Identifiers, something like what's done here: https://github.com/aurelia/webpack-plugin/blob/9f6f7983312c66f857e79b744e4ec257cc287b8b/dist/InlineViewDependenciesPlugin.js
Here are the relevant bits from webpack's code:

You need to use the parser 'evaluate' hook to return a custom BasicEvaluatedExpression instance that has isIdentifier set to true for all function calls that you want to find. Then the call hook will get called with the full expression. In my case I need the full CallExpression that contains both the function and its arguments.


text:
Q: How can I disable Firebase In-App Messaging button action open url Although I have created a Firebase in-app messaging click listener, it tries to open the android system when the button is clicked.
The url like that : https://site_url/product_id
I want to open this url after a logic operation.
class MainActivity : AppCompatActivity() : FirebaseInAppMessagingClickListener {

  override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
      ....

     FirebaseInAppMessaging.getInstance().addClickListener(this)
     FirebaseInAppMessaging.getInstance().triggerEvent("main_activity_ready")
}

  override fun messageClicked(message: InAppMessage, action: Action) {
    val url =( action.actionUrl ?: "")
    Log.d(TAG, "in-app messaging url : $url")
    linkParsePresenter.startLinkParse(url, PreviousPage.InAppMessaging) // This is my logic function.

}
}

messageClicked function invoked. There is no problem. But the system also trying to open this url. How can I override or disable it?

A: I'm struggling with this as well.
Unfortunately it looks like there's no way around it at the moment. Firebase will call your custom FirebaseInAppMessagingClickListener, but then it'll try to navigate to the provided action URL regardless.
This is an extract from FirebaseInAppMessagingDisplay :
actionListener = new OnClickListener() {
                    public void onClick(View v) {
                        if (FirebaseInAppMessagingDisplay.this.callbacks != null) {
                            FirebaseInAppMessagingDisplay.this.callbacks.messageClicked(action);
                        }

                        CustomTabsIntent i = (new Builder()).setShowTitle(true).build();
                        i.launchUrl(activity, Uri.parse(action.getActionUrl()));
                        FirebaseInAppMessagingDisplay.this.notifyFiamClick();
                        FirebaseInAppMessagingDisplay.this.removeDisplayedFiam(activity);
                        FirebaseInAppMessagingDisplay.this.inAppMessage = null;
                        FirebaseInAppMessagingDisplay.this.callbacks = null;
                    }
                };

As you can see Firebase will run through all the custom callbacks but then attempt navigation regardless with launchUrl(activity, Uri.parse(action.getActionUrl())).
The only option I can think of is to properly support deep-links in your app as recommended in Customize your Firebase In-App Messaging messages.

A: I solved it by adding a transparent activity which handles the deeplink.

*

*Create empty activity;

class FirebaseEmptyActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        finish()
    }

}

*Declare it in manifest:

<activity
   android:name=".FirebaseEmptyActivity"
   android:theme="@style/Theme.Transparent">

   <intent-filter>
      <action android:name="android.intent.action.VIEW" />

      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />

      <data
         android:host="example.com"
         android:pathPrefix="/path-to-access"
         android:scheme="customscheme" />
   </intent-filter>
</activity>

So the above deeplink will work for: customScheme://example.com/path-to-access
Declare a transparent theme:
<style name="Theme.Transparent" parent="AppTheme.NoActionbar">
   <item name="android:windowIsTranslucent">true</item>
   <item name="android:windowBackground">@android:color/transparent</item>
   <item name="android:windowContentOverlay">@null</item>
   <item name="android:windowNoTitle">true</item>
   <item name="android:windowIsFloating">false</item>
   <item name="android:backgroundDimEnabled">false</item>
</style>

Now in your activity listen for the button click:
FirebaseInAppMessaging.getInstance().removeAllListeners()
FirebaseInAppMessaging.getInstance().addClickListener { inAppMessage, action ->
   if (action.actionUrl?.contains("your custom scheme url...") == true) {
      // The button was clicked for that action...
   }
}

A: Firebase In-App Messaging (FIAM) is in Beta and doesn't support actions other than dynamic links as of now. And dynamic links are still links, so it will always try to navigate to the web first. Jumps outside the app then back (which makes it look like a virus)
I think a better alternative is to use Firebase Cloud Messaging instead. The implementation looks more complex, but I highly recommend watching this guy explaining everything in detail: https://www.youtube.com/watch?v=p7aIZ3aEi2w
Benefits of Firebase Cloud Messaging over Firebase In-App Messaging:

*

*Push notifications - if the goal with FIAM was to communicate with users, this gets it done

*Custom data - A key/value payload can be sent to the app, so you can customize the click action handler, better than FIAM, where it always opens the dynamic link

*Silent messages - if you really want to replicate FIAM without the notifications part, you can send silent messages and handle the payload with custom dialogs in the app (silent messages can only be sent from the server, not through the Firebase Console yet)

*FCM can be A/B tested as the FIAM

Hope that helps and hope that Firebase makes FIAM more user-friendly in the future (like with a custom callback to handle the button's click)


text:
Q: SendKeys strange behaviour on Windows XP in C# I am using SendKeys in one of my program (C#) which copies selected text when a user presses F8 on keyboard.
It is working fine on Windows 7 but on Windows XP it has the following problem.

*

*Suppose on notepad, following sentence is written "This is test"

*If user selects "is" and presses F8 then the text is not copied.

*After that if user selects "This" then the text copied is "is"

*After that if user selects "test" then the text copied is "This"
As you can see pressing F8 copies previously selected text and not the current one. It is only happening on Windows XP.
Here is the code
System.IntPtr test = GetForegroundWindow();
System.Windows.Forms.SendKeys.Send("^(c)");
string copiedText = Clipboard.GetText();

Since I am using global key binding for F8 hence the first line of code tells me the currently active window. After that Ctrl+C is sent and then text is copied from clipboard.

A: I'd suggest switching to using the SendWait method:

Use SendWait to send keystrokes or combinations of keystrokes to the active application and wait for the keystroke messages to be processed.

(Emphasis added)
At the moment, you have a race condition, with no guarantee that the other application has processed the CTRL-C before you attempt to read the clipboard contents. It's not surprising that sometimes you get the older contents.
(Insert usual caveats about SendKeys being a horrific way to automate other applications, consider using the automation API instead, and avoid trampling all over the clipboard unless necessary)


text:
Q: How to link Libbluetooth for GCC? I am trying to use hci.h, hci_lib.h etc... in my c files. The final command to link the object files into exec look like this:
gcc -g3 -o execfile ./dev1.o ./dev2.o ./main.o ./nets.o `pkg-config --cflags --libs glib-2.0 gio-unix-2.0`

However I am getting linking error like this:
undefined reference to `hci_open_dev'
undefined reference to `hci_le_set_scan_parameters'
undefined reference to `hci_le_set_scan_enable'
undefined reference to `hci_le_set_scan_enable'
undefined reference to `hci_close_dev'

I know that this is because I am not specifying -lbluetooth to gcc.
Is there a way to specify the libbluetooth-dev to pkg-config like I do for glib & gio-unix above?


text:
Q: What to do with overheated GPU? (AMD HD 5470) I'm currently investigating what makes my Dell Studio 1558 so slow sometimes.
I noticed that it was getting really hot, and started checking temperature. It seems that my GPU (AMD Radeon HD 5470) is getting really really hot (even on a laptop stand). While standing on a desk, it easily gets to 80°C (176°F)
I'm using the fglrx version that came with Ubuntu 11.10, the Catalyst 11.8 driver.
So, my questions now are:

*

*What are the risks of an overheated GPU?

*Does an overheated GPU cause my laptop to slow down?

*Can I fix this?

Extra info:
I tried installing Catalyst 11.12 manually, but it kept on saying it found an older installation (sudo apt-get purge fglrx* was not enough it seemed).
In "Additional Drivers", I am not able to install the post-release version of fglrx
When I remove fglrx, I only get a black screen at boot
Hardware:
Dell Studio 1558 - i5 CPU @ 2,40 GHz - 8GB DDR3 memory - AMD HD 5470

A: I found my answer.
I was suffering from this bug: https://bugs.launchpad.net/ubuntu/+source/unity/+bug/803943
Temporary fix is using the PPA of Daniel van Vugt: https://bugs.launchpad.net/ubuntu/+source/unity/+bug/803943/comments/53
When the patch is accepted, it will be fixed in the standard updates.
My CPU usage for compiz dropped from 40% to 5% when idle
My GPU temp lowered from 75°C to 50°C when idle, from 100°C to 75°C when stressed. A huge improvement!

A: I had a similar problem with my video card. I have an ATI Radeon HD 3200 running with an AMD Turion. When I was using Ubuntu 11.10 32 bits it was reaching 90ºC! I tried many different things but none of them worked. So, almost giving up, I changed the Ubuntu 11.10 32 bits for the 64 bits version. Now it reaches at most 80º. If you have an AMD processor and you are using the 32 bits version I think it's interesting to try using the 64 bits version. = )


text:
Q: Get minimum and maximum decimal scale value I have float datatype column in sql server and I need to get minimum decimal scale and maximum decimal scale .
Here is SQL Fiddle
 I am using
Len (Cast(Cast(Reverse(CONVERT(VARCHAR(50), value, 128)
                     ) AS FLOAT) AS BIGINT))

Which work great but when value is something in negative eg -0.061 it throw error Error converting data type varchar to float.
So for alter I search and found that there is function name PARSENAME(@var,1) which is working perfect for negative numbers too but this function returns after decimal value and return type is nchar
Eg : If float value is -0.061 its will return 061 of return type nchar So i can not use len function to get its length.
SO how do I make this working either by using fiddle or by using above function.

A: Try using the ABS() function
SELECT value,
       Decimals = CASE Charindex('.', value)
                    WHEN 0 THEN 0
                    ELSE
   Len (Cast(Cast(Reverse(CONVERT(VARCHAR(50), ABS(value), 128)
                     ) AS FLOAT) AS BIGINT))
                  END
FROM   numbers

A: I guess using ABS() function should be enough. Shouldn't it?

A mathematical function that returns the absolute (positive) value of
  the specified numeric expression.

SELECT value
    , Decimals = CASE CHARINDEX('.', value)
        WHEN 0 THEN 0
        ELSE LEN(CAST(CAST(REVERSE(CONVERT(VARCHAR(50), ABS(value), 128)) AS FLOAT) AS BIGINT))
    END
FROM numbers;

A: This will work.
Just replace simple value with -value when it is negative i.e
CASE WHEN value<0 THEN -value ELSE value END
   SELECT value,
          Decimals = CASE WHEN Charindex('.', value)=0
                          THEN 0
                          ELSE Len (Cast(Cast(Reverse(CONVERT(VARCHAR(50), ABS(value), 128) ) AS FLOAT) AS BIGINT))
                     END
   FROM   numbers

A: To remove - symbol, use ABS function. ABS(value) in place of value


text:
Q: how can solve problem the multiple values in bitbucket? how can solve problem the multiple values in bitbucket?
The message that appeared to me
warning: user.email has multiple values
error: cannot overwrite multiple values with a single value
       Use a regexp, --add or --replace-all to change user.email.

A: Replace multiple values with single one:
git config --global --replace-all user.email your@email


text:
Q: How to change the fistDay in calendar full API but only for weekly, not monthly, etc I am using https://fullcalendar.io/ API to create a custom view for Weekly events and monthly events. The issue I am facing is that for weekly view, I want the start of the week to be Monday (1) and monthly to remain Sunday (0).
If I were to add firstDay: 1 as seen below, it will apply to both customWeek and customMonth views. I only need it for customWeek.
header: {
  left: '',
  center: '',
  right: 'customWeek, customMonth'
},
firstDay: 1,
droppable: true,....

Complete code.
$('#calendar').fullCalendar({
header: {
  left: '',
  center: '',
  right: 'customWeek, customMonth'
},
droppable: true,
eventStartEditable: true,
eventLimit: true,
eventLimitText: "MORE",
views: {
  customWeek: {
    type: 'basicWeek',
    buttonText: ' ',
    eventLimit: 1,
    columnFormat: 'D dddd'
  },
  customMonth: {
    type: 'month',
    buttonText: ' ',
    eventLimit: 1,
    columnFormat: 'dddd',
    defaults: {
      fixedWeekCount: false
    }
  }
},
defaultView: 'customWeek',
events: data});

Any ideas or suggestion is appreciated.

A: As far as I can tell, you can't. It's not one of the options you can pass to a view. The only solution would be to implement a completely custom view which overrides the view class, as detailed here: https://fullcalendar.io/docs/views/Custom_Views .
But that's a lot of work, and I'd argue it's not worth it. I suspect this feature is actually by design - starting on a different day on each view sounds like a great way to confuse your users, who will expect and/or assume that the display is consistent.


text:
Q: Why use c to create a vector when a colon does the same? I have just started learning R from the O'Reilly book "Learning R". It says that colon is used to create a sequence of numbers, while c function is used to concatenate it into a vector. I tried the following in R Studio:
a = 1:5

and the following:
a = c(1:5)

And they both seemed to have the same effect. Even statements like the ones below had the same effect:
a = 1:5 + 1:5
a = c(1:5 + 1:5)

I tried checking their datatype using class() and typeof() and they are the same too. Maybe I do not understand the importance as I have just started, but can someone please explain why c function needs to be used instead of just creating a sequence?
Thank you.


text:
Q: XSL to FO and HTML entities I'm developing a Java class that converts an HTML string  into a FO string via an XSLT document.
Then, the resulting FO string is processed by FOP to create a PDF file.
The problem is that when a special character is found by FOP, i get an error:
(e.g.) The entity "ldquo" was referenced, but not declared.

Now my solution is to replace all these special characters with their Unicode reference.
In this example, """ becomes """
Can I declare those entities in my XSLT file without doing zillions of StringUtils.replaceAll()?

A:
Solved using JTidy with setXmlOut(true)


text:
Q: Magento 2. How to upload images to pub/media Problem
I have a $fieldset. What arguments should I give to ->addField method to create an input field, that loads image to $_FILES?
What was done
For now I have an input field.

Created by
 $fieldset->addField('image',
            'image',
            [
                'title' => __('Image'),
                'label' => __('Image'),
                'name' => 'image',
                'note' => 'Allow image type: jpg, jpeg, gif, png',
            ]
        );

But the $_FILES is empty, when I checking it in controller execute() method.
Additional information
$fieldset arguments was taken from this example.

A: Go to file app/code/Vendor/Modulename/Block/Adminhtml/Modulename/Edit/Form.php
there is 'enctype' => 'multipart/form-data'
 $form = $this->_formFactory->create(
            ['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post', 'enctype' => 'multipart/form-data']]
        );


text:
Q: Declaring object property types before destructuring assignment Let's assume there's a function that returns an object whose property types can either be inferred or are explicitly provided:
const myFn = (arg: number) => {
    return {
        a: 1 + arg,
        b: 'b' + arg,
        c: (() => { return arg + 'c'})()
    }
}

We can then destructure the returned object and assign to new variables:
const { a, b, c } = myFn(10);
console.log('used once', a, b, c);

All nice and dandy. Now let's assume we'll need to reassign to those same variables later on, more specifically in a switch statement. In order to prevent Cannot redeclare block-scoped variable 'xyz'. ts(2451) we'll take advantage of assignment without declaration and proceed like so:
let my_a, my_b, my_c;

switch (true) {
    case Math.random() < 0.5:
        ({a: my_a, b: my_b, c: my_c} = myFn(Math.random()));
        console.log('called at one point', my_a, my_b, my_c);
    default:
        ({a: my_a, b: my_b, c: my_c} = myFn(Math.random()));
        console.log('called at another point', my_a, my_b, my_c);
}

The question is then, how can I declare/extract the types of my_a, my_b etc when I know what they're going to be and don't want to manually type them out? Here's a playground snippet.

ELABORATION
What I'm looking for is a way to declare the types when I initialize the vars using
let my_a, my_b, my_c;

based on what I know about the signature of myFn to prevent
Variable 'my_a' implicitly has an 'any' type,
but a better type may be inferred from usage. ts(7043)

A: You can declare an interface and place your switch logic inside anonymous arrow functions:
interface Alphabet {
    a: number,
    b: string,
    c: string,
}

const myFn = (arg: number): Alphabet =>  {
    return {
        a: 1 + arg,
        b: 'b' + arg,
        c: (() => { return arg + 'c'})()
    }
}

let my_a, my_b, my_c;

switch (true) {
    case Math.random() < 0.5:
        () => {
            const {a: my_a, b: my_b, c: my_c}: Alphabet = myFn(Math.random());
            console.log('called at one point', my_a, my_b, my_c);
        }
    default:
        () => {
            const {a: my_a, b: my_b, c: my_c}: Alphabet = myFn(Math.random());
            console.log('called at one point', my_a, my_b, my_c);
        }
}

A: If you just want to explicitly type the my_* variables ahead of time, then you can do that by drilling into the return type of your function.
let my_a: ReturnType<typeof myFn>['a'],
    my_b: ReturnType<typeof myFn>['b'],
    my_c: ReturnType<typeof myFn>['c'];

typeof myFn gets the function type from the myFn so the type system can work with it. ReturnType<...> will get the type that function returns. And, lastly, ['a'] will get the a property from that return type.
Playground

This isn't really required though. Your playground snippet infers everything correctly and raises no type errors. So I would think about whether this is really necessary.


text:
Q: will reassign a pointer cause memory leak? I have the following code and wondering what will happen when iOS is recollecting the allocated memories. Will the memory p1 pointed to get autoreleased afterwards, although it's pointing to a different memory now? And also will the memory p2 pointed to get autoreleased as well, as p1 is semantically meant to point to autoreleased memory at the beginning?
NSMutableArray *p1 = [NSMutableArray arrayWithCapacity:10];
NSMutableArray *p2 = [[NSMutableArray alloc] init];

// what will happen to the memory p1 and p2 point to
// after the following assignment, and at later stage?
p1 = p2;

A: Nothing will be leaked, p1 is an autoreleased object, in that scenario, after you assign p2 to p1, both of them simply point to the same object. Original object that p1 was pointing to, is managed by autorelease pool and will be released when the pool is drained. ARC or not, there is no leak assuming that you release p2 later.

A: Under ARC, you won't need to do anything Both objects will be released. Outside of ARC:
NSMutableArray *p1 = [NSMutableArray arrayWithCapacity:10];

returns an autoreleaed value. You don't need to release this value. However, this:
NSMutableArray *p2 = [[NSMutableArray alloc] init];

has a manual retain count of 1. You will need to release the value of p2 (which is then assigned to p1) when you are done with it.

A: NSMutableArray *p1 = [NSMutableArray arrayWithCapacity:10];
NSMutableArray *p2 = [[NSMutableArray alloc] init];

// what will happen to the memory p1 and p2 point to
// after the following assignment, and at later stage?
p1 = p2;

" iOS is recollecting the allocated memories" - iOS never had Garbage Collection feature.
p1 is pointer pointing to autoreleased object.
p2 is pointer pointing to non-autoreleased object (you or ARC has to release it later to avoid memory leak)
After p1 = p2, p1 points to non-autoreleased object that p2 is pointing to. Original object p1 was pointing to is orphaned at this point.
If you are using ARC feature, you don't have to do anything. Under Manual memory management environment you do [p2 release]; or [p1 release];  to balance releasing of allocated object that you own.

A: By the way, if you ever have questions like this in the future, it's easily tested by (a) subclassing the class in question; and (b) adding your own dealloc that logs the deallocation. For example:
@interface TestNSMutableArray : NSMutableArray
@end

@implementation TestNSMutableArray
- (void)dealloc
{
    [super dealloc]; // only needed for non-ARC
    NSLog("%s", __FUNCTION__);
}
@end

Then try your code using TestNSMutableArray rather than NSMutableArray. If you see your dealloc, you're good. If not, you're leaking.
Clearly you can also use Instruments, but when I was first getting my hands around Objective-C memory handling, I found this to be a simple, though useful, diagnostic technique.

A: First, this depends on if you are using ARC.
Using ARC:
There will be no memory leaks. The OS will release the memory for p1 and the array will now point to the same location as p2. Then, the OS will release the memory for both arrays when p1 and p2 go away (such as when the class is deallocated).
No ARC:
p1 will be leaked. To fix the leak you will need
[p1 release];

before assigning the value of p2 to p1. If you do not call release on both of these arrays before the class is deallocated, the memory from p2 will be leaked also.