multiple when statement in a Case statement

Question: My SP is as follows:
ALTER PROC ME_SP_GETORDERASSIGNMENT_DETAILS
@COMPANY_CODE  VARCHAR(5),
@TRANSID VARCHAR(10),
@FYEAR VARCHAR(5),
@SMODE VARCHAR(2),
@USERID VARCHAR(5),
@PLANT_CODE NUMERIC(5,0),
@TRANSNO VARCHAR(10),
@STATUS_CODE VARCHAR(10),
@FROM_DATE VARCHAR(15)=NULL,
@TO_DATE VARCHAR(15)=NULL
AS
--New SP created By Ashwini on 11-Nov-2014 for getting order assignment details
BEGIN

DECLARE @SAGENT_CODE VARCHAR(10)
SELECT @SAGENT_CODE = A.SAGENT_CODE FROM SD_SAGENT_C A
INNER JOIN GL_USER_C B ON A.PERSONNEL_ID = B.PERSONNEL_ID AND B.USER_ID = @USERID

SELECT CAST(@PLANT_CODE as Varchar) AS PLANT_CODE, @TRANSNO AS  TRANSACTIONNO,@TRANSID AS TRANSID,@USERID AS USERID,
CAST(0 AS BIT) AS PROCESS,
CAST(0 AS BIT) AS CANCEL,
isnull(F.CUSTOMER_NO,'') AS ASSIGN_COURIER,
isnull(F.NAME1,'') AS ASSIGN_COURIER_NAME,
isnull(F.CUSTOMER_CLASS,'') AS DELIVERY_MODE,
A.PAYMENT_TYPE,
A.PAYMENT_MODE,
A.ORDER_STATUS AS STATUS_CODE,
E.DESCRIPTION AS STATUS_DESC,
A.ORDER_NO, A.ORDER_DATE,
A.CUST_CODE ,
(ISNULL(C.CUST_FNAME,'') + '' + ISNULL(C.CUST_MNAME,'') +''+ISNULL(C.CUST_LNAME,'')) CUSTOMER_NAME,
''CUSTOMER_ADDRESS, B.ITEM_NO AS LINE_ITEM_NO,
B.MAT_CODE,D.DESCRIPTION AS MAT_DESC ,ISNULL(D.DRAWING_NUMBER,'') AS VENDOR_NO, B.QTY, C.CUST_PSTATE AS STATE, '' AS TALUKA,C.CUST_PCITY AS DISTRICT ,C.CUST_PPINCODE AS PINCODE,
CAST(1 AS BIT) AS MANULAUTO, '' AS ASSIGN_CUSTOMER1 ,
C.CUST_PPOSTOFFICE AS POST_OFF ,C.CUST_PPONAME AS PO_NAME, B.ITEM_SALETYPE , G.DESCRIPTION as PRIORITY, H.DESCRIPTION AS PAYMENT_DESC

FROM
 RT_ORDER_H A
INNER JOIN
 RT_ORDER_T B
ON
 A.ORDER_NO = B.ORDER_NO
INNER JOIN
 RT_CUSTADD_M C
ON A.CUST_CODE = C.CUST_CODE
INNER JOIN MM_MATERIAL_BASIC_M D
ON B.MAT_CODE=D.MAT_CODE
LEFT OUTER JOIN
 RT_ORDER_STATUS E
ON A.ORDER_STATUS = E.STATUS_CODE
LEFT JOIN SD_CUSTADD_M F ON A.DELIVERY_BY = F.CUSTOMER_NO
LEFT JOIN RT_ORDER_PRIORITY_C G ON A.ORDER_PRIORITY = G.PRIORITY_TYPE
INNER JOIN RT_PAYTYPE_C H ON A.PAYMENT_TYPE = H.PAYMENT_TYPE
INNER JOIN MM_MATERIAL_PARENT_GRP_D I ON B.MAT_CODE=I.MAT_CODE

WHERE  A.ORDER_STATUS=@STATUS_CODE and year(a.ORDER_DATE)>=2014
--END

AND A.PAYMENT_TYPE = CASE WHEN @STATUS_CODE= '00' then 'PT0001' else A.PAYMENT_TYPE end

AND ( F.SAGENT_CODE = ISNULL( @SAGENT_CODE, 'XX') OR C.CUST_PSTATE_CODE IN ( SELECT STATE_CODE FROM SD_SAGENT_STATE_C WHERE SAGENT_CODE =@SAGENT_CODE))
AND I.PARENT_DESC='Vendor Offers' AND I.ACTIVE=1
and
    CASE
         WHEN (isnull(@FROM_DATE,'')<>'' and ISNULL(@TO_DATE,'')='') THEN Convert(date,A.order_date) >=CONVERT(datetime,@FROM_DATE,105)
         WHEN isnull(@FROM_DATE,'')='' and ISNULL(@TO_DATE,'')<>'' THEN  Convert(date,A.order_date)<=CONVERT(datetime,@TO_DATE,105)
         WHEN isnull(@FROM_DATE,'')<>'' and ISNULL(@TO_DATE,'')<>'' THEN  Convert(date,A.order_date)<=CONVERT(datetime,@TO_DATE,105) and CONVERT(Date,A.ORDER_DATE)>=CONVERT(datetime,@FROM_DATE ,105))
    END
ORDER BY A.ORDER_PRIORITY DESC,C.CUST_PSTATE,D.DESCRIPTION
END

This SP gives an error 'Incorrect syntax near '>'.'
I have to do like if @FROM_DATE and @TO_DATE both blank then after statement  AND I.ACTIVE=1 no condition should add.If @FROM_DATE is not blank and @TO_DATE is blank then one condition should get add like this for all scenarios.
How to resolve this problem?
Comment: Check to evaluate the result outside CASE statement.

or Put the result set into a #table and do the filtration to the #table as separate If Else Conditions
Answer: The predicate involving CASE was not properly formed:
AND CASE
      WHEN ... THEN ...
      WHEN ... THEN ...
    END -- missing a condition here

To fix it, rework your CASE statement like this:
AND
CASE
     WHEN (isnull(@FROM_DATE,'')<>'' and ISNULL(@TO_DATE,'')='') and  Convert(date,A.order_date) >=CONVERT(datetime,@FROM_DATE,105) THEN 1
     WHEN isnull(@FROM_DATE,'')='' and ISNULL(@TO_DATE,'')<>'' and Convert(date,A.order_date)<=CONVERT(datetime,@TO_DATE,105) THEN 1
     WHEN isnull(@FROM_DATE,'')<>'' and ISNULL(@TO_DATE,'')<>'' and Convert(date,A.order_date)<=CONVERT(datetime,@TO_DATE,105) and CONVERT(Date,A.ORDER_DATE)>=CONVERT(datetime,@FROM_DATE ,105)) THEN 1
     ELSE 0
END = 1


Find items from a list starting with the letter a through m

Question: For example we have a list:
l = ["aqi", "cars", "dosage", "dummy", "maze", "quiz", "sample", "trips", "users", "zoo"]

Assuming the list to be sorted.
Will have 2 parameters startAt and endAt

can be both string or int

The function takes in the list and returns all the elements that start from a through m
Here's my implementation:
def get_items_between_indexes(
    items: List[str], startAt: Union[str, int], endAt: Union[str, int]
) -> List[str]:
    """
    Get items between two indexes (inclusive).

    Args:
        items (List[Union[str, int]]): The list of items to search.
        startAt (Union[str, int]): The item to start searching from.
        endAt (Union[str, int]): The item to end searching at.

    Returns:
        List[Union[str, int]]: The list of items between the two indexes (inclusive).

    Example:
        >>> items = [0, 46, 98, "1", "2", "798", "yuyuy", "nm"]
        >>> get_items_between_indexes(items, "2", "y")
        ["2", "798", "yuyuy"]
    """
    # if type(startAt) is int and type(endAt) is int:
    start_index = next(
        (i for i, item in enumerate(items) if str(item).startswith(startAt)), None
    )
    end_index = next(
        (i for i, item in enumerate(items) if str(item).startswith(endAt)), None
    )
    # else:
    #     start_index = next(
    #         (i for i, item in enumerate(items) if str(item).startswith(startAt)), None
    #     )
    #     end_index = next(
    #         (i for i, item in enumerate(items) if str(item).startswith(endAt)), None
    #     )

    if start_index is None or end_index is None:
        return []

    if start_index > end_index:
        start_index, end_index = end_index, start_index

    return items[start_index : end_index + 1]

Here's what I expect:
Example:
>>> items = [0, 2, 46, 64, 98, 181, 7898, "1", "2", "798", "nm", "yuyuy"]
>>> get_items_between_indexes(items, "2", "n")
["2", "798", "nm"]
>>> items = [0, 2, 46, 64, 98, 181, 657, 7898, "1", "2", "798", "nm"]
>>> get_items_between_indexes(items, 46, 1000)
[46, 64, 98, 181, 657]

Comment: `"n" < "nm"`, but in your example it seems as if you want to act as if `"n" == "nm"`.  How does this translate to the int values?  What if there are multiple values that all start with the same letter/digit?
Comment: Then the `start_index` will be the smallest, and the `end_index` will be the largest. We also follow the standard sorting chronology where letters and digits are sorted in a specific manner.
Comment: You may use `itertools.dropwhile()` to find the related start item
Comment: Can you share your implementation for the above use-case? And how would find the last item?
Comment: Can you have mixed parameters like `get_items_between_indexes(items, 100, "8")`?
Comment: Yeah, we can have that... but there may come unexpected edge cases with those. I have thought about implementing a regex expression that matches strings up to the first character, and we generate a pattern based upon the `startAt` & `endAt` arguments.
Answer: Implementation
Here's the solution to the above question...

We will use the arguments to form a pattern
Match and search the list strings only up to the first character

import re

def get_items_between_range(
    items: List[str], startAt: Union[str, int], endAt: Union[str, int]
) -> List[str]:
    if len(startAt) > 1:
        startAt = str(startAt).lower()[1]
    else:
        startAt = str(startAt).lower()

    if len(endAt) > 1:
        endAt = str(endAt).lower()[1]
    else:
        endAt = str(endAt).lower()

    pattern = f"^[{startAt}-{endAt}]"+"{1}"
    items = (item for i, item in enumerate(items) if re.search(pattern, item, re.IGNORECASE))
    return list(items)

Example Usage
l2 = ["aqi", "cars", "dosage", "dummy", "maze", "quiz", "sample", "trips", "users", "zoo"]
get_items_between_range(l2, "d", "u")
>> ['dosage', 'dummy', 'maze', 'quiz', 'sample', 'trips', 'users']


What is the lowest overall baseball draft pick that has played in a major league game?

Question: In an answer to this question, a pro coach "justified" his publicity stunt of picking Johnny Manziel (a football player) with the 837th overall pick by saying, "No 837th pick has ever played in a major league game.
There are thirty major league teams, and I've heard of 20th round (and higher) picks making it to the majors (although this is rare). That might be somewhere in the 600's for overall picks, 750th, if someone actually made it from the 30th round?
What is the lowest overall draft pick that actually made it to the majors?
Answer: According to this perfectgame.org article, the answer is either Clay Condrey (94th round in 1996) or Travis Phelps (89th round in 1996), depending on whether the player was signed when he was drafted.

But Piazza has nothing on Philadelphia Phillies reliever Clay Condrey. Condrey was signed in 1998 as a non-drafted free agent by the San Diego Padres (by current Boston Red Sox GM Theo Epstein, no less), but he had previously been drafted in the 94th round in 1996 out of Angelina (Texas) Junior College, though went unsigned at the time. It gives the journeyman reliever the distinction of being the lowest-round draft selection ever to reach the big leagues.
Travis Phelps, an 89th round pick in 1996, and Scott Seabol, an 88th-rounder that year, are the lowest-round selections in draft history to play in the big leagues among players who signed when they were drafted. But Condrey has the record for being the lowest-round pick to reach the big leagues.
Comment: One thing I will mention is that not every team is drafting in the 94th round.  You can withdraw at anytime.


