text:
Q: Getting Javascript files using Rawgit I'm trying to include a JS file in my website via Ajax by getting it from one of my GitHub repositories, using Rawgit. For some reason, it doesn't work when I use the development or production URLs, but when I use the raw version of my files directly from Github, the problem stops. I don't experience any problems when I use the development URL for a CSS file. Does anyone know why this happens?
Here's my code:
$.get("https://rawgit.com/Larpee/The-Khan-Quiz/master/game.js", function (game) {
    var sketchProc = function (processingInstance) {
        with (processingInstance) {
            size(400, 400);
            frameRate(30);
            eval(game);
        }
    };

    var canvas = document.getElementById("game");
    var processingInstance = new Processing(canvas, sketchProc);
});

Update: I think the problem occurs because GitHub (not Rawgit), serves the files as .txt files, while RawGit serves them as .js.
I would still like to receive an explanation for why getting my JavaScript files with a .js extension isn't working, though

A: For RawGit, you get content-type: application/javascript;charset=utf-8 as expected, and GitHub gives Content-Type: text/plain; charset=utf-8. That seems to be the only difference.
I checked your example and found that when using RawGit (and getting a script response), the success callback wouldn't execute at all, but using GitHub it would (adding a console.log('foo'); statement, for example. I also found that eval() run on your script throws an exception:
Uncaught ReferenceError: createFont is not defined

I made a repo myself with a placeholder JS file that was syntactically correct, in which case success callbacks for $.get() on both RawGit and GitHub did execute, and later added a reference to an undefined name, which caused the call to the RawGit URL fail to execute its callback.
The lesson? When you get a script with $.get(), it is actually immediately executed, and if that eval() fails then everything ends there, silently. This is supported by jQuery getScript load vs execution, which also implies that this (in my opinion) kind of crazy way of dealing with script data ended in version 2.1.0.
Which leads me to suggest that, apart from fixing your script, you should either use $.getScript() (not sure if you have to ensure the result header has application/javascript), or explicitly insert a script element with JS and have an onload callback:
(function(d, script) {
    script = d.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.onload = function(){
        // remote script has loaded
    };
    script.src = '[RawGit URL]';
    d.getElementsByTagName('head')[0].appendChild(script);
}(document));

Additionally, the with block you use should become:
var sketchProc = function (processing) {
    processing.size(400, 400);
    processing.frameRate(30);
}

var canvas = $('#game'); // use jQuery since you have it
var processingInstance = new Processing(canvas, sketchProc);

// game code now manipulates `processingInstance`
// either directly in scope (or even better as object with parameter)
processingInstance.draw = function () {
    var processing = this;
    // if your code originally used `processing` throughout,
    // do this so that it refers to the specific instance you've created
    // ...
}
processingInstance.loop();
// if initialized without a `.draw()` method like above, you need to start the loop manually once there is one

The Processing.js documentation has a lot of examples that are basically in Java and require small modifications to properly deal with JS scope. Sad!


text:
Q: How to change the background colour gradient of view dynamically I want to make a custom view for my android app which has a functionality to change its background colour "gradient".
Something like this, but the centre handle can be moved left and right using code

The catch is that I want a function something like in the view:
changeBackgroundGradient(ratio, startColour, centreColour, endColour);

ratio (having value between 0 to 1) which is given by formula
leftValue/rightValue determining the shape of the gradient
startColour, centreColour and endColour being the colours of which the gradient consists of
How would i make this function?

Regards

A: You can try below code as this is working for me to change my toolbar color dynamically
private void setGradientColor(View header)
{
    String primaryColor = "#f4f3f2"; // any color code
    String primaryDarkColor = "#000000";

    GradientDrawable gd = new GradientDrawable (
    GradientDrawable.Orientation.BR_TL, // check below link for this you can change this value
    new int[] {
        Color.parseColor(primaryColor),
        Color.parseColor(primaryDarkColor)
        }
    );

    gd.setCornerRadius(1f);

    header.setBackground(gd);
}

Update
Check this for more options to apply gradient color in view.

A:
You can try following function. Add these functions in your activity file.

       private Drawable getGradientDrawable()
        {
            GradientDrawable gradient = new GradientDrawable();
            gradient.setGradientType(GradientDrawable.LINEAR_GRADIENT);
            gradient.setColors(new int[]{getRandomHSVColor(), getRandomHSVColor()});
            return gradient;
        }

        protected int getRandomHSVColor(){
            // Generate a random hue value between 0 to 360
            int hue = mRandom.nextInt(361);
            // We make the color depth full
            float saturation = 1.0f;
            // We make a full bright color
            float value = 1.0f;
            // We avoid color transparency
            int alpha = 255;
            // Finally, generate the color
            int color = Color.HSVToColor(alpha, new float[]{hue, saturation, value});
            // Return the color
            return color;
        }
        // Custom method to get a lighter color
        protected int getLighterColor(int color){
            float[] hsv = new float[3];
            Color.colorToHSV(color,hsv);
            hsv[2] = 0.2f + 0.8f * hsv[2];
            return Color.HSVToColor(hsv);
        }

        // Custom method to get reverse color
        protected int getReverseColor(int color){
            float[] hsv = new float[3];
            Color.RGBToHSV(
                    Color.red(color), // Red value
                    Color.green(color), // Green value
                    Color.blue(color), // Blue value
                    hsv
            );
            hsv[0] = (hsv[0] + 180) % 360;
            return Color.HSVToColor(hsv);
        }

Than use this function like below:
your_layout_name..setBackground(getGradientDrawable());

redpajama_set_name: RedPajamaStackExchange


text:
Q: Quadruple integration using Gauss-Legendre quadrature I want to use Gauss-Legendre quadrature to evaluate a quadruple integral in Matlab. I found the following code that works for a double integral but when it comes to switching to 4 variables I don't know how.
a = 2; b=2;
[x,w] = lgwt(50);

y=(b*(1+x))/2;
x=(a*(1+x))/2;
[X, Y] = meshgrid(x,y);
fun = @(x,y) exp(1i*x)./(sqrt(x.^2+y.^2));
t = w * fun(X,Y) * w'

The function I would like to integrate :
fun = @(x,y,z,t) 1./sqrt(x.^2+y.^2+z.^2+t.^2)

Does anyone have an idea?

A: This solution seems like the best option in your case.
The best way to integrate fun = @(x,y,z,t) from
a <= x <= b, c <= y <= d, e <= z <= g, and h <= t <= i is to nest integral3() with integral(). They are both built-in functions of Matlab.
Q = integral(@(x)integral3(@(y,z,t)f(x,y,z,t),c,d,e,g,h,i),a,b,'ArrayValued',true);


text:
Q: Why do only some array methods create new instances? I am new to javascript. Coming from a more object oriented background, one quirk I noticed is that some methods override an array, and some others make new instances. For example:
// initialize array
var arr = [
  "Hi",
  "Hello",
  "Bonjour"
];

// append new value to the original array
arr.push("Hola");

console.log(arr);

whereas concat
var arr = [
  "apple",
  "banana",
  "cherry"
];

arr = arr.concat([ // original array needs to be overridden
  "dragonfruit",
  "elderberry",
  "fig"
]);

console.log(arr);

Why is the behavior between the two methods not consistent?
Examples taken from: How to append something to an array?

A: var foo = 1, bar = 2;

Let's say you wanted to add the values foo and 1 onto bar. This is what you would do:
var foo = 1, bar = 2;
bar = bar + foo + 1;
console.log(bar) //4

But you did not do this:
var foo = 1, bar = 2;
bar + foo + 1; //ineffective
console.log(bar) //2

That is because the operator + simply just adds the values and returns the sum. So you still need to redefine bar. Whereas in:
var foo = 1, bar = 2,i;
for(i=0;i<foo;i++) bar++; //adds 1 foo times
bar++; //adds 1

You do not need to make a redefinition. This is because the increment operator assumes that you want to increment a value, not find their sum. So it does that.

array.concat(foobar) assumes that you want to get two arrays or values, join them together into a new, combined array, and then return the new array. In a sense, it is like the + operator. Thus it only finds their combination, not set the actual array, so you need a redefinition.

Whereas array.push(foobar) assumes that you want to add, stick, glue, or push a value to the end of the array, so it will do so. And because it itself has already added those onto the array, it doesn't need to be used in a redefinition.
They are used in that sense. It may be inconsistent, but you need to become used to it.

A: concat() method does not change the existing array, but returns a new reference.


text:
Q: Eclipse CDT gdb No source file named I have the following Eclipse CDT setup on a Red Hat Linux system:

*

*Eclipse Mars with CDT 8.7

*gdb 7.6

I have two projects open in my workspace

*

*Project1: the main source code that builds the executable I want to debug

*Project2: library code that gets statically linked with the binary in Project1

Project2 is linked to Project1 in its properties.
The problem occurs when I try to set breakpoints in a debug session in source files that are in Project2. gdb reports the following error:
No source file named <absolute_path_to_file>.

The weird thing is that I can set breakpoints in the gdb console in Eclipse using the function name and/or function name and line number syntax. When I do this, gdb reports that it successfully set the breakpoint showing the file and line number. The file name, in the trace message, has no path (maybe relevant?)
Using objdump I was able to confirm that my executable has all of the symbols and files in it (not absolute paths though... relevant?)
Once I get the debugger to stop at the breakpoint after setting it using the function name, I can then add/remove breakpoints within the Debug perspective like normal; even if I restart the debugging session.
I've seen lots of comments about loading shared libraries into gdb, but the code I'm trying to break into is in a statically linked library, not a shared one.
Given that I can add breakpoints using the normal method once I get gdb to break on one added manually in the conosole, indicates to me that maybe something is missing in my gdb settings.
Any thoughts?
Thanks!


text:
Q: Shopify cart should remove all bundle products if one product form that bundle is removed I have make custom bundles in shopify without use of any app. When I click on add to cart all those buld products are moved to cart but on cart there is not any specific if or data-bundle that is common in all these product which i can used to remove all products from cart if one of them is removed.
I am adding the product inside the cart using this script
$('.add_to_cart_btn').on('click',function(e){
e.preventDefault();
var prod_id = $(this).data('id');
var counter_sec = 0;
var open_crt = false;
var total = $('.variant_outer').length;
$('.variant_outer.grinding').each(function(index){
var qty = $(this).find('.qtybox').find('input').val();
if(qty >= 1){
  open_crt = true
  return false;
}
});
setTimeout(function(){
if(open_crt){
  var value = $('input[name="commercial"]:checked').val();
  if(value == 'yes'){
    value = 'For Commercial Use'
  }else{
    value = '';
  }
  if(value != ''){
    var data_value = {id:prod_id,quantity:1,properties:{"Commercial":value}};
  }else{
    var data_value = {id:prod_id,quantity:1};
  }
  $.ajax({
    type:"POST",
    url:'/cart/add.js',
    dataType:'json',
    data:data_value,
    async:false,
    success:function(cart){
      if(value == 'yes'){
        $.post('/cart/update.js',{attributes:{"customAttributes":"For Commercial Use"}},function()
    {},'json')
      }
    }
   });
   $('.variant_outer').each(function(index){
    var qty = $(this).find('.qtybox').find('input').val();
    if(qty >= 1){
      var ids = $(this).find('.qtybox').data('id');
      $.ajax({
        type:"POST",
        url:'/cart/add.js',
        dataType:'json',
        data:{id:ids,quantity:qty},
        async:false,
        success:function(cart){
        }
      })
     }
     if(index == total - 1){
      cartDrawer();
    }
    })
   }else{
   $.fancybox.open({
    src:"#grinding_popup"
   })
  }
  },1500);
 });

