text:
Q: Full text search index on a multilingual column I have a DB in which there is a table shows with a multilingual column title. I would like to optimise full text search by adding an index like so:
CREATE INDEX title_idx ON shows USING gin(to_tsvector(title));

I get this error:
ERROR:  functions in index expression must be marked IMMUTABLE

It basically asks me to add the language parameter to make to_tsvector immutable. the result would be:
 CREATE INDEX title_idx ON shows USING gin(to_tsvector(LANGUAGE, title));

where LANGUAGE would be one of my target languages.
Is it possible to create an index that works for several languages ?

A:
Is it possible to create an index that works for several languages ?

Yes, but you need a second column that identifies the language of the text. Say you added a column doc_language to the table; you could then write:
CREATE INDEX title_idx ON shows USING gin(to_tsvector(doc_language, title));

Of course, this requires that you know the language of the subject text, something that can be hard to do in practice. If you don't need stemming, etc, you can just use the language simple, but I'm guessing you would've done that already if it were an option.
As an alternative, if you have a fixed and limited set of languages, you can concatenate the vectors for the different languages. E.g.:
regress=> SELECT to_tsvector('english', 'cafés') || to_tsvector('french', 'cafés') || to_tsvector('simple', 'cafés');
          ?column?
----------------------------
 'caf':2 'café':1 'cafés':3
(1 row)

That'll match a tsquery for cafés in any of those three languages.
As an index:
CREATE INDEX title_idx ON shows USING gin((
    to_tsvector('english', title) ||
    to_tsvector('french', title) ||
    to_tsvector('simple', title)
));

but this is clumsy to use in queries, as the planner isn't very smart about matching index quals. So I'd wrap it in a function:
CREATE FUNCTION to_tsvector_multilang(text) RETURNS tsvector AS $$
SELECT to_tsvector('english', $1) ||
       to_tsvector('french', $1) ||
       to_tsvector('simple', $1)
$$ LANGUAGE sql IMMUTABLE;

CREATE INDEX title_idx ON shows USING gin(to_tsvector_multilang(title));

If you want you can even get fancy: pass the list of languages as an array (but remember it'll have to be exactly the same order for an index qual match to work). Use priorities with setweight, so you prefer a match in English to one in French, say. All sorts of options.

A: I've just made a Postgres function to test the text language. It's not perfect but it works for long texts.
CREATE OR REPLACE FUNCTION get_language(t text) RETURNS regconfig AS $$
DECLARE
    ret regconfig;
    BEGIN
            WITH l as ( SELECT cfgname, to_tsvector(cfgname::regconfig, title) as vector, length(to_tsvector(cfgname::regconfig, title)) as len
        FROM pg_ts_config, (select t as title) as ti)
    SELECT cfgname::regconfig
    INTO ret
    FROM l
    WHERE len=(SELECT MIN(len) FROM l)
    ORDER BY cfgname='simple' DESC, cfgname ASC
    LIMIT 1;
    RETURN ret;
    END;
$$ LANGUAGE plpgsql;

It just look for the shortest tsvector for the given text (so it tries every ts config of postgres).

A: In my case, I know the language of the current ligne. I have a "language" column. But if I do :
CREATE INDEX filmtraduction_tsindex ON filmtraduction USING GIN (
to_tsvector((case when $1=''language.fr'' then ''french'' when $1=''language.es'' then ''spanish'' else ''english'' end)::regconfig, body));

If have "functions in index expression must be marked IMMUTABLE".
So I need to create an immutable function:
 CREATE FUNCTION toregconfig(text) RETURNS regconfig AS 'select (case
 when $1=''language.fr'' then ''french'' when $1=''language.es'' then
 ''spanish'' else ''english'' end)::regconfig;' LANGUAGE SQL IMMUTABLE
 RETURNS NULL ON NULL INPUT;

Then I can create my index:
CREATE INDEX filmtraduction_tsindex ON filmtraduction USING GIN (
to_tsvector(toregconfig(language), body));

I do the query like this:
select * from movietraduction where to_tsvector(toregconfig(language), body) @@ plainto_tsquery('foo');


text:
Q: I am trying to extract phone numbers using re.findall( ).But it shows TypeError: expected string or bytes-like object
*

*Problem Statement

The need to easily verify phone numbers in any relevant scenario.

Consider the following Phone numbers:
444-122-1234
123-122-78999
111-123-23
67-7890-2019

The general format of a phone number is as follows:
Starts with 3 digits and '-' sign
3 middle digits and '-' sign
4 digits in the end

My Code
import re
l1=[444-122-1234,123-122-78999,111-123-23,67-7890-2019]
k=[]
for i in l1:
    str1=re.findall(r'\d{2}-\d{3}-\d{4}',i)
    print(str1)

A: You just need to put each of the phone numbers in the l1 list inside quotations. Now they are just integers with some minus calculations.

A: With List Comprehension:
 import re
 l1= ['444-122-1234', '123-122-78999', '111-123-23', '67-7890-2019']

 str1 = [re.findall(r'\d{2}-\d{3}-\d{4}', i) for i in l1 if re.findall(r'\d{2}-\d{3}-\d{4}', i) ]
 print(str1)

Output:
Out[18]: [['44-122-1234'], ['23-122-7899']]

redpajama_set_name: RedPajamaStackExchange


text:
Q: How are Akka messages ordered if messages are not reliable? I read that Akka messages are ordered in that between any two actors A and B, if A sends messages in order 1, 2, 3, 4, they must arrive in that order.
Also I read that Akka messages are not reliable.
How can these two things be true? If message arrives 1 and then 4 and then 3, but 2 was never delivered, then what happens?
http://doc.akka.io/docs/akka/snapshot/general/message-delivery-reliability.html

To clarify, if messages 1 2 3 and 4 exist and are sent in that order from actor A.
Lets consider these are points a), b), c) d).
a) At actor B, message 1 arrives.
b) Then at actor B message 4 arrives.
c) Then at actor B message 3 arrives.
d) Message 2 was lost.
At point a) I see no problem, actor B processes the message.
At point b) I see a problem, how can actor B process this message 4 because of message ordering rules, actor B is expecting message 2 to arrive. So I guess at this point actor B cannot process message 4 as message 4 cannot be processes before message 2.
At point c) message 3 has arrived, but we cannot process message 3 without message 2 due to ordering.
At point d) Message 2 has been lost.
So the actor B will only process message 1 and will not process messages 3 and 4, if I apply the rules as I understand them. Is my logic correct? Am I making an incorrect assumption here by assuming that messages could arrive at actor B in any order. However, if two actors are on the internet, shouldn't that be the case? If its fire-and-forget for the message?

A: As the documentation says, if actor A1 sends messages M1, M2 and M3 to actor A2, those messages will be delivered in that order *relative to messages sent from A1 to A2.  If A3 is also sending messages to A2, there is no guarantee regarding how the messages from A1 and A3 will be interleaved.  A message from A3 could arrive in-between two messages from A1.  Messages from A1 would still be in order relative to other messages from A1.
So in your example, (1, 4, 3) is guaranteed not to happen.  (1, 3, 4) is valid since any message can be dropped but if 3 is delivered, it's guaranteed to be delivered before 4.


text:
Q: Randomizing a simulation of a real die I want to simulate the 3D configuration of a real die. I know the sum of opposite faces equals 7 (top: 1 + bottom:6 = 7). Let's say the top face is 1, front is 5, right is 4, back is 2, left is 3 and bottom is 6, as this image suggests.
The real position matters for my code, so how do I randomize a die correctly? For example, if the randomized result top is 1 and the front is 5, then the right side has to be 4. It can't be 3, because in a real die, the 3 would be in the left.
The program have to randomize 2 adjacent faces, the others must be placed according to the 2 randomized adjacent faces.
Pseudocode is just fine, but if you can explain me just with text, I appreciate it too.

A: It's probably easiest to think in terms of the eight corners of the cube. Most of the time, there will be one corner closest to the viewer, and therefore the three faces around that corner will show. Occasionally two corners will be equally distant, so only two faces will show. Rarely (probably never if your viewing angle is not flat with the table) four corners will be equally distant and only one face will show.
Keep a pre-computed list indexed by cube vertex containing, for each, which three faces surround it, and which corner of each face. Then to roll, randomize the upper face, then randomize a rotation, and look up the faces in your table.
American dice have the ace, deuce, and trey clockwise around one corner with the line of the pips not pointing to that corner (so the pips kind of form a triangle around the corner). I don't know if the orientation of the six is standardized. Oriental dice are different.


text:
Q: Can't create share link using dropbox javascript sdk I'm trying to create a shareable link using dropbox api, but the function that I used doesn't return anything.
 var ACCESS_TOKEN = "access_token";
 var SHARED_LINK = "/example/example.doc";
 var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
 var x = dbx.SharingCreateSharedLink({path: SHARED_LINK});
 alert(x);

A: The Dropbox JavaScript SDK returns the API call results asynchronously, not in the return value of the method call.
You can see an example of how to set up the callbacks for the result and error, using then and catch, respectively, here:
https://github.com/dropbox/dropbox-sdk-js/blob/master/examples/javascript/basic/index.html#L54
So, for example, your code should look something like this:
var ACCESS_TOKEN = "access_token";
var filePath = "/example/example.doc";

var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
dbx.sharingCreateSharedLinkWithSettings({path: filePath})
.then(function(response) {
   console.log(response);
 })
 .catch(function(error) {
   console.log(error);
 });


text:
Q: meta box not display data input in the textarea I've had multiple errors with this metabox, first I thought Id fixed a undefined index error with the code below but now that doesn't appear my metabox doesn't save any data.
code before the error:
if ( !wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__)))
        return $post_id;

I tried adding the following to fix the undefined index error on line 108
 if ( !isset( $POST['excerpt_meta_box_nonce'] ) || !wp_verify_nonce($_POST['excerpt_meta_box_nonce'], basename(__FILE__)))
        return $post_id;

after adding this now any data I put in the metabox doesn't save.
any help would be appreciated
code for excerpt meta box
 <?php
// Add the Meta Box
function vs_add_excerpt_meta_box() {
    add_meta_box(
        'excerpt_meta_box', // $id
        'Excerpt Meta Box', // $title
        'vs_show_excerpt_meta_box', // $callback
        'post', // $page
        'normal', // $context
        'high'); // $priority
}
add_action('add_meta_boxes', 'vs_add_excerpt_meta_box');

// Field Array
$prefix = 'custom_';
$excerpt_meta_fields = array(
    array(
        'label' => 'Custom post teaser',
        'desc'  => 'Replace the default excerpt with the text of your choice',
        'id'    => $prefix.'excerpt',
        'type'  => 'textarea'
        )
);

// The Callback
function vs_show_excerpt_meta_box() {
global $excerpt_meta_fields, $post;
// Use nonce for verification
echo '<input type="hidden" name="excerpt_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';

    // Begin the field table and loop
    echo '
';
    foreach ($excerpt_meta_fields as $field) {
        // get value of this field if it exists for this post
        $meta = get_post_meta($post->ID, $field['id'], true);
        // begin a table row with
        echo '

                '.$field['label'].'
                ';
                switch($field['type']) {
                    // case items will go here
            // textarea
            case 'textarea':
                echo '<textarea name="'.$field['id'].'" id="'.$field['id'].'" cols="60" rows="4">'.$meta.'</textarea>

'.$field['desc'].'';
            break;

                } //end switch
        echo '
';
    } // end foreach
    echo '
'; // end table
}