Does ASP.NET transfer ALL session data from SQL server at the start of a request, or only as needed?

Question: I'm using ASP.NET, with session state stored out of process in SQL Server. When a page request begins, are the entire contents of a user's session retrieved from the DB, deserialized, and sent to the ASP.NET process in one fell swoop, or are individual objects transferred to the ASP.NET process only as needed?
Basically, I have a page that stores some large objects in session, and it's hard for my application to determine when the data can be disposed. If the data is only pulled out of the DB when it's used then there isn't an issue; if the entire session state is chunked to ASP.NET for each page request, I might have a performance issue.
Answer: It's all in one go.  The session object is recreated from the store at the beginning of the request. It lets ASP.NET work the same way no matter what the underlying store is.
You can find the gory details here.


How to set default value for route parameter based on configured value?

Question: I have a route with optional parameter that has some default value:
# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
    name: 'there'
  requirements:
    _permission: 'access content'

I'd like to make there value for {name} parameter configurable. Let's assume that this default value for {name} is available in simple config variable.
Comment: Have you tried adding a default value to the controller method  (sayHiAction)?
Comment: Remove the name form route and use it in controller. why are you trying to complicate things for yourself? :D
Comment: @IvanJaros because I want to go by the book, be consistent and maybe use parameter upcasting?
Comment: Either you haven't explained what you want correctly, or I didn't understood what you want or you don't understand what "I want to go by the book" means :D .. as I'm reading the answer from cilefen I think you might want to have a look at \Drupal\Core\Routing\RouteSubscriberBase
Comment: OK, so symfony allows you to use config parameter values in yaml file by referencing them with a % sign. For example: http://stackoverflow.com/a/18782406 I'm looking for similar behavior that will work for Drupal's simple config. BTW it would be awesome if we could use simple config variables in yaml files like we can with symfonys native config parameters. "By the book" I mean the best practice approach, like with symfonys service: you don't use default value in a service constructor but instead you inject the value in your service definition.
Comment: Besides I can't use hard coded value like suggested by @Eyal - this "default" value needs to be configurable.
Answer: You must implement a route alter. In the alter code, extract the setting and set the value on the route definition.
Comment: This looks promissing. I'll give it a shoot. I'd be happy to accept your answer, but can you update it with code example just for sake of stackexchange rules?
Comment: No. SE has their rules and I have mine. It is well-documented at the link.
Answer: Implement two routes one with an argument and the second without.
hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
  requirements:
    _permission: 'access content'
hello.sayHi.default:
  path: '/hello'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
  requirements:
    _permission: 'access content'

hello.config.yml
default_name: there

hello.services.yml
hello.config:
  factory: ['@config.factory', get]
  class: Drupal\Core\Config\Config
  arguments: ['hello.config']

Drupal\hello\Controller\SimpleCallback
protected $configuration;

public function __constructor(Config $configuration) {
  $this->configuration = $configuration;
}

public static function create(Container $container) {
  return new static($container->get('hello.config'));
}

public function sayHiAction($name = NULL) {
  $name = is_null($name) ? $this->configuration->get('default_name') : $name;
  return [
    '#type' => 'inline_template',
    '#template' => 'Hi {name}',
    '#context' => [
      'name' => $name
    ]
  ]
}

Answer: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-routes
Optional parameters
Parameters on routes can be omitted when a default value for the parameter is supplied. Imagine you have a form controller that allows people to report different issues (e.g. bug reports, feature requests and support requests), and if the type is omitted it should default to 'support request'. Supply the default value for the optional parameter in the "defaults" section:
issue.report_form:
  path: '/report/{issue_type}'
  defaults:
    _controller: '\Drupal\issue\Controller\IssueController::report'
    issue_type: 'support-request'
  requirements:
    _permission: 'report issue'


random string of paticular weight

Question: Are there any good classical algorithms which produce strings with length $n$ and have hamming weight $k$? What is the best complexity one can get?
Comment: See Knuth's Algorithm S from section 3.4.2 of "The Art of Computer Programming, Vol. 2: Seminumerical Algorithms".  You can find code here: http://stackoverflow.com/questions/311703/algorithm-for-sampling-without-replacement
Answer: Ross Millikan's suggestion is good, but if $k$ is not too large, the simplest and quickest thing you can do is:
<code>b ← 00000.....0
do k times:
  do:
    r ← random(n)  -- select random number between 1 and n
  until b[r] == 0
  b[r] ← 1
done
return b
</code>
That is, just locate a random unset bit of $b$, set it, and repeat this $k$ times.
This will work well and it should be practical unless $k$ and $n$ are both very large.  It costs next to nothing to try out, so you should try it to see if it is practical before you do anything more complicated. There is a lot to be said in favor of simple algorithms over complex ones. Depending on $n$ and $k$, you might finish running this one before you got a more complicated algorithm written and tested.
The running time here is $O(k)$ if $k\ll n$; the added time from retrying the choice in the inner loop is on the order of $\frac{k^2} n$.
If you want to list all the words of weight $k$, that is a different matter.  In general it will take a long time, because in general there are a lot of words.  (${n\choose n/2}$ is exponential in $n$.) I think you can enumerate all of them in time close to $O(k)$ per word using an obvious algorithm, but  you may want to consult the relevant section of Knuth volume 4.
Comment: Another (poorer) approach to generate a random string: generate the string with $k$ $1$s and $n-k$ $0$s, then perform a [random shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) of this list. And I was going to mention Knuth Volume 4... I think the relevant section is Volume 4, Section 220.127.116.11 ("Generating all combinations"), aka Fascicle 3A.
Comment: I kinda like SreevatsaR's answer! Thanks! also MJD, the strings im trying to generate as for example with n=50 and k=1..49, so basically it does get really huge when k=20 odd, when there are exponential number of strings with hamming weight 20 right? In that case does your algorithm still work in O(n) time? Or could i simply apply ShreevatsaR's algorithm and perform any shuffle?
Comment: There is no case in which ShreevatsaR's algorithm is superior to the one I suggested.  n=50 is very small, not very large.  I did not describe an algorithm for enumerating all the words with weight $k$; I described an algorithm for generating one of those words at random. There is obviously *no* algorithm for quickly enumerating all the strings with $n=50$ and $k=20$ because there are 47129212243960 of them. The best you can do is to enumerate them in a small amount of time *per item*. You asked for an algorithm to produce strings of that form quickly and that is what I gave you.
Answer: The easiest one (ignoring the word random in the title, which is not in the body) is to output $k\  1$'s followed by $n-k \ 0$'s.
If you want a random one, there are $n \choose k$ strings of this sort, so choose a random integer in the range $[0, {n \choose k}-1]$.  If you imagine them sorted in lexicographic order, the first ${n-1 \choose k}$ of them start with $0$, the rest start with $1$.  You can determine the whole string from the random.
Comment: if i was looking to enlist all possible combinations of strings with hamming weight $k$, would this work?
Comment: Yes.  That is the point of saying that is how many there are.  Then the random number picks a particular one.  I show how to start changing the number into a string, and leave getting the rest of the bits to you.  You do it the same way.
Comment: what is the time it takes for this algorithm to solve the problem?
Comment: I think it is dominated by calculating the binomial coefficients.  How many of them do you have to do?  The size gets smaller as you go along.
Comment: As it happens, I implemented this algorithm in Perl a couple of years back. It is useful if you want to generate the words as they are demanded, rather than all at once, since you need only to store the index of the last-generated word, and increment the index each time you generate a new word. Here is the link, in case OP reads Perl: https://github.com/mjdominus/perl-misc/blob/master/Iterator/Subsets/BySize.pm Calculating the binomial coefficients can easily be done in amortized constant time per coefficient.
Comment: Thanks all for the comments, MJD I shall definitely have a look into your script! i have commented on your answer as well

random string of paticular weight


How to render a DS fieldgroup programmatically in a node template?

Question: I am overriding a Display Suite view mode of a node using the template suggestion myLayout-node-myNode-full.tpl.php.
I am getting the $node->content using the node_build_content function. Then I have access and I am rendering all the node display fields using:
drupal_render($node->content['field_myField'])

But I cannot render fieldgroups using the drupal_render function, as it requires array parameter, but my fieldgroups are stdClass objects that can be accessed as:
$node->content['#groups']['group_myGroup']

Printing the $node variable, I do not get any other reference to fieldgroups, eg. $node->content['group_myGroup'] does not exist.
Any suggestions on how I could render fieldgroups in my template file in Drupal 7?
Answer: node_build_content is probably not suitable for your use case. However you should use node_view instead which calls node_build_content anyway but returns you the actual renderable array after it processes it and sends it through an alter as well.
For example:
function mytheme_preprocess_node(&$vars) {
  if (!empty($vars['node'])) {
    $node = $vars['node'];

    if ($node->type == 'my_content_type') {
      $vars['content'] = node_view($node); //optionally supply view_mode as a second argument
    }
  }
}

Now you can just drupal_render($content) from your node template.
Comment: This worked perfectly, now I have the $content variable with the actual renderable array which contains fieldgroup arrays too. Thank you.
Comment: UPDATE: Actually I already had the $content variable provided in my DS template file, without the need to use the node_view function.
Comment: I thought so, I was wondering why you were rendering the content manually. Thought you were doing something with DS arrays.


git: how to move some commits to new branch

Question: I have been working in straight line:
A---B---C---D---E---F (master:HEAD)

Now I want to move backward:
git checkout C

and move few last commits to a new branch:
Option 1:
          D---E---F (new:HEAD)
         /
A---B---C (master)

Option 2:
          F (new:HEAD)
         /
A---B---C (master)

How to rebase to Option 1 and how to Option 2?
Answer: To get from your first diagram (master = HEAD = F) to option 1:
git branch new        # Make a 'new' branch pointing at HEAD, which is F
git reset --hard C    # Move master back to point at C
git checkout new      # Make HEAD follow new, and get F in the working tree

And from option 1 to option 2 (picking up where the above left off),
git rebase -i master  # Start the process of re-jiggering this branch
# edit the commit list that opens up to only include F
# save and exit
# resolve potential conflicts from missing changes in D and E

To go directly from your starting point to option 2:
git checkout -b new C  # Start the 'new' branch at C
git cherry-pick F      # Include F on it
git checkout master    # Switch back to master
git reset --hard C     # Rewind master to the earlier commit

Comment: If you get an error "Updates were rejected because the tip of your current branch is behind its remote counterpart" when trying to push master, you need to use the --force option: `git push --force origin master`


how to make two shell script into one in bash

Question: f1.sh
dweb=$1
web=$2

wget \
      --recursive \
      --no-clobber \
      --page-requisites \
      --html-extension \
      --convert-links \
      --restrict-file-names=windows \
      --domain $dweb \
      --no-parent \
         $web

f2.sh
web=$1

wget \
      --recursive \
      --no-clobber \
      --page-requisites \
      --html-extension \
      --convert-links \
      --restrict-file-names=windows \
      --no-parent \
         $web