A: The simplest way to do bundles is to take advantage of product line item properties. Using those, you can tie a bundle together. Use that in the cart update code. If a product from the bundle is removed, you can look in the line item properties for the connecting glue to the other products in the bundle. Remove them too. It is pretty straightforward and ensures your bundling makes some sense.


text:
Q: Is a question with an obvious answer to ask another question rhetorical? If you were to ask someone a question with an obvious answer just to ask another question or to bring a subject up, would that be rhetorical? Like asking "Are you okay?" when someone is obviously hurt when you really mean "What's wrong?" or "How can I help you?". Or if someone at work is absent and you ask "Is [Person] out today?" when you really mean to ask why they're out.
I've been wondering lately because I've seen a lot people get irritated and think I'm just asking a stupid question with an obvious answer and it's making me wonder if I've been using rhetorical questions wrong.

A: A "rhetorical" question is a question which is asked to make a point rather than get a correct answer or remark. For example, if someone you knew failed their test without trying at all, you would say:

Are you happy with the grade you got?

The question does not require an answer, it was asked to make the student think about his responsibility as a learner.

"Is [Person] out today?"

When you really mean to ask why they're out, is not rhetorical, because you're asking a question without expecting a normal answer. That is different from asking a question which does not require an answer, hence it can be considered incorrect.
A rhetorical question must not be used for casual talk, inquiry or gathering information(Unless absolutely required). Rhetorical questions are better used while debating, in persuasive speeches, when you need to get your point forward to another person.

If you don't know what answer you want for your question, how is the other person supposed to understand what you want?

A: A rhetorical question is one that's asked when the answer is obvious. So it wouldn't be a rhetorical question if the answer only created another question.

A: This looks more like a cultural difference than a language thing. Directness x Indirectness in communications
You're being indirect in the way you communicate, by not directly asking what you want to know, but asking a different question and hoping that the other person will volunteer the information as a follow-up to your question. Typical example is talking about the weather for a conversation starter or ice-breaker.
For cultures that are direct, this comes across as really annoying depending on the subject, because you're asking something you can easily observe. See comparison:
Indirect
1: Hey, is (Person) out today?
2: Yes, they just called in sick. Conjuntivitis, very nasty. I hope I don't get it, I sat with them in a small room all day yesterday.
Direct
1: Hey, is (Person) out today?
2: Yes. (and all variations of a laconic answer with varying degrees of rudeness depending on how annoyed they get with your question, from "Well, they're not here" to "are you blind?")


text:
Q: Spread Liquid `include` over mutliple lines I have an "included" template with several parameters. The contents of the parameters get a bit muddled if I cram them all into a single line, so I would prefer something like this:
{% include product_details
    weight= "5.8lbs (2.6 kg)"
    width=  "22" (56cm)"
    length= "49" (125cm)"
    thickness= "1¼" (3cm)"
    case= "MT51413"
%}

However, this gives me the following error when generating the site:

error: Tag '{%' was not properly terminated with regexp: /\%}/.

Is there any way to spread a Liquid include over several lines?

A: Sorry you can't, the liquid parser expects the whole statement in one line, this is true for all statements not only for include, try to split an if statement and you receive the same error


text:
Q: wp_enqueue_script silently fails I created a plugin which uses bootstrap datetimepicker. So i load corresponding js setting dependancies like this:
wp_enqueue_script('medapp-datetimepicker-js', $medapp_boot_timepicker_js, array(
                'jquery',
                'jquery-ui',
                'moment',
                'medapp-twitter-bootstrap-js'
            ));

 wp_enqueue_script('medapp-frontend-js', $medapp_script_js, array(
                    'jquery',
                  //  'medapp-datetimepicker-js',
                ),'',false);

If the line commented is on, of course in my js file i can't access datetimepicker and i have the following error when i try to instanciate the datetimepicker:
TypeError: jQuery(...).datetimepicker is not a function

So i uncomment the commented line, and then load of scripts silently fails (it seems nothing is loaded after the second wp_enqueue_script, but without any console error), and the page does not display entirely.
I know datetimepicker script is loaded correctly as i output all regegistered handlers like this:
function medapp_inspect_scripts() {
            global $wp_scripts;
            foreach( $wp_scripts->queue as $handle ) {
                MEDAPI::getLogger("MEDAPP")->debug( $handle );
            }
        }

which correctly outputs the datetimepicker handler.
Any idea how i could debug this please ?

A: Basic JS troubleshooting - strip it down to basics. Create a new script which either has a console.log('I am working') or alert('I am working') and enqueue it without any dependencies. If it works, enqueue it with your dependencies - still with your console or alert to easily check whether it's working. If it works, now you can do a really simple function with the datepicker you really want to use in your script. Once that works, put in your more complex custom code.
Another common thing to check - what version of jQuery does your version of Datetimepicker require, and what is loading in your version of WP? Perhaps they're not compatible.

A: Thank you very much @WebElaine, i actually found the bug.
It was a cascading dependancy problem:
My datetimepicker enqueue was specifying a dependancy on moment.js, which is right, but moment was not enqueue as a script in my plugin.
So i enqueued moment.js as other scripts right before enqueing datetimepicker, and it works.
I am just surprised that i was able to enqueue datetimepicker with no error raised on dependancy (maybe another plugin is already enqueuing it ?).
Thank you very much.


text:
Q: Is It possible that heavy query caused to stopped running subsequent code in asp.net? I have a query in my Asp.net project, which create two table and then insert amount of date into it, when there are afew data so there is no problem, it is my query :
    protected void btnLottryInformationSave_Click(object sender, EventArgs e)
    {
        try
        {
            int rowCount;
            var finalTempTableName = FindTableName();

            var selecterServicesList = cblServices.Items.Cast<ListItem>().Where(x => x.Selected).ToList();
            var selectedServices = selecterServicesList.Aggregate(string.Empty, (current, service) => current + ("'" + service.Value + "',")).TrimEnd(',');

            var tempTableName = "Temp_" + finalTempTableName;

            var drawQuery = " if (OBJECT_ID('Temp.dbo." + tempTableName + "') is not null) \ndrop table Temp.dbo." + tempTableName + ";\n";
            drawQuery += " create table Temp.dbo." + tempTableName + "(Number char(11) primary key,RepCount int);\n";
            drawQuery += " if (OBJECT_ID('Temp.dbo." + finalTempTableName + "') is not null) \ndrop table Temp.dbo." + finalTempTableName + ";\n";
            drawQuery += " create table Temp.dbo." + finalTempTableName + "(Id int identity(1,1) primary key,Number char(11));\n";

            drawQuery += " select org.orig \n" +
                         "   into #MoOrig \n" +
                         "    from VSReceiveSend.dbo.OrigPrices org  \n" +
                         "          INNER JOIN VSReceiveSend.dbo.Services     s on (s.Orig   = org.Orig) \n" +
                         " where s.Code in (" + selectedServices + ") and org.MTPrice <> 0  \n ";

            if (drpLotteryType.SelectedValue == "1" || drpLotteryType.SelectedValue == "2")
            {
                drawQuery += " INSERT INTO Temp.dbo." + tempTableName + " (Number,RepCount)\n" +
                             " select number," + (drpLotteryType.SelectedValue == "1" ? "1" : "sum(c) ") +
                             " from (\n" +
                             "     SELECT Number,COUNT(*) c \n" +
                             "     FROM  VSReceiveSend.dbo.ReceivedSMS with(nolock)\n" +
                             "            INNER JOIN VSReceiveSend.dbo.#MoOrig org ON (org.Orig = ReceivedSMS.Orig) \n " +
                             "     WHERE  Date BETWEEN '" + dtpStartDate.Text + "' AND '" + dtpEndDate.Text + "' \n" +
                             "     GROUP BY Number\n" +
                             "     union all \n " +
                             "     SELECT Number,COUNT(*) c \n" +
                             "     FROM  VSReceiveSend.dbo.SentSMS with(nolock) \n" +
                             "            INNER JOIN VSReceiveSend.dbo.OrigPrices org ON (org.Orig = SentSMS.Orig AND org.MTPrice <> 0 ) \n " +
                             "     WHERE  SentDate BETWEEN '" + dtpStartDate.Text + "' AND '" + dtpEndDate.Text + "' AND SentSMS.ServiceCode in (" + selectedServices + ") \n" +
                             "     GROUP BY Number \n" +
                             " ) DerivedTable \n" +
                             " group by number \n" +
                             ((drpLotteryType.SelectedValue == "2" && txtMinAnswerCount.Text != "") ? "HAVING sum(c) >= " + txtMinAnswerCount.Text : "") + ";\n";
            }
            else if (drpLotteryType.SelectedValue == "3")
            {
                var pointCount = int.Parse(txtMinCustomerPoint.Text);

                drawQuery += " INSERT INTO Temp.dbo." + tempTableName + " ( Number,RepCount)\n" +
                             "                                            SELECT Number,SUM(Point) / " + txtDivPoints.Text + " RepCount " +
                             "                                    FROM VsReceiveSend.dbo.SubscriberMatchHistory with(nolock) \n" +
                             "                                where ServiceCode in (" + selectedServices + ") and SUBSTRING(DateTime,1,10)  BETWEEN '" + dtpStartDate.Text + "' AND '" + dtpEndDate.Text + "' \n" +
                             "                                GROUP BY Number\n" +
                             " HAVING SUM(Point) >= " + pointCount + ";\n";
            }

            drawQuery += " with DrawInfo (Number,RepCount) as \n" +
                         "(   select Number,1 \n" +
                         "    from temp.dbo." + tempTableName + "\n" +
                         "       union all \n" +
                         "    select DrawInfo.Number,DrawInfo.RepCount + 1 \n" +
                         "        from Temp.dbo." + tempTableName + "\n" +
                         "    inner join DrawInfo on (DrawInfo.Number = Temp.dbo." + tempTableName + ".Number and DrawInfo.RepCount + 1 <= " + tempTableName + ".RepCount) \n" +
                         ")\n" +
                         " Insert into Temp.dbo." + finalTempTableName + "(Number) \n" +
                         " select DrawInfo.Number \n" +
                         " from DrawInfo";
            if (!checkBoxOrderInformation.Checked)
                drawQuery += " ORDER BY ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) \n";
            else
                drawQuery += " ORDER BY Number \n";

            drawQuery += " option (maxrecursion 0);\n " +
                         " select count(*) from Temp.dbo." + finalTempTableName;

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["VasunReportConnectionString"].ConnectionString))
            {
                var command = new SqlCommand(drawQuery, connection) { CommandTimeout = 999999999 };
                connection.Open();
                drawFieldSet.Visible = true;
                rowCount = (int)command.ExecuteScalar();

                txtNumberOfRow.Text = rowCount.ToString(CultureInfo.InvariantCulture);
            }

            using (var dbs = new ReceiveSendEntitiesV5())
            {
                var matchDrawHistories = new MatchDrawHistory()
                {
                    DrawStartDate = dtpStartDate.Text,
                    DrawEndDate = dtpEndDate.Text,
                    DrawTime = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString(),
                    RowNumber = rowCount,
                    ServiceCode = cblServices.SelectedValue,
                    TableName = finalTempTableName
                };
                dbs.MatchDrawHistories.Add(matchDrawHistories);
                dbs.SaveChanges();
            }

        }
        catch (Exception exp)
        {
            ErrorLabel.Text = "Exception :" + exp.Message;
        }
    }