// Save the Data
function vs_save_excerpt_meta($post_id) {
    global $excerpt_meta_fields;

    // verify nonce
    if ( !isset( $_POST['excerpt_meta_box_nonce'] ) || !wp_verify_nonce($_POST['excerpt_meta_box_nonce'], basename(__FILE__)))
        return $post_id;
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;
    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id))
            return $post_id;
        } elseif (!current_user_can('edit_post', $post_id)) {
            return $post_id;
    }

    // loop through fields and save the data
    foreach ($excerpt_meta_fields as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    } // end foreach
}
add_action('save_post', 'vs_save_custom_meta');
?>

A: Ok, you do have a typo :
add_action('save_post', 'vs_save_custom_meta');

should be :
add_action('save_post', 'vs_save_excerpt_meta');

So you meta box does not have a valid callback. Change this and it will work ^^


text:
Q: Math.Round() randomly skips rounding and removes decimal point I have a live side project that I've been building on for about six months. One page that you can see here allows the user to select two options where they can then select a number and it will display a second number that is calculated, and then rounded to the nearest whole number.  The React component that has the logic for this is as follows:
import React, {useEffect, useState} from 'react'

export default function RatingDifference({label_one, label_two, standard_deviation, currentLinearRegression}) {

    const [currentNumber, SetCurrentNumber] = useState(1500)

    useEffect(()=>{console.log(standard_deviation)},[standard_deviation])

    const handleChange = (e) => {
        SetCurrentNumber(e.target.value)
    }

    return (

                A rating of {' '}
                <input id='find-my-rating' type='number' onChange={handleChange} defaultValue={currentNumber}/>{' '}
                in {label_one} would equal{' '}

                {Math.round((currentLinearRegression.m*currentNumber)+currentLinearRegression.b)}{' '}
                in {label_two}, with an average variation of
                 plus/minus of{' '+ Math.round(standard_deviation)+' '} points.

      )
    }

Unfortunately, I frequently get users who complain that the the calculated number will display as the unrounded number, without a decimal. For example, the calculated number could be 1850.59 and then should be rounded to 1851 before rendering, but the component will instead display 18059. I have struggled to replicate this issue on my own, as when users see this, the issue goes away once they refresh the page. Would anyone be able to help me understand why this happens, and how to fix this issue?


text:
Q: How do I speed up this EF query? How do I speed up this EntityFramework query? The profiler tells me that most of the time is spent in od.Order with ~5000 calls.
var orderDetails = context.OrderDetails.ToList();

foreach (OrderDetail od in orderDetails)
{
   var date = od.Order.date;

   if (!trPerDay.ContainsKey(date))
   {
       trPerDay.Add(date, od.quantity);
   }
   else
   {
       trPerDay[date] += od.quantity;
   }
}

Order property is defined like this:
[MetadataType(typeof(OrderDetailMetaData))]
public partial class OrderDetail
{
   public int orderID { get; set; }

   public string productID { get; set; }

   public int quantity { get; set; }

   public bool upgraded { get; set; }

   public virtual Order Order { get; set; }

   public virtual Product Product { get; set; }
}

A: What you posted loads the entire OrderDetails table in a single query, from a single thread. Then it tries to lazily load each order which results in a separate call to the database.
It's far faster to let the database do the calculations and only load the final results.
In this case it seems the loop is trying to calculate the total order quantity per order date. The SQL query that produces this would be something like :
SELECT Date,SUM(details.Quantity)
FROM Orders inner join OrderDetails details
    on Orders.ID=details.OrderID
GROUP BY Orders.Date

The equivalent in LINQ can be :
var query=context.OrderDetails
                 .GroupBy(d=>d.Order.Date)
                 .Select(g=>new {
                     Date=g.Key,
                     Total=g.Sum(dt=>dt.Quantity)
                  });
var totals=await query.ToListAsync();

or
var totals=await query.ToDictionaryAsync(t=>t.Date,t=>t.Quantity)

In both cases, a GROUP BY query will be generated that calculates the totals by date.
This assumes that Date is what it says - a date. Either a date-typed field in the database, or a datetime without a time component. If it's actually a Date+Time, the query will have to be adjusted to use only the date part. Luckily, EF Core maps DateTime.Date to the equivalent SQL function call:
var query=context.OrderDetails
                 .GroupBy(d=>d.Order.Date)
                 .Select(g=>new {
                     Date=g.Key,
                     Total=g.Sum(dt=>dt.Quantity)
                  });


text:
Q: Update count every second causing massive memory problems Just on my local machine, trying the run the following script causes my computer to crash... What am I doing wrong?
            (function($) {
            var count = '6824756980';
            while (count > 0) {
                setInterval(function() {
                    $('#showcount').html(Math.floor(count-1));
                    count--;
                }, 1000 );
            }
        })(jQuery);

All I need to do is subtract one from the var "count" and update/display it's value every second.

A: what you are doing is setting up 6824756980 timers -> BAD
just do
 $(document).ready(function(){
    var count = 6824756980;
    var timerID = setInterval(function() {
             if(count > 0){
                $('#showcount').html(Math.floor(count-=1));
                count--;
             }
             else clearInterval(timerID);
    }, 1000 );
 });

A: In addition to count being a string instead of a number, you're spawning a very large number of Interval functions with while(count > 0) { setInterval ... }
If I understand, you should be checking for count > 0 inside the Interval function, since it runs every second.

A: Your setInterval is in the wrong place.
It's currently in the body of a while loop which will be looping as fast as your computer can go and each time firing of the function to increment the counter. No wonder it's eating resources.
You only need to call setInterval once.


text:
Q: KQL aggregation function product I'm having the following table:

productName
feature
probability_for _feature

A
w
0.2

A
z
0.8

B
w
0.2

B
z
0.8

B
x
0.3

I want to get for each productName the product of probability for it's feature meaning productName  A have both feature w with probability 0.2 and feature z with probability 0.8 hence the product for feature A will bee 0.2*0.8= 0.16.
Thus , in the table above I will get:

productName
features
probability_for _feature

A
[w,z]
0.16

B
[w,z,x]
0.048

Or just :

productName
probability

A
0.16

B
0.048

I didn't find any product or multiply function as aggregation function and would like to get some help .
Thank you !

A: Here's an option, using a cumulative sum and leveraging the fact that log(x1) + log(x2) … + log(xN) == log(x1 * x2 * … * xN):
datatable(productName:string, feature:string, probability_for_feature:double)
[
    'A', 'w', 0.2,
    'A', 'z', 0.8,
    'B', 'w', 0.2,
    'B', 'z', 0.8,
    'B', 'x', 0.3,
]
| order by productName asc
| extend l = log10(probability_for_feature), rn = row_number()
| extend cumsum = row_cumsum(l, productName != prev(productName))
| summarize arg_max(rn, *), features = make_list(feature) by productName
| project productName, features, product = exp10(cumsum)

productName
features
product

A
[  "w",  "z"]
0.16

B
[  "w",  "z",  "x"]
0.048

A: For aggregation with any function you can use the scan operator.
scan operator example cumulative sum
Example with multiply:
datatable (productName: string, feature: string, probability_for_feature: double)
[
        'A', 'w', 0.2,
        'A', 'z', 0.8,
        'B', 'w', 0.2,
        'B', 'z', 0.8,
        'B', 'x', 0.3,
]
| sort by productName asc
| partition by productName
(
    // for every productName scan all rows
    scan declare (probability: double= 1.0) with
    (
        // multiply probability for every row and return last result
        step s1 output=last: true => probability = probability_for_feature * s1.probability;
    )
)
| project productName, probability


text:
Q: DirectShow CSourceStream filter fails to unload properly I am writing a DirectShow capture filter using CSource / CSourceStream as a base but when I access the cam in Firefox + Flash, I get a debug assert and the following debug error when closing Firefox.
Cam6.ax(tid 1c98)   133506 :
Cam6.ax(tid 1c98)   133506 :    ID             Object Description
Cam6.ax(tid 1c98)   133506 :
Cam6.ax(tid 1c98)   133506 :    19 (001AE940)          Camera Stream
Cam6.ax(tid 1c98)   133507 :    18 (001AE940)                 Camera
Cam6.ax(tid 1c98)   133507 :     6 (001AE940)          Camera Stream
Cam6.ax(tid 1c98)   133507 :     5 (001AE940)                 Camera
Cam6.ax(tid 1c98)   133507 :
Cam6.ax(tid 1c98)   133507 : Total object count     4

From what I can tell this is not my fault. I suspect Flash is uncleanly discarding the DirectShow graph on shutdown. I have read and re-read the MSDN documentation and scoured the net for examples but turned up nothing.
Can anyone help clarify this for me or point me in the right direction?

A: Feeling a little silly about this. After spending a day looking at reference counts and whatnot, it turned out to be a noobie mistake. I compiled strmbasd.lib with the /MDd flag and my code with the /MD flag. The former was targeting the debug runtime libraries, the later the release runtime libraries.
The linker gave a warning which went unheeded and the code ran up until time to release the DLL. Go figure..
Chalk that one up to stupidity I guess. :)


text:
Q: AngularJS - Controller not working inside a diretive Im trying to get some variables or call some methods from a controller of a directive but it is not working.
I have imported all needed files injected everything needed.
If I use the same approach but I use templateUrl it is working but this is not, what am I doing wrong ?
Here is just some part of my code.
class Application {

    constructor($router, alertsHandlerService) {
        this.$router = $router;
        this.routing();
        this.alertsHandlerService = alertsHandlerService;
        console.log("app construct");

    }

    routing(){
        this.$router.config(
            {
                path: '/',
                component: {'main': 'main'} // view-name:component => name.html, NameController
            }
        );
    }

    skuska(){
        console.log("skuska called");
    }
}

Application.$inject = ['$router', 'alertsHandlerService'];

export default function() {
    return {
        scope: {},
        controller: Application,
        controllerAs: 'applicationCtrl'
    };
};

And my shortened html file
<html lang="en" ng-app="agenda" application class="no-js"> <!--<![endif]-->
<body>
{{ applicationCtrl.skuska() }}
</body>
</html>

A: You need to register the Application controller in your agenda module.
import Application from './path/to/controller/Application.js';
import applicationDirective from './path/to/directive/application.js';

Application.$inject = ['$router', 'alertsHandlerService'];

angular
    .module('agenda', []) // app dependencies
    .controller('ApplicationCtrl', Application)
    .directive('application', applicationDirective);

and then you just do
function applicationDirective () {

    return {
        restrict: 'A',
        controller: 'ApplicationCtrl',
        controllerAs: 'ctrl'
    };
}

export default applicationDirective;

and
class Application {

    constructor($router, alertsHandlerService) {
        this.$router = $router;
        this.routing();
        this.alertsHandlerService = alertsHandlerService;
        console.log("app construct");
    }

    routing(){
        this.$router.config(
            {
                path: '/',
                component: {'main': 'main'} // view-name:component => name.html, NameController
            }
        );
    }

    skuska(){
        console.log("skuska called");
    }
}

export default Application;

Something like this should work properly (not tested).


text:
Q: Density analysis with two polygons in ArcGIS Pro I'm a Norwegian student currently conducting a series of site analyzes for a city. In that context I wish to create a building density map but struggle a bit to find out how.
I have made a fishnet polygon of 50x50 meter and wish to find out how much built area there is in each of these squares. My goal is to color the squares according to how much percent of the squares are built area. Both the fishnet and the buildings are polygons and are editable. Please see the image.
Can anyone help me perform the analysis?

A: There are several ways how to do it. Many are already covered on this site as well.
Depending on licenses, you can use Summerize Within (Analysis) in ArcGIS Pro for this purpose.


text:
Q: MVC5 accessing Action/Controller with ActionResult gets skipped and produces "The resource cannot be found" error I have a MVC5 view that has a form on the page that submits to a background process in the /Account Controller. I have 4 others pages that are very similar with ActionResult but they just return a view without any other logic. Does anyone have any ideas on where I went wrong? Ive looked through several similar errors but none touch on what I am experiencing.
HTML/RAZOR FORM
                @using (Html.BeginForm("Process", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true)
                        <input placeholder="Card number" type="text" name="number" class="form-control">
                        <input placeholder="Full name" type="text" name="name" class="form-control">
                        <input placeholder="MM/YY" type="text" name="expiry" class="form-control">
                        <input placeholder="CVC" type="text" name="cvc" class="form-control">
                    }