I combine them in a new mynewfunc.sh file but it doesn't seem to work. f1.sh takes two args f2.sh takes one arg. How do I combine them using mynewfunc.sh without getting any errors so I can use one or two args using one .sh file.
Comment: This is a repost of your earlier question: [how to combine two bash script function to a single sript](https://stackoverflow.com/questions/70092952/how-to-combine-two-bash-script-function-to-a-single-sript).
Comment: just call them from another script: `sh /f1.sh; sh /f2.sh`
Answer: I believe what you are looking for is $# (the amount of parameters of a bash script). When this equals 1, you launch your first script. Otherwise you launch your second one. More information can be found in this other StackOverflow post.


A simple jquery dropdown box when clicked

Question: I can't find the one I want anywhere, yet it's really simple.  All I want is a simple jQuery script that when I click on a link, it pops a small div out (over the top of the current page, not hiding a DIV and sliding it in).
If I've not explained it very well, best think to look at is the notifications popout on Facebook, that's basically what I want.
This is also a good example, except it doesn't seem to work properly when I download the code from here: http://www.awmcreative.com/blog/jquery/jquery-pop-menu/#more-713
Here's an image of what I mean:

Doesn't matter if it retracts by clicking again, or by moving mouse out of the area.
Cheers.
Comment: Wait, is this question a "how do I make it" question or "fix it for me" question? In the latter case, what's not working? In the former, you provided a tutorial.
Comment: It's a "I'm looking for a different one"
Answer: jQuery UI has this functionality built in.
Comment: how is that what the OP wants??
Comment: he asked for a popup, he got a popup
Comment: see link in question and new title


Reorder json in js

Question: I am building a tree, and the order I want is name, desc, then children.
So the json I got is in different order. How do you reorder it or is there a better way to write this code, taking consideration of multiple branches, and may be extra element can be add to the input?
So here is my code:
var arry = [{
        "name": "J",
        "target": "L",
        "desc": "2"
    },

    {
        "name": "L",
        "target": "A",
        "desc": "1"
    },
    {
        "name": "S",
        "target": "L",
        "desc": "3"
    }

];

function toJSON(data) {
    var root = data.find(function(x) {
        return !data.some(function(y) {
            return y.name === x.target
        });
}).target;
    console.log(root)

    var desc = data.find(function(x) {

        return !data.some(function(y) {

            return y.name === x.target

        });

    }).desc;

    var b = data.reduce(function(acc, x) {

        acc[x.target] = acc[x.target] || [];

        acc[x.target].push(x.name);

        return acc;

    }, {});
    var tree = buildTree(root, b);
    function buildTree(name, branches, desc) {
        var tree = {
            'name': name
        };
        if (branches[name]) {
            tree.children = branches[name].map(function(x) {
                return buildTree(x, branches, desc)
            });
            for (var child in branches[name]) {
                var x = arry.find(function(i) {
                    return (i.name === branches[name][child] && i.target === name)
                })
                tree.children[child].desc = x.desc
            }
        }
        return tree;
    }
    if (tree.name === root) {
        tree.desc = root
    }
    for (var i in tree) {
         console.log(i)
    }
    return tree;
} // JavaScript name code
var a = toJSON(arry)

console.log(JSON.stringify(a, null, 2))

The result I got is:
{
  "name": "A",
  "children": [
    {
      "name": "L",
      "children": [
        {
          "name": "J",
          "desc": "2"
        },
        {
          "name": "S",
          "desc": "3"
        }
      ],
      "desc": "1"
    }
  ],
  "desc": "A"
}

The result I want is:
 {
      "name": "A",
      "desc": "A",
      "children": [
        {
          "name": "L",
          "desc": "1",
          "children": [
            {
              "name": "J",
              "desc": "2"
            },
            {
              "name": "S",
              "desc": "3"
            }
          ]
       }
      ]
    }

Comment: Why does the order matter?
Comment: I am writing for a visualization in d3.js for power bi. I had it working when I only have name and children with no desc. I don't know why after adding desc in the json, its not working anymore. I have checked rest of the code, 100% correct. So my last guess is order matter??? So is there a way to reorder it or a better way to write this?
Answer: I agree with the question "Why does order matter"
But if you really want...
When creating object literals the keys/properties remain in the order in which they are/were defined (unless the keys are integers, then they will be in numerical order). On the line where you create your tree node you define an object but only put the name property on it. You then add children, then finally set the desc property.  If you instead define your object right away they will have that order and you can later mutate the values however you want.
const tree = {
  name,
  desc: undefined,
  children: undefined,
};

var arry = [
  {
    name: "J",
    target: "L",
    desc: "2"
  },

  {
    name: "L",
    target: "A",
    desc: "1"
  },
  {
    name: "S",
    target: "L",
    desc: "3"
  }
];

function toJSON(data) {
  var root = data.find(function(x) {
    return !data.some(function(y) {
      return y.name === x.target;
    });
  }).target;
  console.log(root);

  var desc = data.find(function(x) {
    return !data.some(function(y) {
      return y.name === x.target;
    });
  }).desc;

  var b = data.reduce(function(acc, x) {
    acc[x.target] = acc[x.target] || [];
    acc[x.target].push(x.name);
    return acc;
  }, {});

  var tree = buildTree(root, b);

  function buildTree(name, branches, desc) {
    // define your tree node shape here
    var tree = {
      name,
      desc: undefined,
      children: undefined
    };

    if (branches[name]) {
      tree.children = branches[name].map(function(x) {
        return buildTree(x, branches, desc);
      });
      for (var child in branches[name]) {
        var x = arry.find(function(i) {
          return i.name === branches[name][child] && i.target === name;
        });
        tree.children[child].desc = x.desc;
      }
    }
    return tree;
  }
  if (tree.name === root) {
    tree.desc = root;
  }
  for (var i in tree) {
    console.log(i);
  }
  return tree;
} // JavaScript name code
var a = toJSON(arry);

console.log(JSON.stringify(a, null, 2));

Reorder json in js


Find single backslashes followed by alphabet

Question: I need to a regres that find all single backslashes followed by an alphabet.
So I want to find backslashes that exist in patterns like these:
\a
\f
\test

and not in these patterns:
\\a
\"

Thanks
Comment: Okay. Where are you stuck? A very brief look at any regex documentation (like [MDN's](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions) or any of dozens of others) should show exactly how to do this.
Comment: It is nontrivial to match `\a` in `\a` but not in `\\a`.
Answer: Updated:
As @Amadan points out in the comments below, JavaScript does not implement lookbehind, which basically breaks my original answer.
There is an approach suggested in this stackoverflow post that may be a reasonable path to take for this problem.
Basically the poster suggests reversing the string and using lookahead to match. If we were to do that, then we would want to match a string of alphabetic characters followed by a single backslash, but not followed by multiple backslashes. The regex for that would look like this:
/[a-zA-Z]+\\(?![\\]+)/g
[a-zA-Z]+ - match one or more alphabetic characters
\\        - followed by a single backslash
(?![\\]+) - not followed by one or more backslashes
g         - match it globally (more than one occurrence)

The downside of this approach (aside from having to reverse your string) is that you can't match only the backslash, but will have to also match the alphabetic characters that come before it (since JS doesn't have lookbehind).
Original Answer (using lookbehind):
/(?<!\\)\\[a-zA-Z]+/g (using negative lookbehind) will match a single backslash followed by one or more letters of the alphabet, regardless of case. This regular expression breaks down as follows:
(?<!\\)\\   - use negative lookbehind to match a \ that is not preceded by a \
[a-zA-Z]+   - match one or more letters of the alphabet, regardless of case
g           - match it globally

If you only want to match the \ and not the alphabetic characters, then you can use positive lookahead. The regex for that would look like: /(?!>\\)\\(?=[a-zA-Z]+)/g and would break down like this:
(?<!\\)\\     - use negative lookbehind to match a \ that is not preceded by a \
(?=[a-zA-Z]+) - and is followed by one or more alphabetic characters
g             - match it globally

If you only want the regex to match backslashes at the beginning of a line, prepend a ^ to it.
You can use a tool like Rubular to test and play with regular expressions.
Comment: JavaScript does not have lookbehind.
Comment: Thanks for pointing that out @Amadan. I updated my answer to reflect that. Kind of ruins it though. :(


How can I load the transitions for a particular workflow?

Question: I want to load the transition objects for a Workflow. In Drupal 8, I see a Workflow::getTransitions() method, however it seems this method was removed in Drupal 9.
Answer: The easiest way to do this is through the workflow's type plugin, specifically the getTransitions() method.
<code>// First load a workflow, for example:
$workflow = \Drupal::service('content_moderation.moderation_information')
  ->getWorkflowForEntity($entity);

// Then get the workflow's type plugin.
/** @var \Drupal\workflows\WorkflowTypeInterface $workflow_type_plugin */
$workflow_type_plugin = $workflow->getTypePlugin();

// Finally, load the transitions.
$workflow_transitions = $workflow_type_plugin->getTransitions();
</code>
Alternatively, it may be more useful to only get the valid transitions for an entity, i.e. only transitions allowed for the entity from its current state, for the current user. The getValidTransitions() method from the content_moderation.state_transition_validation service does this.
<code>/** @var \Drupal\content_moderation\StateTransitionValidationInterface $transition_validation */
$transition_validation = \Drupal::service('content_moderation.state_transition_validation');
$valid_transitions = $transition_validation
  ->getValidTransitions($entity, \Drupal::currentUser());
</code>


Creating thumbnails of Overlayed images in jquery

Question: I am tying to address a problem which we are facing in creating Thumbnails of the overlayed images.
The problem is
I have database of samller images and a Static image. User will select few smaller images which needs to overlayed on the static image. User also selects the position over the static image where the smaller images needs to overlayed. But as of now we are not creating a seperate image of newly created overlayed image, but we are storing the images and co-ordinate information. when user logs back, we want to show thumbnail view of the overlayed image[though we dont store overlayed image seperately, but we have a his selected image, co-ordinates for overlaying images, etc stored in db].
Are there any jquery plugin avaialable or any other pointer to achieve the same?
Rgds,
Sandep
Comment: What code do you already have? jsFiddle perhaps?
Answer: If you want to produce a stored, combined image of the static one and smaller ones; you will have to process it in the back-end. If you are using PHP, the GD2 library are available.
If your audience is HTML5 compatible, you can also use the HTML5 canvas to overlay the images, then output the raw-pixel-data to an JS Image() object, and then display that on the page.


How to install mongoDB and check the version

Question: I am new in mongoDB and I installed the mongodb in window 32 bit using:-
C:>npm install -g mongo
And It installed successfully But When I used
c:>mongo -v
This is giving Error:-
'mongo' is not recognized as an internal or external command,
operable program or batch file.
I set the environment variable path is:-
C:\mongodb;
But it is not working. Same error happens.
Answer: You've only installed the Nodejs module to interact with mongodb.
Install instructions here: https://docs.mongodb.com/manual/installation/
Once you've installed mongo -v should work.
Comment: means C:>npm install -g mongo
 This command which package installed is not useful
Comment: It is useful to allow nodejs work with mongoldb. You need it, it's just a connector though.
Comment: means now again I have to install mongoDB using some instruction
Comment: @shahzadahmed Yes, RTFM maybe? SO is not about holding your hand to do a basic installation. **phelpsiv** already wasted his time to give a doc link you could find in 5s.
Answer: You can check mongodb version using db.version() if you have installed mongodb.
Comment: Where I have to use this function actually i am fresher in MongoDB
Comment: Are you able to access mongodb shell? in shell just run this method `db.version()`


Função de grupo não funciona

Question: Possuo duas tabelas.

Tabela: Pedido

Colunas: IDPEDIDO, CLIENTE, DT_PEDIDO, FORMA_PGMT, CLIENTE_ID.

Tabela: Itens_Pedido

Colunas: PEDIDO_ID, QT_MERCADORIAS, MERCADORIA, MERCADORIA_ID.

Preciso criar uma consulta para saber qual o produto mais vendido nos meses de Janeiro e Fevereiro de 2015. Fiz a consulta abaixo mas ela está me retornando este erro:

"not a single-group group function"

Consulta:
    Select max(sum(ITENS_PEDIDO.QT_MERCADORIA)),
           ITENS_PEDIDO.MERCADORIA
      From ITENS_PEDIDO
      Join PEDIDO
        On ITENS_PEDIDO.PEDIDO_ID = PEDIDO.IDPEDIDO
     Group By ITENS_PEDIDO.MERCADORIA_IDMERCADORIA,
           ITENS_PEDIDO.MERCADORIA,
           PEDIDO.DT_PEDIDO
    Having PEDIDO.DT_PEDIDO Between to_date('01/01/2015', 'DD/MM/YYYY')
                                And to_date('28/02/2015', 'DD/MM/YYYY');

Comment: Segundo [essa resposta no SOEn](http://stackoverflow.com/questions/20207508/sql-not-a-single-group-group-function-error) você está usando colunas que estão sendo usadas em funções agregadas no GROUP BY. Tente refazer sua query sem incluir `ITENS_PEDIDO.QT_MERCADORIA` no GROUP BY;
Comment: Isso funciona... o problema é que se eu não colocar ITENS_PEDIDO.QT_MERCADORIA ele só mostra a quantidade de mais vendido e não mostra o nome do produto.
Comment: Tente remover o `max()`, criar um alias assim `sum(ITENS_PEDIDO.QT_MERCADORIA) as total_mercadoria`  para usar `order by total_mercadoria desc limit 1`.
Comment: Não funcionou apareceu um resultado 50 que não consigo entender do porque, a soma nunca vai dar 50
Answer: Tente simplificar a sua query:
Select sum(ITENS_PEDIDO.QT_MERCADORIA),
       ITENS_PEDIDO.MERCADORIA
  From ITENS_PEDIDO
       Join PEDIDO
            On ITENS_PEDIDO.PEDIDO_ID = PEDIDO.IDPEDIDO
Where PEDIDO.DT_PEDIDO Between to_date('01/01/2015', 'DD/MM/YYYY')
                           And to_date('28/02/2015', 'DD/MM/YYYY')
 Group By ITENS_PEDIDO.MERCADORIA_IDMERCADORIA,
          ITENS_PEDIDO.MERCADORIA;

O que foi feito:

Remoção da função de agregação MAX: redundante neste caso;
Colocação do critério de filtro para a cláusula WHERE: o HAVING deve ser somente utilizado quando o critério desejado envolve um resultado da sumarização;
Remoção da coluna PEDIDO.DT_PEDIDO do GROUP BY: deduzo pelo fato deste campo não ser selecionado, a sumarização deve ser somente por produto, e não produto/data.

Função de grupo não funciona


IndexError: array index out of range (but index does exist?)

Question: I've had out of range index error, however, it makes no sense to me why this would be the case. the offending code is as follows:
L = []
A = arr.array("i",[])
i=0

while i < 10:
  L.append(df.Title[i])
  A.append(len(df.Title[i]))
  i += 1

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(L,A)
fig.suptitle('Total Characters in a Stack Overflow Post Title with Outliers')
plt.xlabel('Title')
plt.ylabel('# of Characters')
plt.setp(ax.get_xticklabels(), fontsize=10, rotation='vertical')
plt.plot

std = np.std(A)
mean = np.mean(A)

j=0
while j < 10:
  if A[j] > mean - 2 * std or A[j] < mean + 2 * std: #The error occurs on this line with A[j]
    A.pop(j)
    L.pop(j)
  j += 1

In terms of the relevant output, when numbers are appended to the array, the values read as follows:
0
1
2
3
4
5``
6
7
8
9
However when printing from j within the while loop, it only prints up to index 4 and then has the aforementioned array error. Any guidance would be appreciated.
Comment: See what `A.pop(j)` does.
Comment: Ah, that makes sense. Thank you!
Answer: Because  you are popping elements from A using "A.pop(j)". This action reduce your array by one element on each iteration, so when j gets to 4 remaining array elements have been popped out.
Answer: You are removing elements from the array you are iterating on. Meaning the lengths of A  and L before you start the last while loop are both 10, but every time your if statement is true, their length is decreased by 1. A crude, but easy way to bypass this is to define a new variable with the same values as A:
j=0
B = A[:]
while j < 10:
  if B[j] > mean - 2 * std or B[j] < mean + 2 * std:
    A.pop(j)
    L.pop(j)
  j += 1

Comment: Better to decrease `j` by one when removing
Comment: And `while j < len(A)`
Comment: Thank you! this was very helpful, an oversight on my part.


problem when deserializing xml with xmlMapper (java)

Question: I have autogenerated POJOs, to which i want to deserialize XML. XML looks like this:
<RootElement>
  <ListOfEntities>
    <Entity>
      <EntityRecord>
        <Field>123</Field>
      </EntityRecord>
    </Entity>
  </ListOfEntities>
<RootElement>

autogenerated entities looks like this:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "listOfEntitiesType", propOrder = {
    "entity"
})
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-09-23T01:56:05+03:00", comments = "JAXB RI v2.3.3")
public class ListOfEntitiesType {

    @XmlElement(name = "Entity")
    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-09-23T01:56:05+03:00", comments = "JAXB RI v2.3.3")
    protected List<EntityType> entity;
.....
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "entityType", propOrder = {
    "entityRecord"
})
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-09-23T01:56:05+03:00", comments = "JAXB RI v2.3.3")
public class EntityType {

    @XmlElement(name = "EntityRecord")
    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-09-23T01:56:05+03:00", comments = "JAXB RI v2.3.3")
    protected List<EntityRecordType> entityRecord;
.....
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "entityRecordType", propOrder = {
    "field"
})
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-09-23T01:56:05+03:00", comments = "JAXB RI v2.3.3")
public class EntityRecordType {

    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-09-23T01:56:05+03:00", comments = "JAXB RI v2.3.3")
    protected String field;
.....
}

and root element.
I try to deserialize it with this code:
XmlMapper xmlMapper = XmlMapper.builder().enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES).build();
xmlMapper.readValue()

And i get error:
Unrecognized field "field" (class path.to.autogenerated.classes.EntityType), not marked as ignorable (one known property: "entityRecord"])

It looks like when jackson is trying to deserialize ListOfEntities, it iterprets  tag as some kind of wrapper istead of list's element, so it tries to interpret  as element of List. And fails
I tried to code like this:
XmlMapper xmlMapper = XmlMapper.builder().defaultUseWrapper(false).enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES).build();
xmlMapper.readValue()