but when there were a lot of data, my code execute until : txtNumberOfRow.Text = rowCount.ToString(CultureInfo.InvariantCulture);
so these codes does not execute :
 using (var dbs = new ReceiveSendEntitiesV5())
        {
            var matchDrawHistories = new MatchDrawHistory()
            {
                DrawStartDate = dtpStartDate.Text,
                DrawEndDate = dtpEndDate.Text,
                DrawTime = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString(),
                RowNumber = rowCount,
                ServiceCode = cblServices.SelectedValue,
                TableName = finalTempTableName
            };
            dbs.MatchDrawHistories.Add(matchDrawHistories);
            dbs.SaveChanges();
        }

how it is possible!!! what is the problem???


text:
Q: array initializing I came across this code construct in Linux and would like to understand it
struct mystruct {
  int x;
  int b[40];
};

/*later */

static struct mystruct e = { .x = 5,
                             .b = {-1},
                           };

What does .b = {-1} do ? Does it initialize  only the first or all elements of array b ? How does it work ?

A: static struct mystruct e = {
    .x = 5,
    .b = {-1},
             };

here it initializes b[0] to -1. other elements are initialized to 0.

A: It means initialize the member b of the struct with an array that starts with -1 and followed by 0

*

*The .b = is a GCC extensions. (as commented, from C99 this is part of the standard as well)

*The {-1} is standard array initialization.


text:
Q: Curl function does not return response I want to call a Api. I have used Curl for this and made a library. When i call the Curl library function from controller, it returns NULL but if i print the response it displays the data. Can anyone help me?
My Curl Library code :
    public function callApi($jwt_tkn, $url, $postdata, $method)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $jwt_tkn));
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }


text:
Q: My video doesn't show up with youtubebackground api I have a issue, a issue that still remains after 1 week, couldn't discover why my video doesn't show up using the youtubebackground api,
Basicly i am using bootstrap and i defined a container for my video
like this:

then i used the youtubeBackgroundapi here is the order of the scripts:

my app.js is where i put the javascript code related to the behaviour of the video
like this:
$(document).ready(function() {
  $('#video').YTPlayer({
    fitToBackground: true,
    videoId: 'mcFYvy0L2vI',
    playerVars: {
      modestbranding: 0,
      autoplay: 1,
      controls: 1,
      showinfo: 0,
      branding: 0,
      rel: 0,
      autohide: 0,
      start: 10
    }
  });
})

and finnally i changed my css like the docs said to do:
#video {
  position: relative;
  background: transparent;
}

.ytplayer-container {
  position: absolute;
  top: 0;
  z-index: -1;
}

i have no idea why it doesn't show up, i just can see the white content of the div, nothing in there, do i need to run my app in a server to put that on work?

A: Are you including the right libraries and in the right order? Note that you should include jquery before including the jquery youtube background script (see my HTML).  I was able to get it working in JSfiddle and in a Stack Overflow code snippet (see below)
EDIT Another discrepancy is that you are including Jquery 1.11.3 where the Jquery Youtube Background docs include 1.10.2. Perhaps this is making the difference?

$(document).ready(function() {
  $('#video').YTPlayer({
    fitToBackground: true,
    videoId: 'mcFYvy0L2vI',
    playerVars: {
      modestbranding: 0,
      autoplay: 1,
      controls: 1,
      showinfo: 0,
      branding: 0,
      rel: 0,
      autohide: 0,
      start: 10
    }
  });
})
#video {
  position: relative;
  background: transparent;
}