CONTROLLER
    //POST: Process
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Process()
    {
        try
            {
                var myCustomer = new StripeCustomerCreateOptions();

                // set these properties if it makes you happy
                myCustomer.Email = "pork@email.com";
                myCustomer.Description = "Johnny Tenderloin (pork@email.com)";

                // set this property if using a token
                //myCustomer.TokenId = *tokenId*;

                // set these properties if passing full card details (do not
                // set these properties if you have set TokenId)
                myCustomer.CardNumber = "4242424242424242";
                myCustomer.CardExpirationYear = "2012";
                myCustomer.CardExpirationMonth = "10";
                myCustomer.CardAddressCountry = "US";                // optional
                myCustomer.CardAddressLine1 = "24 Beef Flank St";    // optional
                myCustomer.CardAddressLine2 = "Apt 24";              // optional
                myCustomer.CardAddressCity = "Biggie Smalls";        // optional
                myCustomer.CardAddressState = "NC";                  // optional
                myCustomer.CardAddressZip = "27617";                 // optional
                myCustomer.CardName = "Joe Meatballs";               // optional
                myCustomer.CardCvc = "1223";                         // optional

                //myCustomer.PlanId = *planId*;                          // only if you have a plan
                //myCustomer.Coupon = *couponId*;                        // only if you have a coupon
                myCustomer.TrialEnd = DateTime.UtcNow.AddMonths(1);    // when the customers trial ends (overrides the plan if applicable)
                myCustomer.Quantity = 1;                               // optional, defaults to 1

                var customerService = new StripeCustomerService();
                StripeCustomer stripeCustomer = customerService.Create(myCustomer);

                var myCharge = new StripeChargeCreateOptions();

                // always set these properties
                myCharge.Amount = 5153;
                myCharge.Currency = "usd";

                // set this if you want to
                myCharge.Description = "Charge it like it's hot";

                // set this property if using a token
                //myCharge.TokenId = *tokenId*;

                // set these properties if passing full card details
                // (do not set these properties if you have set a TokenId)
                myCharge.CardNumber = "4242424242424242";
                myCharge.CardExpirationYear = "2012";
                myCharge.CardExpirationMonth = "10";
                myCharge.CardAddressCountry = "US";               // optional
                myCharge.CardAddressLine1 = "24 Beef Flank St";   // optional
                myCharge.CardAddressLine2 = "Apt 24";             // optional
                myCharge.CardAddressState = "NC";                 // optional
                myCharge.CardAddressZip = "27617";                // optional
                myCharge.CardName = "Joe Meatballs";              // optional
                myCharge.CardCvc = "1223";                        // optional

                // set this property if using a customer
                myCharge.CustomerId = "E2G1";

                // if using a customer, you may also set this property to charge
                // a card other than the customer's default card
                //myCharge.Card = *cardId*;

                // set this if you have your own application fees (you must have your application configured first within Stripe)
                //myCharge.ApplicationFee = 25;

                // (not required) set this to false if you don't want to capture the charge yet - requires you call capture later
                myCharge.Capture = true;

                var chargeService = new StripeChargeService();
                StripeCharge stripeCharge = chargeService.Create(myCharge);

                return View("SignupPaySuccess", "Home");
            }
        catch
            {
                return View("SignupPayDecline","Account");
            }
    }

ERROR SCREEN

Thanks a ton for your help!
CSSHell

A: You need to indicate a parameter in your action method so that the router can correctly direct your 'post' to an action method with a parameter to bind the posted data.
If you create a model class like:
public class ProcessModel
{
   public string number {get; set;}
   public string name {get; set;}
   public string expiry {get; set;}
   public string cvc {get; set;}
}

and then change your action method signature from
public ActionResult Process()

to
public ActionResult Process(ProcessModel process)

the router should correctly identify the correct endpoint to route to.

A: Are you using areas? if so, try something like this:
Html.BeginForm("Process", "Account", new {area="name-of-the-area"})


text:
Q: How do I get a bidirectional arrow in XY with the barr option \documentclass{article}
\usepackage[cmtip,all,barr]{xy}
\begin{document}

This is a simplified diagram of data flow for LISTSERV. Note that for
IBM-MAIN the gateway to news is one way; replies to the group do not
propagate to LISTSERV.

\begin{figure}
\[
\bfig
\node browser(0,0)[    \textrm{User web browser}]
\node listserv(0,-500)[    \textrm{LISTSERV}]
\node usenet(1000,-500)[    \textrm{News server}]
\node news(2000,-500)[    \textrm{User news agent}]
\node smtp(0,-1000)[    \textrm{Mail gateway}]
\node imap(-1000,-1500)[    \textrm{IMAP4 server}]
\node user(0,-1500)[    \textrm{User mail agent}]
\node pop(1000,-1500)[    \textrm{POP3 server}]
\arrow |r|/{<-}>/[browser`listserv;HTTP]
%\arrow/{<->}/ |r|[browser`listserv;HTTP]
\arrow |r|[listserv`usenet;NNTP]
\arrow |r|[usenet`news;NNTP]
%\arrow/<->/ |r|[usenet`news;NNTP]
%\arrow/<->/ |r|[listserv`smtp;SMTP]
\arrow |r|[listserv`smtp;SMTP]
%\arrow |r|[smtp`imap]
%\arrow |r|[smtp`pop]
\arrow |a|[imap`user;IMAP4]
\arrow |r|[pop`user;POP3]
%\arrow |r|[user`SMTP]
\efig
\]
\end{figure}
\end{document}

I tried putting braces around the <-> but still got error messages, e.g.,
Runaway argument?
<->/ |r|[listserv`smtp;SMTP] \arrow |r|[listserv`smtp;SMTP] \arrow |a\ETC.
! File ended while scanning use of \arrowpp.
<inserted text>
                \par
<*> E:/temp/LaTeX/listserv.tex

A: This is not a direct answer, but I feel that you are not using the optimal tool for that. However, the syntax is very similar to the one of TikZ. So I just tried to translate your code to TikZ and also add a more TikZy version of the figure. And please forgive me if some arrows do not come with the heads you had in mind, but it will be straight forward to fix that. The first part of the code contains a dictionary between xy and TikZ, your original code is behind the %.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
%\usepackage[cmtip,all,barr]{xy}
\begin{document}

This is a simplified diagram of data flow for LISTSERV. Note that for
IBM-MAIN the gateway to news is one way; replies to the group do not
propagate to LISTSERV.

\begin{figure}
\begin{center} %\[
\begin{tikzpicture}[scale=0.35,thick,>=latex] %\bfig
\node (browser) at (0,0) {User web browser};%\node browser(0,0)[    \textrm{User web browser}]
\node (listserv) at (0,-5) {LISTSERV}; %\node listserv(0,-500)[    \textrm{LISTSERV}]
\node (usenet) at (10,-5) {News server}; %\node usenet(1000,-500)[    \textrm{News server}]
\node (news) at (20,-5) {User news agent}; % \node news(2000,-500)[    \textrm{User news agent}]
\node (smtp) at (0,-10) {Mail gateway}; %\node smtp(0,-1000)[    \textrm{Mail gateway}]
\node (imap) at (-12,-15) {IMAP4 server}; % \node imap(-1000,-1500)[    \textrm{IMAP4 server}]
\node (user) at (0,-15) {User mail agent}; % \node user(0,-1500)[    \textrm{User mail agent}]
\node (pop) at (10,-15) {POP3 server}; % \node pop(1000,-1500)[    \textrm{POP3 server}]
\draw[<-] (browser) -- (listserv) node[midway,right]{HTTP}; %\arrow |r|/{<-}>/[browser`listserv;HTTP]
%\arrow/{<->}/ |r|[browser`listserv;HTTP]
\draw[->] (listserv) -- (usenet) node[midway,below]{NNTP}; % \arrow |r|[listserv`usenet;NNTP]
\draw[<->] (usenet) --(news) node[midway,below]{NNTP}; % \arrow |r|[usenet`news;NNTP]
%\arrow/<->/ |r|[usenet`news;NNTP]
%\arrow/<->/ |r|[listserv`smtp;SMTP]
\draw[<->] (listserv)--(smtp) node[midway,right] {SMTP}; % \arrow |r|[listserv`smtp;SMTP]
%\arrow |r|[smtp`imap]
%\arrow |r|[smtp`pop]
\draw[->] (imap) -- (user) node[midway,above]{IMAP4}; % \arrow |a|[imap`user;IMAP4]
\draw[->] (pop) -- (user) node[midway,above]{POP3}; % \arrow |r|[pop`user;POP3]
\draw[->] (user) -- (smtp);%\arrow |r|[user`SMTP]
\end{tikzpicture} %\efig
\end{center}%\]
\caption{A Ti\emph{k}Z version of your figure.}\label{fig:1}
\end{figure}

\begin{figure}
\begin{center}
\begin{tikzpicture}[node distance=1.6cm,thick,>=latex]
\node (browser) at (0,0) {User web browser};
\node[below=of browser] (listserv) {LISTSERV};
\node[right=of listserv] (usenet) {News server};
\node[right=of usenet] (news) {User news agent};
\node[below=of listserv] (smtp) {Mail gateway};
\node[below=of smtp] (user)  {User mail agent};
\node[left=of user] (imap) {IMAP4 server};
\node[right=of user] (pop) {POP3 server};
\draw[<-] (browser) -- (listserv) node[midway,right]{HTTP};
\draw[->] (listserv) -- (usenet) node[midway,below]{NNTP};
\draw[<->] (usenet) --(news) node[midway,below]{NNTP};
\draw[<->] (listserv)--(smtp) node[midway,right] {SMTP};
\draw[->] (imap) -- (user) node[midway,above]{IMAP4};
\draw[->] (pop) -- (user) node[midway,above]{POP3};
\draw[->] (user) -- (smtp);
\end{tikzpicture}
\end{center}
\caption{A more Ti\emph{k}Zy version of figure~\ref{fig:1}.}
\end{figure}
\end{document}

A: The problem turns out to be a syntax error on the arrows; I had the label placement and the shape in the wrong order. This works:
\documentclass{article}
\usepackage[cmtip,all,barr]{xy}
\begin{document}

This is a simplified diagram of data flow for LISTSERV. Note that for
IBM-MAIN the gateway to news is one way; replies to the group do not
propagate to LISTSERV.

\begin{figure}
\[
\bfig
\node browser(0,0)[\textrm{User web browser}]
\node listserv(0,-500)[\textrm{LISTSERV}]
\node usenet(1000,-500)[\textrm{News server}]
\node news(2000,-500)[\textrm{User news agent}]
\node smtp(0,-1000)[\textrm{Mail gateway}]
\node imap(-1000,-1500)[\textrm{IMAP4 server}]
\node user(0,-1500)[\textrm{User mail agent}]
\node pop(1000,-1500)[\textrm{POP3 server}]
\arrow |r|/{<->}/[browser`listserv;HTTP]
\arrow |r|[listserv`usenet;NNTP]
\arrow |r|[usenet`news;NNTP]
\arrow |r|/<->/[usenet`news;NNTP]
\arrow |r|/<->/[listserv`smtp;SMTP]
\arrow |r|[smtp`imap;]
\arrow |r|[smtp`pop;]
\arrow |a|[imap`user;IMAP4]
\arrow |r|[pop`user;\textrm{POP3}]
\arrow |r|[user`smtp;\textrm{SMTP}]
\efig
\]
\end{figure}
\end{document}

Thanks.