but with no effect.
I have no access neither to use annotations on POJOs (because they are autogenerated) nor to make changes on xsd. Can I somehow tell xmlMapper to deserialize correctly?
Answer: It seems to me that you are missing @XmlAttribute as follows:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "entityRecordType", propOrder = {
    "field"
})
@Generated(value = "com.sun.tools.xjc.Driver", date = "2021-09-23T01:56:05+03:00", comments = "JAXB RI v2.3.3")
public class EntityRecordType {

    @XmlAttribute(name = "Field")
    @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-09-23T01:56:05+03:00", comments = "JAXB RI v2.3.3")
    protected String field;
.....
}

Comment: nope, on lowest class's fields there are only @Generated annotation.
Comment: And this class is autogenerated, so i cant add any annotation
Comment: How are you autogenerating it?


$(i_0,i_1):A\vee A\rightarrow A\wedge I_+$ is a cofibration

Question:
This is May & Ponto's More concise algebraic topology. They claimed that $(i_0,i_1):A\vee A\rightarrow A\wedge I_+$ is a cofibration. But I don't know why.
Question: Why the map $(i_0,i_1):A\vee A\rightarrow A\wedge I_+$ is a cofibration.
Could anybody give a proof?
Answer: Consider the folding map $\nabla:A\vee A\rightarrow A$, which is defined to be the identity on each of the wedge summands, and the map $j$ which results by replacing $\nabla$ by a cofibration using the pointed mapping cylinder. Thus we let $M_\nabla$ be the pushout of
$$(A\vee A)\wedge I_+\xleftarrow{in_0}A\vee A\xrightarrow\nabla A$$
and have the cofibration $j:A\vee A\hookrightarrow M_\nabla$ which is induced by the inclusion of $A\vee A$ into the top end of the cylinder.
To proceed we identify
$$(A\vee A)\wedge I_+\cong (A\wedge I_+)\vee (A\wedge I_+)$$
and so have that $M_\nabla$ is the quotient
$$M_\nabla\cong \frac{(A\wedge I_+)\vee (A\wedge I_+)\vee A}{[((a,0),\ast)\sim (\ast,(a,0))\sim a]}.$$
The identifications glue the two cylinders together along the $A$ summand. Up to homeomorphism what is left is
$$M_\nabla\cong A\wedge I_+.$$
Under this identification, one of the cylinders is turned upside down. The map $j$ now includes one summand of $A$ in at the bottom of $A\wedge I_+$ and the other in at the top.
Of course a homemorphism is a cofibration and a composite of cofibrations is a cofibration, so we conclude that
$$j=(in_0,in_1):A\hookrightarrow A\wedge I_+$$
is a cofibration.
Answer: In general it is not true. However, May and Ponto do not consider arbitrary pointed spaces. On p. 7 they make the following general assumption

We nearly always work with based spaces. To avoid pathology, we assume once and for all that basepoints are nondegenerate, meaning that the inclusion $∗ \to X$ is a cofibration.

Note the May and Ponto define free and based cofibrations and clarify their relationship in Lemma 1.3.4. On p. 20 they say

One of the many motivations for our standing assumption that basepoints are nondegenerate is that it ensures that based maps are cofibrations or fibrations in the free sense if and only if they are cofibrations or fibrations in the based sense.

Let us first observe that for a based space $A = (A,a_0)$  we can identify
$A \wedge I_+$ with the quotient space $A \times I / \{a_0\} \times I$.
$A \vee A$ can be regarded as the quotient space obtained from $A \times \{0,1\} \cup \{a_0\} \times I$ by identifying $ \{a_0\} \times I$ to a point. Then $(i_0,i_1) : A \vee A \to A \times I / \{a_0\} \times I$ is given as the map induced on the quotients by the inclusion $i : A \times \{0,1\} \cup \{a_0\} \times I \to A \times I$. The following diagram is a pushout diagram:
$\require{AMScd}$
\begin{CD}
A \times \{0,1\} \cup \{a_0\} \times I  @>{i}>> A \times I \\
@V{}VV @V{}VV \\
A \vee A @>{(i_0,i_1)}>> A \times I / \{a_0\} \times I \end{CD}
Therefore, if $i$ is a cofibration, then so is $(i_0,i_1)$.
But if $A$ is nondegenerately based, then it is well-known that $i$ is a cofibration. Thus, under May and Ponto's general assumption $(i_0,i_1)$ is in fact a cofibration.
For degenerately based $A$ is in general not true. As an example take $A = \{0\} \cup \{ 1/n \mid n \in \mathbb N \}$ with basepoint $0$. It is not hard to show that $(i_0,i_1)$ is no based cofibration (hence no free cofibration); you can do that as a nice exercise.


Finding the angles of $\triangle ABC$, the area of $\triangle ABC$, $BC$, and $AB$