.ytplayer-container {
  position: absolute;
  top: 0;
  z-index: -1;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>


text:
Q: Some songs don't play in iTunes on macOS Some of the songs in my iTunes library refuse to play. When I double click on them, nothing happens. When I play the song before it and then skip over to the next song, it actually skips the song and thus goes forward 2 songs. There is nothing different about this song, it's part of an album where every song plays just fine, it's not unchecked or anything.
When I find this song in my Finder and play it through VLC, it plays absolutely fine, no problem at all.
I am not using Apple Music, but I do have iTunes Match. This song has the status "matched" and is downloaded to my computer. Removing the downloading and fetching it again doesn't help.


text:
Q: Azure scaleset private DNS Is there any possibility to link a scaleset to an internal Azure Load Balancer? I want to have a private scaleset that's not opened to the public for increasing security.
Thank you!

A:
Is there any possibility to link a scaleset to an internal Azure Load
  Balancer?

Yes, we can use PowerShell to deploy VMSS with the internal load balancer.
About use PowerShell to create VMSS, please refer to this link.
About use PowerShell to create internal load balancer, please refer to this link.
Here a similar case, please refer to it.


text:
Q: E-Mail's body format after procmail processing I have the following scenerio:
SMTP server on the GNU/Linux machine is accepting mails. Accepted mail is being sent to procmail for further processing. Here's my .procmailrc:
VERBOSE=yes
LOGFILE=$HOME/procmail.log
SUBJECT=`formail -xSubject: | tr -d '\n' | sed -e 's/^ //' | /usr/bin/perl -MEncode -ne 'print encode ("utf8",decode ("MIME-Header",$_ )) '`
FROM=`formail -rt -xTo:`
DATE=`formail -xDate:`
BODY=`formail -I ""`
:0fbW
* ^From.*some_special_name@special_server.com
| echo "FROM:$FROM" > $HOME/res.txt; \
  echo "DATE:$DATE" >> $HOME/res.txt; \
  echo "SUB:$SUBJECT" >> $HOME/res.txt; \
  echo "BODY:" >> $HOME/res.txt; \
  echo $BODY >> $HOME/res.txt; process.py

This little script first creates a local file $HOME/res.txt and then launches another script called process.py. Now, the $HOME/res.txt is populated with the following entries:
FROM:some_special_name@special_server.com
DATE:Mon, 06 Oct 2014 13:14:32 +0200
SUB:Some subject
BODY:
This is a multi-part message in MIME format. --------------030006020609010705060803 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit Hello, Some kind of long tekst where I cannot see the line feed chars nor any other control chars...

The body contains the raw string without the original format of the body. What I mean by this is that \n or \t characters are filtered out. The process.py script demands the body part of the message to maintain the original format of the email message.
How can I achieve this?

A: As always in shell scripts, you need to properly duoble-quote variables unless you specifically require the shell to perform token splitting and wildcard expansion on the value.  See e.g. this answer for a detailed explanation.
  echo "$BODY" >>$HOME/res.txt; \

Additionally, I don't understand why you mix multiple actions like that.  Between the lines, I guess you mean that process.py reads res.txt instead of its standard input; if it were reading standard input, it would receive the correct, unmangled message.
Without context, I'll go out on a limb and speculate that the f flag is also wrong.  Unless process.py prints a new message on standard output which should replace the incoming message for the remainder of your Procmail recipe file, you should simply take it out.
There is also a race condition here: if multiple messages arrive at roughly the same time (where "same time" can be a rather wide window if your system is under heavy load), they will overwrite res.txt and trample over each others' results in unpredicable ways.  The customary solution to that is to use a local lock file; but the vastly superior solution is to remove the need for a temporary file, and change process.py so that it reads standard input instead.
Since you are using Python anyway, I would do all the header parsing in Python, with the possible exception of formail -rtzxTo:, which is rather complex to reimplement; this would simplify your Procmail recipe significantly, and probably improve process.py (or the wrapper you create, if you cannot modify it).


text:
Q: Requests-html: searching for the xpath of an element returns an empty list I'm trying to scrape data from this website: myworkdayjobs link
The data I want to collect are the job advertisemnts and their respective data.
Currently there are 7 jobs active.
On the inspect page I can see the 7 wanted elements all having the same:
li class="css-1q2dra3"
But the page.html.xpath() always returns me an empty list.
The steps I've taken are:
session = HTMLSession()
url = (
    'https://nvidia.wd5.myworkdayjobs.com/NVIDIAExternalCareerSite'
    '?locations=91336993fab910af6d6f80c09504c167'
    '&jobFamilyGroup=0c40f6bd1d8f10ae43ffaefd46dc7e78'
    )
page = session.get(url)
page.html.render(sleep=1, keep_page=True, scrolldown=1)
cards = page.html.xpath("the_xpath_here")
print(cards)

I've also tried multiple other xpaths including the xpath I get when I copy the xpath path from rightclicking the element on the inspect page:
//*[@id="mainContent"]/div/div[2]/section/ul/li[1]/div[1]
/html/body/div/div/div/div[3]/div/div/div[2]/section/ul/li[1]/div[1]
//*[@id="mainContent"]/div/div[2]/section/ul/li[1]

Now, the only time I get results for a li element is when I
cards = page.html.xpath('//li')

Which returns me the li elements at the bottom of the page. But it fully ignores the elements that I want...
I'm not an expert on webscraping or so, but I have made it work with an other careers page before. What am I missing? Why can't I access those elements?
=========================================================
Additional information:
The problem that I experience seems to happen after the section element.
When I
cards = page.html.xpath('//*[@id="mainContent"]/div/div[2]/section/*')
print(cards)

[<Element 'p' data-automation-id='jobFoundText' class=('css-12psxof',)>, <Element 'div' data-automation-id='jobJumpToDetailsContainer' class=('css-14l0ax5',)>, <Element 'div' class=('css-19kzrtu',)>]

Why isn't there no ul element in the list? It's clearly there in the inspect window.
=========================================================
Answer
(Because the answer is in the accepted solution comment)
The page had aparently not fully loaded by the time of the assignement of cards and thus the ul was not there yet.
Adding one more second on the renderer sleep did the trick (sleep=2).
session = HTMLSession()
url = (
    'https://nvidia.wd5.myworkdayjobs.com/NVIDIAExternalCareerSite'
    '?locations=91336993fab910af6d6f80c09504c167'
    '&jobFamilyGroup=0c40f6bd1d8f10ae43ffaefd46dc7e78'
    )
page = session.get(url)
page.html.render(sleep=2, keep_page=True, scrolldown=1)
cards = page.html.xpath("the_xpath_here")
print(cards)

A: You can try to use their Ajax API to get the Json data about the jobs. For example:
import requests

api_url = (
    "https://nvidia.wd5.myworkdayjobs.com/wday/cxs/nvidia/NVIDIAExternalCareerSite/jobs"
)

payload = {
    "appliedFacets": {
        "jobFamilyGroup": ["0c40f6bd1d8f10ae43ffaefd46dc7e78"],
        "locations": ["91336993fab910af6d6f80c09504c167"],
    },
    "limit": 20,
    "offset": 0,
    "searchText": "",
}

data = requests.post(api_url, json=payload).json()
print(data)

Prints:
{
    "total": 7,
    "jobPostings": [
        {
            "title": "Senior CPU Compiler Engineer",
            "externalPath": "/job/UK-Remote/Senior-CPU-Compiler-Engineer_JR1954638",
            "locationsText": "7 Locations",
            "postedOn": "Posted 18 Days Ago",
            "bulletFields": ["JR1954638"],
        },
        {
            "title": "CPU Compiler Engineer",
            "externalPath": "/job/UK-Remote/CPU-Compiler-Engineer_JR1954640-1",
            "locationsText": "7 Locations",
            "postedOn": "Posted 26 Days Ago",
            "bulletFields": ["JR1954640"],
        },

...and so on.

A: You say you want li elements but your 3 variants of xpath point to div or single li. Try out specific xpath you need '//li[@class="css-1q2dra3"]'


text:
Q: how to create a receiving class java in Android manifest - Delphi I have a simple application android in delphi. It is already the default sms app. But I can not get messages, I've read several posts here, and by what seems to need to create a class in java even using delphi.
Example:
receiver android:name="" <-- In this field I should put the name of the java class, but how do I do this? My application is in Delphi.
Thanks

A: you need to create your own .java file, after with this java you need to create a jar, and after with this jar you need to include it in the application manager > android > librairies (in delphi berlin at least) and then in the android manifest you can add a reference to it


text:
Q: dynamic pages with .htaccess I currently have dynamic pages. For example, index.php?p=proposal opens a page from /pages/landing.php in the root of my website www/researchportal/
Currently, the page http://localhost/researchportal/proposal does seem to load by its own (just the content of proposal.php, no CSS), but not through the index.php file. Which means that the CSS is not loaded properly.
http://localhost/researchportal/index.php?p=proposal

This link loads up properly with the CSS loaded.
http://localhost/researchportal/proposal

This link doesn't contain the header and CSS which are defined in the index.php file.
My .htaccess file located in the root of my website www/researchportal/
RewriteEngine On
RewriteRule ^([A-Za-z0-9-_]+)$ index.php?p=$1

Why isnt http://localhost/researchportal/proposal loading properly?

A: I think the server request for xxx.css is rerouted to index.php you should add an exeption for your css and image directory to your regex pattern. Allowing an exception for robots.txt would be usefull too.

A: Your current rule will send all requests to index.php. You need to add a condition to prevent requests for actual files/directories that exist e.g. css from being sent to index.php
RewriteEngine On
#Also recommend that you add a an explicit RewriteBase
RewriteBase /

#only run this rule if the request is not for an existing file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9-_]+)$ index.php?p=$1


text:
Q: Databinding in user control inside another user control I have a DataBoundControl (Calendar.cs). It is a calendar that I can fill with events that are painted in it (The calendar shows the entire month and each day is divided in 24, showing different colours depending on the event that is on that hour).
Inside each day of the calendar, I have a button that opens a UserControl with the detail of the day clicked (DetailedDay.ascx). The control show all the events in that day, showing some info about them. In this user control, you can click on the event and this will open another form with the detail of the event. The event can be of different types (opening differents forms depending on the type of the event, for example EventsXXX.ascx), so this functionality is defined on the page (aspx) containing the Calendar by a delegate method.
The problem that I have is that I want the DetailedDay.ascx.cs to refresh the painted data after I change the hour of the event in EventsXXX.ascx
Right now, I am passing the events of the day in the Show method of the DetailedDay.ascx, but this obviously won't work after I change the info of one event.
I would like a way to pass the info to DetailedDay.ascx that could being refresh on postback.
Maybe something like defining an ObjectDataSource in the aspx page but that could be accessible in the control DetailedDay (remember that it is contained in another user control Calendar).
Or something like accessing parent user control (Calendar) to take the information through it.


text:
Q: $p$ divides the sum of the quadratic residues $\bmod p$ Could you help me at the following exercise?
Show that, if $p>3$ is a prime,then $p$ divides the sum of the quadratic residues $\bmod p$.

A: Let $S$ be the sum of the quadratic residues. As $k$ runs from $1$ to $p-1$, the number $k^2$ runs (twice) over the quadratic residues modulo $p$. Thus
$$2S\equiv 1^2+2^2+\cdot +(p-1)^2.$$
By using the formula for the sum of the first $n$ consecutive squares, we find that
$$2S\equiv \frac{(p-1)(p)(2p-1)}{6}\pmod{p},$$
and therefore
$$12S\equiv (p-1)(p)(2p-1)\pmod{p}.$$
Since $p$ divides $(p-1)(p)(2p-1)$ but $p\gt 3$, it follows that $p$ divides $S$.
Another way: Let $g$ be a primitive root of $p$. Then the quadratic residues are congruent, modulo $p$, to $g^2,g^4,\dots, g^{p-1}$. Thus if $S$ is the sum of the quadratic residues, we have
$$S\equiv g^2+g^4+\cdots +g^{p-1}\pmod{p}.$$
Multiply both sides by $g^2-1$. We get
$$(g^2-1)S\equiv g^2(g^{p-1}-1)\pmod{p}.$$
By Fermat's Theorem, the right-hand side is congruent to $0$ modulo $p$. And if $p\gt 3$, then $g^2\not\equiv 1\pmod{p}$, and therefore $S\equiv 0\pmod{p}$.

A: Let the quadratic residues mod $p$ be $a_1,a_2,a_3,\cdots$ and the sum is $S$.
Clearly(prove) $p|S\iff p|1^2+2^2+\cdots+(p-1)^2$
The sum is $$\frac{(p-1)p(2p-1)}{6}$$
and we are done.

A: No sum formulas are needed for this one. The non-zero quadratic residues form a subgroup $Q_p$ of the multiplicative group $\Bbb{Z}_p^*$. Because $p>3$ the residue class of $4$ is a quadratic residue. Because $\overline{4}\in Q_p$, we have, by basic properties of groups, that $x$ will range over $Q_p$ as $4x$ does. So in the field $\Bbb{Z}_p$ we have
$$
S=\sum_{x\in Q_p}x=\sum_{x\in Q_p}4x=4S.
$$
This gives the equation (still in the field $\Bbb{Z}_p$)
$$
0=4S-S=3S\quad\Longrightarrow\quad S=0,
$$
as $3$ is also a unit in the field.
Mapping everything back to integers gives then $S\equiv 0\pmod p$ as requested.


text:
Q: Include SQL in XML Is it possible to include an SQL query inside an XML into raw/ directory? For example:
<query name ="mainQuery">SELECT e.*, et.name as name FROM employee e, employee_type et where e.type = et._id and et._id < et._id</query>

or
<query name ="mainQuery" value="SELECT e.*, et.name as name FROM employee e, employee_type et where e.type = et._id and et._id < et._id" />

Both these give errors on XML structure. One workaround is using < and friends, but this really makes no sense as SQL syntax.
Thanks in advance.

A: Have you looked into putting the query in a comment and then reading the comment from within your activity?
See here: http://www.codeproject.com/Articles/11178/Writing-SQL-queries-in-XML-A-support-intensive-app

A: You can use CDATA. Example:
<query name ="mainQuery"><![CDATA[SELECT e.*, et.name as name FROM employee e, employee_type et where e.type = et._id and et._id < et._id]]></query>


text:
Q: Disabling the default MediaRecorder sound in camcorder apps I am currently developing an Android Camera/Camcorder application, and I am looking to play my own sounds when capturing video and pictures.
I am using Camera API (not Camera2, I will be using this later) to develop the app
When capturing pictures, using Camera.takePicture(), I have successfully disabled the shutter sound using CameraInfo.canDisableShutterSound() and Camera.enableShutterSound(false)
When capturing video though, as soon as I have the MediaRecorder object start capturing frames, the default "bloop" noise plays at the same time as mine. Is there a way to disable the MediaRecorder sound, similar to Camera.enableShutterSound(false), that I am missing in the API docs? Is there a system setting I can request to be change from my app? Or am I out of luck?


text:
Q: Yoda Speak Api. Is it the key or code? I am trying to use the Yoda speak api. Here is my fiddle of it:

*

*http://jsfiddle.net/Dansker/tdhnmmye/
$.ajax({
    url: 'https://yoda.p.mashape.com/yoda', // The URL to the API. You can get this by clicking on "Show CURL example" from an API profile
    type: 'GET', // The HTTP Method
    data: {sentence: $("#boxArea").val()}, // Additional parameters here
    datatype: 'json',
    success: function (data) {
        alert(data);
    },
    error: function (err) {
        alert(err);
    },
    beforeSend: function (xhr) {
        xhr.setRequestHeader("X-Mashape-Authorization", "<RvyROurVRvmshRzDcAtXABdytvkDp1MtroWjsnXo8Dcs9Dq6SB>"); // Enter here your Mashape key
    }
});});});

I think the code all works but I keep getting 403 errors saying my key does not work. I keep resetting my key but it keeps saying that it does not work. Is it the key or something else? Also the "yoda speak" will be displayed as alert?

A: Just a guess, but have you tried removing the outer angle brackets?
Try changing this:
xhr.setRequestHeader("X-Mashape-Authorization", "<RvyROurVRvmshRzDcAtXABdytvkDp1MtroWjsnXo8Dcs9Dq6SB>");

To this:
xhr.setRequestHeader("X-Mashape-Authorization", "RvyROurVRvmshRzDcAtXABdytvkDp1MtroWjsnXo8Dcs9Dq6SB");


text:
Q: How can I apply a function to a dataframe which needs a row index in Pandas? I have to use survey data from ipums to get the average number of people who are unemployed in two successive periods. I wrote a function that uses an index and a dataframe as input,
def u1(x,df):
if df.loc[x]['LABFORCE']==2 and df.loc[x]['CPSIDP']==df.loc[x+1]['CPSIDP']:
    if df.loc[x]['EMPSTAT']==21 or df.loc[x]['EMPSTAT']==22:
        return True
else:
    return False

where x is the index and df is the dataframe. CPSIDP identifies the survey respondent, LABFORCE checks the respondent is in the labor force and EMPSTAT is what I need to use to check the employment status of the respondent.
And then I planned to use apply as
result= df.apply(u1, axis=1)

It is not clear what arguments I should pass in my function (and please let me know if this approach is just philosophically wrong). Passing a number or a variable for the index gives me a 'bool' object is not callable error.
The smallest dataframe subset that generates the error (left most column is the number of the observation, it is the x I need to pass through u1):
          YEAR  MONTH          CPSIDP  EMPSTAT  LABFORCE
15285896  2018      7  20180707096701       10         2
15285926  2018      7  20180707098301       10         2
15285927  2018      7  20180707098302       10         2
15285928  2018      7  20180707098303        0         0
15285929  2018      7  20180707098304        0         0
15285930  2018      7  20180707098305       10         2
15286095  2018      7  20180707108203       21         2