text:
Q: How to compute $\lim_{x\to 0}\frac{e^x -1-x-\frac{x^2}{2}}{x^3}$ without using L'Hospital rule? Find the following limit without using L'Hospital rule nor series
$$\lim_{x\to 0}\frac{e^x -1-x-\frac{x^2}{2}}{x^3}$$
I tried to divide it into two limits such that one of the be
$$\lim_{x\to 0}\frac{e^x-x-1}{x^2}$$ because i know it solution but i could not do that ?

A: $e^x$ is a (log-)convex function, hence $e^x\geq 1+x$ holds for any $x\in\mathbb{R}$. By integrating both sides over the interval $(0,z)$ we get $e^z\geq 1+z+\frac{z^2}{2}$ for any $z>0$ and $e^z\leq 1+z+\frac{z^2}{2}$ for any $z<0$. Performing the same trick twice we get $e^{z}\geq 1+z+\frac{z^2}{2}+\frac{z^3}{6}+\frac{z^4}{24}$ for any $z>0$ and the converse inequality for any $z<0$. By squeezing, the wanted limit equals $\frac{1}{6}$.

A: My attempt of the general case :|
$$\lim_{x\rightarrow 0} \frac{e^{x}-\sum\limits^{p-1}_{k=0}\frac{x^{k}}{k!}}{x^{p}}= \frac{1}{p!}. $$
Using the definition $e^{x}= \lim_{n \rightarrow \infty} (1+\frac{x}{n})^n$.
we will work the expression
$$(1+\frac{x}{n})^n-\sum\limits^{p-1}_{k=0}\frac{x^{k}}{k!}= $$
for $n>p$, expand $(1+\frac{x}{n})^n$ by the binomial
$$=\sum_{k=0}^{n}{n \choose k}(\frac{x}{n})^k -\sum\limits^{p-1}_{k=0}\frac{x^{k}}{k!}=\underbrace{\sum_{k=0}^{p-1}{n \choose k}(\frac{x}{n})^k + {n \choose p}(\frac{x}{n})^p+\sum_{k=p+1}^{n}{n \choose k}(\frac{x}{n})^k}_{\sum\limits_{k=0}^{n}{n \choose k}(\frac{x}{n})^k} -\sum\limits^{p-1}_{k=0}\frac{x^{k}}{k!} =$$
$$=\sum_{k=0}^{p-1}x^{k}\underbrace{({n \choose k}\frac{1}{n^{k}}-\frac{1}{k!})}_{\rightarrow 0} +\underbrace{{n \choose p}(\frac{x}{n})^p}_{\rightarrow  \frac{x^p}{p!}}+\sum_{k=0}^{n-p-1}{n \choose k+p+1}(x)^{k+p+1}\frac{1}{n^{k+p+1}} =$$
we have  $\lim_{n \rightarrow \infty} {n \choose k}\frac{1}{n^{k}} =\lim_{n \rightarrow \infty}  \frac{1}{k!} (\frac{n}{n})\cdots (\frac{n-k+1}{n})= \frac{1}{k!}$, (every factor has limit 1) so as we take $n \rightarrow \infty $ in the first sum the resultant is zero, dividing the expression by  $x^p$ and applying the limit we have
$$ \lim_{x \rightarrow 0} \lim_{n \rightarrow \infty} \frac{1}{p!} +\sum_{k=0}^{n-p-1}{n \choose k+p+1}(x)^{k+1}\frac{1}{n^{k+p+1}} = $$
changing the order of the limits
$$ \lim_{n \rightarrow \infty}  \lim_{x \rightarrow 0} \frac{1}{p!} +\sum_{k=0}^{n-p-1}{n \choose k+p+1}\underbrace{(x)^{k+1}}_{\rightarrow 0}\frac{1}{n^{k+p+1}}  = \frac{1}{p!}$$
so
$$\lim_{x\rightarrow 0} \frac{e^{x}-\sum\limits^{p-1}_{k=0}\frac{x^{k}}{k!}}{x^{p}}= \frac{1}{p!}. $$

A: If the limit exists, let it be $L$, by the change of variable $x\to-x$ and taking the average,
$$L=\lim_{x\to0}\frac{e^x-1-x-\dfrac{x^2}2}{x^3}=\lim_{x\to0}\frac{e^{-x}-1+x-\dfrac{x^2}2}{-x^3}=\lim_{x\to0}\frac{\sinh x-x}{x^3}.$$
Now with $x\to3x$, and using $\dfrac{\sinh x}x\to1^*$,
$$L=\lim_{x\to0}\frac{\sinh 3x-3x}{27x^3}=\lim_{x\to0}\frac{3\sinh x+4\sinh^3x-3x}{27x^3}=\frac19L+\frac4{27}.$$
Hence,
$$L=\frac16.$$

$^*$With the same trick,
$$\lim_{x\to0}\frac{e^x-1}x=\lim_{x\to0}\frac{e^{-x}-1}{-x}=\lim_{x\to0}\frac{\sinh x}x=1.$$

A: It's basically the LH's rule, but not the simple application of it:
$$\lim_{x \to 0}\frac{e^x-1-x-\frac{x^2}{2}}{x^3}$$
Let's call $e^x-x-\frac{x^2}{2}:=f(x)$, so:
$$\lim_{x \to 0}\frac{f(x)-1}{x^3}=\lim_{x \to 0}\frac{f(x)-f(0)}{x^3-0}=\lim_{x \to 0}\frac{f(x)-f(0)}{x^3-0^3}=\lim_{x \to 0}\frac{f(x)-f(0)}{x^3-0^3}\cdot\frac{\frac{1}{x-0}}{\frac{1}{x-0}}=\lim_{x \to 0}\frac{\frac{f(x)-f(0)}{x-0}}{\frac{x^3-0^3}{x-0}}=\frac{\lim\limits_{x \to 0}\frac{f(x)-f(0)}{x-0}}{\lim\limits_{x \to 0}\frac{x^3-0^3}{x-0}}\stackrel{def}{=}\frac{f'(0)}{(x^3)'(0)}=\lim_{x \to 0} \frac{e^x-1-x}{3x^2}$$
And doing it again 2 times you can get:
$$\lim_{x \to 0} \frac{e^x}{6}=\frac{1}{6}$$
Or using $\lim\limits_{x \to 0}\frac{e^x-1-x}{x^2}$ :
$$f(x):=\left\{
 \begin{array}{ll}
  \frac{e^x-1-x}{x^2}  & \mbox{if } x \neq 0 \\
  \frac{1}{2} & \mbox{if } x =0
 \end{array}
\right.$$
Now your limit can be rewritten this way:
$$\lim\limits_{x \to 0}\frac{f(x)-f(0)}{x}=\lim\limits_{x \to 0}\frac{f(x)-f(0)}{x-0}\stackrel{def}{=}f'(0)=\lim_{x \to 0} \frac{e^x(x-2)+x+2}{x^3}$$
So:
$$A:=\lim_{x \to 0} \frac{e^x(x-2)+x+2}{x^3}$$
$$B:=\lim_{x \to 0}\frac{e^x-1-x-\frac{x^2}{2}}{x^3}$$
From this:
$$A+2B=\lim_{x \to 0}\frac{(x-2)e^x +x+2+2\left(e^x-1-x-\frac{x^2}{2}\right)}{x^3}=\lim_{x \to 0}\frac{x\left(e^x-x-1\right)}{x^3}=\lim_{x \to 0} \frac{e^x-1-x}{x^2}=\frac{1}{2}=3\lim_{x \to 0}\frac{e^x-1-x-\frac{x^2}{2}}{x^3}$$
So:
$$\lim_{x \to 0}\frac{e^x-1-x-\frac{x^2}{2}}{x^3}=\frac{1}{6}$$


text:
Q: The hyperref package breaks AUCTeX preview with two different journal style files The following LaTeX MWE compiles, but AUCTeX preview does not work. This file tests for two different journal style files. One is Bayesian Analysis, the other is Oxford Bioinformatics (links are to the LaTeX files for each journal). To switch between them, comment/uncomment the relevant lines at the top of the file.
Removing the hyperref package fixes the problem.
This is on Debian wheezy with AUCTeX 11.87 and both emacs 23.4.1 and emacs 24.3.1. Someone else tried it on Gentoo with auctex 11.87.2 emacs 24.3.1 and he said preview worked OK.
To start with, can anyone reproduce this? If so, do you have any idea what the problem might be? The Debian AUCTeX package is upstream with a few harmless looking patches added. I guess I could try without the patches.
% Comment/uncomment to switch between Bayesian Analysis and Bioinformatics.
\def\ba{}
%\def\bio{}

\ifdefined\ba
\documentclass[bib]{ba}
\else\ifdefined\bio
\documentclass{bioinfo}
\fi\fi

\usepackage{hyperref}
\begin{document}

$x=1$

\end{document}


text:
Q: Declare a new Text Object in Google Script I'm trying to declare a new Text object in Google script so that I can use the methods shown in the following: https://developers.google.com/apps-script/reference/document/text.
However, when I use the syntax style shown in http://www.w3schools.com/js/js_object_definition.asp, it doesn't work out for me.
What is the syntax for declaring a new Text object and assigning it a string value?
Thank you,
Nicholas Kincaid

A: You are trying to mix things that can't be mixed.
The text Class you refer to is an element of the document class that belongs to the DocumentApp Service.
All the elements of the DocumentApp Service have only specific methods that are described in the documentation.
It is true that Google Apps Script is based on JavaScript and that you can create objects, assign and read their properties, build function and about whatever you want but you can't create classes that belong to Google service without using Google services ! (this applies to Spreadsheets, documents, drive files, calendars etc...
Hoping I was clear enough.


text:
Q: Deduction of the type of a nested template variadic non-type list Consider the following classes:
template<class T, int...> struct MyClass1 {};
template<class T, unsigned int...> struct MyClass2 {};
template<class T, long long int...> struct MyClass3 {};
template<class T, unsigned long long int...> struct MyClass4 {};

I cannot modify these classes.
Is it possible to write an helper class or function or something, that will return the type of the variadic list:
something<MyClass1>::type (-> int)
something<MyClass2>::type (-> unsigned int)
something<MyClass3>::type (-> long long int)
something<MyClass4>::type (-> unsigned long long int)

and size_t if the variadic list is empty ?

A: I couldn't come up with a way to define one generic metafunction that does it, but here is a possible workaround:
#include <iostream>
#include <type_traits>

using namespace std;

// PRIMARY TEMPLATE

template<typename T>
class something
{
};

// SPECIALIZATIONS FOR int

template<typename T, int... U, template<typename, int...> class L>
class something<L<T, U...>>
{
public:
    typedef int type;
};

template<typename T, template<typename, int...> class L>
class something<L<T>>
{
public:
    typedef size_t type;
};

// SPECIALIZATIONS FOR unsigned int

template<typename T, unsigned int... U, template<typename, unsigned int...> class L>
class something<L<T, U...>>
{
public:
    typedef unsigned int type;
};

template<typename T, template<typename, unsigned int...> class L>
class something<L<T>>
{
public:
    typedef size_t type;
};

/* ... OTHER SPECIALIZATIONS ... */

struct A {};
struct B {};

int main()
{
    static_assert(is_same<something<MyClass1<A, 1, 2>>::type, int>::value, "Error!");
    static_assert(is_same<something<MyClass1<A>>::type, size_t>::value, "Error!");
    static_assert(is_same<something<MyClass2<B, 1U, 2U, 3U>>::type, unsigned int>::value, "Error!");
    static_assert(is_same<something<MyClass2<B>>::type, size_t>::value, "Error!");
    return 0;
}

I tried to write only single specialization that would cover all cases, like this:
template<typename U, typename T, U... V, template<typename, U...> class L>
class something<L<T, V...>>
{
public:
    typedef U type;
};

But Clang 3.2 complains that the type of U cannot be deduced, so this specialization of get_type will never be used. So if you follow this approach you will have to explicitly define each specialization. This may or may not be acceptable depending on your use cases. Hope it helps.


text:
Q: how to install cms, south, mptt, mptt? I am trying to integrate django-cms with my project and getting these errors
No module named cms

No module named south

No module named menu

No module named mptt

A: use pip.
https://pypi.python.org/pypi/pip
after installing:
pip install south

etc.

A: Try using
pip install django-cms

to install django-cms. This will install all the required dependecies by default.


text:
Q: postgres reverse jsonb array Postgres 13
I have a table with jsonb array and I need to revert the array. Any idea on how I can do that?
CREATE OR REPLACE FUNCTION array_reverse(anyarray) RETURNS anyarray AS $$
SELECT ARRAY(
    SELECT $1[i]
    FROM generate_subscripts($1,1) AS s(i)
    ORDER BY i DESC
);
$$ LANGUAGE 'sql' STRICT IMMUTABLE;

create table route (
   session_id serial primary key,
   name varchar(20),
   data jsonb
);

insert into route(name, data)
VALUES('NY-LA',
'["{\"x\":40.83382,\"y\":-75.051552}", "{\"x\":33.740055,\"y\":-118.199982}"]'
);

insert into route(name, data)
VALUES('NY-CH',
'["{\"x\":40.83382,\"y\":-75.051552}", "{\"x\":39.740055,\"y\":-90.199982}"]');

SELECT * FROM route;

What I need is to revert the column data. E.g. select data->0->'x' from route where id = 1; returns 39.740055. I found array_reverse() function suggested by Postgres, but do not understand how to convert jsonb into ARRAY so that I can use array_reverse(array) function.
Thank you.

A: anyarray means any SQL-level array.  It does not cover the JSONB subtype.  You will need a function specifically for that:
CREATE OR REPLACE FUNCTION array_reverse(jsonb) RETURNS jsonb AS $$
SELECT jsonb_agg(value order by ordinality desc)
    FROM jsonb_array_elements($1) with ordinality;
$$ LANGUAGE 'sql' STRICT IMMUTABLE;


text:
Q: Getting data from firebase I am trying to retrieve data from firebase I have checked code many times but when it runs the app crashes and return to the main activity
void getdata()
{
    String string;
     DatabaseReference mDatabase;
     FirebaseAuth mAuth;
     FirebaseDatabase firebaseDatabase;
     mAuth = FirebaseAuth.getInstance();
     firebaseDatabase= FirebaseDatabase.getInstance();
     string=mAuth.getCurrentUser().getUid();
   mDatabase=firebaseDatabase.getReference().child("Users").child(string);
    mDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            email=dataSnapshot.child("email").getValue().toString();
            name=dataSnapshot.child("name").getValue().toString();
            tvHeaderName.setText(email);
            tvFooterName.setText(name);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(Home.this,databaseError.getCode(), Toast.LENGTH_SHORT).show();
        }
    });
}