Question: At the triangle $ABC$ is $AC = 8, B = 30^\circ$ and the length of the normal $BP$ from $B$ on the line through $AC$ is $6$, see figure.
a) Determine the angles in $ABC$.
b) Determine the area in $ABC$.
c) Determine $BC$ and $AB$
Comment: You should post this on the math Stack Exchange site.  This site is for the software package "Mathematica".
Comment: You would learn a great deal more if you started participating in the High School Geometry sub-forum of the Art of Problem Solving.  Give it a try. :)    And it's not just for high-schoolers either.
Comment: Welcome to Math.SE! ... The community prefers/expects a question to include something of what the asker knows about the problem. (*What have you tried? Where did you get stuck?* etc) This helps answerers tailor their responses to best serve you, without wasting time (theirs or yours) explaining things you already understand or using techniques beyond your skill level. (It also helps convince people that you aren't simply trying to get them to do your homework for you. An isolated problem statement with no evidence of personal effort makes a poor impression, attracting down- and close-votes.)
Comment: Let no one ignorant of geometry enter here!
Comment: @Artes with the amount of reputations you acquired, maintain more humble statements - how you define ignorant? At what level someone is non-ignorant? Did you pass an IGNORANT test? Blue has 68K+ and Taussig 64.9K and both provided with REALLY VALUED response!
Comment: @Aril part of the problem is obvious, a second simple calculation, and third Pythagorean relation.
Comment: @Moti  Since you don't know what had been written above Plato's academy these words are fair also to you. I don't like this site since there are too many full of complexes. I prefer Mathematica.Stackexchenge.com
Comment: @Moti It is not so easy. If you can solve in more simple way, or even express final answer in more simple form, please show how.
Answer:
The most simple part of problem is finding area of $ABC$: $S=AC\cdot BP/2=8\cdot 6/2=24$.
There are many possible way of solving of other parts using equations. There is also way of solving step-by-step without equations. This way is given below.
Let draw circumscribed circle of ABC wit center O. Then $\angle AOC=2\angle ABC=60°$ and $OA=OC$, therefore triangle $OAC$ is equilateral, therefore $OA=OC=OB=8$.
Let connect O with middle D of segment AC. OD is median of equilateral triangle and is perpendicular to AC. Length of OD can be found from ODA triangle: $OD=\sqrt{OA^2-DA^2}=4\sqrt{3}$.
Let draw point E on OD such that BE is perpendicular to OD. Quadrilateral BPDE is rectangle, because it has three angles of 90°. Then $ED=BP=6$. Then $OE=OD-DE=4\sqrt{3}-6$. Length of BE can be found from OEB triangle: $BE=\sqrt{OB^2-OE^2}=2\sqrt{12\sqrt{3}-5}$. $DP=BE=2\sqrt{12\sqrt{3}-5}$, $AP=DP-AD=2\sqrt{12\sqrt{3}-5}-4$. Length of AB can be found from APB triangle: $AB=\sqrt{AP^2+BP^2}=4 \sqrt{3\sqrt{3}+2-\sqrt{12\sqrt{3}-5}}$.
Length of BC can be found from area of ABC: $BC=\frac{2S}{AB\sin ABC}=\frac{24}{\sqrt{3\sqrt{3}+2-\sqrt{12\sqrt{3}-5}}}=4 \sqrt{3\sqrt{3}+2+\sqrt{12\sqrt{3}-5}}$.
Sine of angle ACB can be found from sine rule:
$\sin ACB=\frac{AB}{AC}\sin ABC=\frac{1}{4} \sqrt{3\sqrt{3}+2-\sqrt{12\sqrt{3}-5}}$. $AB < AC$, then $\angle ACB < 30°$, then $\angle ACB=\arcsin \sin ACB=\arcsin(\frac{1}{4} \sqrt{3\sqrt{3}+2-\sqrt{12\sqrt{3}-5}})$. Angle CAB can be found from sum of angles: $\angle CAB=180°-\angle ABC-\angle ACB=150°-\arcsin(\frac{1}{4} \sqrt{3\sqrt{3}+2-\sqrt{12\sqrt{3}-5}})$
Comment: Thank you for your explanation, Ivan Kaznacheyeu!


RPM Generation X86_64

Question: I am generating RPM for the fisrt time. I have created folder structure
mkdir -p tmp/rpm/{BUILD,BUILDROOT,RPMS/x86_64,SOURCES,SRPMS,SPECS} .
But when I generated my RPM, it generates my RPM with i586 extension. How to tell RPM to generate x86_64 extension
Answer: rpmbuild doesn't do major-arch crosscompiling. Build your package on a x86-64 system, with x86-64 tools.
Answer: Your best option would be to use http://build.opensuse.org as it builds for both i386 and x86_64 as well as taking care of both RedHat, SuSE, CentOS and Debian.
The other thing to do if you don't want to use build.opensuse.org is to set the arch environment variable. The first option though is the easier.

RPM Generation X86_64


How does the 45 degree banking rule apply when plotting multiple data series in one chart?

Question: Cleveland's rule of thumb that the average slope of a line should be 45 degrees. But what about when a chart plots multiple data series? Is there a generalization of Cleveland's rule, or do you set the chart's aspect ratio by the "Eh, that looks good" method?
Comment: Bill Cleveland did spectacularly good work on graphics, but this rule of thumb long predates him. It's in Fisher's _Statistical methods for research workers_, in essence, to name only one antecedent. But it was always about the typical slope, and that principle just extends when there are several variables as well as several up- or down- segments in a single series.
Answer: The Visweek 2012 paper, An Empirical Model of Slope Ratio Comparisons [PDF] by
Justin Talbot, John Gerth, and Pat Hanrahan, attempts to generalize the question of optimal banking. Excerpt from introduction:

Despite the practical success of this guideline, its perceptual underpinnings
  remain unclear. Cleveland et al. justified the guideline with
  an experiment that showed that placing the mid-angle of two lines (the
  angle halfway between them) at 45° minimizes errors made in judging
  the ratio of their slopes. However, examination of their experimental
  design suggests that this conclusion might not be generally applicable.
  ...
  This paper seeks to improve our understanding of slope ratio estimation
  in line plots through empirical modeling and experimentation.

The experiments suggest the optimal median angle may be around 30° and that flatter is better for perceiving angle differences. Excerpt of a graph supporting the former point (observed error in black; predicted error in red):

However, like seemingly every other research paper, the bottom line is:

It is still unclear if the results derived in our studies for pairwise discrete comparisons will transfer to real plots. ...
  there remains substantial work to be done to
  build a solid understanding of aspect ratio selection.

Related papers:

Arc Length-Based Aspect Ratio Selection [PDF], Justin Talbot, John Gerth, and Pat Hanrahan
Crowdsourcing Graphical Perception: Using Mechanical Turk to Assess Visualization Design [PDF], Jeffrey Heer and Michael Bostock
Comment: Nice answer! Another similar paper on testing Cleveland's perceptual hierarchy is Heer and Bostock http://vis.stanford.edu/files/2010-MTurk-CHI.pdf. For time series it is important to plot on several different aspect ratios, to see long term trend vs seasonal trend. For multivariate data scatterplots should have a square aspect ratio to perceive association better. Show your data on several different aspect ratios in your plots, like you would use several different binwidths when making histograms.
Comment: Thanks Di, I added a link to that paper and another I found. I like your other points. You might expand them into a separate answer or appended them to this answer.


Gcc/clang: error: unknown class name 'Exception'; did you mean 'std::exception'

Question: I've write a experimental library and on working on Array I've got error: unknown class name 'Exception'; did you mean 'std::exception'. How can I fix it?
Array.hpp
#ifndef _RFwC__ARRAY_HPP_
#define _RFwC__ARRAY_HPP_

#include "util.hpp"
#include "Object.hpp"
#include "IDefaultType.hpp"
#include "Exception.hpp"

class ArrayException : public Exception {}; // here error
class IndexOutOfRangeException : public ArrayException {};

template<typename T_Value>
class Array : public Object, IDefaultType{
public:
    Array(const intnum_t _length);
    Array();
// next array code and closing for guard symbols

Exception.hpp
#ifndef _RFwC__EXCEPTION_HPP_
#define _RFwC__EXCEPTION_HPP_

#include "IThrowable.hpp"
#include "Object.hpp"
#include "String.hpp"

class Exception : public Object, IThrowable {
public:
    Exception(const String _message, const Exception * _pInner);
    Exception(const String _message);
    Exception();

    const String getMsg() const;
    const Exception * getInner() const;

    virtual void onThrow();
protected:
    String __msg;
    const Exception * __pInner;
};

#endif //   _RFwC__EXCEPTION_HPP_

Output:
c++ -DPLATFORM_=linux -DCAPACITY_=32 -std=c++11 -fPIC -o obj/core_Exception.cpp.o -c src_Core/Exception.cpp
In file included from src_Core/Exception.cpp:23:
In file included from src_Core/Exception.hpp:26:
In file included from src_Core/IThrowable.hpp:27:
In file included from src_Core/String.hpp:28:
src_Core/Array.hpp:31:31: error: unknown class name 'Exception'; did you mean 'std::exception'?
class ArrayException : public Exception {};
                              ^~~~~~~~~
                          std::exception
/usr/bin/../lib/gcc/i686-linux-gnu/4.7/../../../../include/c++/4.7/exception:61:9: note: 'std::exception' declared here
  class exception
        ^
1 error generated.
make: *** [core_Exception.cpp.o] Ошибка 1

Comment: Is that all there is in the header? Could it be that you copy pasted something from the headers, so the header guards on top of `Exception.hpp` are the same as the header guards on another header file, effectively preventing the contents of `Execption.hpp` to be read by the compiler?
Comment: It's a case of circular includes.
Comment: @john, that's absolutely right, I just noticed the same!
Comment: This probably isn't the problem, but names that begin with an underscore followed by a capital letter (`_RFwC__ARRAY_HPP_`) and names that contain two consecutive underscores (`__msg`) are reserved to the implementation. Don't use them.
Answer: You have a circular loop in your header files.  "Exception.cpp" includes "Exception.hpp" which includes "IThrowable.hpp" which includes "String.hpp" which includes "Exception.hpp" again.
This causes the include guards to prevent the second inclusion of Exception.hpp, but then when you use Exception in String.hpp, it's not defined.
There are two common solutions:

Use a forward declaration of Exception in String.hpp, and do not #include it there.  This will allow you to use the type in your String.hpp header file, with less of an issue.  You would then put the #include into the String.cpp
Rearrange the header files so that you don't have a circular dependency.  This isn't always possible, but usually involves taking the common code and placing it elsewhere.

Of the two, #1 is the preferred solution, as it will also reduce dependencies between your headers, which is generally a good thing.
Comment: No, it's contain guard symbols, but i've remove them from posted source
Comment: @DrMGC - read the answer again, carefully. Especially the second sentence. Include guards don't address this problem.
Answer: Exception.hpp includes String.hpp, which tries to re-include Exception.hpp; circular dependencies like this aren't possible.
Since Exception contains a String, the first inclusion is necessary. So you'll need to change String.hpp so it doesn't include Exception.hpp. If the type is needed, then forward-declare class Exception;, and move any code that needs the full definition into the source file.
Also, don't use reserved names like __msg. I won't comment on the wisdom of trying to replace the standard library with something that looks like Java; I'll never need to deal with that insanity, so it's not my problem.
Answer: There's a circular dependency among the includes.
A forward declaration of Exception will resolve the problem.
A bit of unsolicited advice: an unqualified type called Exception is asking for collisions/confusion.  Please either make the name more specific or use a namespace to qualify this very global-sounding name.


Problemas ao utilizar getJSON para carregar Json da página php

Question: A inteção é pegar o resultado de um select, atribuir em um array, e colocar o seu valor em um elemento html.
o valor é listado e atribuído ao array, porém, não consigo inserir ele no meu html
meu jquery que efetua isso

php para a listagem:

$id_veiculo = $_REQUEST['id_carro'];
$cpf = "25836914766";

$conn = new Conexao();
$link = $conn->getLink();

$select = "SELECT veiculo.PLACA , veiculo.NOME as NOME_VEICULO,cliente.NOME as NOME_CLIENTE,cliente.TELEFONE FROM `veiculo` INNER join cliente on veiculo.CPF = cliente.CPF WHERE cliente.CPF =$cpf AND veiculo.ID_CARRO =$id_veiculo ";
$resultado_consulta = mysqli_query($link, $select);

while( $row = mysqli_fetch_assoc($resultado_consulta) )
{
 echo $row['NOME_CLIENTE'];
 echo "
";
 echo $row['NOME_VEICULO'];
 echo "
";
 echo $row['TELEFONE'];
 echo "
";
 echo $row['PLACA'];

 $resultado[] = array(
 'nome_cliente' =>$row['NOME_CLIENTE'],
 'cpf' =>$cpf,
 'telefone' =>$row['TELEFONE'],
 'nome_veiculo' =>$row['NOME_VEICULO'],
 'placa' =>$row['PLACA'],
 );
}

echo(json_decode($resultado));
?>

nunca havia usado json, estou começando e estou bem perdido
Comment: o JSON retorna correto? Qual o problema que está apresentando?
Comment: O json está retornando correto, o que está acontecendo é que não consigo pegar o valor do array retornado por ele e atribuir a um elemente html
Comment: Se eu der um var_dump em $resultado, ele retorna isso
Comment: array(1) { [0]=> array(5) { ["nome_cliente"]=> string(13) "JOÃO DA SILVA" ["cpf"]=> string(11) "25836914766" ["telefone"]=> string(11) "48997466427" ["nome_veiculo"]=> string(5) "Fusca" ["placa"]=> string(8) "abc-9809" } }
Comment: Então quer dizer que o array foi preenchido. O problema está em ele através do json ali no código jquery
Comment: da um `console.log(resultado)` pra ver sde o json esta chegando corretamente
Comment: não está chegando. Ele me retorna false
Answer: Porque não tentas fazer da seguinte forma:
Script:

PHP para trabalhar nos resultados que queres ir buscar a base de dados
<?php

Uma vez que fizemos uma chamada em metodo POST
if(isset($_POST)){
    $id_veiculo = $_POST['id'];
    $cpf = $_POST['cpf'];

$conn = new Conexao();
$link = $conn->getLink();

$select = "SELECT veiculo.PLACA , veiculo.NOME as NOME_VEICULO,cliente.NOME as NOME_CLIENTE,cliente.TELEFONE FROM `veiculo` INNER join cliente on veiculo.CPF = cliente.CPF WHERE cliente.CPF =$cpf AND veiculo.ID_CARRO =$id_veiculo ";
$resultado_consulta = mysqli_query($link, $select);

while( $row = mysqli_fetch_assoc($resultado_consulta) )
{
 echo $row['NOME_CLIENTE'];
 echo "
";
 echo $row['NOME_VEICULO'];
 echo "
";
 echo $row['TELEFONE'];
 echo "
";
 echo $row['PLACA'];

 $resultado = array(
 'nome_cliente' =>$row['NOME_CLIENTE'],
 'cpf' =>$cpf,
 'telefone' =>$row['TELEFONE'],
 'nome_veiculo' =>$row['NOME_VEICULO'],
 'placa' =>$row['PLACA']
 );
}

echo(json_decode($resultado));
}else{
    // Retorne o seu erro.
}
    ?>

Comment: Bom, continua não funcionando. Descobri que o problema está em atribuir os valores para o array $resultado. Se dou um echo em alguma posição ele mostra como se fosse indefinida.


Grabbing an article from a pdf file - Python

Question: I have more than 5000 pdf files with at least 15 pages each and 20 pages at most. I used pypdf2 to find out which among the 5000 pdf files have the keyword I am looking for and on which page.
Now I have the following data:

I was wondering if there is a way for me to get the specific article on the specific page using this data. I know now which filenames to check and which page.
Thanks a lot.
Answer: There is a library called tika. It can extract the text from a single page. You can split your pdf in such a way, that you have only the page in question still available. Then you can use:
<code>parsed_page = parser.from_file('sample.pdf')
print(parsed_page['content'])
</code>
NOTE: This library requires Java to be installed on the system


Why do Olympic soccer teams need to be U-23?

Question: Why do Olympic soccer teams need to be under the age of 23?
Are there any exceptions about age restriction?
Are there any differences between men and women?
Answer: Indeed Olympic football rules are different for men and women tournament and preliminary (qualifying) and final (Olympics) competitions:

Men's Tournament

All players participating in the preliminary and final competitions of the Tournament shall be born on or after 1 January 1989.
However,  a maximum of  three male players who do not meet this age limit may
also be included in the official list of players for the finals
competition.

Women's Tournament

There are no age restrictions for the players participating in the women's  Tournament.

Please note that the men over 23 can only play at the Olympic finals, not the preliminary or qualifying rounds.
Source: Regulations of the Olympic Football Tournaments
A little bit of history:

For the 1984 Los Angeles Games, the IOC decided to admit professional
players.   FIFA still did not want the Olympics to rival the World
Cup, so a compromise was struck that allowed teams from Africa, Asia,
Oceania, and CONCACAF to field their strongest professional sides,
while restricting UEFA and CONMEBOL teams to players who had not
played in a World Cup.
Many countries fielded young teams, including
France, who won the 1984 Olympic title.
Since 1992 male competitors must be under 23 years old, with three over-23 players  allowed per squad. The new format allows teams from around the world to compete
equally, and African countries have taken particular advantage of
this, with Nigeria and Cameroon winning in 1996 and 2000 respectively.
The first women's tournament was at the 1996 Atlanta Games.

Source
Answer: Another reason this rule exists is maybe for the media : If any player could participate, the football tournament would be taking a lot of mediatic place, to the detriment of the other sports.
Comment: Could you provide a reference for this? At the moment, it seems to be just speculation.
Comment: As I said : "Maybe". It's a tentative to find more explanation than what is commonly known.
However : in 2009, a proposal was made by FIFA for the Olympic Tournament to become a U-21 one. This was rejected by the IOC, and Blatter thought of 2 possibles way to change : making it a U21 tournament or abolishing age restriction and replacing it by banning players with world cup experience : http://news.bbc.co.uk/sport2/hi/olympic_games/8396974.stm


Views_infinite_scroll not working

Question: I'm using Drupal 8 latest stable version: 8.5.x
I have 2 blocks (Upcoming events and Past events).
On Past events views infinite scroll is working with a button enabled providing the user ability to view more. It has many items and the module works as designed.
Same structure Upcoming events block returning only one upcoming event. When user clicks view more button the page is returning nothing and even the one item listed get disappeared.
Ajax is enabled on both views, the only difference is that upcoming events is returning only one result.
How can i solve this?
Answer: Why don't you duplicate the view that works and just reconfigure the filter criteria to met your requirements?
Comment: Because the module is not working when there is only one result
Comment: But then the purpose of the module is not to "manage" a single result view, right?
Comment: Right, but in case if there is only one result os still loads the view more button, and clicking it will do nothimg. In my case it is returning blank page and the one result is disappearing.
Comment: Beyond my current knowledge of Drupal, but I would try to take over the template and hide the button with a conditional statement based on the number of items of the view or build a different view
Comment: Overriding template file is the last thing I want to do. Anyway thank you for your time.

Views_infinite_scroll not working


Correlation between an observation and its rank in a random sample

Question: Suppose $X_1,X_2,\ldots,X_n$ are i.i.d random variables with an absolutely continuous distribution.
We say the observation $X_i$ has rank $R_i$ if $$X_i=X_{(R_i)}\quad,\,i=1,2,\ldots,n,$$
where $X_{(k)}$ is the $k$-th order statistic.
I am looking for the correlation between $X_i$ and $R_i$ for each $i=1,\ldots,n$.
Let us assume that $X_i\sim F$, where the distribution function $F$ is known.  The difficulty I am facing is that I do not know the joint distribution of $(X_i,R_i)$, which is required for finding $E(X_iR_i)$ in the expression for the covariance. But I suspect that the correlation can be derived regardless.
We can find the mean and variance of $X_i$ and $R_i$ separately once we have the distribution $F$ at hand. But how can we find the covariance?
I know that the conditional distribution $[(X_1,\ldots,X_n)\mid X_{(1)},\ldots,X_{(n)}]$ has the form
$$P\left[X_1=x_1,\ldots,X_n=x_n\mid X_{(1)}=x_{(1)},\ldots,X_{(n)}=x_{(n)}\right]=\frac{1}{n!}\mathbf1_{(x_1,\ldots,x_n)\in A},$$
where $A$ is the set of $n!$ realisations of $(x_{(1)},\ldots,x_{(n)})$.
And that the rank vector $(R_1,R_2,\ldots,R_n)$ is also distributed as
$$P(R_1=r_1,\ldots,R_n=r_n)=\frac{1}{n!}\mathbf 1_{(r_1,\ldots,r_n)\in B},$$
where $B$ is the set of $n!$ realisations of $(1,2,\ldots,n)$.
Any hints on how to proceed would be great.
Answer: I will give a hint. The key concept is exchangeability, meaning that the random vector $(X_1, \dotsc, X_n)$ has the same distribution as $(X_{\pi 1}, \dotsc, X_{\pi n})$ for all permutations $\pi$ of $(1,2,\dotsc, n)$.  Then you can check that the vector of ranks $(R_1, \dotsc, R_n)$ also will be exchangeable.  Exchangeability is a generalization of iid, so will generalize your eventual result.
We need something more: even the distribution of the $n$ pairs
$$
\left( (\begin{smallmatrix} X_1\\R_1\end{smallmatrix}), \dotsc, (\begin{smallmatrix} X_n\\R_n\end{smallmatrix}) \right)
$$
is exchangeable. (Then of course we need to assume first exist).
Now calculate: (for some $j$ between 1 and $n$)
\begin{align} \DeclareMathOperator{\E}{\mathbb{E}}
& \sum_\pi \E X_{\pi j} R_{\pi j} \\
= {} & \E \sum_\pi X_{\pi j} R_{\pi j} \\
= {} & \E \sum_{r=1}^n \sum_{\pi\colon R_{\pi j=r}} X_{\pi j} R_{\pi j} \\
= {} & (n-1)! \sum_{r=1}^n \E X_{\pi j} r \\
= {} & (n-1)! \mu \frac{n (n+1)}{2}
\end{align}
where $\mu$ is the common expectation of the $X_i$. You should be able to conclude.
Comment: I have been thinking about this. There is [this](https://math.stackexchange.com/questions/1689769/correlation-between-a-random-variable-and-its-rank/) similar question on Math.SE where the answer suggests that the correlation can be non-zero. I will get back to you when I make some progress.
Comment: The answer given there cannot be correct, see my comment there.
Comment: No. By exchangeability, all the expectations summed over are equal, so the sum is that common expectation times $n!$. So the expectation is $\mu \times \frac{n+1}{2}$, which you can see equals $\E X_j \times \E R_j$. It will follow that the correlation is zero.
Comment: @StubbornAtom: You are right, my answer is wrong. I will look into it to see where it went wrong ...
Comment: Thanks. Could you tell me why the $(n-1)!$ comes in the 3rd step?
Comment: Because the sum over n! permutations is divided i to n classes, each one fixing the rank of variable j, each one having (n-1)! elements
Comment: Does this mean that for each $j=1,\ldots,n$, $$E(X_jR_j)=\frac{\mu(n-1)!(n+1)}{2 n!}$$? I think I am misunderstanding the argument.
Comment: I have attempted at a solution myself after coming across this discussion in a textbook. Please have a look when you can. It appears that the correlation is non-zero in general. I should also add that @joriki's answer on Math.SE matches with the general expression I found.
Answer: We can find $\operatorname E\left[R_1X_1\right]$ using the conditional distribution of $X_1$ given $R_1$. The distribution of $X_1$ conditioned on $R_1=j$ is simply the distribution of $X_{(j)}$, since $R_1=j \implies X_1=X_{(j)}$ by definition for every $j=1,\ldots,n$.
Hence,
\begin{align}
\operatorname E\left[R_1X_1\right]&=\sum_{j=1}^n \operatorname E\left[R_1X_1\mid R_1=j\right]\Pr(R_1=j)
\\&=\frac1n\sum_{j=1}^n j\operatorname E\left[X_1\mid R_1=j\right]
\\&=\frac1n\sum_{j=1}^n j\operatorname E\left[X_{(j)}\right]
\end{align}
Now $R_1$ has a uniform distribution on $\{1,2,\ldots,n\}$ with mean $\frac{n+1}2$ and variance $\frac{n^2-1}{12}$.
So if $\sigma^2$ is the variance of $X_1$, then
$$\operatorname{Corr}(X_1,R_1)=\left(\frac{12}{n^2-1}\right)^{1/2}\frac{\sum_{j=1}^n j\operatorname E\left[X_{(j)}\right]- (n(n+1)/2)\operatorname E[X_1]}{n\sigma}$$
Nonparametric Statistical Inference (5th ed.) by Gibbons and Chakraborti discusses this result on pages 191-192:

The authors subsequently give an alternative expression for the correlation by deriving
$$\sum_{j=1}^n j\operatorname E\left[X_{(j)}\right]=n(n-1)\operatorname E\left[X_1F(X_1)\right]+n\operatorname E[X_1]\,,$$
where $F$ is the common cdf of the $X_j$'s.
And finally,
$$\boxed{\operatorname{Corr}(X_1,R_1)=\left(\frac{12(n-1)}{n+1}\right)^{1/2}\frac1{\sigma}\left[\operatorname E\left[X_1F(X_1)\right]-\frac12 \operatorname E[X_1]\right]}$$


Multiple Field Values on Separate Page

Question: I have multiple values for a field in a node, and am displaying only the top 5 using CSS, however, I would like to display the full list of values on a separate page with a, 'View More' link to that page.
My initial reaction would be to create a views page, but how would I associate that view page with a specific node, and then how would I link to that views page from the original node?
The example:

The main node would be a content type for, 'Author'
Another content type that get's referenced from Author are, 'Publication'
The Author's node will display the top 5 Publications and then have a View More link to the full list of publication.

Is there any better way to accomplish this? All thoughts will be much appreciated.
Answer: Using Views would be the most common way to do this. I will show you a Display Suite method though.
Install these modules:
Display Suite (or any model that can give you extra view modes such as Entity view modes

Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files. A predefined list of layouts (D7
  only) is available for even more drag and drop fun!

View Mode Page

Create separate pages for different view modes for a given content
  type.
On the manage display page for a given content type, you can assign
  patterns for view modes so that they will become a page at the given
  path. For instance, if you want to show the teaser at a specific URL,
  you could do node/%/teaser. If you also use Display Suite or other
  modules that allow you to create new view modes, you can use these
  modes to display one or more fields from a node at a separate URL.

Field multiple limit

This is a simple module that provides settings to limit the number of
  values to display on fields with multiple values.

Token

Provides additional tokens not supported by core (most notably
  fields), as well as a UI for browsing tokens.

Default View Mode:
On your content type's default view mode activate One Column Display Suite layout and click on the gear next to your multi value field and set it to show the first 5 of the multi value field. Use Display Suite to create a Code Field on entities node, with Field code:
Show all.
Tick Token. Back on the manage display for the default view mode you will now see that field: Show all. Drag it to where you want it displayed
Show all View Mode:
Use Display Suite to create an additional View mode. Go to Manage display for the new View mode and set the 'View mode pages' URL pattern to node/%/all. Make sure you set the multi value field to show all values.

Multiple Field Values on Separate Page


Comparison test help

Question:
I've worked out (b) (i) through the ratio test and I realize that comparison test should be used for (ii) but I'm unsure how to do this with a root n on top, or if your meant to relate it to (i).
Answer: It's simpler if you use equivalents: $3n+1\sim_\infty3n$, hence
$$\frac{2\sqrt n}{3n+1}\sim_\infty \frac{2\sqrt n}{3n}=\frac23\frac1{\sqrt n},$$
which diverges.
Comment: Cheers, for the response
Answer: For two notice that $$\frac{2\sqrt{n}}{3n+1}\geq \frac{2\sqrt{n}}{3n+n} = \frac{1}{2\sqrt{n}} \geq \frac{1}{2}\left(\frac{1}{n}\right)$$ so $$\frac{1}{2}\sum_{n=1}^\infty \frac{1}{n} \leq \sum_{n=1}^\infty \frac{2\sqrt{n}}{3n+1}$$
Comment: Alright, thanks for the answer

Comparison test help


Naming conventions for `d3.select(this.el)` in Backbone

Question: Inside a Backbone.View this.el normally refers to the node element that the view is based
on, and this.$el refers to the jquery version $(this.el).
I'm using Backbone with the d3 library and was wondering if there was a standard naming convention for the d3 version d3.select(this.el)? Perhaps this.d3el?
Comment: In coffeescript with `@el` and `@$el` such a convention would be percentage wise even more helpful.
Comment: My strong suspicion is that not enough people have a) used these libraries together and b) thought to cache the D3 selection to actually have produced any conventions around this. Use whatever works for you :).
Answer: Isn't d3 defined as window.d3? Therefore, it's available globally so there shouldn't be a need to scope it within the view. Unless I'm missing something here!
Comment: I'm not talking about the d3 library, but the d3 selection of the view element


How to predict (classify) user sentence with BERT model and TensorflowLite

Question: I'm trying to train a MobileBERT model with TFLite Model Maker ; the training part is OK, the testing too (I can use the mb_model.evaluate(mb_test_data)).
But I'm totally lost on how to predict a result with a string sentence, with Python...
Here is a training sample script :
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import configs
from tflite_model_maker import ExportFormat
from tflite_model_maker import model_spec
from tflite_model_maker import text_classifier
from tflite_model_maker.text_classifier import DataLoader

mb_spec = model_spec.get('mobilebert_classifier')
mb_train_data = DataLoader.from_csv(
    filename=os.path.join(os.path.join(data_dir, 'nlu_train.tsv')),
    text_column='sentence',
    label_column='label',
    model_spec=mb_spec,
    delimiter='\t',
    is_training=True)
mb_test_data = DataLoader.from_csv(
    filename=os.path.join(os.path.join(data_dir, 'nlu_test.tsv')),
    text_column='sentence',
    label_column='label',
    model_spec=mb_spec,
    delimiter='\t',
    is_training=False)
mb_model = text_classifier.create(mb_train_data, model_spec=mb_spec, epochs=30, batch_size=8)
config = configs.QuantizationConfig.for_float16()
config._experimental_new_quantizer = True
mb_model.export(export_dir='/')

It exports /model.tflite
I can test with an existing sentence like that :
import numpy as np
import tensorflow as tf

interpreter = tf.lite.Interpreter(model_path="nlu (6).tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.int32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)

But instead of input_data = np.array(np.random.random_sample(input_shape), dtype=np.int32), I want to use a custom sentence, like :
input_data = "My user sentence"
output_data = interpreter.predict(input_data)

Does someone knows how to do this ? I don't find any documentation, the reverse on TFLite Model Maker (and BERT on official.nlp.data repository) sources ,is hard...
I didn't find the full preprocessing used on string and tokenization process, to get the int32 list that replace the original sentence :/
Thanks !
Answer: You can use BertNLClassifier to do the inference. It will handle the pre-processing and post-processing part.
Comment: Can you try this instead? `from official.nlp.data import classifier_data_lib as lib` `example = lib.InputExample(guid='0', text_a='Your sentence', label=None)` `feature = lib.convert_single_example(ex_index=0, example=example, label_list=None, max_seq_length=mb_spec.seq_len,
                           tokenizer=mb_spec.tokenizer)`. Then the three inputs should be: `feature.input_ids`, `feature.input_mask` and `feature.segment_ids`. pease see the input_details names to see the order of three inputs.
Comment: As for the second error, as I mentioned, there're three inputs, please see input_details and mapped the variable name. The mappings are: 1. `feature.segment_ids`: `'serving_default_input_type_ids:0'`, 2. `feature.input_ids`: `'serving_default_input_word_ids:0'`, 3. `feature.input_mask`: `serving_default_input_mask:0`
Comment: But there isn't any Python API ; I can use an external call to the C++ API, but I'm looking for a Python solution
Comment: I see. Can you try with ```token_ids = mb_spec.preprocess('My user sentence')```? We will consider adding `predict` method later in model_maker.
Comment: It fails :
`from tflite_model_maker import model_spec`
`mb_spec = model_spec.get('bert_classifier')`
`token_ids = mb_spec.preprocess('Est-ce qu\'il est grand ?')`
`print(token_ids)`

AttributeError: 'BertClassifierModelSpec' object has no attribute 'preprocess'
Comment: It fails with `AttributeError: 'BertClassifierModelSpec' object has no attribute 'tokenizer'`. I will try with `from official.nlp.bert import tokenization` `tokenizer = tokenization.FullTokenizer(vocab_file="output/data/vocab.txt", do_lower_case=True)`
Comment: It outputs feature, but if I try `interpreter.set_tensor(input_details[0]['index'], feature.input_ids)` I get `ValueError: Cannot set tensor: Got value of type INT64 but expected type INT32 for input 0, name: serving_default_input_type_ids:0 `
Comment: As for the first error about tokenizer, you need `mb_spec.build()` if you didn't load data before.
Comment: Allright, I had to encapsulate each value in an array and convert them to int32, like this : `interpreter.set_tensor(input_details[0]['index'], [np.array(feature.segment_ids, dtype=np.int32)])`. I set the 3 input_details entries, and I have a result now :) A bad result, but maybe my training isn't good enough, thanks !


SSHing with the nobody user

Question: I am on FreeBSD. Essentially, I am trying to have a php script (run by apache) ssh into another machine. I am running into the problem that nobody does not have a .ssh configuration file and so am getting the error:
Could not create directory '/nonexistent/.ssh'.
Host key verification failed.
Is there a way to work around this? Bonus points if you can do this without root access so I do not need to pay my web hosting company to do this.
Thanks.
Answer: Try to start ssh with the following options:
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ...

That way, ssh doesn't try to load and create the .ssh/known_hosts file.
Answer: The entire idea behind user nobody is that he has almost no rights on the host. Nobody is not part of any group. Nobody has no home directory.
Without homedir there is no .ssh dir in a homedir. So this is not going to work as nobody.
Possibly you can run the process under an other user? (Though that would require creating another user, which requires root access. Which you stated as undesirable.
Answer: What if you assign a shell to the user.  On my system, nobody is assigned /sbin/nologin as the shell.  what if you changed that to /bin/bash.
I have SSHed into a system plenty of times when no home folder exists, it will create it for you, you just need a shell.
Comment: Root access would still be needed to do this.
Comment: Assigning a shell to user nobody would give more options to `nobody`. That might not be bad if the apache/php is the only program using this user. If others also use nobody then you are removing safeties from multiple programs.  Creating a separate user for this would be better from a security point of view.

SSHing with the nobody user


Ao selecionar um item do select, alterar o campo input

Question: Tenho os seguintes campos:

O select conterá RG e CPF. Como eu poderia fazer para que ao selecionar o CPF, o campo altere para o que tem máscara? O campo que contém máscara já tenho pronto, só preciso incluí-lo nessa alteração.
Vejam o código:

            <input type="text" name="NomePAX[]" class="form-control" placeholder="Nome do pax" value="">

              <select name="TipoDocumento" class="form-control">
                <option>Selecione o tipo de documento</option>
              </select>

                <input type="text" name="RGPessoaAutorizada[]" class="form-control" placeholder="RG da pessoa autorizada" value="">

                 <input type="text" name="CPF[]" id="cpf" class="form-control" data-inputmask="'alias': '999.999.999-99'">

            <button type="button" class="removerCampo btn btn-danger" title="Remover linha"> Remover</button>

            <button type="button" class="adicionarCampo btn btn-primary" title="Adicionar item"> Adicionar mais passageiros</button>

JQuery

Answer: Coloque um eventListener no seu select, desabilite os inputs irrelevantes e esconda-os. Você pode guardar informações para te ajudar na pesquisa no atributo datado HTML

$('#TipoDocumento').change(function(e) {
  let opcaoSelecionada = this.querySelector('option:checked');

  //desabilita e esconde todos os inputs
  let inputs = $('#InputsDocumento input');
  inputs.attr('type', 'hidden');
  inputs.attr('disabled', '');

  //habilita e mostra o input relevante
  let inputEscolhido = inputs.filter('#'+ opcaoSelecionada.dataset.tipo);
  inputEscolhido.attr('type', 'text');
  if (opcaoSelecionada.dataset.tipo !== 'placeholder')
     inputEscolhido.removeAttr('disabled');
});

<select id="TipoDocumento" name="TipoDocumento" class="form-control">
  <option data-tipo="placeholder">Selecione o tipo de documento</option>
  <option data-tipo="RG">RG</option>
  <option data-tipo="CPF">CPF</option>
</select>

  <input type="text" id="placeholder" placeholder="Documento" disabled>

  <input type="hidden" name="RGPessoaAutorizada[]" id="RG" placeholder="RG da pessoa autorizada" disabled>

  <input type="hidden" name="CPF[]" id="CPF" placeholder="CPF" disabled>

Comment: Olá user130157. Certo. Mas infelizmente não funciona quando clico em adicionar mais campos. Quando faço isso, ele só funciona no primeiro campo.


Rename the taxonomy menu in drupal 7

Question: I have taxonomy menu as the menu in my page.Here when i edit the taxonomy menu it is not getting updated in my menu.Can anyone help menu to fix this issue.
For example let say I have taxonomy menu item hello.Now i go to structure-->taxonomy-->Home page menu--->list links and I edited the hello to test.When I come to my home page it still showing the hello and it is not getting updated.
Answer: When you edit your vocabulary, on "Structure > Taxonomy > Home page menu > Edit" there should be a "Select to rebuild the menu on submit" checkbox.  This helped in my case.
Because the following warning, you should consider making a backup before doing this.

This will delete then re-create all of the menu items. Only use this option if you are experiencing issues like missing menu items or other inconsistencies.
Comment: There is any way to rebuild the menu automatically.If i do the "Select to rebulid the menu on submit",the id of the menus are getting changed.I need the same id even when the taxonomy menu is get edited.
Comment: Here when i select the "Select to rebuild the menu on submit." it delete and recreate all the menu.But I want only menu get upadate if there is any change
Comment: Thats bad - in this case you could use the module Menu Names CSS http://drupal.org/project/menu_css_names. This module adds the target path of a menu item as a sanitized css-class to the li-item, to which you can refer in your stylesheet.

Rename the taxonomy menu in drupal 7


Rendering glb file in React using npx gltfjsx model.glb command

Question: I am trying to add animation to my React project. Animation is taken from mixamo.com and then exported to a glb file using blender. I saved the glb file in my public folder. Next, I used:
npx gltfjsx model.glb

but I receive the following error:
  ERROR Objects are not valid as a React child (found: Error: Invalid hook call. Hooks can only be called inside of the body of a
       function component. This could happen for one of the following reasons:
       1. You might have mismatching versions of React and the renderer (such as React DOM)
       2. You might be breaking the Rules of Hooks
       3. You might have more than one copy of React in the same app
       See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.). If you meant to render a
       collection of children, use an array instead.

 - 1. You might have mismatching versions of React and the renderer (such as React DOM)
 - 2. You might be breaking the Rules of Hooks
 - 3. You might have more than one copy of React in the same app
 - See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.). If you meant to render a
   collection of children, use an array instead.
 - throwOnInvalidObjectType (node_modules/ink/node_modules/react-reconciler/cjs/react-reconciler.development.js:4612:15)
 - createChild (node_modules/ink/node_modules/react-reconciler/cjs/react-reconciler.development.js:4850:7)
 - reconcileChildrenArray (node_modules/ink/node_modules/react-reconciler/cjs/react-reconciler.development.js:5100:25)
 - reconcileChildFibers (node_modules/ink/node_modules/react-reconciler/cjs/react-reconciler.development.js:5506:14)
 - reconcileChildren (node_modules/ink/node_modules/react-reconciler/cjs/react-reconciler.development.js:8417:28)
 - updateHostComponent (node_modules/ink/node_modules/react-reconciler/cjs/react-reconciler.development.js:9059:3)
 - beginWork (node_modules/ink/node_modules/react-reconciler/cjs/react-reconciler.development.js:10507:14)
 - Object.invokeGuardedCallbackProd (node_modules/ink/node_modules/react-reconciler/cjs/react-reconciler.development.js:12101:10)
 - invokeGuardedCallback (node_modules/ink/node_modules/react-reconciler/cjs/react-reconciler.development.js:12292:31)
 - beginWork$1 (node_modules/ink/node_modules/react-reconciler/cjs/react-reconciler.development.js:16531:7)

If I try to manually add the Model.js file using:
import React, { useRef, useEffect } from 'react';
import { useGLTF, useAnimations } from '@react-three/drei';

export default function Model({ ...props }) {
   const group = useRef();
   const { nodes, materials, animations } = useGLTF('/model.glb');

   const { actions } = useAnimations(animations, group);

   // 'Armature|mixamo.com|Layer0' is the name of the animation we need to run.
   // console.log(actions);

   useEffect(() => {
      actions['Armature|mixamo.com|Layer0'].play();
   });

   return (
      <group ref={group} {...props} dispose={null}>
         <primitive object={nodes.Hips} />
         <skinnedMesh
            geometry={nodes.Wolf3D_Body.geometry}
            material={materials.Wolf3D_Body}
            skeleton={nodes.Wolf3D_Body.skeleton}
         />
         <skinnedMesh
            geometry={nodes.Wolf3D_Glasses.geometry}
            material={materials.Wolf3D_Glasses}
            skeleton={nodes.Wolf3D_Glasses.skeleton}
         />
         <skinnedMesh
            geometry={nodes.Wolf3D_Hair.geometry}
            material={materials.Wolf3D_Hair}
            skeleton={nodes.Wolf3D_Hair.skeleton}
         />
         <skinnedMesh
            geometry={nodes.Wolf3D_Outfit_Bottom.geometry}
            material={materials.Wolf3D_Outfit_Bottom}
            skeleton={nodes.Wolf3D_Outfit_Bottom.skeleton}
         />
         <skinnedMesh
            geometry={nodes.Wolf3D_Outfit_Footwear.geometry}
            material={materials.Wolf3D_Outfit_Footwear}
            skeleton={nodes.Wolf3D_Outfit_Footwear.skeleton}
         />
         <skinnedMesh
            geometry={nodes.Wolf3D_Outfit_Top.geometry}
            material={materials.Wolf3D_Outfit_Top}
            skeleton={nodes.Wolf3D_Outfit_Top.skeleton}
         />
         <skinnedMesh
            name="EyeLeft"
            geometry={nodes.EyeLeft.geometry}
            material={nodes.EyeLeft.material}
            skeleton={nodes.EyeLeft.skeleton}
            morphTargetDictionary={nodes.EyeLeft.morphTargetDictionary}
            morphTargetInfluences={nodes.EyeLeft.morphTargetInfluences}
         />
         <skinnedMesh
            name="EyeRight"
            geometry={nodes.EyeRight.geometry}
            material={nodes.EyeRight.material}
            skeleton={nodes.EyeRight.skeleton}
            morphTargetDictionary={nodes.EyeRight.morphTargetDictionary}
            morphTargetInfluences={nodes.EyeRight.morphTargetInfluences}
         />
         <skinnedMesh
            name="Wolf3D_Head"
            geometry={nodes.Wolf3D_Head.geometry}
            material={materials.Wolf3D_Skin}
            skeleton={nodes.Wolf3D_Head.skeleton}
            morphTargetDictionary={nodes.Wolf3D_Head.morphTargetDictionary}
            morphTargetInfluences={nodes.Wolf3D_Head.morphTargetInfluences}
         />
         <skinnedMesh
            name="Wolf3D_Teeth"
            geometry={nodes.Wolf3D_Teeth.geometry}
            material={materials.Wolf3D_Teeth}
            skeleton={nodes.Wolf3D_Teeth.skeleton}
            morphTargetDictionary={nodes.Wolf3D_Teeth.morphTargetDictionary}
            morphTargetInfluences={nodes.Wolf3D_Teeth.morphTargetInfluences}
         />
      </group>
   );
}

useGLTF.preload('/model.glb');

in console, the object is showing empty and the app is not working (an empty page shows up with just the background color) while the following error is received in the console:
Error message showing browser console
Avatar.jsx where I want to render the Model.js
import React, { Suspense } from "react";
import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import Model from "./Model";

function Avatar() {
  return (
    <Canvas camera={{ position: [2, 0, 12.25], fov: 15 }}>
      <ambientLight intensity={1.25} />
      <ambientLight intensity={0.1} />
      <directionalLight intensity={0.4} />
      <Suspense fallback={null} r3f>
        <Model />
      </Suspense>
      <OrbitControls />
    </Canvas>
  );
}

Any help or suggestions are welcome. (Before adding animation I was able to add the 3D image in my project, the app was working fine.)
Answer: the glb file must saved inside of "public" folder.


How to interpret the interaction term of a standardized variable and a binary variable correctly?

Question: I have the following model:
$$y=\beta_{0}+\beta_{1}x_1+\beta_{2}x_2+\beta_{3}x_1x_2+u$$
where
$y$=dependent variable
$x_1$=standardized independent variable
$x_2$=dummy (binary) independent variable
$x_1x_2$=interaction term of $x_1$ and $x_2$.
The interpretation of standardized variable is a bit tricky. If we give (ceteris paribus) an additional one unit of standard deviation to $x_1$, $y$ will differ by $\beta_1$. What is the correct interpretation of the interaction term in this case? Does $\beta_3$ mean an additional unit or an additional unit of standard deviation (c.p.) affecting $y$?
Answer: Notice that, if $x_2=0$, then
$$y= \beta_0 + \beta_1 x_1 + u$$
and that, if $x_2=1$, then
$$y= (\beta_0+\beta_2) + (\beta_1+\beta_3) x_1 + u,$$
so $(\beta_1+\beta_3)$ is how much one would expect $y$ to change for a unitary change in $x_1$ if $x_2=1$ and $\beta_1$ is how much one would expect $y$ to change for a unitary change in $x_1$ if $x_2=0$.
That is, the expected change in $y$ depend on whether $x_2=0$ or $x_2=1$.
In that context, one way to think of $\beta_3$ is as an additional (positive or negative) expected change in $y$ when $x_2=1$ beyond the expected change $\beta_1$. It is possible even that $\beta_1$ and $\beta_3$ cancel out one another, in which case $y$ is constant w.r.t. $x_1$ when $x_2=1$.
Since you mention no other transformation besides standardization, both $\beta_1$ and $\beta_3$ must be thought of as the expected change in $y$ in case of observing an increase of one standard deviation in the independent quantitative variable in its original scale.