A: IIUC it would be more efficient to create a boolean Series using the logic from your function.
Here & is the AND operator.
result = (df['LABFORCE'].eq(2) &
           df['CPSIDP'].eq(df['CPSIDP'].shift()) &
           df['EMPSTAT'].isin([21,22]))

result

15285896    False
15285926    False
15285927    False
15285928    False
15285929    False
15285930    False
15286095    False


text:
Q: Can an awaited Task return false in IsCompleted I found this piece of code:
Task task = DoSomethingAsync( someObject );
await task.ConfigureAwait( false );
if ( task.IsCompleted ){ ... }

I wonder if I can safely replace it with
await DoSomethingAsync( someObject ).ConfigureAwait( false );

and drop the if clause.
My question: can task.IsCompleted ever be false when an awaited task has returned?
The documentation of IsCompleted  tells us:

true if the task has completed (that is, the task is in one of the three final states: RanToCompletion, Faulted, or Canceled); otherwise, false.

I looked up the possible states but it is still not clear to me which of the states is possible when the awaited task hast returned.
Please help me to shed light on this matter. Thanx in advace.

A: Docs: await operator (C# reference)

The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes.

After Task taskInstance = ...; await taskInstance;, taskInstance.IsCompleted will always be true.

A: Based on this article:
https://profinit.eu/en/blog/lets-dive-into-async-await-in-c-part-3/
the example that you found is a bad approach. So you can use safely the version:
await DoSomethingAsync( someObject ).ConfigureAwait( false );

You can omit ConfigureAwait(false) but depends on the context where you use the method DoSomethingAsync.


text:
Q: Como dividir corretamente um número até somente um digito em C? Eu tenho a seguinte função :
divisibilidade11(int num);

E as seguintes variáveis :
int dividendo;
int divisor;

Quando o usuário entrar com o digito 11 para a variável divisor a função divisibilidade11 será chamada e irá verificar se a variável dividendo é divisível pelo divisor. E para verificar se é ou não divisível, terá que seguir os critérios : Caso a soma deste algarismo de ordem par (Sp) subtraído da soma de ordem impar (Si), resultar em 0 ou em um número divisível por 11, ele retorna true e caso não, ele retorna false.
Exemplo :

O usuário entra com o número 2376 para a variável dividendo;
O usuário entra com o número 11 para a variável divisor;
É chamada a função divisibilidade11, para verificar se é ou não divisível;
É feita a soma dos impares (Si) = 3+6 = 9;
É feita a soma dos pares (Sp) = 2+7 = 9;
Si - Sp = 0; Logo, portanto, 2376 é divisível por 11.
OBS : O algarismo mais a direita é o primeiro de ordem impar.

Exemplo de como apareceria para o usuário :

A função divisibilidade11 tem que repetir o processo até que o resultado seja um número com um digito. Se este digito for igual a 0, então o número original é divisível por 11.

A: Utilizando Strings
Sabendo que o valor máximo para inteiros que a maioria dos computadores suporta nos dias atuais é de até 19 dígitos, utilizarei uma string de 20 dígitos para realizar esta operação.
#include <string.h>
#include <stdio.h>

char divisibilidade11(long long int dividendo){
    char array_numerico[20] = "";
    int total_par = 0;
    int total_impar = 0;
    snprintf(array_numerico, 20, "%lld", dividendo);
    for(char iterador = strlen(array_numerico) - 1, par = 0; iterador >= 0; iterador -= 1){
        if(!par){
            total_impar += array_numerico[iterador] - 48;
            par = 1;
        }
        else{
            total_par += array_numerico[iterador] - 48;
            par = 0;
        }
    }
    if((total_par - total_impar) == 0 || ((total_par - total_impar) % 11 == 0)){
        return 1;
    }
    else{
        return 0;
    }
}

Utilizando Operações Matemáticas Decimais
char divisibilidade11(long long int dividendo){
    int total_par = 0;
    int total_impar = 0;
    char par = 0;
    while(dividendo != 0){
        if(!par){
            total_impar += (dividendo % 10);
            par = 1;
        }
        else{
            total_par += (dividendo % 10);
            par = 0;
        }
        dividendo /= 10;
    }
    if((total_par - total_impar) == 0 || (total_par - total_impar) % 11 == 0)
        return 1;
    else return 0;
}


text:
Q: Database design for "alternate" names with master reference What would be the best practice to store alternate names for entities and link them to a "master" record for rolling up data?
For example, I have a list of companies;
id name
1  Orange Kid Industries
2  Apple Kid Inc.
5  O.K.

Company 5 O.K. is an alternate name for 1 Orange Kid Industries. These companies need to be stored discreetly so that if a child record needs to be tied to 5 and not 1, (in the interest of storing historical data if the company name changed for instance,) it can.
I need to tie 5 O.K. back to 1 Orange Kid Industries as the "master" record so, when looking at all children of 1 Orange Kid Industries, I see all children of 1 and 5 combined.
I'm leaning toward a required master ID for all records. If a user creates a new company 6 Moldy Orange Kid Industries, he can assign it a master ID of 1 to signify that this is just another name for 1 Orange Kid Industries.
id name                        master
1  Orange Kid Industries       1
2  Apple Kid Inc.              2
5  O.K.                        1
6  Moldy Orange Kid Industries 1

This seems to be the simplest route without requiring much redundant data. Are there any downsides to this approach?

A: That seems like a good solution to me.  The only think I might change is to leave master null if a record is it's own master.  Probably not a huge deal, but seems like a potential infinite loop pitfall.

A: I think I would normalize the data.  A company master table and a company names table end a company names table that would have foreign key to the company master table.  I would also avoid nulls and any logic based on nulls enforce foreign key constraints.  The null mean you do not know.


text:
Q: Design inquiry: Choosing between Singleton, Factory, etc I have read the book First Java: Design Patterns and am a newbie.
I'm making my own game engine just for practice and I'm using Singleton Pattern (I know that's a sin for most of you) to create unique classes like: InputManager, ScreenManager, GameManager, etc. I really find it useful, but I don't want to go against the current.
Is it wiser maybe to use the Factory Method to create this classes (maybe creating them as inner classes) and then pass those objects to whatever class needs them?
Is that bad practice too?
I just want to make sure that there's one instance of those unique classes and only one way to access them.
Maybe something like:
public final class Factory(){
private static final InputListener inputlst = new InputListener();
private static final Screen window = new Screen();
private static final GameManager gameManager = new GameManager();
public Factory(){
}
public static InputListener getInputListener(){
    return inputlst;
}
public static Screen getWindow(){
    return window;
}
private static class InputListener implements KeyListener, MouseListener, MouseMotionListener, MouseWheelListener{
}
private static class Screen extends JFrame{
}
private static class GameManager{
}

A:
I just want to make sure that there's one instance of those unique classes and only one way to access them.

Sounds like the singleton pattern to me: static accessor in the class returns the single instance of that class.
Don't try to overcomplicate things up front with inner classes/passing things around unless you find that you absolutely need to.  See Difference between singleton and factory pattern for some further reading that might help you out.

A: If you want to have exactly one instance of those unique classes then singleton is the pattern for you with some method like getInstance etc.
Factory pattern is one which creates and returns new objects of different type but invaribale extending from the same subclass. It's a way of abstracting the instantiation of a class.

A: Frankly patterns are there for a reason. The reason is simple. What change do you expect in your code in future. There is nothing like a good practice to use patterns. You use where do you expect the change, based on where you expect the change, you need to take the part that changes OUT and SEPARATE from the part that remains constant. When you do this patterns help you understand.
No SINGLETON is not evil. Its usage is evil. Singleton is a WONDERFUL pattern used to solve a very unique problem with OOP's and OOAD.
Factory cannot be used in place of SINGLETON. Both have very unique propositions. Who knows, if you take time to understand your requirements (and future requirements) carefully, you may realize that you need to use a mix of both. You may need just one factory, and may need to make that factory singleton.
Understand the change, the future change and separate out what changes from what remains constant


text:
Q: VBA Excel pie chart plotting, how do i select the correct pie chart? I am plotting a lot of piecharts, but the problem i have is selecting the correct pie charts.
But somehow excel gives me the wrong chart, there are two types of Pie charts, i want the one marked in
this picture with a green circle, however my code gives me the one marked with RED :(
Pie chart selection  ->   https://imgur.com/a/KTy9xzA
     With Sheets("Visualisation").ChartObjects.Add _
        (Left:=rng.Left, Width:=rng.Width, Top:=rng.Top, Height:=rng.Height)

        .Chart.SetSourceData Source:=Sheets("Data").Range("F4:H4") '  PlotBy:=xlColumns
        .Chart.SetElement (msoElementChartTitleAboveChart)
        .Chart.SetElement (msoElementPlotAreaShow)
        .Chart.HasLegend = False
        .Chart.ChartType = xlPie

        .Chart.PlotArea.Format.Fill.Visible = msoFalse
        .Chart.ChartArea.Format.Fill.Visible = msoFalse
        .Chart.ChartArea.Format.Line.Visible = msoFalse

' more stuff, about placement etc....
     End with

I also notice there is a difference in the plot code.
The full blue one shows
=SERIES(;;Data!$F$4;1)
As if it is ONLY showing F4
The correct one shows
=SERIES(;;Data!$F$4:$H$4;1)
Correctly including F, G and H  4..
Any suggestions on how to select the correct one in VBA?


text:
Q: Libertine font numbers have a different height than text Currently I am writing my thesis and I want the libertine font because for example the Capital "ß" and other stuff. Following to my question, is it possible to set the numbers height on the same height as the text?
Thank you.
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Linux Libertine O}
\begin{document}
55155TTT
\end{document}

Some Examples from my thesis, also in my \cite for example [Mar06] it looks strange

A: The height of numbers in some fonts tend to be optimised for appearance in normal text which means that they usually are slightly smaller than the height of the upper case glyphs.
This however becomes an issue when these glyphs are surrounded by upper case. Numbers are not the only glyphs that follow that rule, the dash is also on of these glyphs that can require change when surrounded by upper case.
To fix that, some fonts include the case feature that will switch to the "upper case" glyphs instead. That feature is probably not to be used throughout your document but can be used sporadically when needed.
Where it becomes a judgement call is then you have these glyphs between an upper and a lower case.
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Linux Libertine O}

\begin{document}

Without the \texttt{case} feature:\\
55155TTT, DIN4322, H13, Figure 5\\
CD-ROM or cd-rom\\

With the \texttt{case} feature:\\
{\addfontfeatures{RawFeature={+case}}%
55155TTT, DIN4322, H13, Figure 5\\
CD-ROM or cd-rom}

\end{document}


text:
Q: Flutter Bloc - Register Handler issue I am looking for some help with my code. I want to create some swappable cards and for that I have created blocs. However, when I finished and tried to launch it, following message appears :

Bad state: add(LoadMissionsEvent) was called without a registered event handler.
Make sure to register a handler via on((event, emit) {...})

  class MyApp extends StatelessWidget {
  const MyApp({
    Key key,
  }) : super(key: key);
  // final StreamChatClient client;
  // final Channel channel;

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
        providers: [
          BlocProvider(
              create: (_) => SwipeBloc()
                ..add(LoadMissionsEvent(
                    missionDescriptions:
                        MissionDescription.missionsDescriptions)))
        ],
        child: MaterialApp(
          debugShowCheckedModeBanner: false,
          title: "Student App",
          home: MissionChoice(),
          localizationsDelegates: [GlobalMaterialLocalizations.delegate],
          supportedLocales: [Locale('en'), Locale('fr')],
          // Scaffold(
          //   backgroundColor: d_green,
          // ),
        ));
  }
}