It should set email and name on
tvHeaderName.setText(email);

tvFooterName.setText(name);

NOTE: I had declared the tvFooterName and tvHeaderName globally;


text:
Q: Show a Geofield as a map field from an entity reference For several days I have been looking for a way to display in a content, field "field_geofield" from other content.
To explain, I first have a "lieu" content containing the field Geofield. There is also another "Reunion" content where there is a field of reference to an entity "field_lieu".
I would like to display in my template not a link to "lieu", but the map that is displayed in the "place" content. For the "lieu" content, I have to download the modules and libraries for leaflet which allowed me to display the map correctly.
Nevertheless, when I use this in "Reunion" : {{ node.field_lieu.0.entity.field_geofield.0.value }}
The map is not displayed but only the value of the long and the lat (example: POINT(1.080064 49.428707) )
Any idea?
Sorry for my approximate English, I am a French student.
Thank you in advance !


text:
Q: How to record a macro in sublime text 2? I am using sublime text 2 and want to record a macro for uploading the current file vie transmit docsend (super+u) and saving it locally (super+s).
So I start to record a macro ctrl+q and see the status notification in the footer
Starting to record macro ...

Then I hit super+s and it saves and the upload it vie super+u. After hitting ctrl+q for stopping macrorecording the footer says
Stopping recording macro

But I do not have the Option in the menu "Tools/Playback macro" and when I hit save Macro it doesnt do anything.
Any Idea?
PS: I am working on OS X and I have no directory
/Library/Application\ Support/Sublime\ Text\ 2

Have I to create it as admin?
Thanks a lot
Now I realized that I dont need the folder /Library... but ~/Library...
But after saving the File ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/User/transmit-upload-and-save.sublime-macro
[
{"command": "save"},
{"command": "transmit_docksend"}
]

and adding the following to user shortcuts
[
{ "keys": ["super+u"], "command": "run_macro_file", "args": {"file": "Packages/User/transmit-upload-and-save.sublime-macro"} }
]

it does not save but uploads ... whats wrong?

A: To simply playback last recorded Macro press Ctrl+Shift+q.
In Sublime Text2 Macros are not saved to file by default they reside in the macro buffer instead.  More here
The reason it's uploading is because your key is only defined as [super+u] which is for upload - it should be [super+s] for save.
Hope that helps


text:
Q: Finding Document Root I can browse the company intranet site using the following URL.
http://192.168.1.2/admin/index.php
How do I find the full path of the file "index.php"?
I tried...
locate admin/index.php

and it gave me a lot of results from different directories. What I need to do is to make some changes to index.php file.
I searched for httpd.conf and again I found several files in different locations.

A: Using grep -i 'DocumentRoot' <Location of your config file> you can find the DocumentRoot location.
Source

A: Since you're talking about httpd.conf I presume you're running apache.
By default the main httpd.conf file is /etc/apache2/httpd.conf or
/etc/apache/httpd.conf
If you type locate httpd.conf you should get some results there.
Now if you locate that file open it up and look at it.
You should find either some includes and other paths or some virtual hosts.  You might be lucky and see DocumentRoot in there.  Often this is in another file but at least this file provides a starting point.


text:
Q: Create dictionary by multiplying other dictionary in Python I've got a dictionary with variables:
variables = {
    'a': ['x','y','z'],
    'b': [1,2,3,4],
    'c': ['xx','yy','zz']
}

and for each potential combination of variables, I would like to make a separate scenario, like so:
scenarios = {
    1: {a: 'x', b: 1, c: 'xx'},
    2: {a: 'y', b: 1, c: 'xx'},
    3: {a: 'z', b: 1, c: 'xx'},
    4: {a: 'x', b: 2, c: 'xx'},
    5: {a: 'y', b: 2, c: 'xx'},
    6: {a: 'z', b: 2, c: 'xx'},
    7: {a: 'x', b: 3, c: 'xx'},
    8: {a: 'y', b: 3, c: 'xx'},
    9: {a: 'z', b: 3, c: 'xx'},
    .. }

How to do this?

A: You can use a nested dictionary combination with zip, enumerate, and itertools.product.
>>> {i: {n: v for n, v in zip(names, p)}
...  for names, values in [zip(*variables.items())]
...  for i, p in enumerate(itertools.product(*values), start=1)}
...
{1: {'a': 'x', 'b': 1, 'c': 'xx'},
 2: {'a': 'x', 'b': 2, 'c': 'xx'},
 3: {'a': 'x', 'b': 3, 'c': 'xx'},
 ...
 36: {'a': 'z', 'b': 4, 'c': 'zz'}}

