text:
Q: buggy JQuery .animation() here i have 6 divs (.sticker) inside a single div, onClicking one of them i would like to fadeOut the others keeping the clicked one in it position (that's why i do the postop/posleft thing) then i want to move it on the middle of the bigger div while it grows by height and width, showing a hided div (.info). The same for closing!
So, this code it's working but it's really laggy, it's not smooth as jQuery should be, am i doing something wrong?
Thanks to all the comunity!
$("body").on('click', '.sticker', function () {

    if (!is_open) {
        postop = $(this).position().top;
        posleft = $(this).position().left;
        $('.sticker').not(this).fadeOut(350, function () {
            $(".sticker").css("position", "absolute").css("left", posleft + "px").css("top", postop + "px");
            $(".sticker").animate({
                'top': '0px',
                'left': '300px',
                'height': '480px',
                'width': '750px',
                'left': '90px'
            }, 350);
            $(".sticker").children(".wrap").animate({
                'height': '343px',
                'width': '750px'
            }, 350);
            $(".sticker").find(".imgspace").animate({
                'height': '343px',
                'width': '750px'
            }, 350);
            $(".sticker").find(".info").animate({
                'height': '100px'
            }, 350);
            $('.arrow-left').animate({
                'left': '-20px'
            }, 450);
            $('.arrow-right').animate({
                'left': '880px'
            }, 450);
            is_open = true;

        });
    }
    if (is_open) {
        $(".sticker").children(".wrap").animate({
            'height': '193px',
            'width': '300px'
        }, 350);
        $(".sticker").find(".imgspace").animate({
            'height': '193px',
            'width': '300px'
        }, 350);
        $(".sticker").find(".info").animate({
            'height': '0px'
        }, 350);
        $(".sticker").animate({
            'height': '230px',
            'width': '300px',
            'top': postop,
            'left': posleft
        }, 350, function () {
            $(".sticker").css("position", "static");
            $(".sticker").not(this).fadeIn(300);
            is_open = false;
        });

    }

});

A: You will want to use .siblings to hide all others when you click on one. I would do some research on the jQuery API document.  This is where I would start.

A: As Yotam has commented, difficult to debug without a jsFiddle. But things that stuck out to me (and in no way is this exhaustive and I am no JavaScript expert):

*

*cache your jQuery objects rather than keep requerying the DOM (var $sticker = $('.sticker'))

*Chain together your animations on the same objects

*What is the difference between  $sticker.children(".wrap") and $sticker.find(".imgspace")? Can you not use $sticker.find(".wrap, .imgspace")?

You could further simplify the code by setting your values to variable objects rather than call the same method twice hard coded with different values.
$("body").on('click', '.sticker', function () {

    if (!is_open) {
        var $position = $(this).position(),
            $sticker = $('.sticker');

        $sticker.not(this).fadeOut(350, function () {
            $sticker.css({
                        position: 'absolute',
                        left: $position.left+'px',
                        top: $position.top+'px'
                    })
                    .animate({
                        'top': '0px',
                        'left': '300px',
                        'height': '480px',
                        'width': '750px',
                        'left': '90px'
                    }, 350);
            $sticker.find(".wrap, .imgspace").animate({
                'height': '343px',
                'width': '750px'
            }, 350);
            $sticker.find(".info").animate({ 'height': '100px' }, 350);
            $('.arrow-left').animate({ 'left': '-20px' }, 450)
                            .animate({ 'left': '880px' }, 450);
            is_open = true;

        });
    }
    if (is_open) {
        $sticker.find(".wrap, .imgspace").animate({
            'height': '193px',
            'width': '300px'
        }, 350);
        $sticker.find(".info").animate({
            'height': '0px'
        }, 350);
        $sticker.animate({
            'height': '230px',
            'width': '300px',
            'top': $position.top,
            'left': $position.left
        }, 350, function () {
            $sticker.css("position", "static")
                    .not(this).fadeIn(300);
            is_open = false;
        });
    }
});


text:
Q: what is the effective way to compare strings? I am writing the different set of strings generated by a piece of software into a text file. I want to write a test so that it compares the generated and written text for any possible error!
What is the effective way to do such test?

A: To compare two strings in C programming, you have to ask the user to enter the two strings and start comparing using the function strcmp().
If it will return 0, then both strings are equal.
If it will not return 0, then both strings are not be equal to each other.

A: The standard method to compare C strings is the strcmp() function declared in <string.h>.
There are a few special cases where more efficient solutions can be sought:

*

*if the strings have a known length: memcmp() can be used and might perform better as it does not need to test for end of strings.

*if only equality is to be tested, the extra work performed by strcmp() to compute the  relative lexicographical order of the strings could be avoided, but strcmp() is usually implemented very efficiently, so it is unlikely you get any improvement by handcoding an alternative in C.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Recursively create Graph from seed and Nest GraphUnion, keeping VertexStyle, EdgeLabels, VertexCoordinates, EdgeShapeFunction TL;DR;
GraphUnion does not preserve properties of the input Graphs.
How do I combine two Graph preserving and/or modifying properties?
Detail
I want to recursively create a Graph from a seed, Nest and a grow function using GraphUnion (or similar), preserving the seed properties on  VertexStyle, EdgeLabels, VertexCoordinates, EdgeShapeFunction.
For example, let's say I have the following seed
esf =   {
            Line[{Transpose[#1].{0.97, 0.03}, Transpose[#1].{0.55,0.45}}],
            Arrow[{Transpose[#1].{0.45,0.55}, Transpose[#1].{0.02,0.98} }]
        }&

seed = Graph[
      {1, 2}
    , { DirectedEdge[1, 2] }
    , VertexStyle -> { 1 -> Red, 2 -> Blue }
    , EdgeLabels -> { DirectedEdge[1, 2] -> 1 }
    , VertexCoordinates -> { {-1, 0}, {+0, 0} }
    , EdgeShapeFunction -> esf
]

The grow function will take a Graph and join it with a modified copy of itself.
something like
grow[gr_Graph]:= GraphUnion[
    gr
    , IndexGraph[gr, VertexCount[gr]+1 ]  (* Modified Graph *)
    , Graph[                    (* New edge connects two Graphs*)
        DirectedEdge[
            VertexCount[gr],
            2*VertexCount[gr]
        ]
    ]
]

but with some modification. Example mod modifications could be:

*

*Increment EdgeLabels

*Change VertexStyle

*TransformationFunction VertexCoordinates
But if I do
grow[seed]

(* Graph[{1, 2, 3, 4}, {DirectedEdge[1, 2], DirectedEdge[3, 4], DirectedEdge[2, 4]}]] *)

It drops all information about VertexStyle, EdgeLabels, VertexCoordinates, EdgeShapeFunction.
I would like the output of grow[seed] to be something around
Graph[
    {1, 2, 3, 4}
    ,
    {
        DirectedEdge[1, 2], DirectedEdge[3, 4], DirectedEdge[2, 4]
    }
    , VertexStyle ->
        {
            1 -> Red
          , 2 -> Blue
          , 3 -> Lighter[Red]    (* Original colour modified *)
          , 4 -> Lighter[Blue]
        }
    , EdgeLabels ->
        {
             DirectedEdge[1, 2] -> 1,
             DirectedEdge[3, 4] -> 1,
             DirectedEdge[2, 4] -> 2     (* New edge increments label *)
        }
    , VertexCoordinates ->               (* TransformationFunction *)
        {
            {-1, -1}
          , {-1,  0}
          , { 0, -1}
          , { 0,  0}
        }
    , EdgeShapeFunction -> esf
]

So I can later do things like
Nest[grow, seed, 6]

Question
How do I combine two Graph preserving and/or modifying properties?
How do I extract and modify properties of a Graph ?


text:
Q: Query monthly having group_concat and group by need help I'm stuck on a join tables query presenting data monthly involving GROUP BY and GROUP_CONCAT.
Here's a simple client table (DDL and DML at the bottom of this post):
id | Name
1  | Sony
2  | Toshiba
3  | Apple
4  | LG
5  | Uco

Then the event table
id | client_id | date_start
1 | 1 | 2017-01-12 18:44:42
2 | 1 | 2017-01-13 18:44:42
3 | 1 | 2017-01-14 18:44:42
4 | 1 | 2017-02-12 18:44:42
5 | 1 | 2017-03-12 18:44:42
6 | 1 | 2017-07-12 18:44:42
7 | 2 | 2017-02-12 18:44:42
8 | 2 | 2017-03-12 18:44:42
9 | 2 | 2017-04-12 18:44:42
10 | 3 | 2017-01-12 18:44:42
11 | 3 | 2017-01-14 18:44:42
12 | 3 | 2017-01-20 18:44:42
13 | 3 | 2017-03-12 18:44:42
14 | 3 | 2017-05-12 18:44:42
15 | 3 | 2017-06-12 18:44:42
16 | 4 | 2017-07-12 18:44:42
17 | 4 | 2017-07-20 18:44:42
18 | 5 | 2017-09-12 18:44:42
19 | 5 | 2017-10-12 18:44:42
20 | 5 | 2017-03-12 18:44:42

The desired result is as follows. The string number, for example (10-01-12) on Jan/Apple is formatted as id-month-day.

What I've done so far is using case when to split result monthly:
select * from (
select e.id, c.name as client,
(CASE WHEN MONTH(e.date_start) = 1 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as jan,
(CASE WHEN MONTH(e.date_start) = 2 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as feb,
(CASE WHEN MONTH(e.date_start) = 3 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as mar,
(CASE WHEN MONTH(e.date_start) = 4 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as apr,
(CASE WHEN MONTH(e.date_start) = 5 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as may,
(CASE WHEN MONTH(e.date_start) = 6 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as jun,
(CASE WHEN MONTH(e.date_start) = 7 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as jul,
(CASE WHEN MONTH(e.date_start) = 8 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as aug,
(CASE WHEN MONTH(e.date_start) = 9 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as sep,
(CASE WHEN MONTH(e.date_start) = 10 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as oct,
(CASE WHEN MONTH(e.date_start) = 11 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as nov,
(CASE WHEN MONTH(e.date_start) = 12 then GROUP_CONCAT(CONCAT(e.id,'-',LPAD(month(date_start),2,'0'), '-', LPAD(day(date_start),2,'0')) SEPARATOR ',')END) as `dec`

from
 event as e
 left join client as c on c.id=e.client_id
group by month(date_start),client
order by client
) t

But query above need final touch to group by client. How do I concat having group by client result as appear on the desired table above with comma as separator?
The second part is counting the sum of each data monthly. Not as important, I really need to get part one to work.
Here is the SQL for data and tables.
CREATE TABLE `client` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(128) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

LOCK TABLES `client` WRITE;

INSERT INTO `client` (`id`, `name`)
VALUES
    (1,'Sony'),
    (2,'Toshiba'),
    (3,'Apple'),
    (4,'LG'),
    (5,'Uco');

UNLOCK TABLES;

CREATE TABLE `event` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `client_id` int(11) unsigned DEFAULT NULL,
  `date_start` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`),
  KEY `client_id` (`client_id`),
  KEY `date_start` (`date_start`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

LOCK TABLES `event` WRITE;

INSERT INTO `event` (`id`, `client_id`, `date_start`)
VALUES
    (1,1,'2017-01-12 18:44:42'),
    (2,1,'2017-01-13 18:44:42'),
    (3,1,'2017-01-14 18:44:42'),
    (4,1,'2017-02-12 18:44:42'),
    (5,1,'2017-03-12 18:44:42'),
    (6,1,'2017-07-12 18:44:42'),
    (7,2,'2017-02-12 18:44:42'),
    (8,2,'2017-03-12 18:44:42'),
    (9,2,'2017-04-12 18:44:42'),
    (10,3,'2017-01-12 18:44:42'),
    (11,3,'2017-01-14 18:44:42'),
    (12,3,'2017-01-20 18:44:42'),
    (13,3,'2017-03-12 18:44:42'),
    (14,3,'2017-05-12 18:44:42'),
    (15,3,'2017-06-12 18:44:42'),
    (16,4,'2017-07-12 18:44:42'),
    (17,4,'2017-07-20 18:44:42'),
    (18,5,'2017-09-12 18:44:42'),
    (19,5,'2017-10-12 18:44:42'),
    (20,5,'2017-03-12 18:44:42');

UNLOCK TABLES;

A: Terminology and Methodology
This kind of transformation – rows to columns – is called pivoting. It is typical to pivot data simultaneously with their aggregation, as seems to be a requirement in your case too. In SQL you can do both operations as a single logical step. Other SQL products even offer special syntactical extensions for pivoting, but there is a way to do that using more generic syntax, one that is supported by at least every major RDBMS, which includes MySQL.
The method is called conditional aggregation, and you almost nailed it. The conditional, implemented as a CASE expression in your query, is supposed to go inside the aggregate function, and the criterion that the conditional is checking on (MONTH(e.date_start) in your case) needs to be excluded from the GROUP BY.
So, instead of
SELECT
  CASE WHEN MONTH(e.date_start) = 1 THEN GROUP_CONCAT(...),
  ...
FROM
  ...
GROUP BY
  MONTH(e.date_start),
  client

it should be
SELECT
  GROUP_CONCAT(CASE WHEN MONTH(e.date_start) = 1 THEN ...),
  ...
FROM
  ...
GROUP BY
  MONTH(e.date_start),
  client

The exclusion part may seem counter-intuitive – after all, you are intending to get monthly data. However, you should keep in mind that in SQL you are grouping rows. In your case, one row is one client – therefore, grouping should be by client only. You could say that monthly grouping is implicit, as it is implemented through conditional aggregation only.
Anyway, what about the last row? The last row is special, and not just because it is a rollup row, thus representing aggregated data over the entire set. In my view, it is special more because it contains entirely different data: counts instead of concatenated strings.
Based on that fact, it seems natural to me to consider a distinct logical step – a separate SELECT – for getting the last row's results. The two result sets would then be combined into one with the help of a UNION ALL operator. This approach would make the logic clear, in my opinion: different kinds of data in the output would be accounted for by different legs of the query. And clear logic ultimately means ease of maintenance.
Solution
So, taking into account all of the above, the complete query could look like this:
SELECT
  c.name AS client,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN  1 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS jan,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN  2 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS feb,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN  3 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS mar,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN  4 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS apr,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN  5 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS may,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN  6 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS jun,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN  7 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS jul,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN  8 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS aug,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN  9 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS sep,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN 10 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS oct,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN 11 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS nov,
  GROUP_CONCAT(CASE MONTH(e.date_start) WHEN 12 THEN CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) END SEPARATOR ',') AS `dec`
FROM
  event AS e
  INNER JOIN client AS c ON e.client_id = c.id
GROUP BY
  c.name

UNION ALL

SELECT
  NULL,
  COUNT(MONTH(e.date_start) =  1 OR NULL),
  COUNT(MONTH(e.date_start) =  2 OR NULL),
  COUNT(MONTH(e.date_start) =  3 OR NULL),
  COUNT(MONTH(e.date_start) =  4 OR NULL),
  COUNT(MONTH(e.date_start) =  5 OR NULL),
  COUNT(MONTH(e.date_start) =  6 OR NULL),
  COUNT(MONTH(e.date_start) =  7 OR NULL),
  COUNT(MONTH(e.date_start) =  8 OR NULL),
  COUNT(MONTH(e.date_start) =  9 OR NULL),
  COUNT(MONTH(e.date_start) = 10 OR NULL),
  COUNT(MONTH(e.date_start) = 11 OR NULL),
  COUNT(MONTH(e.date_start) = 12 OR NULL)
FROM
  event AS e

;

Or, perhaps, like this, if we wanted to make it look slightly less cumbersome by eliminating repetition of some code:
SELECT
  client,
  GROUP_CONCAT(CASE month WHEN  1 THEN item END SEPARATOR ',') AS jan,
  GROUP_CONCAT(CASE month WHEN  2 THEN item END SEPARATOR ',') AS feb,
  GROUP_CONCAT(CASE month WHEN  3 THEN item END SEPARATOR ',') AS mar,
  GROUP_CONCAT(CASE month WHEN  4 THEN item END SEPARATOR ',') AS apr,
  GROUP_CONCAT(CASE month WHEN  5 THEN item END SEPARATOR ',') AS may,
  GROUP_CONCAT(CASE month WHEN  6 THEN item END SEPARATOR ',') AS jun,
  GROUP_CONCAT(CASE month WHEN  7 THEN item END SEPARATOR ',') AS jul,
  GROUP_CONCAT(CASE month WHEN  8 THEN item END SEPARATOR ',') AS aug,
  GROUP_CONCAT(CASE month WHEN  9 THEN item END SEPARATOR ',') AS sep,
  GROUP_CONCAT(CASE month WHEN 10 THEN item END SEPARATOR ',') AS oct,
  GROUP_CONCAT(CASE month WHEN 11 THEN item END SEPARATOR ',') AS nov,
  GROUP_CONCAT(CASE month WHEN 12 THEN item END SEPARATOR ',') AS `dec`
FROM
  (
    SELECT
      c.name AS client,
      MONTH(e.date_start) AS month,
      CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) AS item
    FROM
      event AS e
      INNER JOIN client AS c ON e.client_id = c.id
  ) AS derived
GROUP BY
  client

UNION ALL

SELECT
  NULL,
  COUNT(month =  1 OR NULL),
  COUNT(month =  2 OR NULL),
  COUNT(month =  3 OR NULL),
  COUNT(month =  4 OR NULL),
  COUNT(month =  5 OR NULL),
  COUNT(month =  6 OR NULL),
  COUNT(month =  7 OR NULL),
  COUNT(month =  8 OR NULL),
  COUNT(month =  9 OR NULL),
  COUNT(month = 10 OR NULL),
  COUNT(month = 11 OR NULL),
  COUNT(month = 12 OR NULL)
FROM
  (
    SELECT
      MONTH(e.date_start) AS month
    FROM
      event AS e
  ) AS derived

;

If you are not very familiar with the A = B OR NULL formula, think of it as an alternative to CASE WHEN A = B THEN 1 ELSE NULL END. For details on how it really works I refer you to this Stack Overflow question:

*

*Why do I need "OR NULL" in MySQL when counting rows with a condition
Alternative
All that nice talk about clear logic and maintainability notwithstanding, you might still like to be able to implement the query as a single SELECT. Even though we have managed to simplify the initial version by reducing code repetition, the MONTH(date_start) expression still has to be specified twice across the query, because each SELECT leg needs it, so why not try eliminating that repetition too? And if that is not enough of a reason, the alternative solution might turn out faster, maybe even noticeably. And maybe the resulting query would not look too ugly. In the end, it would just be nice to have a choice, plain and simple.
So, how would it be possible to rewrite the query using WITH ROLLUP, so that both the client details and the rollup row would be produced by the same SELECT statement (without any UNION ALL kind of cheating)?
Well, you can use the former solution as a prototype. One part of that query performs group concatenation over clients. The other part counts rows over the entire set. Now, if you want to have a single-part query, the single part must do both operations at both levels.
Which kind of information to show at which level should then be determined by another set of conditionals.
Taking the above-mentioned points into consideration, here is my attempt at a single-step query:
SELECT
  client,
  IF(client IS NULL, COUNT(month =  1 OR NULL), GROUP_CONCAT(CASE month WHEN  1 THEN item END SEPARATOR ',')) AS jan,
  IF(client IS NULL, COUNT(month =  2 OR NULL), GROUP_CONCAT(CASE month WHEN  2 THEN item END SEPARATOR ',')) AS feb,
  IF(client IS NULL, COUNT(month =  3 OR NULL), GROUP_CONCAT(CASE month WHEN  3 THEN item END SEPARATOR ',')) AS mar,
  IF(client IS NULL, COUNT(month =  4 OR NULL), GROUP_CONCAT(CASE month WHEN  4 THEN item END SEPARATOR ',')) AS apr,
  IF(client IS NULL, COUNT(month =  5 OR NULL), GROUP_CONCAT(CASE month WHEN  5 THEN item END SEPARATOR ',')) AS may,
  IF(client IS NULL, COUNT(month =  6 OR NULL), GROUP_CONCAT(CASE month WHEN  6 THEN item END SEPARATOR ',')) AS jun,
  IF(client IS NULL, COUNT(month =  7 OR NULL), GROUP_CONCAT(CASE month WHEN  7 THEN item END SEPARATOR ',')) AS jul,
  IF(client IS NULL, COUNT(month =  8 OR NULL), GROUP_CONCAT(CASE month WHEN  8 THEN item END SEPARATOR ',')) AS aug,
  IF(client IS NULL, COUNT(month =  9 OR NULL), GROUP_CONCAT(CASE month WHEN  9 THEN item END SEPARATOR ',')) AS sep,
  IF(client IS NULL, COUNT(month = 10 OR NULL), GROUP_CONCAT(CASE month WHEN 10 THEN item END SEPARATOR ',')) AS oct,
  IF(client IS NULL, COUNT(month = 11 OR NULL), GROUP_CONCAT(CASE month WHEN 11 THEN item END SEPARATOR ',')) AS nov,
  IF(client IS NULL, COUNT(month = 12 OR NULL), GROUP_CONCAT(CASE month WHEN 12 THEN item END SEPARATOR ',')) AS `dec`
FROM
  (
    SELECT
      c.name AS client,
      MONTH(e.date_start) AS month,
      CONCAT(e.id, '-', RIGHT(DATE(e.date_start), 5)) AS item
    FROM
      event AS e
      INNER JOIN client AS c ON e.client_id = c.id
  ) AS derived
GROUP BY
  client
  WITH ROLLUP
;

As you can see, the query is calculating both the COUNTs and the GROUP_CONCATs both at the client level and at the whole set level. But each pair of the results is put inside an IF function, so that ultimately only one or the other result is returned in each column.
The condition to check is client IS NULL. If client happens to be null, that means that the current group represents the entire set and in that case each IF function chooses the COUNT result. When client value is not null, that means we are at the client level and each group of rows represents a specific client. In that case the GROUP_CONCAT result is returned, which is according to requirements, because for clients we must show concatenated strings.
Both solutions can be found at dbfiddle.uk.
Additional remarks
In my explanation above I tried to focus on the solutions and how they work. To avoid distractions, I allowed certain anti-patterns in my code that are worth mentioning.

*

*Reliance on precedence rules when implicitly converting data.
The results of the functions COUNT() and GROUP_CONCAT() are different. One returns an integer, the other a string. When you are trying to put values of such different types into a single column, the server must decide which type to convert to which other type. It is good to know these rules but you should never rely on them in production code. That is just bad practice.
In the queries above, a COUNT and a GROUP_CONCAT are either in the same column in different legs of the same query or in the same conditional that chooses between the two. In each case MySQL needs to apply its rules of type precedence. To avoid that, you can just explicitly cast each COUNT as a string:
CAST(COUNT(...) AS char)

*Missing ORDER BY in GROUP_CONCAT.
If you omit an ORDER BY, you are simply saying that you do not care if one time the query returns the string as A,B,C and the other as B,A,C and later as C,B,A. If you want your results to be predictable, always specify an ORDER BY and always use enough criteria to avoid ties.
In the above queries the lines were simply very long already and I purposefully omitted the ORDER BYs for presentability's sake. The issue can be easily fixed with an ORDER BY like this:
ORDER BY item ASC

More specifically, in GROUP_CONCAT it would be used like this:
GROUP_CONCAT(CASE month WHEN 12 THEN item END ORDER BY item ASC SEPARATOR ',')

A: Proposed Query
SELECT IFNULL(month_of_date_start,'Year') month_of_date_start,IFNULL(name,'Total') name
,IF(ISNULL(name)=1,LENGTH(val)-LENGTH(REPLACE(val,',',''))+1,val) key_values
FROM (SELECT A.name,MONTH(B.date_start) month_of_date_start,
GROUP_CONCAT(CONCAT(B.id,'-',DATE_FORMAT(date_start,'%m-%d')) ORDER BY B.id) val
FROM client A LEFT JOIN (SELECT * FROM event
WHERE date_start >= MAKEDATE(2017,1) AND date_start < MAKEDATE(2018,1)) B
ON A.id = B.client_id GROUP BY MONTH(date_start),A.name WITH ROLLUP) AA;

Output of Proposed Query
mysql> SELECT IFNULL(month_of_date_start,'Year') month_of_date_start,IFNULL(name,'Total') name
    -> ,IF(ISNULL(name)=1,LENGTH(val)-LENGTH(REPLACE(val,',',''))+1,val) key_values
    -> FROM (SELECT A.name,MONTH(B.date_start) month_of_date_start,
    -> GROUP_CONCAT(CONCAT(B.id,'-',DATE_FORMAT(date_start,'%m-%d')) ORDER BY B.id) val
    -> FROM client A LEFT JOIN (SELECT * FROM event
    -> WHERE date_start >= MAKEDATE(2017,1) AND date_start < MAKEDATE(2018,1)) B
    -> ON A.id = B.client_id GROUP BY MONTH(date_start),A.name WITH ROLLUP) AA;
+---------------------+---------+----------------------------+
| month_of_date_start | name    | key_values                 |
+---------------------+---------+----------------------------+
| 1                   | Apple   | 10-01-12,11-01-14,12-01-20 |
| 1                   | Sony    | 1-01-12,2-01-13,3-01-14    |
| 1                   | Total   | 6                          |
| 2                   | Sony    | 4-02-12                    |
| 2                   | Toshiba | 7-02-12                    |
| 2                   | Total   | 2                          |
| 3                   | Apple   | 13-03-12                   |
| 3                   | Sony    | 5-03-12                    |
| 3                   | Toshiba | 8-03-12                    |
| 3                   | Uco     | 20-03-12                   |
| 3                   | Total   | 4                          |
| 4                   | Toshiba | 9-04-12                    |
| 4                   | Total   | 1                          |
| 5                   | Apple   | 14-05-12                   |
| 5                   | Total   | 1                          |
| 6                   | Apple   | 15-06-12                   |
| 6                   | Total   | 1                          |
| 7                   | LG      | 16-07-12,17-07-20          |
| 7                   | Sony    | 6-07-12                    |
| 7                   | Total   | 3                          |
| 9                   | Uco     | 18-09-12                   |
| 9                   | Total   | 1                          |
| 10                  | Uco     | 19-10-12                   |
| 10                  | Total   | 1                          |
| Year                | Total   | 20                         |
+---------------------+---------+----------------------------+
25 rows in set (0.01 sec)

I'll leave you the gory details of displaying the data
Notes
If you want to examine a different year (like 2012), simply change
WHERE date_start >= MAKEDATE(2017,1) AND date_start < MAKEDATE(2018,1)) B

to
WHERE date_start >= MAKEDATE(2012,1) AND date_start < MAKEDATE(2013,1)) B

GIVE IT A TRY !!!


text:
Q: I can't send post request from react form to flask server I have a reactjs as a frontend and flask server as a backend. I'm trying to send data from register form (using Formik). When I do a post request I have an error 500.
I notice that when I'm using postman everything is good and flask create new record in postgresql.
frontend is on http://localhost:3000/register,
backend is on http://localhost:5002/adduser
What I should do now ?
function handleSubmit(values, actions) {

  const options = {
    headers: {
      'Content-type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Referrer-Policy': 'origin-when-cross-origin'
    },
    method: 'POST',
    mode: 'no-cors',
    body: JSON.stringify(values)
  }

fetch('http://localhost:5002/adduser', options)
    .then(response => console.log(response))
    .catch(error => console.error(error))
}

@app.route('/adduser', methods=['GET', 'POST'])
def register():
  if request.method == "POST":
    print(request.form['userName'])
    print(request.form['email'])
    data = {
      'name': request.form['userName'],
      'surname': request.form['surname'],
      'email': request.form['email'],
      'user_password': request.form['password'],
      'phone_number': request.form['phoneNumber']
    }
    mydb = Database(host=os.getenv('host'), database=os.getenv('database'), user=os.getenv('user'), password=os.getenv('password'))
    mydb.insert_data(data)

    return jsonify({'mydata': data})

    # name = request.form['name']
    # surname = request.form['surname']
    # email = request.form['email']
    # password = request.form['password']
    # phone_number = request.form['phoneNumber']
  return "
Hello Flask
"

if __name__ == "__main__":
    app.run(debug=True, port=5002)
    app.secret_key = os.urandom(24)

A: You can't access to request.form via json Content-type request.
You need to replace
'Content-type': 'application/json'

By
'Content-Type': 'multipart/form-data'

Your handleSubmit function will be similar to this:
function handleSubmit(values, actions) {

let options = {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    method: 'POST'
  };

  options.body = new FormData();
  for (let key in values) {
    options.body.append(key, values[key]);
  }

  fetch('http://localhost:5002/adduser', options)
    .then(response => console.log(response))
    .catch(error => console.error(error))
  }
}
}

Another possible solution is to keep client code without change and access to your data via request.json instead of request.form.


text:
Q: Masked input plugin returning `undefined is not a function` This is an example of masked input plug in. The demo is looking good so i want to try it out the problem is i am getting error in line
jQuery(function($) {
    $("#comp_id").mask("99-9999-999");
});

i Copied the maskedinput.js from the link and i also have a jquery-1.11.1.min.js What seems to be the problem here?


text:
Q: noexcept to become part of the type system I hear that noexcept will become part of the function type in C++17. What difference will this make? Does it mean that we will have to distinguish between noexcept and non-noexcept functions and member functions in our templates (which will double the amount of boilerplate code we have to write)?
For example, for current templates that matches function pointers:
template<typename R, typename... Args>
struct Foo<R (*)(Args...)> {};

We will need an additional:
template<typename R, typename... Args>
struct Foo<R (*)(Args...) noexcept> {};

And this is only for good old functions. For member functions we have const, volatile, and ref-qualifiers already, yielding a huge load of combinatuons. With the addition of noexcept it will get twice as bad.

A: If they had blindly changed things so that noexcept qualifications were part of a function pointer's type, they would have broken tons of code, generic and not. As such, there's a back-door.
In accord with P0021R1, any pointer to a noexcept-qualified function can be implicitly converted to a pointer to a non-noexcept-qualified function. The same goes for pointers to member functions with such qualifications.
Indeed, building that loophole seems to be what around 2/3rds of the language in the proposal is for.

A: In addition to @NicolBolas answer I'd like to point out that given two specializations :
// 1
template<typename R, typename... Args>
struct Foo<R (*)(Args...)> {};

and
// 2
template<typename R, typename... Args>
struct Foo<R (*)(Args...) noexcept> {};

Then Foo<decltype(fun)> will match the first one for
int fun1(int) {}

and the second one for
int fun2(int) noexcept {}

Also given two overloads (it goes without saying that we'll be able to overload on exception specification since this will alter the type of a parameter):
int foo(int (*a)(int)); // 1
int foo(int (*a)(int) noexcept); // 2

the compiler will choose the first overload for fun1 and the second for fun2


text:
Q: Twitter message length counting This is from twitter doc: https://developer.twitter.com/en/docs/basics/counting-characters.html
"Twitter counts the length of a Tweet using the Normalization Form C (NFC) version of the text ...  Twitter also counts the number of codepoints in the text rather than UTF-8 bytes."
It works for Western languages. But when I apply FormC normalization to the following, for example:
(I posted an example in Korean, but stackoverflow considers it spam and doesn't let me post it)
I get the value of 160. On Twitter's Web client, this is the maximum available message - adding even one character goes over the limit.
Applying FormD to the above gets a value over 300.
Since Twitter limit is either 140 or 280, I really don't understand how that message's char count is determined by Twitter.
So - how in the world can I figure out what the actual message length is for non-Western languages for a tweet?
The code to normalize, in c#:
    private static int GetCodepointLength(string inp)
    {
        var info = new StringInfo(inp.Normalize(NormalizationForm.FormC));
        return info.LengthInTextElements;
    }


text:
Q: Backbone.xmpp: Fetching subscriptions How do I use Backbone.xmpp to fetch subscriptions? I know I get them by XMPPConnection.PubSub.getSubscriptions(); but how do I use Collections, Models and a View for subscriptions? Do I have to use a Backbone.Collection and Backbone.Model because Backbone.xmppSync's Collections and Models are for leaf nodes only.

A: As mentioned in the documentation, subscriptions are not managed by the nodes directly. The node models provides by Backbone.xmpp merely sync with the XMPP nodes and provide real time notifications.
You have to do it either server-side (preferable as you can impose whatever security workflow you like) or client side by utilising the bundled pubsub plugin for Strophe.
Again, it's pretty straight forward, have a look at the inline documentation. A user can manage his subscription or getting all of them by using subscribe, unsubscribe, getSubscriptions.
So for instance,
var p = connection.PubSub.subscribe('/nodes/my_node')
    .done(function () { console.log('You are subscribed'); })
    .fail(function () { console.log('Ohoh, something went wrong'); });

will subscribe the connected user to the node /nodes/my_node


text:
Q: Using JavaScript variables for django template list lookup I've used js vars before with django templates, and it has worked, but this case is a bit different.
I need to use js var as a list index number to look up objects from a passed list in a django template var.
var index = 0;
$(.someclass).html (
    {{ list.index.some_attr }}
}

This does not work, and what's weird is I tested this:
$(.someclass).html (
     {{ list.0.some_attr }}
 )

And it works!, This also works:
var index = 0;
$(.someclass).html (
     index
}

This is a bit confusing, can anyone give an explanation? Thanks!

A: You cant access an iterable's member attribute without iterating it or pointing the member by index. This is quite normal in OOP. That said what is the problem you are trying to solve?


text:
Q: Consume a web service method with multiple args in Mule esb Hello what I want to apply seems very simple but I don't know how, need some clarifications.
here is the scenario:
I want to call a web service method, this method name is find() and accept as argument an object, the object represent a composed primary key, composed by two strings an id and a type.
the object -which is the primary key- representation in soap is :
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsd="http://wsdouane/">
   <soapenv:Header/>
   <soapenv:Body>
      <wsd:find>
         <entity>
            <id>string_1</id>
            <type>string_2</type>
         </entity>
      </wsd:find>
   </soapenv:Body>
</soapenv:Envelope>

my first idea was about reading the two args (the id and the type)from an http post request to create the wanted primary key object with a java transformer which call the primary key class constructor , then pass the created object to a soap component to creat the soap request based on the object, then call the web service with an http component and finally write the response into a file.
this the resulting flow:
<flow name="testObjetFlow1" doc:name="testObjetFlow1">
    <http:inbound-endpoint exchange-pattern="one-way" host="localhost" port="8088" doc:name="HTTP"/>
    <custom-transformer class="com.test.transformer.HttpRequestToPrimaryKeyObject" doc:name="PK Object Transformer"/>
    <cxf:jaxws-client operation="find" serviceClass="douane.Douane" port="douanePort"  doc:name="SOAP"/>
    <http:outbound-endpoint exchange-pattern="request-response" method="POST" address="http://localhost:8080/ClientsDB/douane" doc:name="douaneWS"/>
    <mulexml:object-to-xml-transformer doc:name="Object to XML"/>
    <file:outbound-endpoint path="C:\MuleStudio\SandBox\output" outputPattern="#[function:datestamp:dd-MM-yy]_#[function:systime].xml " responseTimeout="10000" doc:name="Outgoing File"/>
</flow>

My custom transformer
package com.test.transformer;

import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
import douane.DouanePK;
public class HttpRequestToPrimaryKeyObject extends AbstractMessageTransformer {

    @Override
    //DouanePK represent the primary key entity
    public DouanePK transformMessage(MuleMessage message, String outputEncoding)
            throws TransformerException {
        // TODO Auto-generated method stub
        String id = message.getInboundProperty("id");
        String type = message.getInboundProperty("type");

        DouanePK primKey = new DouanePK();
        dp.setId(id);
        dp.setType(type);

        return primKey;
    }

}

when I run the project I get the error
ERROR 2013-05-16 09:44:13,191 [[mediation_mod].testObjetFlow1.stage1.03] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message               : Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject() : Cannot marshal the XStream instance in action
---- Debugging information ----
-------------------------------
message             : Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject()
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       : Cannot marshal the XStream instance in action
------------------------------- (com.thoughtworks.xstream.converters.ConversionException). Message payload is of type: byte[]
Code                  : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. Cannot marshal the XStream instance in action
---- Debugging information ----
------------------------------- (com.thoughtworks.xstream.converters.ConversionException)
  com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker:44 (null)
2. Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject() : Cannot marshal the XStream instance in action
---- Debugging information ----
-------------------------------
message             : Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject()
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       : Cannot marshal the XStream instance in action
------------------------------- (com.thoughtworks.xstream.converters.ConversionException)
  com.thoughtworks.xstream.converters.reflection.SerializationMethodInvoker:140 (null)
3. Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject() : Cannot marshal the XStream instance in action
---- Debugging information ----
-------------------------------
message             : Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject()
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       : Cannot marshal the XStream instance in action
------------------------------- (com.thoughtworks.xstream.converters.ConversionException). Message payload is of type: byte[] (org.mule.api.transformer.TransformerMessagingException)
  org.mule.transformer.AbstractTransformer:139 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transformer/TransformerMessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
com.thoughtworks.xstream.converters.ConversionException: Cannot marshal the XStream instance in action
---- Debugging information ----
-------------------------------
    at com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker.marshal(SelfStreamingInstanceChecker.java:44)
    at com.thoughtworks.xstream.core.AbstractReferenceMarshaller.convert(AbstractReferenceMarshaller.java:69)
    at com.thoughtworks.xstream.core.TreeMarshaller.convertAnother(TreeMarshaller.java:58)
    + 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************

ERROR 2013-05-16 09:44:13,182 [[mediation_mod].testObjetFlow1.stage1.02] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message               : Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject() : Cannot marshal the XStream instance in action
---- Debugging information ----
-------------------------------
message             : Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject()
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       : Cannot marshal the XStream instance in action
------------------------------- (com.thoughtworks.xstream.converters.ConversionException). Message payload is of type: byte[]
Code                  : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. Cannot marshal the XStream instance in action
---- Debugging information ----
------------------------------- (com.thoughtworks.xstream.converters.ConversionException)
  com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker:44 (null)
2. Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject() : Cannot marshal the XStream instance in action
---- Debugging information ----
-------------------------------
message             : Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject()
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       : Cannot marshal the XStream instance in action
------------------------------- (com.thoughtworks.xstream.converters.ConversionException)
  com.thoughtworks.xstream.converters.reflection.SerializationMethodInvoker:140 (null)
3. Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject() : Cannot marshal the XStream instance in action
---- Debugging information ----
-------------------------------
message             : Could not call org.apache.cxf.binding.soap.SoapMessage.writeObject()
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       : Cannot marshal the XStream instance in action
------------------------------- (com.thoughtworks.xstream.converters.ConversionException). Message payload is of type: byte[] (org.mule.api.transformer.TransformerMessagingException)
  org.mule.transformer.AbstractTransformer:139 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transformer/TransformerMessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
com.thoughtworks.xstream.converters.ConversionException: Cannot marshal the XStream instance in action
---- Debugging information ----
-------------------------------
    at com.thoughtworks.xstream.converters.reflection.SelfStreamingInstanceChecker.marshal(SelfStreamingInstanceChecker.java:44)
    at com.thoughtworks.xstream.core.AbstractReferenceMarshaller.convert(AbstractReferenceMarshaller.java:69)
    at com.thoughtworks.xstream.core.TreeMarshaller.convertAnother(TreeMarshaller.java:58)
    + 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************

I dont know if my logic is wrong or if there is a simple way to get the job done ??
thak you for your help.

A: First, I would not create a custom-transformer for simply instantiating a class, I would just use an expression:
<expression-transformer
    expression="#[new douane.DouanePK(message.inboundProperties.id,message.inboundProperties.type)]" />

Second, the exception you're getting comes from the inability of mulexml:object-to-xml-transformer to transform a SoapMessage object to XML using XStream (which is kind of expected). It is the responsibility of cxf:jaxws-client to do this unmarshalling in the response phase of the flow.
So you need to the mulexml:object-to-xml-transformer and the file:outbound-endpoint elements in a response element above the cxf:jaxws-client so they are processed after CXF has unmarshalled the response to the right object.

A: xml to object error comes because of SOAP component, in your case, you may avoid it,, and just use and expression tranformer


text:
Q: React async and hooks the problem is that iam trying to use prop as initialstate for useState, which
comes asynchronously from store and after page refresh iam getting , that this prop is undefined, how can i load props before call, check my code below.
logic: prop in coming from store through redux for first time i redirect to this page everything works after page refresh iam getting error which i sent below.
p.s i hide imports and connect func from snippet for less code.

    const PropertyComponent = (props) => {
      const {
        offer,
        icons,
        activeOffer,
        onOfferCardHover,
        onOfferCardLeave,
        history,
        setBookmarkStatus,
      } = props;

      const onUserNameClick = () => history.push(`/favorites`);

      const [status, setStatus] = useState(offer.is_favorite);

      const bookmarkHandler = () => {
        setStatus(Number(!status));
        setBookmarkStatus(offer.id, Number(!status));
      };

      const bookmarkClass = cn(`property__bookmark-button button `, {
        'property__bookmark-button--active': status
      });

      return (

          {!offer && (

              <Loader type="ThreeDots" color="#4873FA" height={200} width={200} />

          )}
          {offer && (

                  {offer.images.map((image, index) => {
                    return (

                    );
                  })}

                  {offer.is_premium && (

                      Premium

                  )}

{offer.title}

                    <button
                      className={bookmarkClass}
                      type="button"
                      onClick={bookmarkHandler}
                    >
                      <svg
                        className="property__bookmark-icon"
                        width="31"
                        height="33"
                      >
                        <use xlinkHref="#icon-bookmark" />
                      </svg>
                      To bookmarks
                    </button>

                      <span style={{width: `${offer.rating * 20}%`}} />
                      Rating

                      {offer.rating}

                      {offer.type}

                      {offer.bedrooms} Bedrooms

                      Max {offer.max_adults} adults

                    €{offer.price}
                     night

What's inside

                      {offer.goods.map((feature, index) => {
                        return (

                            {feature}

                        );
                      })}

Meet the host

                      {offer.host.name}

                        A quiet cozy and picturesque that hides behind a a river by
                        the unique lightness of Amsterdam. The building is green and
                        from 18th century.

                        An independent House, strategically located between Rembrand
                        Square and National Opera, but where the bustle of the city
                        comes to rest in this alley flowery and colorful.

                    <ReviewList offerId={offer.id} />
                    <ReviewForm offerId={offer.id}/>

              <section className="property__map map" style={{padding: `0 15rem`}}>
                {<Map icons={icons} activeIconId={activeOffer} />}

          )}
          {offer && (
            <NearPlaces
              offerId={offer.id}
              onOfferCardHover={onOfferCardHover}
              onOfferCardLeave={onOfferCardLeave}
            />
          )}
          {offer && }

      );
    };

error_image
mainPage
here iam getting error after refesh

A: Problem may be the prop offer. You may try adding default is_favorite by controlling the is_favorite from the offer.
You can do such thing
useState((offer.is_favorite !== undefined ) ? offer.is_favorite:"default_is_favorite");


text:
Q: Numerically minimize a function question screenshot
I am very bad at maths in general, so I dont even know which topic this question falls into.
Got this from a mathemtatics exam, and I would like to know where can I get some example solutions related to this question. I personally can learn maths more by observing example solutions rather than the theories.
Thanks in advance for any guidance.


text:
Q: Show/hide button with BooleanToVisibilityConverter does not work In my application I want to show/hide a button according to the users authorization level.
If the user is a team leader the button should be shown. If the user is not a team leader it shouldn't be shown.
I tried to resolve this issue using a BooleanToVisibilityConverter which is defined in my resource dictionary:

<BooleanToVisibilityConverter x:Key="VisibilityConverter" />

Implementation of the converter:
<Button Grid.Row="1" Grid.Column="5"
Click="TeamLeader_Click" Visibility="{Binding IsTeamLeader, Converter={StaticResource
VisibilityConverter}}" Style="{StaticResource ButtonStyleMenu}" />

In my code behind class I'm using a dependency property to change the visibility of the button.
public static readonly DependencyProperty IsTeamLeaderProperty =
DependencyProperty.Register("IsTeamLeader", typeof(bool),
typeof(MainMenu), new FrameworkPropertyMetadata(false));

public bool IsTeamLeader
{
    get { return (bool)GetValue(IsTeamLeaderProperty); }
    set { SetValue(IsTeamLeaderProperty, value); }
}

In the "loaded event" of my user control I initialize my property with false so the button should be collapsed.
private void ViewPage_Loaded(object sender, RoutedEventArgs e)
{
   this.IsTeamLeader = false;
}

But this won't work. No matter which value the IsTeamLeader property has on startup the button is always visible.
So can you please help me and give me a hint where I did the mistake? Is there a problem with the BooleanToVisiblityConverter or is there something wrong with my dependency property implementation? Or what?
Thank you!

A: You must just set DataContext like this:
this.DataContext = this;

A: It appears (from reading the comments) that you have not set your datacontext. :-)
But to debug this issue in the future you should work your way back from the knowns in the debugger. Let me explain

*

*Put a breakpoint in the Converter. If it is not being called the binding has failed at the source; such as what you found. If it is working, (and the return value is appropriate) then go to #2.

*Make the dependancy property have a changed handler and put a breakpoint in there such as:
    public bool MyBoolProperty
    {
        get { return (bool)GetValue(MyBoolPropertyProperty); }
        set { SetValue(MyBoolPropertyProperty, value); }
    }

    /// <summary>
    /// Identifies the MyBoolProperty dependency property.
    /// </summary>
    public static readonly DependencyProperty MyBoolPropertyProperty =
        DependencyProperty.Register(
            "MyBoolProperty",
            typeof(bool),
            typeof(MyClass),
            new PropertyMetadata(false, OnMyBoolPropertyPropertyChanged));

    /// <summary>
    /// MyBoolPropertyProperty property changed handler.
    /// </summary>
    /// <param name="d">MyClass that changed its MyBoolProperty.</param>
    /// <param name="e">Event arguments.</param>
    private static void OnMyBoolPropertyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MyClass source = d as MyClass; // Breakpoint here...
        bool value = (bool)e.NewValue;
    }

If the event never gets fired...you have a type mismatch between the data coming into the dependancy and what you expect as the type.
The above example uses a value type and that one is hard to mismatch so that might not be the case...but sometimes you have data as interface at the source and the dependency property can't convert the interface to its target object which is what it expects.


text:
Q: Disable visual editor on one specific page I would like to remove the visual editor from one specific page because if I edit this one page in Visual mode, it breaks the code. I want to make sure the client doesn't have this option on the particular page. However, I don't want to remove the html editor.
This line of code removes the visual editor and the html editor:           remove_post_type_support('page', 'editor');
a closer look at remove_post_type_support:
http://codex.wordpress.org/Function_Reference/remove_post_type_support
But I want to only disable the visual editor.
Initial testing, in functions.php for this theme, I have:
function remove_editor_init() {

 if ( is_admin() ) {
    if (is_page(2548)) {

    remove_post_type_support('page', 'editor');
    }
 }
}
add_action('init', 'remove_editor_init');

However, the conditional statements is_admin() and is_page() don't seem to working together.
Any suggestions?

A: In your code, calling the action admin_init makes is_admin() unnecessary. And, if not mistaken, is_page() is meant to be used in the front-end...
But the solution is the following (based on this Answer):
add_filter( 'user_can_richedit', 'wpse_58501_page_can_richedit' );

function wpse_58501_page_can_richedit( $can )
{
    global $post;

    if ( 28 == $post->ID )
        return false;

    return $can;
}

A: This is how I've resolved this:
add_filter( 'admin_footer', 'removes_editor_visual_tab', 99 );

function removes_editor_visual_tab()
{
    $post_id = $_GET['post'];
    if($post_id == 1434){
    ?>
        <style type="text/css">
        a#content-tmce, a#content-tmce:hover {
            display:none;
        }
        </style>
        <script type="text/javascript">
        jQuery(document).ready(function() {
            document.getElementById("content-tmce").onclick = 'none';
        });
        </script>
    <?php
    }
}

You can select the page ID(s) that you'd like this to reflect on


text:
Q: Two FOR statements coupled into one Is is possible to put two for statements into one statement. Something like
A = [ 0   0   0   5
      0   2   0   0
      1   3   0   0
      0   0   4   0];
  a=size(A);
  b=size(A);
  ind=0;
  c=0;
  for ({i=1:a},{j=1:b})
  end

A: Your question is very broad, but one thing to consider is that in MATLAB you can often take advantage of linear indexing (instead of subscripting), without actually having to reshape the array.  For example,
>> A = [ 0   0   0   5
         0   2   0   0
         1   3   0   0
         0   0   4   0];
>> A(3,2)
ans =
     3
>> A(7) % A(3+(2-1)*size(A,1))
ans =
     3

You can often use this to your advantage in a for loop over all the elements:
for ii=1:numel(A),
   A(ii) = A(ii) + 1; % or something more useful
end

Is the same as:
for ii=1:size(A,2),
    for jj=1:size(A,1),
        A(jj,ii) = A(jj,ii) + 1;
    end
end

But to address your specific goal in this problem, as you stated in the comments ("I am storing the non zero elements in another matrix; with elements like the index number, value, row number and column number."), of making sparse matrix representation, it comes to this:
>> [i,j,s] = find(A);
>> [m,n] = size(A);
>> S = sparse(i,j,s,m,n)
S =
   (3,1)        1
   (2,2)        2
   (3,2)        3
   (4,3)        4
   (1,4)        5

But that's not really relevant to the broader question.

A: Actually you can combine multiple loops into one for, however it would require you to loop over a vector containing all elements rather than the individual elements.
Here is a way to do it:
iRange = 1:2;
jRange = 1:3;
[iL jL] = ndgrid(iRange,jRange);
ijRange = [iL(:) jL(:)]';
for ij = ijRange
    i = ij(1); j = ij(2);
end

Note that looping over the variables may be simpler, but perhaps this method has some advantages as well.

A: No
read this http://www.mathworks.com/help/matlab/matlab_prog/loop-control-statements.html
i also don't see any added value even if it was possible

A: No I don't think you can put two for loops in one line.
Depends on your operation, you may be able to reshape it and use one for loop. If you are doing something as simple as just printing out all elements,
B = reshape(A,a*b,1);
for i=1:a*b
    c = B(i);
    ...
end


text:
Q: SpringBoot SOAP web service with multiple wsdls I am working on a SpringBoot Soap service that will have two WSDLs .Can I get a sample service for reference that make use of two WSDLS?
I get conflicts while generating xsds like below
com.sun.istack.SAXParseException2: Property "Abc" is already defined. Use <jaxb:property> to resolve this conflict.
Also want to make sure there wont be a namespace issues.
A sample or tutorial will be helpful.


text:
Q: how to decode a qrcode using zxing through webcam i have a code to decode a qrcode that take a image file and decode it. am using zxing library. but how can i make this capture qrcode from webcam and decode it. what are the changes i need to do?? can any one plz explain this step by step.
here is the code:
public class QrCodeDecoder
{
    public String decode(File imageFile)
    {
         BufferedImage image;
         try
         {
             image = ImageIO.read(imageFile);
         }
         catch (IOException e1)
         {
         return "io outch";
         }

         // creating luminance source
         LuminanceSource lumSource = new BufferedImageLuminanceSource(image);
         BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource));

         // barcode decoding
         QRCodeReader reader = new QRCodeReader();
         Result result = null;
         try {
             result = reader.decode(bitmap);
         }
         catch (ReaderException e)
         {
         return "reader error";
         }

         return result.getText();

         }

}

A: You are pretty far away from a solution, I don't think anyone can explain it "step by step".  You will first need to find a library that is capable of grabbing an image from a webcam.  You might start with this library, though I'm sure there are others.
Once you can capture an image, start to figure out if it is in a format that the above code expects.  If you are lucky, it will be, if not you will have to convert between the two formats.


text:
Q: Await for a for loop to finish Hey guys I am having trouble understanting await. What I really need to do is have a for loop which searches between 10,000 values in an array show me which values contain certain letters.
Right now without Tasks this process works but lags the app around 4 seconds per request which is why I believe I need to do this using Tasks and Await.
The task doesnt need to return anything. All I really need it to tell it to wait until the Task has ended without causing me to lag. It lags when using the searchbar and typing in letters, every letter causes the app to lag 5 seconds. What I want is for the input for the searchbar to not lag at all and just wait for the Task to finish.
This is the function I am trying to work with.
         async Task searchLoop()
        {
            string word = GetDataValue(items[x], "Name:");
            searchWord = searchWord.ToLower();

            if (word.Contains(searchWord))
            {
                myButton[counter].Text = GetDataValue(items[x], "Name:");
                myButton[counter].StyleId = x.ToString();
                counter++;
            }
        }

I tried a similar thing using Webclient and DownloadStringTaskAsync and it works exactly like I want it to, but I want to do it locally and not need a Webclient to feed me the information I need.


text:
Q: P entails Q implies P I have been looking at the following:
P entails Q implies P

And developed the proof as follows:
1. P
2. Q (Start of new subproof)
2.1 P (By 1)
3 Q implies P by INTRODUCTION OF IMPLICATION 2, 2.1

However, while it makes sense in terms of logic, I can't get it's general meaning.
To me, this is like saying: "I have P. Assuming I have Q, I still have P. So Q must imply P."
Or: "It's raining. Assuming I don't have an umbrella, it's still raining. So the fact I don't have an umbrella implies it's raining."
Is this proof simply stating that whatever assumption, the base assumptions will still hold, so it's trivially true, or...?

A: One nice way to make sense of what is happening: We have that $P$.
Assume we have $Q$, and reassert what we know we have: $P$.
Then we conclude that "If we have $Q$, then we have $P$, which we symbolize by $\;Q\rightarrow P$.
It so happens that in this case, we have $P$ even when we don't have $Q$, but that doesn't matter, since any implication with a true consequent (in this case $P$) holds.

Note also that from the premise $P$, we can derive $\lnot Q \lor P$ by $\lor$ introduction. And $\lnot Q\lor P \equiv Q\rightarrow P$, and indeed that equivalence can be derived if needed.

A: No, it's just that it's only valid to say that "$Q \Rightarrow P$" is  false if $Q$ is true and $P$ is false. Suppose your friend calls you up and tells you "If I manage to find a cab, I'll be there in five minutes". And he does show up in five minutes, but not in a cab. He hitched a ride. Would you say your friend lied? No, he just said that if he gets a cab, he'd reach in five minutes. He didn't say "otherwise I won't".

A: Use: $Q\implies P$ is equivalent to $\neg(Q \land \neg P)$

*

*Assume $P$

*Assume $Q\land \neg P$

*$\neg P$ (Elim $\land$, from 2)

*$P \land \neg P$ (Intro $\land$, 1, 3)

*$\neg (Q \land \neg P)$ (Conclusion, from 2, 4)

*$Q\implies P$ (Equivalence, from 5)

*$P\implies (Q\implies P)$ (Conclusion, from 1, 6)


text:
Q: Symfony convert native sql to query-builder I have an sql query:
SELECT users.username, count(follows.user_id)
FROM follows
INNER JOIN users ON follows.follow_user_id=users.id
GROUP BY follow_user_id;

In Sonata Admin, I want to filter my data with the number of followers.
The request works, but I can't use it in Sonata Admin.
I have the function:
public function callbackFilterFollow($queryBuilder, $alias, $field, $value)
{
    if (!$value) {
        return;
    }
    //$queryBuilder->select('username')->addGroupBy('o.id');
    return true;
}

I cannot figure out how to use the query-builder to convert my SQL query.

A: Have you mapped your query tables to entities?
If not take a look at the doctrine documentation for oneToMany relationships.
Once you have done that you can do something like this, keep in mind to use your object fields and not like below the table field names!!
$qb->select('u.username, COUNT(f.user_id) as cnt')
        ->from('UserBundle:Follows' , 'f') //this is your entity
        ->leftJoin('UserBundle:Users','u') //your users entity
        ->groupBy('f.follow_user_id')
        ->getQuery()
        ->getOneOrNullResult();

Your entities might need to have the full path. There are however two things that I don't get about what you are doing.

*

*You are counting for an inner join, if you just SELECT COUNT(*) with the inner join you don't need the group by.

*You are creating a sonata filter but I don't see where you use a parameter, I assume your real query looks the different and has the value as a parameter somewhere.
So you might need some changes, you can find more info on this other post.


text:
Q: Given a single view, Django can only handle one request for that view at a time? I was trying out some things with a new Django project (Django 1.8 and Python 2.7 32bit) and I encountered this situation.
This is my view.py:
from django.http import HttpResponse
import time
def memory(request):
    print("Memory Request Started")
    yay = '123456'
    i = 0
    hi = []
    while i < 1000:
        i += 1
        if len(yay) > 1000000:
            hi.append(yay + str(i))
            if i%100 == 0:
               print(len(hi))
        else:
            yay += yay
    time.sleep(5)
    return HttpResponse(len(yay))

def memory2(request):
    print("Memory Request 2 Started")
    yay = '123456'
    i = 0
    hi = []
    while i < 1000:
        i += 1
        if len(yay) > 1000000:
            hi.append(yay + str(i))
            if i%100 == 0:
               print(len(hi))
        else:
            yay += yay
    time.sleep(5)
    return HttpResponse(len(yay))

As you can see memory and memory2 are copies of each other.
My urls:
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()
from view import memory, memory2

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'testdjango.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^test/', memory),
    url(r'^test2/', memory2),
)

Using this view and urls, I used python manage.py runserver. So I then used my browser and accessed localhost:8000/test/ and localhost:8000/test2/ at the same time. This crashed Django with a MemoryError (which was what I was trying to do).
However, when I used my browser and opened 2 pages of localhost:8000/test/, the requests ran sequentially and didn't crash Django. I tried Apache+mod_wsgi as well and encountered the same behavior. Is this expected Django behavior and if so why?


text:
Q: Python saving an eval function Say I have a function fun(f, x, y) where x and y are numbers and f is a string specifying a function such as "1 / x ** 2 + y".
I wish to use this function f a lot, say a few million times, and the values of x and y change between each use.
Therefore calling eval(f) takes a significant amount of time as opposed to just calculating the value of the function each time. (About 50x, in my measured case.)
Is there any way to save this function f so that I would only have to call eval once?
PS. Please do not discuss the (un)safety of using eval here, I am aware of it, but this code isn't going anywhere where a 3rd party will run it, nor is it relevant to my question.

A: You could eval the lambda, so you just evaluate it once, and after that it's a function that you can use:
s = "1 / x ** 2 + y"

s = "lambda x,y: "+s
f = eval(s)
x = 2
y = 3
print(f(x,y))

I get 3.25, but I can change x and y as many times I need without evaluating the expression again.

A: If Jean_Francois' solution still isn't fast enough, you can take a look at numba. f_numba = jit(f), and then probably also @jit the function that calls f_numba so that f_numba is inlined into the caller. Depends on your application.


text:
Q: Horizontal character spacing using \resizebox I have some LaTeX code that uses the \resizebox command to make some hipster text, but the compiled letters are not completely flush to each side. There is a slight space on each side of the line as the font size changes, as shown in the screenshot.
I have tried to adjust this using the titlesec package but I'm a bit lost, as to how I would change this.
Has anyone got any ideas?
Here's my code too
Edit: Current Code
\documentclass[a4paper]{article}
\usepackage{graphicx,showframe}

\setlength{\parindent}{0mm}
\setlength{\parskip}{1mm}

\begin{document}
\resizebox{1\hsize}{!}{LINE ONE OF TEXT}

\resizebox{1\hsize}{!}{LINE 2 IS A BIT SMALLER}

\resizebox{1\hsize}{!}{LINE THREE IS REALLY SMALL}

\resizebox{1\hsize}{!}{THIS LINE IS IN ITALLICS}

\resizebox{1\hsize}{!}{A LINE!}

\resizebox{1\hsize}{!}{I CAN JUST KEEP GOING}

\resizebox{1\hsize}{!}{AND GOING AND}

\resizebox{1\hsize}{!}{GOING}
\end{document}

A: You could use some trimming from adjustbox to compensate for the reduced bounding box of certain letters - a font-specific attribute:

\documentclass{article}
\usepackage[export]{adjustbox}
\usepackage{showframe}

\setlength{\parindent}{0mm}
\setlength{\parskip}{1mm}

\begin{document}

\resizebox{\linewidth}{!}{LINE ONE OF TEXT}%

\adjustbox{width=\linewidth,trim=0.1ex 0pt}{LINE ONE OF TEXT}%

\resizebox{\linewidth}{!}{A LINE!}%

\adjustbox{width=\linewidth,trim=0.08ex 0pt 0.2ex 0pt}{A LINE!}%

\end{document}

The visual alignment can be made as perfect as you want it, although the selection from within the PDF viewer may also be influenced by the trimming.
For a visual discussion on bounding boxes, see Standalone producing cropped / truncated formulae.


text:
Q: How to autofocus Android camera automatically? I want to autofocus Android camera as soon as camera holds still. Im looking for tutorials or samples how to do it or at least small sample that shows what classes I can use to hook on such events.

A: Looks like you should continuous autofocus as is discussed here.
There is a question here that you can reference.

A: Try to use Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO or Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE.
See below:
Camera.Parameters params = camera.getParameters();
if (params.getSupportedFocusModes().contains(
    Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
  params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(params);

It's important to test whether the phone is supporting your chosen mode before attempting to use it, otherwise setParameters() will throw a runtime exception.
(Edit code now working properly)

A: Following code works for me.
Setting autofocus (preview class):
Parameters params = camera.getParameters();
params.setFocusMode(Parameters.FOCUS_MODE_AUTO);
//some more settings
camera.setParameters(params);

Call camera for shot a picture in case that autofocus is ready (activity class):
public void butClick(View v){
    preview.camera.autoFocus(new AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            if(success){
                camera.takePicture(shutterCallback, rawCallback, jpegCallback);
            }
        }
    });
}

Get picture (activity class):
PictureCallback jpegCallback = new PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {
        //do something
    }
};

A: For me this worked a treat:
//set camera to continually auto-focus
Camera.Parameters params = c.getParameters();
//*EDIT*//params.setFocusMode("continuous-picture");
//It is better to use defined constraints as opposed to String, thanks to AbdelHady
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
c.setParameters(params);

A: This works perfectly for preview callback:
Camera.Parameters parameters = camera.getParameters();
if (parameters.getSupportedFocusModes().contains(
        Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
}
camera.setParameters(parameters);

A: you can try code:
ShutterCallback _pfnShutterCallback = new ShutterCallback() {

        @Override
        public void onShutter() {
            // TODO Auto-generated method stub

        }

    };

    PictureCallback _pfnRawPictureCallback = new PictureCallback() {

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            // TODO Auto-generated method stub

        }
    };

    private AutoFocusCallback _pfnAutoFocusCallback = new AutoFocusCallback() {

        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            // TODO Auto-generated method stub
            camera.autoFocus(null);
            camera.takePicture(_pfnShutterCallback, _pfnRawPictureCallback,
                    mPicture);

        }
    };
    private PictureCallback mPicture = new PictureCallback() {

        public void onPictureTaken(byte[] data, Camera camera) {
            new SavePhotoTask().execute(data);
            camera.startPreview();

        }
    };
class SavePhotoTask extends AsyncTask<byte[], String, String> {
// Process save file image
}

call capture : mCamera.autoFocus(autoFocusCallback);
You can refer at:
http://android-er.blogspot.com/2011/01/start-camera-auto-focusing-autofocus.html


text:
Q: Angular ngAnimate module will break my open layers map directive I've made a directive that display an Open Layers map (below is not my production code, but a simplified version used to create a plunkr. Don't pay attention to the hardcoded DOM element ID).
EDIT : the hardcoded ID was indeed the issue, see comments below...
app.directive('tchOlMapCopy', function () {

    return {

        restrict: 'E',

        replace: true,
        template: '

',

        link: function postLink(scope, element, attrs) {
            var map = new OpenLayers.Map("tchMap");
            map.addLayer(new OpenLayers.Layer.OSM());
            map.setCenter(new OpenLayers.LonLat(3, 47).transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), 5);
        }
    }

I had that issue that, when I change route in my app an go from one screen including that directive to another, the map won't display on the second screen. The link function in the directive isn't even called.
I've narrowed down the issue to be related to ngAnimate module. If I remove dependency to this module, the map will display correctly on second route change.
I've made a Plunkr to illustrate this issue. Comment or uncomment the ngAnimate module in app.js file to see the issue.
Does anybody have an idea why ngAnimate breaks my directive call ?

A: Having multiple instance of this directive which has an hardcoded id seems a very bad idea. Should be a unique identifier : http://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#id


text:
Q: Bitly Gem/ Oauth Gem issues when starting app in production I'm trying to deploy my rails application to production however I've hit a bit of a problem. I'm using Nginx and Unicorn and the application has been running fine in production for a while now but a hardware error with my hosting provider earlier today has brought the site down and while trying to revive it the following errors appeared in the unicorn error log:
E, [2012-11-23T21:30:03.291386 #4370] ERROR -- : reaped #<Process::Status: pid 7795 exit 1> worker=0
I, [2012-11-23T21:30:03.291819 #4370]  INFO -- : worker=0 spawning...
I, [2012-11-23T21:30:03.310884 #7801]  INFO -- : worker=0 spawned pid=7801
I, [2012-11-23T21:30:03.311488 #7801]  INFO -- : Refreshing Gem list
/home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/faraday-0.7.6/lib/faraday/connection.rb:1:in `require': no such file to load -- addressable/uri (LoadError)
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/faraday-0.7.6/lib/faraday/connection.rb:1:in `<top (required)>'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/faraday-0.7.6/lib/faraday.rb:68:in `require'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/faraday-0.7.6/lib/faraday.rb:68:in `<top (required)>'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/oauth2-0.5.2/lib/oauth2/client.rb:1:in `require'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/oauth2-0.5.2/lib/oauth2/client.rb:1:in `<top (required)>'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/oauth2-0.5.2/lib/oauth2.rb:2:in `require'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/oauth2-0.5.2/lib/oauth2.rb:2:in `<top (required)>'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/bitly-0.7.0/lib/bitly/v3.rb:5:in `require'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/bitly-0.7.0/lib/bitly/v3.rb:5:in `<top (required)>'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/bitly-0.7.0/lib/bitly.rb:9:in `require'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/bitly-0.7.0/lib/bitly.rb:9:in `<top (required)>'
from /home/deployer/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.5/lib/bundler/runtime.rb:68:in `require'
from /home/deployer/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.5/lib/bundler/runtime.rb:68:in `block (2 levels) in require'
from /home/deployer/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.5/lib/bundler/runtime.rb:66:in `each'
from /home/deployer/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.5/lib/bundler/runtime.rb:66:in `block in require'
from /home/deployer/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.5/lib/bundler/runtime.rb:55:in `each'
from /home/deployer/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.5/lib/bundler/runtime.rb:55:in `require'
from /home/deployer/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.5/lib/bundler.rb:119:in `require'
from /home/deployer/apps/stealthygecko/releases/20121123212740/config/application.rb:7:in `<top (required)>'
from /home/deployer/apps/stealthygecko/releases/20121123212740/config/environment.rb:2:in `require'
from /home/deployer/apps/stealthygecko/releases/20121123212740/config/environment.rb:2:in `<top (required)>'
from config.ru:4:in `require'
from config.ru:4:in `block in <main>'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/builder.rb:51:in `instance_eval'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/rack-1.4.1/lib/rack/builder.rb:51:in `initialize'
from config.ru:1:in `new'
from config.ru:1:in `<main>'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/unicorn-4.2.1/lib/unicorn.rb:44:in `eval'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/unicorn-4.2.1/lib/unicorn.rb:44:in `block in builder'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/unicorn-4.2.1/lib/unicorn/http_server.rb:694:in `call'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/unicorn-4.2.1/lib/unicorn/http_server.rb:694:in `build_app!'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/unicorn-4.2.1/lib/unicorn/http_server.rb:567:in `init_worker_process'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/unicorn-4.2.1/lib/unicorn/http_server.rb:587:in `worker_loop'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/unicorn-4.2.1/lib/unicorn/http_server.rb:487:in `spawn_missing_workers'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/unicorn-4.2.1/lib/unicorn/http_server.rb:498:in `maintain_worker_count'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/unicorn-4.2.1/lib/unicorn/http_server.rb:272:in `join'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/gems/unicorn-4.2.1/bin/unicorn:121:in `<top (required)>'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/bin/unicorn:23:in `load'
from /home/deployer/apps/stealthygecko/shared/bundle/ruby/1.9.1/bin/unicorn:23:in `<main>'

Here's my Gemfile:
gem 'rake'
gem 'rails', '3.2.6'
gem 'mysql2'
gem 'bcrypt-ruby', '~> 3.0.0'
gem 'gravtastic'
gem "friendly_id"
gem "videawesome"
gem "will_paginate", "~>3.0.3"
gem "bitly"
gem "sanitize"
gem "newrelic_rpm"
gem 'capistrano'
gem 'rvm-capistrano'
gem "unicorn", "~> 4.2.1"
gem "wysihtml5-rails", "~> 0.0.2"
gem 'airbrake'

group :assets do
  gem 'less-rails'
  gem 'jquery-rails'
  gem 'therubyracer'
  gem 'uglifier'
  gem 'twitter-bootstrap-rails'
end

From what I can see its the Bitly gem requiring oauth thats the problem, however I'm not sure how to fix this. if anyone can help I'd really appreciate it.
Thanks in advance.

A: Looks like the faraday gem is trying to require addressable/uri but that's not in your Gemfile.

A: after several hours or deploying and supposedly getting nowhere, it turned out that all I had to do was stop Unicorn completely and start it up again rather than just restart it. its now finding all the necessary dependencies.
The thing that confused me in all this was that I read that Faradays dependency on Addressable had been removed back in August, so naturally I was stumped as to why it was still being referenced.
Thanks for your help Ipwnstuff it was much appreciated.


text:
Q: Lyx - Add appendix after bibliography How can I insert Appendix after Bibliography ?
If I put the cursor after the last character of the bibliography, then the last line of the bibliography is inside the appendix. If I click return after the last character of the bibliography, then insert the appendix, a new key appears in the appendix, and if I remove it, the appendix disappears.
Thanks,
Edit:
I click on alt+Enter after the bibliography to close it. Then I insert a clear page, insert a new chapter, and start the appendix.
Everything looks OK in Lyx, but in the PDF, I have the title "Bibliography" on top of the pages of the Appendix.
My document class is "book(more font sizes)".
Edit 2: I am using the following preamble (if it has anything to see with the problem):
\usepackage{babel}
\addto\captionsfrench{%
  \renewcommand\tablename{Tableau}
}

\usepackage{color}
\definecolor{hellgelb}{rgb}{1,1,0.85}
\definecolor{colKeys}{rgb}{0,0,1}
\definecolor{colIdentifier}{rgb}{0,0,0}
\definecolor{colComments}{rgb}{1,0,0}
\definecolor{colString}{rgb}{0,0.5,0}
\lstset{%
     language=Matlab,%
     float=hbp,%
     basicstyle=\footnotesize\ttfamily,%
     identifierstyle=\color{colIdentifier},%
     keywordstyle=\color{colKeys},%
     stringstyle=\color{colString},%
     commentstyle=\itshape\color{colComments},%
     columns=fixed,
     tabsize=4,%
     frame=single,%
     framerule=1pt,
     extendedchars=true,%
     showspaces=false,%
     showstringspaces=false,%
     numbers=left,%
     numberstyle=\tiny\ttfamily,%
     numbersep=1em,%
     breaklines=true,%
     breakindent=10pt,%
     backgroundcolor=\color{hellgelb},%
     breakautoindent=true,%
     captionpos=t,%
     xleftmargin=1em,%
     xrightmargin=\fboxsep%
}

A: If you create bibliography by selecting Bibliography from the drop-down menu, and writing the bibliography manually, you can 'close' this by hitting Alt + Enter when the cursor is at the end of the last entry. Then you can type stuff after the bibliography, and start the appendices.

A: On OS X, rather than alt-enter use ctrl-enter. If you have Lyx's "source pane" open, you can see this finally moves the cursor beyond the end of the'bibliography section. (Alt-enter just adds extra lines inside of the final bib'item, which isn't helpful.)
This will make you free to "start appendix here" (lyx document menu) and create the chapters of the appendix. Then you can move on to grappling with the format of their headings and table of contents entries!

A: After your bibliography insert a blank line as Chapter and write your chapter title. Then use de menu entry Document->Start appendix and that will make the trick. In your TOC the chapters in the appendix box will appear after the bibliography and using letters instead of numbers.


text:
Q: X-UA-Compatibility with HTTP Header actually i'm having a problem with a website in IE which is not on intranet and the "always show pages in compatibility mode is not activated" but it still opens in quirks mode sometimes, despite adding
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>

I have red that i can send this compatibility order in an HTTP Header or in htaccess
My problem is that i have searched on how to send an HTTP header and actually found no clue, and btw i'm a php developer just in case this information was necessary.
I would really appreciate if someone could provide me what's needed to add (for both, or for one at least) and how/where to add it, i have been looking for the whole week and it's quiet urgent to find the fix so soon !
Is this way to send it as an HTTP header as a first line in the page is right ?
<?php
header('X-UA-Compatible: IE=edge');
?>

(I have just found it)
I really appreciate any help can be provided and i'm thankful in advance.

A: As you correctly noted the header can be set in php:
<?php header('X-UA-Compatible: IE=edge,chrome=1');

It can also be set in .htaccess like so:
<IfModule mod_headers.c>
  Header set X-UA-Compatible "IE=Edge,chrome=1"
  # mod_headers can't match by content-type, but we don't want to send this header on *everything*...
  <FilesMatch "\.(appcache|crx|css|eot|gif|htc|ico|jpe?g|js|m4a|m4v|manifest|mp4|oex|oga|ogg|ogv|otf|pdf|png|safariextz|svg|svgz|ttf|vcf|webm|webp|woff|xml|xpi)$">
    Header unset X-UA-Compatible
  </FilesMatch>
</IfModule>

(copied from the HTML5 Boilerplate template)
However, if you are setting these headers and finding that IE still defaults to quirks-mode then I'd be inclined to suggest that there is something else at work.  Have you ensured that your pages include a valid doctype? Notably one that isn't of the HTML 4.01 flavour.


text:
Q: Add different items in listview for each tab among 3 tabs in android I have created 3 tabs in the activity. Now I want to add a ListView for every tab. But the contents of the tabs should be different. How to achieve this?

A: you can have three different layout files and three different kind of adapters, and based on the tab selected, inflate the relevant layout file and set values in the particular adapter and set adapter to listview.
OR
you can use fragments.

A: You can have just one ListFragment, and put a switch case in it and for each tab, set different Adapter.
But for better performance it is better to have 3 different Fragments with same xml. But different Adapters.
Hope it's helpful and for more details please feel free to ask :)

A: Thank you everyone for yur answers. problem has been solved. I set the content of 3 different xml with its respective java class for each tab :)


text:
Q: Having Problem with React-native-gesture-handler(cannot find symbol String overflow = ((ReactViewGroup) view).getOverflow();) I am having an issue with react-native-gesture-handler. Whenever I link my react-native-gesture-handler to my project it stops working and shows this error. But after unlinking react-native-gesture-handler from my project the application work fine. But as I need to navigate from several screens, I need gesture handler.
First I thought it was the problem of the react-native version as I was using react-native version 0.57.0 but it's not working on 0.58.0 and 0.55.4 either.
package com.swmansion.gesturehandler.react;

import android.os.Build;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.react.uimanager.PointerEvents;
import com.facebook.react.uimanager.ReactPointerEventsView;
import com.facebook.react.views.view.ReactViewGroup;
import com.swmansion.gesturehandler.PointerEventsConfig;
import com.swmansion.gesturehandler.ViewConfigurationHelper;

public class RNViewConfigurationHelper implements ViewConfigurationHelper {

  @Override
  public PointerEventsConfig getPointerEventsConfigForView(View view) {
    PointerEvents pointerEvents;
    pointerEvents = view instanceof ReactPointerEventsView ?
            ((ReactPointerEventsView) view).getPointerEvents() :
            PointerEvents.AUTO;

    // Views that are disabled should never be the target of pointer events. However, their children
    // can be because some views (SwipeRefreshLayout) use enabled but still have children that can
    // be valid targets.
    if (!view.isEnabled()) {
      if (pointerEvents == PointerEvents.AUTO) {
        return PointerEventsConfig.BOX_NONE;
      } else if (pointerEvents == PointerEvents.BOX_ONLY) {
        return PointerEventsConfig.NONE;
      }
    }

    switch (pointerEvents) {
      case BOX_ONLY: return PointerEventsConfig.BOX_ONLY;
      case BOX_NONE: return PointerEventsConfig.BOX_NONE;
      case NONE: return PointerEventsConfig.NONE;
    }

    return PointerEventsConfig.AUTO;
  }

  @Override
  public View getChildInDrawingOrderAtIndex(ViewGroup parent, int index) {
    if (parent instanceof ReactViewGroup) {
      return parent.getChildAt(((ReactViewGroup) parent).getZIndexMappedChildIndex(index));
    }
    return parent.getChildAt(index);
  }

  @Override
  public boolean isViewClippingChildren(ViewGroup view) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && !view.getClipChildren()) {
        if (view instanceof ReactViewGroup) {
            String overflow = ((ReactViewGroup) view).getOverflow();
            return "hidden".equals(overflow);
        }
        return false;
      }
    return true;
  }
}

A: You can try manual linking.
Also check this issue out :
https://github.com/kmagiera/react-native-gesture-handler/issues/205

A: If you get the problem in Android, but not iOS, it could be that you need to add a polyfill for symbols.  I can't remember where I found this, but I have used it in my own projects and it works.  Just stick it in your index.js:
if (Platform.OS === 'android') {
  if (typeof Symbol === 'undefined') {
    if (Array.prototype['@@iterator'] === undefined) {
      Array.prototype['@@iterator'] = function() {
        let i = 0;
        return {
          next: () => ({
            done: i >= this.length,
            value: this[i++]
          })
        };
      };
    }
  }
}


text:
Q: Getting Deadlocks from simple atomic concurrent updates stmts. Any Ideas? Here's the message:
Transaction (Process ID 80) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

Here's the query:
update EDescriptionsCategories set CategoryId = Ids.CategoryId, AccessedDate = getdate()
from EDescriptionsCategories
join ( select * from (values (512528, 20870),(29596457, 20870)) as Ids(Id,CategoryId) ) as Ids on
Ids.Id = EDescriptionsCategories.Id

Here's the table definition:
CREATE TABLE [dbo].[EDescriptionsCategories](
    [CategoryId] [int] NOT NULL,
    [AccessedDate] [datetime] NOT NULL,
    [Id] [int] NOT NULL,
 CONSTRAINT [PK_EDescriptionsCategories] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)

Couple of those queries are running in parallel. Why the deadlock from single atomic update?
No other queries are running against this table. No indexes except primary key. However it is a big table 21 million rows.


text:
Q: Android retrofit add header and also a HttpLoggingInterceptor I'm currently studying retrofit in android:
and this is my current code:
 HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

       OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {

            Request newRequest  = chain.request().newBuilder()
                    .addHeader("Authorization", "Bearer " + Globals.BEARER_TOKEN)
                    .build();
            return chain.proceed(newRequest);
        }
    }).build();

How can i add my HttpLoggingInterceptor to the client and also at the same time add my header to the client?

A: You can add both interceptors calling the method addInterceptor twice:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(new Interceptor() {
        @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request newRequest = chain.request().newBuilder()
                    .addHeader("Authorization", "Bearer " + Globals.BEARER_TOKEN)
                    .build();
                return chain.proceed(newRequest);
            }
        })
   .addInterceptor(interceptor).build();

A: To add an interceptor to Retrofit you include it while building OkHttpClient,
OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(new HttpLoggingInterceptor())

Then you build Retrofit using this client,
Retrofit.Builder builder = new Retrofit.Builder()
                .client(client);

Retrofit retrofit = builder.build();


text:
Q: Obtaining starting View from Handler of the command I have a certain View.
In this view there is a TreeViewer.
When I right-click one element of the tree, I open the contextual menu that trigger the command "rename".
In the HANDLER of this command, how can I obtain the ID of the view of the selected element?
Is it possible to get it?
Thanks very much to everyone will answer!

A: See HandlerUtil. In this example, since you right-click on an element in a view, it should become active and you can use
HandlerUtil.getActivePartId(e);


text:
Q: Can't display list of agm-markers using ngFor in Angular 6 I am using agm-marker to display list of markers. The list of markers is not displayed on the map using ngFor. I know I am supposed to use the class Number for latitude and longitude, but I still can't see the markers.
googlemaps.component.html

    <agm-map [latitude]="lat" [longitude]="lng" style="height: 80vh"  *ngIf="mapReady">
        <agm-marker  *ngFor="let locationItem of allLocations" [latitude]="locationItem.latitude" [longitude]="locationItem.longitude">
        </agm-marker>
    </agm-map>

googlemaps.component.ts
export class GoogleMapsComponent implements OnInit {

  lat = 30.2672;
  lng = -97.7431;
  allLocations: LocationData[] = new Array();
  mapReady = false;

  constructor(private googleMapsService: GoogleMapsService) {
  }

  ngOnInit() {
    this.allLocations = this.googleMapsService.getAllLocations();
    this.mapReady = true;
    console.log(this.allLocations);
     }
}

googlemaps.service.ts
import {Injectable} from '@angular/core';
import {LocationData} from './location';

const allLocationsData = [{

  locationId: '1',
  locationTitle: 'IcenHaur',
  locationText: 'First Date.',
  hasImages: false,
  latitude: '30.259610',
  longitude: '-97.738238'
},
  {locationId: '2',
    locationTitle: 'DogWood',
    locationText: 'Second Date.',
    hasImages: false,
    longitude: ' 30.401192',
    latitude: '-97.722935'
  },
  {locationId: '3',
    locationTitle: 'KungFoo',
    locationText: '3rd Date.',
    hasImages: false,
    longitude: '30.259656',
    latitude: '-97.738217'
  },
  {locationId: '4',
    locationTitle: 'Shack512',
    locationText: 'Scenic Drive',
    hasImages: false,
    longitude: '30.462621',
    latitude: '-97.913168'
  }]

@Injectable({
  providedIn: 'root'
})

export class GoogleMapsService {

  getAllLocations(): LocationData[] {

    let allLocations = new Array();
    allLocationsData.forEach(location => {
        let locationObject = new LocationData();
      locationObject.hasImages = location.hasImages;
      locationObject.locationId = location.locationId;
      locationObject.locationTitle = location.locationTitle;
      locationObject.longitude =  Number(location.longitude);
      locationObject.latitude =  Number(location.latitude);
      locationObject.locationText = location.locationText;
      locationObject.hasImages = location.hasImages;
      allLocations.push(locationObject);
    });
    return allLocations;
  }
}

locations.ts
export class LocationData {
  public locationId: string;
  public locationTitle: string;
  public locationText: string;
  public hasImages: boolean;
  public latitude: Number;
  public longitude: Number;
}

A: I think you'll need to cast these numbers explicitly to Number by using the Number constructor. TypeScript only provides assistance and hints on type casting, it won't expliciting convert it from a string.


text:
Q: C#: How do we try parse based on a condition? Am trying to try parse based on a condition between two enums, how do we do this?
bool _isEnum1 = true;

public enum _Enum1
{
value,
Text,
Image
}

public enum _Enum2
{
TextArea,
Button,
Label
}

var _enum = _isEnum1 ? Enum.TryParse("value", out _Enum1 _enum) : Enum.TryParse("TextArea", out _Enum2 _enum)

I want '_enum' to hold right enum type value. Is this possible? Any other alternative is also fine.

A: Well, you're trying to have the type being dynamically resolved at runtime. You either have to split your entire program flow
if(_isEnum1)
{
    Enum1 e = (Enum1)Enum.Parse(typeof(Enum1), "value");
    HandleEnum1(e);
}
else
{
    Enum2 e = (Enum2)Enum.Parse(typeof(Enum2), "value");
    HandleEnum2(e);
}

where HandleEnumX are strongly typed with EnumX, so that the compiler knows what's going on, or go completely crazy overboard and use dynamic
dynamic e;
if(_isEnum1)
{
    e = (Enum1)Enum.Parse(typeof(Enum1), s);
}
else
{
    e = (Enum2)Enum.Parse(typeof(Enum2), s);
}
// Now e is either Enum1 or Enum2, resolved at runtime.

However, this seems wildly overcomplicated and more of a thought experiment than real code you should be pushing to production. You should probably rethink your design of this part of the program. At the very least, you might want to wrap your enums in a class to allow a more flexible design.
As a side note - you're using TryParse but never testing the returned value, so I took the liberty of exchanging them to Parse.

A: Enum result;
if (this._isEnum1)
{
    result = (_Enum1)Enum.Parse(typeof(_Enum1), "value");

}
else
{
    result = (_Enum2)Enum.Parse(typeof(_Enum2), "TextArea");
}