text:
Q: ACE Editor Autocomplete to open on `.` If you enable live autocomplete, the tooltip opens up as you type things. However, it will never open up on pressing . until you type something else after.
So if I were to type fo there will be a tooltip trying to match fo to something (for or function, etc). However, if type fo. then the tooltip disappears, and it will not open until I type a further letter.
I have custom autocompletion keys, and I really want the tooltip to open up with all my suggestions.
Let's say I have user as a special key with name, age, profile as the suggestions. I want to be able to type event. and the tooltip to show name, age, profile. Right now, I have to type event.n for example to get name to show as a suggestion.

A: Use this snippet of code during the editor initialization to show the tooltip to open up with all the suggestions
editor.commands.on("afterExec", function (e) {
    if (e.command.name == "insertstring" && /^[\w.]$/.test(e.args)) {
        editor.execCommand("startAutocomplete");
    }
});

A: This worked for me for special characters (I needed the autocomplete on '.' and '{'. For some reason it is not working for '$':
@ViewChild('editor') public aceEditor: AceEditorComponent;
let editor = this.aceEditor.getEditor();
// create your completers
this.langTools.setCompleters(completers);
// trigger typeahead
editor.completer.showPopup(editor);

A: Found a simple solution for that finally:
const doLiveAutocomplete = editor => {
  editor.insert('.');
  editor.execCommand('startAutocomplete');
};

Use enableLiveAutocompletion with a custom command { bindKey: { win: '.', mac: '.' }, exec: doLiveAutocomplete }.
Using react-ace it's simply:
<AceEditor
  {...props}
  enableLiveAutocompletion
  commands={[{ bindKey: { win: '.', mac: '.' }, exec: doLiveAutocomplete }]} />


text:
Q: Unable to create workflows in SPD I'm currently trying to develop a workflow for my site but am having a hard time. When I access the site online through the web, I am able to create a workflow. However, whenever I access the site via SharePoint designer, I am unable to create a workflow.
When I try to create a new workflow on SPD, it allows me to enter the name but it never shows up. In addition, the WFs that I create on the web shows up in SPD when I click on the associated list, but never on the workflow list on the left panel.
Thanks for your help.


text:
Q: Are there numbers with the property that the sum of their squares equals the square of their sum? Are there numbers a and b with the property that
$a^2 + b^2= (a+b)^2$
Note that the answer is yes. For instance, $a=0 , b= \mathbb{R}$ would work. Can you think of other numbers that would also work?
I have found that it will also work when $a=0 , b=0$
Can you think of others ?

A: As has been said in the comments you can reduce the property in the following way
$$ a^2 + b^2 = (a+b)^2 \Leftrightarrow a^2+b^2 = a^2+2ab+b^2 \Leftrightarrow 0 = 2 a b$$
which just reduces to $a b = 0$. Therefore the solutions you found are all there are because for a product to be zero at least one of the factors has to be zero.


text:
Q: Reverse has_many with polymorphism I have two models:  Users and Projects.  The idea is that Users can follow both projects AND other users.  Naturally, Users and Projects are part of a polymorphic "followable" type.  Now, using the user model, I'd like to get three things:
user.followed_users
user.followed_projects
user.followers

The first two work fine; It's the third that I'm having trouble with.  This is sort of a reverse lookup where the foreign key becomes the "followable_id" column in the follows table, but no matter how I model it, I can't get the query to run correctly.
User Model
has_many :follows, :dependent => :destroy
has_many :followed_projects, :through => :follows, :source => :followable, :source_type => "Project"
has_many :followed_users, :through => :follows, :source => :followable, :source_type => "User"
has_many :followers, :through => :follows, :as => :followable, :foreign_key => "followable", :source => :user, :class_name => "User"

Follow Model
class Follow < ActiveRecord::Base
  belongs_to :followable, :polymorphic => true
  belongs_to :user
end

My follows table has:
 user_id
 followable_id
 followable_type
Whenever I run the query I get:
SELECT `users`.* FROM `users` INNER JOIN `follows` ON `users`.`id` = `follows`.`user_id` WHERE `follows`.`user_id` = 7

where it should be "followable_id = 7 AND followable_type = 'User", not "user_id = 7"
Any thoughts?

A: Figured it out.  Took a look at a sample project Michael Hartl made and noticed that the correct way to do this is to specify not only a relationship table (in this case follows) but also a reverse relationship table (which I called reverse follows).
    has_many    :follows,
                        :dependent => :destroy

    has_many    :followed_projects,
                        :through => :follows,
                        :source => :followable,
                        :source_type => "Project"

    has_many    :followed_users,
                        :through => :follows,
                        :source => :followable,
                        :source_type => "User"

    has_many    :reverse_follows,
                        :as => :followable,
                        :foreign_key => :followable_id,
                        :class_name => "Follow"

    has_many    :followers,
                        :through => :reverse_follows,
                        :source => :user

Hope this helps some people out down the line!

A: I think you need to explicitly spell out the foreign key. You have:
:foreign_key => "followable"

you need:
:foreign_key => "followable_id"

full code:
has_many :followers, :through => :follows, :as => :followable, :foreign_key => "followable_id", :source => :user, :class_name => "User"


text:
Q: Add custom network device icons in Mac OS X Finder? Mac OS X Finder is smug enough to display any non-Mac device as a picture of a PC with a BSOD, but I'm wondering if it's possible to add other devices, so my Ubuntu machine is detected and has a picture of a Ubuntu PC, and my Windows PCs has a picture of Windows crashing, etc.
I know that public.generic-pc.icns exists and can be replaced but I'm not interested in replacing it per se, more interested in getting finder to recognise other devices (or learn how it recognises other Apple devices) and map custom icons to them.
Any clue?

A: Seems that I was very close, I just wasn't getting my machine to advertise itself properly.
I finally got it to work:

The method I used is below:

*

*First, on the Mac, I created a custom bundle which I called "ComputerTypes" by copying and pasting an existing bundle such as MobileDevices.bundle or MachineTypes.bundle in the /System/Library/CoreServices/CoreTypes.bundle/Contents/Library folder.

*I then opened Contents/Info.plist with XCode Plist Editor and edited all the details to create a custom bundle, changing the Bundle Identifier, Name, etc.

*I removed all the existing entries in the "UTExportedTypeDeclarations" key then created a new entry per device. Each device entry has a "UTTypeConformsTo", "UTTypeDescription", "UTTypeIconFile", "UTTypeIdentifier" and "UTTagSpecification", where the "UTTagSpecification" dictorinary contains an Array in the key "com.apple.device-model-code" with all of the mDNS _device-info._tcp identifiers to accept. UTTypeIconFile refers to a icns file in the Resources folder.

*I then saved the bundle to /System/Library/CoreServices/CoreTypes.bundle/Contents/Library folder and rebooted.

*On the other machine, I needed to set up to advertise a _smb._tcp service as well as the _device-info._tcp TXT record, as usual except using a custom model name rather than a Mac product name.

*After rebooting the Mac, it should appear like the picture above.
I uploaded the finished bundle to http://dl.dropbox.com/u/4140005/ComputerTypes.bundle.zip as an example.

A: This is probably only worthy of being a comment to Adam's answer, but I need formatting.
In Windows, assuming iTunes or Bonjour for Windows is installed, you can advertise a samba share with the following:

*

*Open two cmd prompts.

*Run the following commands (in different consoles):
dns-sd -R ComputerName _device-info._tcp local 445 model=Xserve3,1
dns-sd -R ComputerName _smb._tcp local 445
Dns-sd won't exit, and if you Ctrl-C or close cmd, the share will disappear from Finder. I can only manage to use the default OSX icons, despite Adam's helpful sample file (it might be a 10.6 vs. 10.8 issue... there are plist differences between his and 10.8's). Also, I'm having a heck of a time figuring out how to get windows to run this command and shut it down at poweron/poweroff and wake/sleep (though, to shut down dns-sd from a bat script you'd just use taskkill).

A: I can't comment because of rep but I would like to add to this because people now might come across it and want to pull this off. With Sierra's SIP implementation, Adam's method no longer works by default due to the inability to copy files to any CoreServices subdirectories. You would have to disable SIP first.
Before I go further you must understand that SIP is a protective measure put in place by Apple to make sure the integrity of your system is not compromised.
I will not go into how I feel about SIP as an application developer but suffice it to say that I'm not always in sync with Apple's decision making.
To do this:
Reboot your Mac.
When you hear the chime, press and hold CMD+R until you see the desktop start to appear.
From the 'Utilities' menu on the top, select 'Terminal'
Type "csrutil disable" and hit enter.
Type "reboot" and hit enter.
SIP is now disabled. I generally don't care for SIP myself but understand I'm in the minority. Also, I don't want Apple too mad at me. That said, I recommend if you are doing this to replace a system icon that you reenable SIP immediately when you are done. To do so, follow the instructions to disable but replace the word "disable" with "enable".


text:
Q: Mismatched type error with functions in a hash map I am trying to create a hash map where the key is a string and the value is a function fn(&f32,&f32) -> f32. The error gives me mismatched types and I do not know what I am missing.
use std::collections{Hashmap}
use lazy_static::lazy_static;
// declared functions
fn fnc1(x:&f32, y: &f32) -> f32 {
    x+y
}
fn fnc2(x:&f32, y: &f32) -> f32 {
    x-y
}

// creating and populating hashmap

lazy_static! {
    static ref OPS: HashMap<&'static str, fn(&f32, &f32) -> f32> = {
        let mut m = HashMap::new();
        m.insert("sum", fnc1);
        m.insert("minus", fnc2); // Error occurs on this line with fnc
        m
    };

Error below
mismatched types
expected fn item `for<'a, 'b> fn(&'a f32, &'b f32) -> _ {fnc1}`
   found fn item `for<'a, 'b> fn(&'a f32, &'b f32) -> _ {fnc2}`
constraint.rs(24, 11): arguments to this function are incorrect
map.rs(1103, 12): associated function defined here


text:
Q: How to download the notebook from watson studio desktop How does one download a notebook from Watson Studio Desktop?
We are trying to test the notebooks from watson studio desktop to work with WML Server.We want to download this notebooks so that we can put them in github for our users to be able to access.
However, there are no options under the File menu, or the action menu when looking at the project assets.

A: There is no download notebook option in WSD from the notebook page.  To retrieve the notebook you need to find the notebook in the Application data folder.
From the project you can go to the View folder link and navigate to the project assets.
Documented here:
https://www.ibm.com/support/knowledgecenter/SSBFT6_1.1.0/wsd/files.html


text:
Q: How to render a 7 minutes video duration but only play 4 minutes and then stop but total length of video is still remain 7 minutes with ffmpeg? How to render a 7 minutes video duration but only play 4 minutes and then stop but total length of video is still remain 7 minutes when i uploaded it to youtube, just like this image:
enter image description here
I try nullsrc fillter but it didn't success,it's still play entire 7 minutes to end video not 4 minutes
I had researched google but i didn't have a clue, then is there a way to do it?

A: You'll need streams of unequal lengths, and will have to stop ffmpeg from duplicating frames to match audio length.
ffmpeg -f lavfi -t 240 -i color -i 7-min-audio -vsync vfr out.mp4


text:
Q: Unable to connect to postgresql with pgAdmin4: readonly attribute error I have a local postgresql 10 server (tested the same on 9.6, don't think it's related to the DB at all, only to pgAdmin4, as pgAdmin3 works just fine)
As in the screenshot, I am trying to connect to the localhost db with user postgres on a fresh installation, but I keep receiving this message:
readonly attribute

I searched everywhere for this error, but couldn't find any useful solutions or workarounds

A: This error is related to psycopg2. Please verify the version of psycopg2 installed on your system and update it to at least version 2.7.
At version 2.7 psycopg2 connection class the notices attribute is writable. On earlier versions it is a read only attribute.
If you comment the code in line 313 of /usr/share/pgadmin4/web/pgadmin/utils/driver/psycopg2/connection.py you could check it out.
#pg_conn.notices = deque([], self.ASYNC_NOTICE_MAXLENGTH)

A: You can try using pgAdmin4 wheel file, you will not face any such issues of an older version of packages from the native repo.
https://askubuntu.com/questions/831262/how-to-install-pgadmin-4-in-desktop-mode-on-ubuntu

A: pg4Admin 4 now is working for me. I got an update of python-psycopg2 to 2.7.4-1.pgdg16.04+1 amd64 version on my KDE Neon, that solved, to me, the readonly attribute problem.

A: I am on Ubuntu 16.04, but using postgresql and pgAdmin from apt.postgresql.org.  I struck this bug.  But the new version of psycopg2 that came through with the latest apt update solved the problem for me.


text:
Q: IE10 on Windows 7 page redirect not behaving as expected I am doing my testing on IE 10 standards mode. I have a Login.aspx page which is in Login directory (i.e Login/Login.aspx). I do response.redirect to a page Default.aspxwhich is a page in root directory(ie. Response.Redirect("../Default.aspx",true);). Also tried ~/Default.aspx to navigate to root. But instead of going to Default.aspx control reaches to Login.aspx.
I do observe in IE developer's tool that it hits Default.aspx but transaction time < 1ms. I see it do not hit init/load event defined in default.aspx. Instead of redirect if I use Server.transfer it works but i want it to work with redirect only.
Also it works fine in my colleagues machine without making any change and also on latest firefox and chrome on my machine it works fine. It works fine on IE9 standard too on my machine but not on IE 10 standard.
Anyone happen to know if any setting or something I am missing.
Thanks in advance

A: You can use the DestinationPageUrl parameter?
<asp:Login ID="Login1" runat="server" PasswordRecoveryText="Password forgotten?"
                    DestinationPageUrl="~/Default.aspx"
                    >
                </asp:Login>

A: Check your Antivirus settings,
Got the same issue at work  ...
For another real life sample
go here
http://www.trojaner-board.de/133535-redirect-problem-ihavenet-ie10-win7.html
hope it'll help


text:
Q: PARABOLA : Problem Find the equation of line touching both the parabolas
$$ x^2=-32y.......(1)$$ $$ y^2=4x.........(2) $$
i have equated slopes of both the parabolas and applied the condition that all the points on the line lie outside the parabolas.

A: HINT:
Parametric equation of $x^2=-32y: x=8t,y=-2t^2$
The equation of tangent at $(8t,-2t^2)$  will be  $$x(8t)=-16(y-2t^2)\iff xt+2y-4t^2=0$$
Similarly find the equation of tangent of $y^2=4x$ at $(v^2,2v)$
These two equation must be same$\implies$
the ratio of the coefficients of $x$
$=$ the ratio of the coefficients of $y$
$=$  the ratio of the constants

A: General equation for a tangent of the parabola $y^2=4ax$ is $y=mx+\frac{a}{m}$.And similarly for the parabola $x^2=4by$ the general equation of tangent is $x=ny+\frac{b}{n}$.According to the question $a=1$ and $b=-8$.And by comparing the equations $y=mx+\frac{1}{m}$ and $x=ny-\frac{8}{n}$(which have to be the same) we can conclude that $m=0.5$ and $n=2$.Therefore the equation of the tangent is :- $$x=2y-4$$I hope this was helpful.

A: Let the common tangent line be $y=mx+q$. Then we know that the resolvent equations of the systems
$$
\begin{cases}
y=mx+q\\
x^2=-32y
\end{cases}
\qquad
\begin{cases}
y=mx+q\\
y^2=4x
\end{cases}
$$
have zero discriminant. The resolvent equations are
$$
x^2+32mx+32q=0
\qquad
m^2x^2+(2mq-4)x+q^2=0
$$
so we get
$$
\begin{cases}
32^2m^2-4\cdot32q=0\\[4px]
(2mq-4)^2-4m^2q^2=0
\end{cases}
$$
that simplifies to
$$
\begin{cases}
q=8m^2 \\[4px]
mq-1=0
\end{cases}
$$
Can you finish?


text:
Q: How do I get an instance of IAppBuilder elsewhere in my ASP.NET MVC 5.2.3 application? I need to build an Owin middle-ware object but not from within the Startup class. I need to build it from within anywhere else in my code, so I need a reference to the AppBuilder instance of the application. Is there a way to get that from anywhere else?

A: You could simply inject AppBuilder itself to OwinContext. But since Owin context only supports IDisposable object, wrap it in IDisposable object and register it.
public class AppBuilderProvider : IDisposable
{
    private IAppBuilder _app;
    public AppBuilderProvider(IAppBuilder app)
    {
        _app = app;
    }
    public IAppBuilder Get() { return _app; }
    public void Dispose(){}
}

public class Startup
{
    // the startup method
    public void Configure(IAppBuilder app)
    {
        app.CreatePerOwinContext(() => new AppBuilderProvider(app));
        // another context registrations
    }
}

So in everywhere of your code you have access IAppBuilder object.
public class FooController : Controller
{
    public ActionResult BarAction()
    {
        var app = HttpContext.Current.GetOwinContext().Get<AppBuilderProvider>().Get();
        // rest of your code.
    }
}


text:
Q: How to modify the shell prompt? I would like to learn how to make my shell look like this:
[user@host ~/Folder]
$

instead of (the default):
[user@host ~/Folder]$.

Also, I'd like to have color on user@host and Folder. How can I do this?
Note: This prompt is my model.

A: Here's a script that I personally use:
###
### Set the prompting to my liking
###

    # Save the old prompt

OLD_PS1="$PS1"

    # Put the "non-printing" characters between \[ and \] for the prompt so
    #  that the shell can properly determine the length of the prompt.

if [ -z "$TERM" ] || [ "$TERM" = "dumb" ]
then
    BOLD=""
    NORM=""
    BLUE=""
    BLACK=""
    RED=""
else
    BOLD="\\[$(tput bold)\\]"
    NORM="\\[$(tput sgr0)\\]"
    BLUE="\\[$(tput setf 1)\\]"
    BLACK="\\[$(tput setf 0)\\]"
    RED="\\[$(tput setf 4)\\]"
fi

PS1="$NORM"'\n'"$BOLD"'\w'"$NORM"'\n'"$BLUE"'\u@\h, $?>'"$NORM"' '

    # For use with set_prompt_comment:
BASE_PS1="$PS1"

##
##
##

set_prompt_comment ()
{
    typeset comments

    if [ -z "$BASE_PS1" ]
    then
        echo "Need BASE_PS1 to be defined to proceed!" >&2
    else
        comments="$*"

        if [ -z "$comments" ]
        then
            PS1="$BASE_PS1"
        else
            PS1="\\n${RED}${comments}${BASE_PS1}"
        fi
    fi
}

Working with this, the following may give what you want:
PS1="[${RED}user@host${NORM} ${BLUE}~/Folder${NORM}]\\n$ "


text:
Q: How to use bit manipulation to find 5th bit, and to return number of 1 bits in an integer Assume Z is an unsigned integer. Using ~, <<, >>, &, | , +, and - provide statements which return the desired result.
I am allowed to introduce new binary values if needed.
I have these problems:
1.Extract the 5th bit from the left Z.
For this I was thinking about doing something like
  x x x x x x x x
& 0 0 0 0 1 0 0 0
___________________

  0 0 0 0 1 0 0 0

Does this make sense for extracting the fifth bit? I am not totally sure how I would make this work by using just Z when I do not know its values. (I am relatively new to all of this). Would this type of idea work though?
2.Return the number of 1 bits in Z
Here I kind of have no idea how to work this out. What I really need to know is how to work on just Z with the operators, but I m not sure exactly how to.

Like I said I am new to this, so any help is appreciated.

A: Problem 1
You're right on the money.  I'd do an & and a >> so that you get either a nice 0 or 1.
result = (z & 0x08) >> 3;

However, this may not be strictly necessary.  For example, if you're trying to check whether the bit is set as part of an if conditional, you can exploit C's definition of anything nonzero as true.
if (z & 0x08)
        do_stuff();

Problem 2
There are a whole variety of ways to do this.  According to that page, the following methodology dates from 1960, though it wasn't published in C until 1988.
for (result = 0; z; result++)
        z &= z - 1;

Exactly why this works might not be obvious at first, but if you work through a few examples, you'll quickly see why it does.
It's worth noting that this operation – determining the number of 1 bits in a number – is sufficiently important to have a name (population count or Hamming weight) and, on recent Intel and AMD processors, a dedicated instruction.  If you're using GCC, you can use the __builtin_popcount intrinsic.

A: Problem 1 looks right, except you should finish it by shifting the result right by 4 to get that bit after the mask.
To implement the mask, you need to know what integer is represented by a single 5th bit. That number is incidentally 2^5 = 32. So you can just AND z with 32 and shift it right by 4.
Problem 2:
int answer = 0;
while (z != 0){  //stop when there are no more 1 bits in z

   //the following masks the lowest bit in z and adds it into answer
   //if z ends with a 0, nothing is added, otherwise 1 is added
   answer += (z & 1);
   //this shifts z right by 1 to get the next higher bit
   z >>= 1;
}
return answer;

A: To find out the value of the fifth bit, you don't care about the bottom bits so you can get rid of them:
unsigned int answer = z >> 4;

The fifth bit becomes the bottom bit, so you can strip it off with a bitwise-AND:
answer = answer & 1;

To find the number of 1-bits in a number you can apply stakSmashr's solution. You could optimise this further if you know you need to count the number of bits in a lot of integers - precompute the number of bits in every possible 8-bit number and store it in a table. There will only be 256 entries in the table so it won't use much memory. Then, you can loop over your data one byte at a time and find the answer from the table. This lookup will be quicker than looping again over each bit.


text:
Q: Adding Marginal Histogram to Highcharter Stock Chart I want to add a marginal histogram to a highcharter stock chart but not having any luck. Below is a minimal code example that I am using.
library(highcharter)
library(TTR)

data(ttrc)
ticker<-ttrc

hc_base <- highchart(type = "stock")%>%
  hc_xAxis(categories = as.vector(ticker$Date),
           offset=0, opposite=FALSE,
           reversed=FALSE, gridLineColor="black")%>%

  hc_add_series(data=ticker[,5],
                visible = TRUE)%>%

  hc_add_series(data=list(x=hist(ticker[,5])$breaks, y=hist(ticker[,5])$counts),
                visible = TRUE)

hc_base


text:
Q: Google Cloud Datastore python local dev can't find datastore module I followed the instructions given in this Google Cloud Datastore tutorial in python to test Datastore locally.  When I run this code:
from google.cloud import datastore

client = datastore.Client()

I get the following error:
from google.cloud import datastore
ModuleNotFoundError: No module named 'google.cloud'

I installed google-cloud-datastore, yet the problem persists.
It seems like a missing dependency problem, yet I don't know what module to install since I installed everything in the requirements.txt file.

A: This is a missing (or broken) dependency problem.  It's fixed by installing google-cloud-storage.
pip install google-cloud-storage

Google should have added this to datastore's dependency tree to make our lives easier.

A: It sounds like the google-cloud-datastore either didn't get properly installed or isn't installed in the same environment you're trying to import it from.
From an empty environment, I can install the google-cloud-datastore package, and then be able to import it:
/tmp $ python -m venv env

/tmp $ source env/bin/activate

(env) /tmp $ pip freeze

(env) /tmp $ pip install google-cloud-datastore==1.7.0
Collecting google-cloud-datastore==1.7.0
  ...lots of output...
Successfully installed cachetools-2.1.0 certifi-2018.8.24 chardet-3.0.4 google-api-core-1.4.0 google-auth-1.5.1 google-cloud-core-0.28.1 google-cloud-datastore-1.7.0 googleapis-common-protos-1.5.3 grpcio-1.15.0 idna-2.7 protobuf-3.6.1 pyasn1-0.4.4 pyasn1-modules-0.2.2 pytz-2018.5 requests-2.19.1 rsa-3.4.2 six-1.11.0 urllib3-1.23

(env) /tmp $ pip freeze
cachetools==2.1.0
certifi==2018.8.24
chardet==3.0.4
google-api-core==1.4.0
google-auth==1.5.1
google-cloud-core==0.28.1
google-cloud-datastore==1.7.0
googleapis-common-protos==1.5.3
grpcio==1.15.0
idna==2.7
protobuf==3.6.1
pyasn1==0.4.4
pyasn1-modules==0.2.2
pytz==2018.5
requests==2.19.1
rsa==3.4.2
six==1.11.0
urllib3==1.23

(env) /tmp $ python
Python 3.7.0 (default, Jul 30 2018, 11:52:05)
[Clang 9.1.0 (clang-902.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from google.cloud import datastore
>>>


text:
Q: R: using the mutate function to combine strings I've got a dataset called data1 with headers year and count.
My sample data looks like this:
  Year  Count
1 2005  3000
2 2006  4000
3 2007  5000
4 2008  6000

I add another column to the data which works out the yearly increase. This is my code:
data1growth <- data1 %>%
mutate(Growth = Count - lag(Count))

I want to be able to add another column called period so that I can get the following output:
  Year  Count  Growth  Period
1 2005  3000   NA      NA
2 2006  4000   1000    2005-2006
3 2007  5000   1000    2006-2007
4 2008  6000   1000    2007-2008

What code should I add to the mutate function to get the desired output, or am I off the mark completely? Any help is appreciated.
Thanks everyone.

A: library(dplyr)
data1 %>%
  mutate(
    Growth = Count - lag(Count),
    period = if_else(
      row_number() > 1,
      paste0(lag(Year), "-", Year),
      NA_character_
    )
  )

#   Year Count Growth    period
# 1 2005  3000     NA      <NA>
# 2 2006  4000   1000 2005-2006
# 3 2007  5000   1000 2006-2007
# 4 2008  6000   1000 2007-2008

Reproducible data
data1 <- data.frame(
  Year  = seq(2005L, 2008L, 1L),
  Count = seq(3000L, 6000L, 1000L)
)

A: If you want 'Period' to just be a string, you can just use another mutate:
library(tidyverse)
data1 <- tibble(Year = 2005:2008, Count = c(3000, 4000, 5000, 6000))
data1growth <- data1 %>%
    mutate(Growth = Count - lag(Count))

# Period as string
data1growth %>%
    mutate(Period = paste0(Year, "-", Year-1))
#> # A tibble: 4 x 4
#>    Year Count Growth Period
#>   <int> <dbl>  <dbl> <chr>
#> 1  2005  3000     NA 2005-2004
#> 2  2006  4000   1000 2006-2005
#> 3  2007  5000   1000 2007-2006
#> 4  2008  6000   1000 2008-2007

# Period as string (don't include NA Growth)
data1growth %>%
    mutate(Period = ifelse(is.na(Growth), NA, paste0(Year, "-", Year-1)))
#> # A tibble: 4 x 4
#>    Year Count Growth Period
#>   <int> <dbl>  <dbl> <chr>
#> 1  2005  3000     NA <NA>
#> 2  2006  4000   1000 2006-2005
#> 3  2007  5000   1000 2007-2006
#> 4  2008  6000   1000 2008-2007

A: Here is a base R option
transform(df1,
  Grouth = c(NA, diff(Count)),
  Period = c(NA, paste0(Year[-nrow(df1)], "-", Year[-1]))
)

which gives
  Year Count Grouth    Period
1 2005  3000     NA      <NA>
2 2006  4000   1000 2005-2006
3 2007  5000   1000 2006-2007
4 2008  6000   1000 2007-2008


text:
Q: Match multiple values in a case of a switch I wonder if I can do a switch whose cases only fall when several values match.
I have an array with values 'X', 'O' or ' '. I want that when some values are 'X', fall through the case.
This is the idea:
switch(numbers.indexOf('X')) {
    case 0 && 1 && 2:
        //Do something
        break;
    case 2 && 3 && 4:
        //Do something
        break;
}

I know that I can do it with if - else easily, but I would like do it with a switch if it is possible.
Thanks!

A: Likely what you'll want to do is stick the different functions you want to perform in their own section and then call them in each switch case. Sadly switch cases don't let you stack them like that, it would be lovely wouldn't it? Something like:
function a(){};
function b(){};
switch(x){
    case 0:
        a();
        break;
    case 1:
        a();
        break;
    case 2:
        b();
        break;
    case 3:
        b();
        break;
}

A: Try this one:
switch(variable) {
  case 0:
  case 1:
  case 3:
    alert("Found necessary index");
    break;
  default:
    console.log(variable);
    break;
}


text:
Q: Prevent put absolute paths in javascript for css files I am using javascript and somethimes a cretain js file need specific css file made for it.
I want to prevent put absolute paths of the css files in javascript.
I even want to put the js file in the same folder of the css file.
But the path of the js file is calculated from the file that executes it.
How can I connect between this js file and the css file?

A: There is no perfect solution to this.
One of the solutions that come to mind is to analyze (using DOM) the script tags on page to find out the path that was used to load script itself, then calculate path relative to this.
Other solution is to use js combiner and css combiner and just always load all js and css needed for site.

A: It would be simpler just to define the needed CSS within the JavaScript file, if you absolutely need to link the CSS and JavaScript together. You can make a HTML page use CSS files dynamically from JavaScript by adding new link tags, but to my best knowledge, there is no way to specify the paths relative to the JavaScript file.
However, one thing you could do is this. First have each HTML file specify the script root path relative to that file, like:
<script type="text/javascript">
    var jsPath = "relative_to_this_file/styles_and_scripts/"
</script>
<script type="text/javascript"
    src="relative_to_this_file/styles_and_scripts/styler.js">
</script>

and having the styler.js code do this:
var myStylePath = jsPath + "myStyle.css"
// add link tag for the CSS to HTML here using myStylePath

You could also generate absolute paths in JavaScript or in code that is serving the JavaScript dynamically in a similar fashion. If the root part of the absolute path changes, you only need to adjust a single line of code accordingly.
Alternatively, you could also consider a different strategy: link the CSS files statically from your HTML pages, and use classes in your CSS selectors (.myClass { float: left; } ). Then you can easily use JavaScript to add new classes to the HTML tags you want to style.

A:
But the path of the js file is calculated from the file that executes it

This is not always true. Just start the path with a forward slash and it will be relative to  your root web directory e.g.
<link type="text/css" rel="stylesheet" href="/path/to/style.css" />

A: You can declare one global variable holding the "relative" path than use it whenever you need to specify file path. Example:
<script type="text/javascript">
var _relPath = "MyFolder/CSS";

...

function SomeFunc() {
   var cssFileName = _relPath + "/myfile.css"; //instead of MyFolder/CSS/myfile.css
}

...
</script>

This way it's easier to change.
If you have server side language in use e.g. ASP.NET, classic ASP, PHP - you can output the relative path of the current page let us know if relevant.


text:
Q: Mapbox iOS - Show multiple callouts I want to show multiple annotations at once in Mapbox (note: NOT MKMap). There doesn't seem to be a method to show multiple annotations, although it can add multiples.
e.g.
mapView.addAnnotations(<annotationsArray>)

Even though there is a method as follows, it does not show the annotations.
mapView.showAnnotations(<annotationsArray>, animated: true)

What I want it to show multiple instances as shown in the image below. i.e. I want to show several "Hello World" annotations in the map, for each point the user added.

Is there a similar method in Mapbox to show multiple annotations in Swift?

A: Use this to display multiple annotations:
func setAnnotations() {
        var index = 0
        for placeModel in self.placesList! {
            let marker = MyMGLPointAnnotation()
            marker.willUseImage = true
            marker.id = placeModel.id
            marker.type = placeModel.type
            if let img = placeModel.images.first {
                marker.imgURL = img.thumbnail
            }
            marker.coordinate = CLLocationCoordinate2D(latitude: placeModel.location?.latitude ?? 0, longitude: placeModel.location?.longitude ?? 0)
            marker.title = placeModel.name.withoutHtmlTags
            marker.subtitle = placeModel.descr.htmlToString

            //DispatchQueue.main.async {
                self.mapView.setCenter(CLLocationCoordinate2D(latitude: latitude, longitude: longitude), zoomLevel: 12, animated: false)

                self.mapView.addAnnotation(marker)
        }
    }

You can display multiple instance of the annotations but for the selection you can tap one by one and it will show title like the image you shared.
Edit: There is way you can create your custom xib load as annotation to show the title.
Check: https://github.com/mapbox/ios-sdk-examples/blob/0e2c8ce878de500f36c4168f7a1e62041c8adbdf/Examples/Swift/AnnotationViewsAndImagesExample.swift
https://docs.mapbox.com/ios/maps/examples/annotation-view-image/