This generates the items in a different order, though. If you want your exact order, you can reversed-sort the items before calculating the product:
>>> {i: {n: v for n, v in zip(names, p)}
...  for names, values in [zip(*sorted(variables.items(), reverse=True))]
...  for i, p in enumerate(itertools.product(*values), start=1)}
...
{1: {'a': 'x', 'b': 1, 'c': 'xx'},
 2: {'a': 'y', 'b': 1, 'c': 'xx'},
 3: {'a': 'z', 'b': 1, 'c': 'xx'},
 ...

Both will work with any number of variables.

A: You can easily iterate through all combinations with nested for-loops.
variables = {
  'a': ['x','y','z'],
  'b': [1,2,3,4],
  'c': ['xx','yy','zz']
}

# New dict
scenarios = {}
i = 0

# iterates through all values of each dict item
for a_value in variables['a']:
  for b_value in variables['b']:
    for c_value in variables['c']:
      scenarios[i] = {'a': a_value, 'b': b_value, 'c' : c_value}
      i += 1

To check that this produces the desiered outcome you can run the following:
for key in sinarios:
  print(key, sinarios[key])

A: You can use itertools and string for a short solution:
import itertools
from string import ascii_lowercase as l
variables = {
'a': ['x','y','z'],
'b': [1,2,3,4],
'c': ['xx','yy','zz']
}
new_vars = {i:dict(zip(l[:3], a)) for i, a in enumerate(itertools.product(*[variables[i] for i in l[:3]]), start=1)}

Output:
{1: {'a': 'x', 'c': 'xx', 'b': 1}, 2: {'a': 'x', 'c': 'yy', 'b': 1}, 3: {'a': 'x', 'c': 'zz', 'b': 1}, 4: {'a': 'x', 'c': 'xx', 'b': 2}, 5: {'a': 'x', 'c': 'yy', 'b': 2}, 6: {'a': 'x', 'c': 'zz', 'b': 2}, 7: {'a': 'x', 'c': 'xx', 'b': 3}, 8: {'a': 'x', 'c': 'yy', 'b': 3}, 9: {'a': 'x', 'c': 'zz', 'b': 3}, 10: {'a': 'x', 'c': 'xx', 'b': 4}, 11: {'a': 'x', 'c': 'yy', 'b': 4}, 12: {'a': 'x', 'c': 'zz', 'b': 4}, 13: {'a': 'y', 'c': 'xx', 'b': 1}, 14: {'a': 'y', 'c': 'yy', 'b': 1}, 15: {'a': 'y', 'c': 'zz', 'b': 1}, 16: {'a': 'y', 'c': 'xx', 'b': 2}, 17: {'a': 'y', 'c': 'yy', 'b': 2}, 18: {'a': 'y', 'c': 'zz', 'b': 2}, 19: {'a': 'y', 'c': 'xx', 'b': 3}, 20: {'a': 'y', 'c': 'yy', 'b': 3}, 21: {'a': 'y', 'c': 'zz', 'b': 3}, 22: {'a': 'y', 'c': 'xx', 'b': 4}, 23: {'a': 'y', 'c': 'yy', 'b': 4}, 24: {'a': 'y', 'c': 'zz', 'b': 4}, 25: {'a': 'z', 'c': 'xx', 'b': 1}, 26: {'a': 'z', 'c': 'yy', 'b': 1}, 27: {'a': 'z', 'c': 'zz', 'b': 1}, 28: {'a': 'z', 'c': 'xx', 'b': 2}, 29: {'a': 'z', 'c': 'yy', 'b': 2}, 30: {'a': 'z', 'c': 'zz', 'b': 2}, 31: {'a': 'z', 'c': 'xx', 'b': 3}, 32: {'a': 'z', 'c': 'yy', 'b': 3}, 33: {'a': 'z', 'c': 'zz', 'b': 3}, 34: {'a': 'z', 'c': 'xx', 'b': 4}, 35: {'a': 'z', 'c': 'yy', 'b': 4}, 36: {'a': 'z', 'c': 'zz', 'b': 4}}


text:
Q: In iOS app ,can i copy bundle resources to sandbox's tmp directory with XCode? i want to copy some files to the app's tmp directory when the xcode package the app , so when the user install the app , the files is be put in the tmp directory already , but in xcode 's copy bundle resources , the files can't be copied to the tmp directy , is there anyway to achive this?

A: From your question, I understand that you're trying to make several files be put in the tmp directory at app install time.
Unfortunately, that is not possible. The iOS creates 3 containers upon an app installation as mentioned here.

*

*Bundle Container: This is where the app gets installed

*Data Container: Creates 3 separate folders where the app can store data

*iCloud Container: Where iCloud specific data can be saved

Workaround

You can simply check every time the app launches to see if it's the first time the app launches and manually copy the files to your destination. You can use a Boolean in your app's NSUserDefaults to check whether the app was installed before.


text:
Q: How to dynamically add view in page or layout I can't figure out how to programatically add a view into a layout or page.
I need to add views at runtime without using static xml declaration since i need to fetch them from an http requested object... . I didn't find useful informations in the docs.
Anyone knows how to do?

A: I think you meant to dynamically add some view / controls to the page rather than to navigate into another page.
If so, you just need to add some controls into one of the layouts in your page (only containers [=layouts] can have multiple children.
so, your code (viewmodel/page controller) would look something like:
var layout = page.getViewById("Mycontainer");
// create dynamic content
var label = new Label();
label.text = "dynamic";
// connect to live view
layout.addChild(label)

A: In addition to having a page included inside your app (normal); you download the xml, css, & js to another directory and then navigate to it by then doing something like page.navigate('downloaded/page-name');
you can also do
var factoryFunc = function () {
    var label = new labelModule.Label();
    label.text = "Hello, world!";
    var page = new pagesModule.Page();
    page.content = label;
    return page;
};

topmost.navigate(factoryFunc);

https://docs.nativescript.org/navigation#navigate-with-factory-function

A: You should check out this thread on the {N} forum.
The question is about dynamically loading a page and module from a remote server. The (possible) solution is given in this thread.


text:
Q: External entry point C++ (lib or dll) I wondered if it was possible to create an entry point (main or winmain) in an library of some sorts. I'm trying to write a window manager code and I'd like to have the main function in a library with the application specific files just defining a few external functions called by winmain (such as extern render() or extern refresh())
I tried to do this on my own, but I'm getting an error of the entry point not being defined.

A: You can specify exports from your DLL using a Module-Definition file in your project.

A: I just spend the last couple of days trying to figure out this for myself and got lucky.
note I only tried this for static libraries (.lib)
The thing with .lib files is that they only get used and connected to your project if you call a function of the library.
now the problem with a minimal project is that you will only have a main function.
But this isn't called by your project so how is it connected with it then?
My solution, might not be that elegant but it works for me:
create a LibConnection.h where you include the lib.h and call one dummy function from you lib.cpp.
The bad part, in my opinion, is that you have to include your lib.h and your Connectionlib.h to your project files.
like this:
//Lib.h
void ConnectionFunction();

//Lib.cpp
int main(int argc, char* argv[])
{
    //do some stuff
}

//This function doesn't do anything but it is important
//that you define it in your lib.h and declare it in your lib.cpp
void ConnectionFunction()
{
}

now you have a basic library and have to create a connection file
like this:
//LibConnection.h
#include "Lib.h"
//now we call the connectionfunction
//remember non of this get really called but it makes possible connecting with your
//almost empty library
void Dummy()
{
     ConnectionFunction();
}

and then in you empty project:
//testapp.cpp
#include "LibConnection.h"
//remember to include the lib.h and the libconnection.h into your project files

void Foo()
{
    //this function doesn't get called but your project is running!
}

Hope this helps :)


text:
Q: In react-admin , while creating dynamic resources - useLocation and useHistory hooks are not working In React-admin , I am implementing dynamic resource
this file return my resource as object ,
In this component react-router-dom hooks giving error and undefined
import React from "react";
import { useLocation, useHistory } from "react-router-dom";
import RoomList from "../components/Room";

const AdminResources = () => {
  const [resourceToBeLoaded, setResourceToBeLoaded] = React.useState("");
  const location = useLocation();
  const history = useHistory();
  const resourceName = location?.pathname;
  let id = "";
  console.log(history, location);
  if (resourceName) {
    const roomId = resourceName.split("/")[2];
    id = roomId;
  }
  console.log(id, resourceName);

  React.useEffect(() => {
    const obj = {
      [`/room/${id}`]: {
        name: `room/${id}`,
        list: RoomList,
      },
    };
    if (obj[resourceName]) {
      setResourceToBeLoaded(obj[resourceName]);
    }
  }, [resourceName, id]);
  console.log(resourceToBeLoaded, "BEFORE SENDING");
  return resourceToBeLoaded;
};

export default AdminResources;

my app.js
import React from "react";
import { Admin, Resource } from "react-admin";

import MyLoginPage from "./pages/MyLoginPage";
import HomePage from "./pages/HomePage";
import customRoutes from "./customRoutes";
import MyLayout from "./components/Layout/MyLayout";

import ClassroomPage from "./pages/ClassroomPage";

import authProvider from "./utils/authProvider";
import dataProvider from "./utils/dataProvider";
import AdminResources from "./AdminResources";

function App() {
  return (
    <Admin
      dashboard={HomePage}
      loginPage={MyLoginPage}
      customRoutes={customRoutes}
      authProvider={authProvider}
      layout={MyLayout}
      dataProvider={dataProvider("http://localhost:5000/org")}
      disableTelemetry
    >
      <Resource name="classroom" {...ClassroomPage} />
      {AdminResources && <Resource {...AdminResources()} />}

    </Admin>
  );
}

export default App;

ERROR :-
hooks.js:29 Uncaught TypeError: Cannot read properties of undefined (reading 'location') at useLocation (hooks.js:29) at AdminResources (index.js:8) at App (App.js:35)

A: Looking at your example code made me realize what I did wrong myself. The way you have written the component useLocation will be called outside the scope of the <Admin> component. The Admin component supplies the context needed for that hook.
So bellow is how I would change your code to fix that particular issue. However, I didn't understand the intention of the code in AdminResources so I left that out. Felt out of scope for the useLocation issue.
const AdminResources = () => {
  const [resourceToBeLoaded, setResourceToBeLoaded] = React.useState(null);
  const location = useLocation();
  const history = useHistory();
  const resourceName = location?.pathname;
  /* ... TODO populate resourceToBeLoaded ... */
  return resourceToBeLoaded ? <Resource {...resourceToBeLoaded} /> : null;
};

function App() {
  return (
    <Admin
      dashboard={HomePage}
      loginPage={MyLoginPage}
      customRoutes={customRoutes}
      authProvider={authProvider}
      layout={MyLayout}
      dataProvider={dataProvider("http://localhost:5000/org")}
      disableTelemetry
    >
      <Resource name="classroom" {...ClassroomPage} />
      <AdminResources />

    </Admin>
  );
}

(I realize this is very old but hope it will help next person who ends up here.)


text:
Q: Unable to set a default image conditionally based on ThisItem value I'm using SQL Server IMAGE field type to store an image for a record.  I set the Image attribute like so:
If(IsBlank(ThisItem.VisitorImage), 'full+pink+stroke+small+cropped (1)', ThisItem.VisitorImage)
If I set the image just to 'full+pink+stroke+small+cropped (1)' it works fine, so the image reference itself is fine.  But none of my records have an IMAGE value yet, the database just shows null, and I want to display a default.  How can I check for a blank/null IMAGE to display a default?
This also doesn't give me what I want.
Coalesce(ThisItem.VisitorImage, 'full+pink+stroke+small+cropped (1)')

A: Currently it is not possible to check, in Power Apps, if a SQL Server image is null (I'll create a bug with the product team to fix that). There are a couple of options you have:

*

*Add a second image control with the 'full+pink+stroke+small+cropped (1)' image, and reorder it so that it lies behind the image control with the actual image; if there is no image in the row, then it won't show anything, and the backup image will be shown.

*

*This may not work well if the image has transparent pixels

*Add a new column in the SQL table, that tells whether it has an image or not. Something along the lines of ALTER TABLE <tableName> ADD HasVisitorImage AS IIF(VisitorImage IS NULL, 0, 1), and use this new column to choose whether to show the original or backup image: If(ThisItem.HasVisitorImage, ThisItem.VisitorImage, 'full+pink+stroke+small+cropped (1)')


text:
Q: How to Fix MAVEN ERROR: The JAVA_HOME environment variable is not defined correctly, this environment variable is needed to run this program I am unable to get apache maven to run locally on my Windows OS & I'm not sure why. I have mapped the system environmental variables as follows & am still receiving an error when I run command mvn --version using my command prompt:
The JAVA_HOME environment variable is not defined correctly,
this environment variable is needed to run this program.

Can anyone tell me what I am missing in terms of successfully updating my system environmental variables so that I can run maven builds? Please see screenshots of how my system environmental variables & system path variables are configured:

Thank you!

A: Figured it out - Turns out the users did not have permissions to access the Maven OR Java JDK folders. Updated the permissions & had no issues. Thank you!


text:
Q: TikZ: How to define the level spacing between node children? In this MWE, is there anyway to automatically set the spacing between the second parent children instead of this manual approach
first/.style={level distance=6ex},
second/.style={level distance=12ex},
third/.style={level distance=18ex},

?
\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{arrows.meta,positioning,calc,trees}

\begin{document}
\pagestyle{empty}
\def\gap{10mm}

\begin{tikzpicture}[
        node distance = 18mm and \textwidth/3,
        on grid,
        font = \sffamily,
        line/.style = {draw, -Latex,black},
        rbox/.style = {draw=blue!80!black, fill=blue!20,
            rounded corners, inner sep=2mm,
            text width=(\textwidth-6*\gap)/3, align=center},
        grandchild/.style={grow=down,xshift=+2em,anchor=west,edge from parent path={ [line] ([xshift=0,yshift=0em]\tikzparentnode.south) |- (\tikzchildnode.west)}},
        first/.style={level distance=6ex},
        second/.style={level distance=12ex},
        third/.style={level distance=18ex},
    ]

    \node (Grandparent)   [rbox] {Grandparent};

    \node (1stparent)  [rbox,below  left=of Grandparent] {1st parent};

    \node (2ndparent)  [rbox,below=of Grandparent]{2nd parent}
    child[grandchild,first] {node[rbox]{1st child}}
    child[grandchild,second] {node[rbox]{2nd child}}
    child[grandchild,third] {node[rbox]{3rd child}};

    \node (3rdparent)  [rbox,below right=of Grandparent] {3rd parent};

    \path [line] (Grandparent) -- coordinate (a) (2ndparent);
    \path [line] (a) -| (1stparent);
    \path [line] (a) -| (3rdparent);
\end{tikzpicture}

\end{document}

Edit
Following cfr answer forest approach, how can I edit this code to make the children at level 3 (e.g. He-Ne, I, CO2, etc) be folder-like?
\documentclass[border=10pt,multi,tikz]{standalone}
\usepackage[edges]{forest}
\usetikzlibrary{arrows.meta,shadows.blur}
\begin{document}
\newlength\gap
\setlength\gap{10mm}
\begin{forest}
    forked edges,
    for tree={
        draw=blue!80!darkgray,
        fill=blue!80!darkgray!25,
        rounded corners,
        text width=(\textwidth-6*\gap)/3,
        edge={-Latex},
        font=\sffamily,
        text centered,
        blur shadow,
    },
    %  where level=0{%
    parent anchor=children,
    %  }{%
    if level=2{%
        folder,
        grow'=0,
        l sep+=10pt,
        before typesetting nodes={child anchor=north},
        edge path'={%
            (!u.parent anchor) -- ++(0,-10pt) -| (.child anchor)
        },
        }{},
    %  }
    [Active Media
        [Gases
            [Atoms
                [He-Ne]
                [I]
            ]
            [Molecules
                [CO2]
                [CO]
            ]
            [Ions
                [Ar]
                [Kr]
            ]
            [Excimers
                [ArF]
            ]
        ]
        [Liquids
            [Dyes
                [Rhodamines]
            ]
        ]
        [Solids
            [Insulators
                [Nd:YAG]
            ]
            [Semiconductors
                [GaAs]
            ]
        ]
    ]
\end{forest}
\end{document}

A: If you are happy to use Forest, the package will layout the tree automatically for you. The folder option from the edges library makes this much easier with Forest version 2 than version 1. However, there is a slight glitch in that it is not possible to combine folder with forked edges easily. So, for the first edges, we set the edge path manually and override child anchor.
\documentclass[border=10pt,multi,tikz]{standalone}
\usepackage[edges]{forest}
\usetikzlibrary{arrows.meta,shadows.blur}
\begin{document}
\newlength\gap
\setlength\gap{10mm}
\begin{forest}
  forked edges,
  for tree={
    draw=blue!80!darkgray,
    fill=blue!80!darkgray!25,
    rounded corners,
    text width=(\textwidth-6*\gap)/3,
    edge={-Latex},
    font=\sffamily,
    text centered,
    blur shadow,
  },
  where level=0{%
    parent anchor=children,
  }{%
    folder,
    grow'=0,
    l sep+=10pt,
    if level=1{%
      before typesetting nodes={child anchor=north},
      edge path'={%
        (!u.parent anchor) -- ++(0,-10pt) -| (.child anchor)
      },
    }{},
  }
  [Grandparent
    [1\textsuperscript{st} parent
    ]
    [2\textsuperscript{nd} parent
      [1\textsuperscript{st} child]
      [2\textsuperscript{nd} child]
      [3\textsuperscript{rd} child]
    ]
    [3\textsuperscript{rd} parent
    ]
  ]
\end{forest}
\end{document}

EDIT
For the tree added in the edited question, you might adjust the code as follows.
\documentclass[border=10pt,multi,tikz]{standalone}
\usepackage[edges]{forest}
\usetikzlibrary{arrows.meta,shadows.blur}
\begin{document}
\newlength\gap
\setlength\gap{10mm}
\begin{forest}
  forked edges,
  for tree={
    draw=blue!80!darkgray,
    fill=blue!80!darkgray!25,
    rounded corners,
    minimum width=(\textwidth-6*\gap)/3,
    minimum height=4ex,
    edge={-Latex},
    font=\sffamily,
    text centered,
    blur shadow,
  },
  where={level()<=1}{%
    parent anchor=children,
   }{%
     folder,
     grow'=0,
     l sep+=5pt,
     if level=2{%
       before typesetting nodes={child anchor=north},
       !u.s sep'+=10pt,
       edge path'={%
         (!u.parent anchor) -- ++(0,-10pt) -| (.child anchor)
       },
     }{},
   }
    [Active Media
        [Gases
            [Atoms
                [He-Ne]
                [I]
            ]
            [Molecules
                [CO2]
                [CO]
            ]
            [Ions
                [Ar]
                [Kr]
            ]
            [Excimers
                [ArF]
            ]
        ]
        [Liquids
            [Dyes
                [Rhodamines]
            ]
        ]
        [Solids
            [Insulators
                [Nd:YAG]
            ]
            [Semiconductors
                [GaAs]
            ]
        ]
    ]
\end{forest}
\end{document}

Note that the key level here is the one before the one where siblings are stacked vertically. If that is level 3, the crucial level is level 2. Everything before that level gets styled in one way, everything after gets styled another. Nodes at that level need some tweaking.
If you say
if level=2 ...

in the tree's preamble, it will have no effect as it is only applied to the root node, where the conditional fails. Likewise, options put here simpliciter only apply to the root. This is the difference between if and where: where issues for tree; if does not. See the manual for details and further options.


text:
Q: Repmat in Matlab to replicate specific elements I have the following lines of code where I find an event "41" in my cell array called Events (minimal example of this array included below) and the lines of code allow me to add 8 events labeled "411" after "41" and this is output in out1 (a result of this is shown as well). My issue is that I need to include 5 entries of "411" BEFORE "41" and I'm not sure how to do it.
How can I modify the lines below to be able to do that easily?
out1 = arrayfun( @(x,b) [x; repmat({'411'}, 8*b, 1)], Events, strcmp('41',Events), 'uni', 0 );
out1 = vertcat(out1{:});

Events = ['9991'    '9991'  '9991'  '9991'  '9991'  '9991'  '9992'  '10'    '11'    '41'    '42'    '10'    '11'    '43'    '44'];

out1 = ['9991'  '9991'  '9991'  '9991'  '9991'  '9991'  '9992'  '10'    '11'    '41' '411' '411'  '411' '411' '411' '411' '411' '411'   '42'    '10'    '11'    '43'    '44'];

Thanks!

A: In order to help, could you be more specific to define the issue? Will the array "Events" always be single dimension? Do you expect that "41" will appear only once or multiple times?
I have no way to test it right now but I guess this should do it:
out1 = arrayfun( @(x,b) [repmat({'411'}, 5*b, 1), x], Events, strcmp('41',Events), 'uni', 0 );
out1 = vertcat(out1{:});
Let me know if you still have trouble with it and I can have a more in depth look this evening


text:
Q: How to do JNDI in Tomcat by using externalized Property file I am just configuring tomcat for JNDI using the externalized. I have done some thing wrong, but no clue.
In Context.xml
<Resource name="jdbc/AppDB" auth="Container" type="javax.sql.DataSource"
                            driverClassName="org.postgresql.Driver"
                            factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
                            url="${app.env.database.url}"
                            username="${app.env.database.user}"
                            password="${app.env.database.password}"
                            maxActive="100"
                            maxIdle="50"
                            minIdle="10"
                            suspectTimeout="60"
                            timeBetweenEvictionRunsMillis="30000"
                            minEvictableIdleTimeMillis="60000"
                            validationQuery="select 1"
                            validationInterval="30000"
                            testOnBorrow="true"
                            removeAbandoned="true"
                            removeAbandonedTimeout="60"
                            abandonWhenPercentageFull="10"
                            maxWait="10000"
                            jdbcInterceptors="ResetAbandonedTimer;StatementFinalizer"
            />

While running the Tomcat , I am setting this
-DappProperties=c:/user/abc/app.properties

On Starting the server, I am getting below error.
Caused by: javax.naming.NamingException: Driver:org.postgresql.Driver@d8cf794 returned null for URL:${app.env.database.url}
    at org.apache.naming.NamingContext.lookup(NamingContext.java:858)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:152)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:829)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:152)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:829)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:152)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:829)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:166)
    at org.apache.naming.SelectorContext.lookup(SelectorContext.java:157)
    at javax.naming.InitialContext.lookup(InitialContext.java:411)
    at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:155)
    at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87)
    at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152)
    at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:179)
    at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95)
    at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:106)
    at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:231)
    at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:217)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)
    ... 31 more

Can any one please help.
Please note : application is working good if I change ${app.env.} with actual values.
Thank you for your help

A: Are you using Maven? You need to use resource filtering plugin so maven will transform your property file values into actual values. Something like:
<build>
...
<resources>
  <resource>
    <directory>src/main/resources</directory>
  </resource>
  ...
</resources>
...

Where the directory contains your xml file should work


text:
Q: Canvas HTML5, IE vs Chrome vs FireFox - font and offset properties I developed an HTML5 canvas graph that retrieves SQL-stored information and plots them graphically (color-coded) on a HTML5 canvas. The canvas allows scrolling over a timeline to show various events that have occured (Say between 1990 - 2013).
IE works like a charm.
Chrome has issues with the context font being muddy/bleeding effect - i was using monospace 11px, I changed it to verdana later on, but still a bit muddy with chrome. Firefox doesn't have this issue.
Firefox has an issue, where it retrives and plots information on the canvas, but when i click on the canvas to scroll in the past or future of current position on the timeline, the entire canvas dissapears. Chrome doesn't have this issue.
I 've tried to explain my issues on this question, if you need more clarification please ask.
here is the sample code:-
http://jsfiddle.net/WNpKE/16/
(if you click on the link and open it in IE, FireFox, and Chrome, I hope that the issue will become more evident.)
  // defining the canvas element
            var can = document.getElementById("myCanvas"),
                ctx = can.getContext("2d"),
                dragging = false,
                translated = 0,
                lastX = 0,
                grid = (function (dX, dY) {
                    var can = document.createElement("canvas"),
                        ctx = can.getContext('2d');
                    can.width = dX;
                    can.height = dY;
                    // fill canvas color
                    ctx.fillStyle = 'black';
                    ctx.fillRect(0, 0, dX, dY);

                    // x axis
                    ctx.strokeStyle = 'orange';
                    ctx.moveTo(.5, 0.5);
                    ctx.lineTo(dX + .5, 0.5);
                    ctx.stroke();

                    // y axis
                    ctx.moveTo(.5, .5);
                    ctx.lineTo(.5, dY + .5);
                    ctx.stroke();

                    return ctx.createPattern(can, 'repeat');
                })(72, 50);

            ctx.save();
            /*ctx.scale(1, -1);
            ctx.translate(0, -900);*/

            // when mouse is clicked on canvas
            can.onmousedown = function (e) {
                var evt = e || event;
                dragging = true;
                lastX = evt.offsetX;
            }

            // when mouse is clicked again and the canvas is deselected
            window.onmouseup = function () {
                dragging = false;
            }

            window.onmousemove = function (e) {
                var evt = e || event;
                if (dragging) {
                    var delta = evt.offsetX - lastX;
                    translated += delta;
                    //console.log(translated);
                    ctx.restore();
                    ctx.clearRect(0, 0, 930, 900);
                    ctx.save();
                    ctx.translate(translated, 0);
                    lastX = evt.offsetX;
                    timeline();
                }
            }

            // Function that draws the timeline on the xy grid along with data points.
            function timeline() {

                // fill canvas color
                ctx.fillStyle = "black";
                ctx.fillRect(-translated, 0, 930, 900);
                ctx.fillStyle = grid;
                ctx.fillRect(-translated, -250, 930, 900);

                // y-co-ordinate texts - Home, Office, Emergency, etc...
                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("Home", -translated, 510);

                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("Office", -translated, 460);

                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("Emergency", -translated, 410);

                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("Foster Home", -translated, 360);

                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("SNF", -translated, 310);

                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("LTC", -translated, 260);

                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("Drug/Rehab", -translated, 210);

                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("Hospital", -translated, 160);

                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("Hospice", -translated, 110);

                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("ANP Exams", -translated, 540);
                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("Life Event", -translated, 560);
                ctx.strokeStyle = "White";
                ctx.font = "10px Verdana";
                ctx.strokeText("Care Plan", -translated, 610);

I have changed a bit since this code, but the basic idea of click and scroll is still the same. Thanks.

A: Use fillText instead of strokeText.
The FF error is happening because the FF event object doesn't have an offsetX property. Use pageX instead.
Updated fiddle: http://jsfiddle.net/WNpKE/18/

A: Take a look at the highcharts API. It's free and has an enormous amount of features. I've recently used it in a web application effort querying data from an SQL database not unlike what you're doing. It works across all the major browsers.
I am guessing that the canvas element (being a new feature of html5) isn't being rendered the same way between browsers. You may be better off either re-writing in javascript / java or just using the highcharts framework as-is. I realise this isn't a solution to your current problem, but it may save you some time.
Good Luck!


text:
Q: Неожиданное поведение элементов при использовании float Ну совсем непонятное явление. Не помог ни Гугл, ни игра с CSS-свойствами. Прошу помощи здесь.
На странице два блока - левая колонка (float:left) и правая (основное содержимое).
Так вот, если в правой колонке использовать для какого-либо элемента свойство float:left, и даже после этого очистить float (clear:left или clear:both), то последующие неплавающие элементы внезапно выравниваются по уровню левой колонки, которая никакого отношения к правой колонки не имеет.

.wrapper {
 width:100%;
 height: 100%;
 box-sizing: border-box;
}
.left-bar {
 float: left;
 width:200px;
 height: 400px;
 background: red;
}
.right-bar {
 height: 700px;
 margin-left: 210px;
 background: #adc6e7;
}

Левая колонка

Строчка 1

Строчка 2

Абзац

A: clear: left Это правило гарантирует, что все элементы, к которому применено свойство, будут смещены ниже ВСЕХ перемещаемых влево элементов.
Так как у нас .left-bar имеет float: left; и находиться до применения clear: left, clear: left опустилось ниже блока .left-bar (см. скрин).

A: Вот тут говорят, что clear работает сразу на все уровни (https://stackoverflow.com/questions/30885721/css-how-to-clear-a-floating-object-only-one-level-not-the-all-the-way-to-the-l)
Почему бы не использовать флексбокс для лэйаута?
https://jsfiddle.net/k5z15sds/
.wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  box-sizing: border-box;
}

.left-bar {
  flex: 0 0 200px;
  height: 400px;
  background: red;
}

.right-bar {
  flex: 1;
  height: 700px;
  background: #adc6e7;
}

A: Как уже правильно сказали, вложенность не имеет значения. На вскидку, единственное что могу предложить overflow: hidden; для правого блока (что бы вложенные элементы не обращали внимание на то, что находится вне родителя), если это приемлемо ...

.wrapper {
 width:100%;
 height: 100%;
 box-sizing: border-box;
}
.left-bar {
 float: left;
 width:200px;
 height: 400px;
 background: red;
}
.right-bar {
 height: 700px;
 margin-left: 210px;
 background: #adc6e7;
 overflow: hidden; // Собственно "трикс" ...
}

Левая колонка

Строчка 1

Строчка 2

Абзац

A: Это происходит из за контекста форматирования. Об этом почему-то не часто говорят, хотя знания о нем значительно уменьшит количество ошибок при верстке.
Блочный контекст форматирования может быть создан чем-либо из этого списка:

*

*корневой элемент или что-то, что содержит его

*плавающие элементы (элементы, у которых float не равно none)

*абсолютно позиционированные элементы (элементы, значение  position которых либо absolute, либо fixed)

*«строчные блоки» (элементы с display: inline-block)

*И т.д.

Подробнее тут
Если хочется посмотреть в действие результат тут
В примере у класс wrap-box раскомментируйте любую строчку
.wrap-box{
  //display: inline-block;
  //display: flow-root;
  //float: left;
  //overflow: auto;
  //overflow: hidden;
  width: 100%;
  background-color:#aacccc;
}


text:
Q: What exactly is the total size of the array using size in python? I am learning about "Numpy" and I read somewhere that to get the total size of the array we can use "size".
Below commands are what I executed :
print("x3 shape:", x3.shape)

print("x3 size: ", x3.size)

Result :
x3 shape: (3, 4, 5)

x3 size: 60

I cannot understand why for 12 values the total size is 60.
I tried but still not able to visualize it.

A: In numpy shape is used to get the dimensional details of the array whereas size returns the total elements present in the array.
In your example, the matrix is three dimensional hence its size would be 3*4*5 = 60.


text:
Q: Bash output the line with highest value my question is pretty much like this one but with one difference; i want the output the line that has highest score on the 3rd tab. my data is like:
1.gui  Qxx  16
2.gui  Qxy  23
3.guT  QWS  11

and i want to get this:
1.gui  Qxy  23
3.guT  QWS  11

I used:
cat file.f | uniq | cut -d" " -f3 | sort | uniq -d >>out.f

but did not get what i want!?

A: With sort:
$ sort -rk3 file             # Sort on column 3, display all results

2.gui  Qxy  23
1.gui  Qxx  16
3.guT  QWS  11

$ sort -rk3 file | head -2   # Sort on column 3, filter number of results

2.gui  Qxy  23
1.gui  Qxx  16

$ sort -rk3 file | uniq      # Sort on column 3, on display unique results

2.gui  Qxy  23
1.gui  Qxx  16
3.guT  QWS  11

-r reverse sort, highest first.
-k3 sort on the 3rd column.

If you only want to display line which the 3rd column is greater than some value (i.e. 15) then try this using awk:
awk '$3>15' file | sort -rk3  # Display line where column 3 > 15 and sort

2.gui  Qxy  23
1.gui  Qxx  16

A: for future users with same question:
do not forget to introduce -n switch to the -sort command, or your values are ordered starting from 9999's and followed by 999's etc.. so use
sort -rnk3 file

and if you want to get only one line with highest value (remove duplicates) use this:
sort -rnk3 file | awk '!x[$2]++'

and if you have an usual delimiter you can tell -awk to notice:
sort -rnk3 file | awk -F"[. ]" '!x[$2]++'

A: This must give you the highest value for those lines where the name is repeated and conserve those lines that have not repeated names.
sort -rk3 file | awk '!seen[$1]++' > file_filtered.txt


text:
Q: Functors preserve isomorphisms, sections and retracts. Do they reflect these properties? Functors preserve isomorphisms, sections and retracts. Which of these properties, if any, do functors reflect?
Are there other fundamental properties preserved and or reflected by functors?
Please specify covariant or contravariant if applicable.
Don't assume I understand any cat theory - all I know is triangles and functional languages.

A: You can find a table of many preserved and reflected properties of functors in wonderful "The Joy of Cats" (JOC) book which you can find online at:
http://www.tac.mta.ca/tac/reprints/articles/17/tr17.pdf
In general:

*

*functors need not reflect isomorphisms (JOC 3.22)

*functors need not reflect sections (JOC 7.23)

*functors need not reflect retracts (JOC 7.29)

However: full and faithful functors reflect isomorphisms, sections and retracts (JOC 7.30)


text:
Q: Determine frequency from received audio mic input For searching over internet , i have enough code to record audio mic input.Using Speak here sample code from apple sample code.What i want is ,i want to display a Frequency in (UILabel) in my application. I have an ipod touch 3rd generation ,i record audio using Headphone mic.Whatever i received input over mic , i want to display its frequency range(hz) in UILabel. I also downloaded the code aurio touch but all give some tips to find frequency.No one gave any sample code to determine frequency using fft in auriotouch.I am new to iphone app development.This is my first task,so i want done it good.So plz guide me a right way to do this.And i am also didnt know about digital signal processing.(I have one doube , is it only possible to determine frequency using drawed area of sine wave or we calculate over own).
For long surfing i have got one more sample name SCListener , there is source in github.When i download and run the code it displayed averagePower,peakPower,and frequency values displayed in label.Is this correct example to use in my code ?And also i didnt know the output should be in hz or khz.
How to check the recorded frequency displayed in label should be correct ?
Plz plz help me ........
Thanks in advance..Sorry for my bad english.

A: You need to use a Fourier transform. The best library I am aware is FFTW.
Remember, you're not going to get a single frequency; you'll get a mix of all of them up to sample_rate/2. You need some algorithm to pick the correct spike.
You may want to take a step back and read about Nyquist theory and signal processing (specifically FFT) before you go much further otherwise you're going to make a lot of mistakes.

A: One way to check that your frequency label is displaying the correct value is to test it using some sort of calibrated signal generator.
You might be able to find a Mac or PC audio synthesis/generator program that can play a sine wave at a known frequency.  Try it, and check the results displayed by your app using your iPod Touch or the iOS Simulator.  (Do not use a musical sound to test, and it may produce a bunch of frequencies very different from the recognized pitch.)
If you have audio input to an FFT working, and are measuring the frequency of a sine wave much louder than any other spectral content, you can try determining the FFT bin (result index) with the largest magnitude.  A very approximate estimate of the frequency will be:
frequency_estimate = bin_number * sample_rate / fft_length_in_samples;

The estimate error will be proportional to (sample_rate / fft_length_in_samples).


text:
Q: Submit multiple forms using only 1 ajax? I'm getting my multiple forms using a while loop (fetch data in the database).
<form id="form" class="form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test1">
<input type="text" class="form-control" name="car_type">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>
<form id="form" class="form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test2">
<input type="text" class="form-control" name="car_type" value="test2">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>

Here's my ajax (It only works in the 1st form but the rest not working):
$(document).ready(function(){
 $(".form").submit(function(e) {
       e.preventDefault();
        $("#buttona").html('...');
        $("#buttona").attr("disabled", "disabled");
        sendInfo();

     });
});

Function for ajax:
function sendInfo() {
        $.ajax({
          type: 'POST',
          url: '../process.php',
          data: $(".form").serialize(),
          success: function(data){
             if(data == 'Success') {
                $('#text_errora').html('added');
             }else {
               $('#text_errora').html('not aadded');
               }
          }
      })
        return false;
    }

How can I set or how ajax will recognize the button I click/submit to process the form?

A: *

*You don't close your <form> tag.

*You use the same id twice.

*You select anything with class form, not ID form.

Actually, I am amazed it works even one time.
Try this (no need to touch the JavaScript), your form should submit, but the button changing might not work (you use identical IDs there too; tip: an id has to be unique within the entire HTML DOM).
<form class="form form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test1">
<input type="text" class="form-control" name="car_type">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>

A: Using "this" keyword inside submit handler, you will receive a reference to the form to which the clicked button belongs.
$(document).ready(function(){
$(".form").submit(function(e) {
       e.preventDefault();
        var form_to_submit = this;
        $("#buttona").html('...');
        $("#buttona").attr("disabled", "disabled");
        sendInfo(form_to_submit);

     });
});

function sendInfo(form_to_submit) {
    $.ajax({
        type: 'POST',
        url: '../process.php',
        data: $(form_to_submit).serialize(),
        success: function(data){
            if(data == 'Success') {
                $('#text_errora').html('added');
            }else {
                $('#text_errora').html('not aadded');
            }
        }
    })
    return false;
}


text:
Q: Appling div class based filters I have a form - which allows the user to select an option from a dropdown
<form action="/create_tasks/" name="form2" , id="form2" method="post" class="row row-cols-lg-auto g-3 align-items-center">
  <input type="hidden" name="csrfmiddlewaretoken" value="F9Xrs4SIcjDS3yVMCH1hbAB1p3encpExp14ynCZV5jsDgjcD41qFoVeDn4wtpGr8">

    Preference
    <select class="form-select" id="inlineFormSelectPref">
      <option selected value='all'>All </option>
      <option value=SQL>SQL</option>
      <option value=Apache Spark>Apache Spark</option>
      <option value=Python>Python</option>
      <option value=Linux>Linux</option>
    </select>

    <button type="submit" class="btn btn-primary">filter</button>

</form>

I have divs underneath like this:

If the user selects a value from the dropdown, i want to only show the divs with that class (e.g. select Python , only show python divs). If they select 'all' I want to show them all
I had a play with some options but i cant make it work. Can anyone point me in the right direction please?

A: You can add input event listener on your select field. This will trigger every time you change option in your select. When this event trigger, simply read select value and show divs accordingly.

const select = document.getElementById('select');
const showSelected = name => {
    document.querySelectorAll('.form-option').forEach(card => {
        card.style.display = name === 'all' ? 'block' : 'none';
        if (name !== 'all' && card.classList.contains(name.replace(' ', '-'))) {
            card.style.display = 'block';
        }
    });
}

showSelected('all');
select.addEventListener('input', () => {
    showSelected(select.value);
});
<select id="select">
    <option selected value='all'>All</option>
    <option value="SQL">SQL</option>
    <option value="Apache Spark">Apache Spark</option>
    <option value="Python">Python</option>
    <option value="Linux">Linux</option>
</select>

SQL

Apache Spark

Python

Linux