text:
Q: Setting data for custom control in ASCX file I need to set data for a custom control in my HTML file but I'm experiencing problems with ParseChildren property which doesn't work and my code raises a "Parser Error" for "Object not set to an instance of an object".
Here is my code behind:
namespace UserControls
{
    [ParseChildren(true)]
    public partial class MainVisit : UserControl
    {
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public MyCollection MyList { get; private set; }

        public MainVisit()
        {
            this.MyList = new MyCollection();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.MyList = new MyCollection();
        }
    }

    public class MyCollection : List<SecondaryVisit> { }

    public class SecondaryVisit
    {
        public string Name { get; set; }
        public SecondaryVisit() { }
    }
}

And this is the HTML file
<%@ Register TagPrefix="mscuc" TagName="MainVisitForm" Src="~/UserControls/MainVisit.ascx" %>
<mscuc:MainVisitForm id="MainVisitForm"  runat="server">
    <VisitList>
        <mscuc:SecondaryVisit Name="visit_name" />
    </VisitList>
</mscuc:MainVisitForm>

So when I compile and try to execute this code an exception is raised for "Object not set to an instance of an object" at line

Any idea?


text:
Q: Fixing the top bar SharePoint 2013 The ribbonbar and suitebar which makes the top bar in SharePoint 2013 have a fixed like position on the site. When the user scrolls, the top bar follows.
I want this bar to stay at the top and NOT have this fixed like position.
Any idea how to do that?

A: #topbar {overflow : hidden;position:fixed; top :0px; left:0px; }

A: Moving both the ribbonbar and the suitebar to the s4-workspace in the master file solved this issue

redpajama_set_name: RedPajamaStackExchange


text:
Q: table view Warning i have tried the table view sample with the viewcontroller.when im running i got this error may i know wher im making mistake
WARNING: Using legacy cell layout due to delegate implementation of tableView:accessoryTypeForRowWithIndexPath

A: tableView:accessoryTypeForRowWithIndexPath: is deprecated in iPhone OS 3.0 with the following note:

Use the accessory-view and accessory-type properties (for both normal and editing modes) of the UITableViewCell class when configuring table-view cells.

They mean you should set accessoryType/accessoryView properties in tableView:cellForRowAtIndexPath: instead.


text:
Q: Elasticsearch search with nested objects I have the following object in elastic.
Is there way to run a full text search query like: Fizz AND bar
{
  "258": "Fizz buzz",
  "12416": [
    {
      "161": 54,
      "273": "text doc.txt",
      "544": [
        "text/plain"
      ],
      "12290": "foo bar",
    }
  ]
}

I've read about Runtime fields but it supports only keyword type and will work only in case of full match.

A: Query string will not work on nested field. You can either use a nested query or implement a custom _all field
PUT index117
{

  "mappings": {
    "properties": {
      "_all":{
        "type": "text"
      },
      "258":{
        "type": "text",
        "copy_to": "_all"  --> copies data to _all field
      },
      "12416":{
        "type": "nested",
        "properties": {
          "12290":{
            "type":"text",
            "copy_to": "_all"
          }
        }
      }
    }
  }
}

POST index117/_doc
{
  "258": "Fizz buzz",
  "12416": [
    {
      "161": 54,
      "273": "text doc.txt",
      "544": [
        "text/plain"
      ],
      "12290": "foo bar"
    }
  ]
}

GET index117/_search
{
  "query": {
    "query_string": {
      "default_field": "_all",
      "query": "foo AND bar"
    }
  }
}


text:
Q: NodeJs TypeError: Cannot read property 'key' of undefined i want to create a cloud function which sends email if some data where added to my database. Unfortunately while trying to deploy my function i receive this error:
TypeError: Cannot read property 'key' of undefined
Here is my function:
const functions = require('firebase-functions')
const nodemailer = require('nodemailer')
const postmarkTransport = require('nodemailer-postmark-transport')
const admin = require('firebase-admin')

// 2. Admin SDK can only be initialized once
try {admin.initializeApp(functions.config().firebase)} catch(e) {
    console.log('dbCompaniesOnUpdate initializeApp failure')
 }

// 3. Google Cloud environment variable used:

const postmarkKey = functions.config().postmark.key
const mailTransport = nodemailer.createTransport(postmarkTransport({
auth: {
         apiKey: postmarkKey
}
  }))

 // // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-
 functions
//

exports.sendingEmailForlocationsRequests =
 functions.database.ref('/clubs/{clubId}/{pushId}')
.onWrite((event) => {
//I want to retrieve the pushID

return sendEmail();
})

    function sendEmail() {
    // 5. Send welcome email to new users
    const mailOptions = {
            from: '"Dave" <noreply@clate.de>',
            to: 'locations@clate.de',
            subject: 'Welcome!',
            html: `<Test>`
    }
    // 6. Process the sending of this email via nodemailer
    return mailTransport.sendMail(mailOptions)
            .then(() => console.log('dbCompaniesOnUpdate:Welcome
    confirmation email'))
            .catch((error) => console.error('There was an error while
    sending the email:', error))
    }

A: It looks like 'postmark' isn't set in your firebase configuration. You can set what's retrieved by functions.config() using the CLI: https://firebase.google.com/docs/functions/config-env


text:
Q: Changing ELMAH database in code I have several websites that have separate ELMAH databases. I would like to have one separate website to view all these databases.
I've created a new ASP.NET MVC 4 website for this purpose. I've added the NuGet package "Elmah.MVC" and added the following to Web.config:
<connectionStrings>
    <add name="Elmah.Sql" connectionString="..." />
</connectionStrings>
<elmah>
    <errorLog type="Elmah.SqlErrorLog" connectionStringName="Elmah.Sql" />
</elmah>

This works just fine going to a single database. I can also switch database by changing the connectionstring, but now I want to be able to switch database from code. Is there a way to do that?

A: I'm retrieving the connection string at runtime so the option from ThangChung wasn't working for me. But with a few minor changes i made it work.
The SqlErrorLog, both the constructors are required.
 public class ElmahSqlErrorLog : SqlErrorLog
 {
    public override string ConnectionString
    {
        get { return SettingsXmlService.GetConnectionString(); }
    }

    public ElmahSqlErrorLog(IDictionary config) : base(config)
    {
    }

    public ElmahSqlErrorLog(string connectionString) : base(connectionString)
    {
    }
 }

The web.config (add after system.webServer)
 <elmah>
    <errorLog type="Business.Infrastructure.Elmah.ElmahSqlErrorLog, Business" connectionString="-" applicationName="Topsite" />
 </elmah>

The value of the connectionString doesn't matter because we retrieve it at runtime, it can't be empty though.

A: ELMAH has a class for customize the error log. You only need to implementing this class like
public class YourErrorLog : SqlErrorLog
{
    public override string ConnectionString
    {
        get
        {
            //return any connection string that you want
        }
    }
}

in this implementation, you can read any connection string that you want.
Finally you can tell the ELMAH know about that ErrorLog by
<elmah>
    <errorLog type="YourAssembly.YourErrorLog, YourAssembly" connectionStringName="elmah-sqlserver" />
</elmah>

You can see the details here
I also found out one example in your case here
Hope this help.

A: If you want to switch the database from code, you won't be able to rely on the Web.config. You're going to need to store the active connection in a class like this:
public class DatabaseSession
{
    public string ConnectionString { get; set; }
}

and then you'll need to store an instance of that in Session:
Session["DatabaseSession"] = new DatabaseSession() { ConnectionString = "your connection string"; }

and you'll need to run that line every time you want to change the database connection. Then, when you want to connect to the database, you'll need to pull it out of session.
However, you could store all the different connection strings in the Web.config and let the user choose from that list -you just can't leverage it to determine the connection string.
NOTE: you could simply store the connection string in the session too Session["DatabaseConnection"] = "your connection string"


text:
Q: Some localStorage items are not being displayed I have 5 items in localStorage, however, when I try to output all the files,
only 2 items are being output, and not all.
JS that puts into localStorage:
$(document).ready(function () {
    $.fn.SaveToCart = function (id, iName, iAlbum, iPrice) {
        var quantity = 0;
        if (localStorage.getItem('Product_' + id) === null) {
            quantity = 1;
        } else {
            var tempItem = JSON.parse(localStorage.getItem('Product_' + id));
            var tempQuantity = parseInt(tempItem['quantity']);
            quantity = tempQuantity + 1;
        }
        var cartItem = {
            'quantity': quantity,
            'name': iName,
            'album': iAlbum,
            'price': iPrice
        }
        localStorage.setItem('Product_' + id, JSON.stringify(cartItem));
    };

Cart JS:
function ShoppingCart() {

    var output;
    var productName;
    var productAlbum;
    var productQuantity;
    var productPrice;
    var productSubTotal = 0;
    var totalPrice;

    for (var i = 0; i < localStorage.length - 1; i++) {
        var keyName = localStorage.key(i);
        if (keyName.indexOf('Product_') == 0) {
            var product = localStorage.getItem(keyName);

            var product = localStorage.getItem('Product_' + i);

            var result = JSON.parse(product);

            totalPrice = 0;
            productName = result.name
            productAlbum = result.album;
            productQuantity = parseInt(result.quantity);
            productPrice = parseFloat(result.price).toFixed(2);
            productSubTotal = parseInt(productQuantity) * parseFloat(productPrice).toFixed(2);

            outputName = "

NAME: " + productName + "

";
            outputAlbum = "
ALBUM: " + productAlbum + "
";
            outputQuantity = "
QUANTITY: " + productQuantity + "
";
            outputPrice = "
PRICE:  EUR " + productPrice + "
";
            outputSubTotal = "
SUB-TOTAL:  EUR " + productSubTotal + "

";

            var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal;

            document.getElementById("Cart-Contents").innerHTML = document.getElementById("Cart-Contents").innerHTML + TotalOutput;
            totalPrice += parseFloat(totalPrice) + parseFloat(productSubTotal);
            productSubTotal = productSubTotal + productSubTotal;
        }
        i++;

    }
    totalPrice = productSubTotal;

    localStorage.setItem("price", totalPrice);

    var outputTotal = "

TOTAL: EUR " + totalPrice + "

";
    document.getElementById("total-price").innerHTML = document.getElementById("total-price").innerHTML + outputTotal;

}

function ClearCart() {

    localStorage.clear();
    document.location.reload(true);

}

window.onload = ShoppingCart;

    </script>

HTML:

Also, I have another problem, the Total Price is not getting calculated correctly. I am getting  28.12 as a total of 14.06 + 16.40. WHy is this happening?
To give you an idea:
http://i.imgur.com/RmftSoU.png
http://i.imgur.com/qO8FQN8.png

A: Change your for loop to this: for (var i = 0; i < localStorage.length; i++){.
And don't add i++; to the end of your loop's body.
Both would cause your loop to not hit all items, for different reasons.


text:
Q: How to parse an ONVIF metadata from RTSP stream in QT? First I've built some examples using QMediaPlayer, but it couldn't handle the RTSP stream (problem with GStreamer 0.10 on ubuntu 14.04).
Some other ideas didn't work so I switched to other solutions.
I've built a qt player based on LibVLC and vlc-qt DemoPlayer example(QT 5.4.1).
The stream works well, the video is working like a charm.
I would want to parse an ONVIF metadata stream from an IP Camera's RTSP stream (it sends some simple xml data with information about object movement and so on) and draw some lines based on the metadata gathered from the stream.
I'm having a bit of trouble with finding the right place to get that data.
As far as I can see LibVLC ignores the part of a stream that it cannot parse.
Has anyone tried to do something like that and point me in the right direction or maybe I'm on a wrong track and there is a better solution?:)

A: With gst-launch, you can simply use this pipeline:
gst-launch-1.0 rtspsrc location=camera_uri ! application/x-rtp, media=application ! fakesink dump=true

and you will get camera metadata in terminal.
But this data will have rtp packet header. To remove it you have to write depayloader element. ( I didn't find any ), that only remove rtp header.
Example of depayloader process method:
static GstBuffer *
gst_rtp_xml_depay_process (GstRTPBaseDepayload * depayload, GstBuffer   *   buf)
{
  guint8 *payload;
  GstRTPBuffer rtp = { NULL };
  GstRtpXMLDepay *rtpxmldepay;
  rtpxmldepay = GST_RTP_XML_DEPAY (depayload);
  gst_rtp_buffer_map (buf, GST_MAP_READ, &rtp);
  payload = (guint8*)gst_rtp_buffer_get_payload_buffer (&rtp);
  return (GstBuffer*)payload;
}

If you want to get metadata in your app, you can use appsink.

A: You will need to somehow attach to the GStreamer signal "handle-request" as documented here:
http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-good-plugins/html/gst-plugins-good-plugins-rtspsrc.html#GstRTSPSrc-handle-request
The data you need should be contained in the user_data pointer.


text:
Q: How to match only the digits that are between two dots excluding the dots using regex I have series of numbers (versioning) like this:

1.6.8
1.9.7 (also with two digits in the middle)

How should I do to target only the middle numbers, the ones between dot and dot?
I tried something like that this:
\.\d+(?=\.)

and it is targeting the middle number, but also the first dot.

A: Something like this?

var myRegexp = /\d+\.(\d+)\.\d+/;

var match = myRegexp.exec('1.33.4');
console.log(match[1]); //33
var match = myRegexp.exec('441.54.12345647');
console.log(match[1]); //54
match = myRegexp.exec('13.2222.33');
console.log(match[1]); //2222

match = myRegexp.exec('version 1.2.3');
console.log(match[1]); //2

function getMiddle(inputversion) {
    var myRegexp = /\d+\.(\d+)\.\d+/;
    var match = myRegexp.exec(inputversion);
    if(match != null) {
        if(match.length > 0) {
            return match[1];
        }
    }
    return null;
}

console.log('should be 34:', getMiddle('my app version: 1.34.55'));
console.log('should be null:', getMiddle('my app needs no versions.it.is.awesome'));

The group selector () matches the most  middle digits.
The + makes sure also larger numbers than 9 can get captured.
https://regex101.com/r/wFgpRI/3

A: I don't see a need for using regex here. You could use split:

var versions = '1.6.8 1.9.7'

console.log(versions.split(' ').map(el => el.split('.')[1]))

If you don't want to use that method, you could use regex anyway, as pointed out by wiktor:

var versions = '1.6.8 1.9.7'
console.log(versions.match(/(?<=\.)\d+(?=\.)/g))


text:
Q: how to pass key value pair to dwr using javascript I have a piece of code like,
var jObj = {"key1" : "value1",
            "key2" : "value2"};

What I want to do is, I want to pass this as a parameter of DWR call like this,
dwrClass.dwrMethod(jObj);

Is it possible?


text:
Q: Do skin makers with lower-rarity skins get more money? Not sure if this goes in gamedev.SE or gaming.SE, but here goes.
Apparently users who contribute skins to the game that Valve adds will receive a small profit every time a user gets their gun.  Does this mean that since higher rarity guns will spread out far less than lower rarity guns, do the contributors who contribute lower rarity guns get more money? Or is the profit solely derived from the user unboxing the crate?

A: It all depends on the rarity of the gun and how many people obtain it. If it is a low level gun, then a lot of people will have a chance at obtaining it, but the payout to you may not be that big.
If it is say a Restricted Rifle or better than you will get a higher payout if more people get ahold of it.
But as user1337 also stated, it is also based on Supply and Demand. A lot of people getting it means a lot of pay for you. But if not a lot of people are getting it, not a lot of pay for you, but each time you do get paid it will be higher.
I may not be entirely correct on this, it is just what I have noticed in the time I have played CS:GO


text:
Q: What is the best way of resolving an expression with square roots in denominator? I was resolving the following question from my textbook:

Write each of the following expressions as a single fraction, simplifying your answer where possible:
$4 - \frac{1}{\sqrt{12}} + \frac{10}{\sqrt{3}}$

I have resolved it this way:

$ \frac{4\sqrt{12}\sqrt{3}}{\sqrt{12}\sqrt{3}} -
 \frac{\sqrt{3}}{\sqrt{12}\sqrt{3}} +
 \frac{10\sqrt{12}}{\sqrt{12}\sqrt{3}} = \frac{4\sqrt{36} -
 \sqrt{3}+10\sqrt{4}\sqrt{3}}{\sqrt{36}}=\frac{24 - \sqrt{3} +
 20\sqrt{3}}{6}$

while in the textbook it is resolved like this:

$4 - \frac{1}{\sqrt{4 \times 3}} + \frac{10}{\sqrt{3}} = 4 -
 \frac{1}{2\sqrt{3}} + \frac{10}{\sqrt{3}} = \frac{8\sqrt{3} - 1 +
 20}{2\sqrt{3}}= \frac{8\sqrt{3} + 19}{2\sqrt{3}}$

I am wondering did I do it correctly and if so, which way is better?

A: Your answer of $$\frac{24 - \sqrt{3} +
 20\sqrt{3}}{6}=\frac{24 +
 19\sqrt{3}}{6}$$
matches the answer given by the book within a factor of $\sqrt 3\over \sqrt 3$:
$$\frac{24 +
 19\sqrt{3}}{6}=\frac{8\sqrt3+19}{2\sqrt 3}$$
Your method was effective in solving the problem, although putting $\sqrt{12}\sqrt 3$ as the denominator does not follow the "usual" method of coming up with a "least common multiple" for the final denominator; in this case, we have $(12,3)=3$, and therefore we would use $\sqrt {12}=2\sqrt 3$ as the final denominator and avoid a couple extra multiplications in the process.  But another intent in solving problems like this is often to "rationalize the denominator", which your method achieves quite effectively.  In the end, you'll want to first make sure that you understand the problem and the solution, and then follow the guidelines of the instructor you are working under: if you have a professor or teacher, match what their expectations are in the final answer form; if it's just a book or self-learning, try to match "common" notation and approaches that you see.


text:
Q: Discord Bot (C#) Problems Joining Voice Channel I have a problem with my bot joining voice channel.
Code:
    using Discord;
    using Discord.Commands;
    using Discord.Audio;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace DodoBot
    {
        class MyBot
        {
            DiscordClient discord;
            CommandService commands;
            Random rand;
            string[] cats = new string[]
            {
                "cate.jpg",
                "gut.jpg",
                "meh.jpg",
                "ugly.jpg",
                "wow.jpg",
            };

            public MyBot()
            {
                rand = new Random();
                discord = new DiscordClient(x =>
                {
                    x.LogLevel = LogSeverity.Info;
                    x.LogHandler = Log;
                });

                discord.UsingCommands(x =>
                {
                    x.PrefixChar = '!';
                    x.AllowMentionPrefix = true;
                });

                commands = discord.GetService<CommandService>();

                RegisterHiCommand();
                RegisterCatdCommand();
                RegisterCatCommand();

                OnJoin();
                OnLeave();

                discord.UsingAudio(x =>
                {
                    x.Mode = AudioMode.Outgoing;
                    RegisterJoinVoiceCommand();
                });

                discord.ExecuteAndWait(async () =>
                {
                    await discord.Connect("MyToken", TokenType.Bot);
                });
            }

            private void RegisterJoinVoiceCommand()
            {
                commands.CreateCommand("summon")
                    .Do(async (e) =>
                    {
                        await e.Channel.SendMessage("```Joining masta!```");
                        await discord.GetService<AudioService>().Join(discord.FindServers("VoiceChannel").FirstOrDefault().VoiceChannels.FirstOrDefault());
                    });
            }

            private void RegisterCatdCommand()
            {
                commands.CreateCommand("catd")
                    .Do(async (e) =>
                    {
                        Message[] msg2Del;
                        msg2Del = await e.Channel.DownloadMessages(1);
                        await e.Channel.DeleteMessages(msg2Del);
                        int imgIndex = rand.Next(cats.Length);
                        await e.Channel.SendFile("Cats/"+cats[imgIndex]);
                    });
            }
            private void RegisterCatCommand()
            {
                commands.CreateCommand("cat")
                    .Do(async (e) =>
                    {
                        int imgIndex = rand.Next(cats.Length);
                        await e.Channel.SendFile("Cats/" + cats[imgIndex]);
                    });
            }
            private void RegisterHiCommand()
            {
                commands.CreateCommand("hi")
                    .Do(async (e) =>
                    {
                        await e.Channel.SendMessage("HelloWorld!");
                    });
            }

            private void OnJoin()
            {
                discord.UserJoined += async (s, e) =>
                {
                    var channel = e.Server.FindChannels("general").FirstOrDefault();
                    var user = e.User.Name;
                    await channel.SendMessage(string.Format("@"+user + " has joined!"));
                };
            }

            private void OnLeave()
            {
                discord.UserLeft += async (s, e) =>
                {
                    var channel = e.Server.FindChannels("general").FirstOrDefault();
                    var user = e.User.Name;
                    await channel.SendMessage(string.Format("@"+user + " has left!"));
                };
            }

            private void Log(object sender, LogMessageEventArgs e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }

I've done everything like it's written in the documentation here.
It executes the SendMessange command but it doesn't join the voice channel.
But Visual Studio says:
here.
Did I make a mistake?
Thank you for your answers.

A: Does your server called "VoiceChannel"?
If not, than by calling
discord.FindServers("VoiceChannel")
your client, most likely, founds nothing (null) instead of collection of servers, and tries to fetch voice channels from First() of them
for example, if your server named "My server" and has voice channel named "VoiceChannel" you can use this construction to get your voice channel:
discord.Servers.Single(s => s.Name == "My server").VoiceChannels.Single(v => v.Name == "VoiceChannel")

A: Call this right under your class myBot,
IVoiceChannel channel;
IAudioClient client;
Try using this in your music command, if you need more information, I can share my entire Music Module but this should do the trick.
IVoiceChannel channel = (Context.User as IVoiceState).VoiceChannel;
IAudioClient client = await channel.ConnectAsync();


text:
Q: Configure htaccess to use Angular and PHP routing I'm trying to use Angular 4 and PHP routing, but I'm not able to configure it in order to use both at the same time. I could make it work with one or the other, but not both.
This is my folder structure:
root
│ index.html
│ vendor.bundle.js
| [..other angular files..]
│
└─api
│  │ index.php
│  │ init.php
│  │
│  └─vendor
└─assets
└─[..other project files..]

On the file api/index.php is where I'm setting the PHP route.

So, when I use this .htaccess, the PHP route works as expected, but the Angular route doesn't work when I refresh the page, because it treats as a PHP route.
<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule . api/index.php [L]

    RewriteBase /
    RewriteRule ^index.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

I tried to change the .htaccess to redirect only if the url being called contain the route /api/, but it didn't worked. Like this:
<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{REQUEST_URI} api
    RewriteRule . api/index.php [L]

    RewriteBase /
    RewriteRule ^index.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

With this code, the Angular route works, even when I refresh the page, but the PHP route never redirects to the index.php file, so it always return null.
What do I need to do to fix this problem?

A: Since I don't know a lot about htaccess, I don't know if this answer is 100% right, but I managed to make it work.
What I did was to move the line RewriteBase / to the top and remove the RewriteRule ^index.html.., with a final .htaccess that looks like this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} api
RewriteRule . api/index.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>

Now this is working as expected. I'll leave the question open in case someone has a better answer.


text:
Q: Save Layout to bitmap(Xamarin) I have layout and need to save it to bitmap
here is code
public void Save()
{
    LinearLayout view = FindViewById<LinearLayout>(Resource.Id.badge);

    view.DrawingCacheEnabled = true;
    view.BuildDrawingCache();
    Bitmap layout = view.GetDrawingCache(true);

}

I set breakpoint to  Bitmap layout = view.GetDrawingCache(true); and I see that's layout is null.
Where is my mistake, how to save layout to bitmap?
UPDATE
I try to save view to bitmap like this
public  Bitmap CreateBitmapFromView(View view, bool autoScale = true)
    {
        var wasDrawingCacheEnabled = view.DrawingCacheEnabled;
        view.DrawingCacheEnabled = true;
        view.BuildDrawingCache(autoScale);
        var bitmap2 = view.GetDrawingCache(autoScale);
        view.DrawingCacheEnabled = wasDrawingCacheEnabled;
        return bitmap2;

    }

All ok, bitmap2 is returning.
But also I need to save it to SD
I wrote method like this
public  Bitmap CreateBitmapFromView(View view, bool autoScale = true)
    {
        var wasDrawingCacheEnabled = view.DrawingCacheEnabled;
        view.DrawingCacheEnabled = true;
        view.BuildDrawingCache(autoScale);
        var bitmap2 = view.GetDrawingCache(autoScale);
        view.DrawingCacheEnabled = wasDrawingCacheEnabled;
        var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
        var filePath = System.IO.Path.Combine(sdCardPath, "test.png");
        var stream = new FileStream(filePath, FileMode.Create);
        bitmap2.Compress(Bitmap.CompressFormat.Png, 100, stream);
        return bitmap2;

    }

And have this error.

Object reference not set to an instance of an object.

A: change it to something likes this :
public Bitmap CreateBitmapFromView(View view, bool autoScale = true)
{
    var wasDrawingCacheEnabled = view.DrawingCacheEnabled;
    view.DrawingCacheEnabled = true;
    view.BuildDrawingCache(autoScale);
    var bitmap = view.GetDrawingCache(autoScale);
    view.DrawingCacheEnabled = wasDrawingCacheEnabled;
    return bitmap;
}

UPDATE
try to define var bitmap2 as global variable
public  Bitmap CreateBitmapFromView(View view, bool autoScale = true)
    {
        var wasDrawingCacheEnabled = view.DrawingCacheEnabled;
        view.DrawingCacheEnabled = true;
        view.BuildDrawingCache(autoScale);
        view.DrawingCacheEnabled = wasDrawingCacheEnabled;
        var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
        var filePath = System.IO.Path.Combine(sdCardPath, "test.png");
        var stream = new FileStream(filePath, FileMode.Create);
        bitmap2.Compress(Bitmap.CompressFormat.Png, 100, stream);
        return bitmap2;
    }


text:
Q: Convert PSD to PNG/JPG with ANT I am playing around with build processes and the idea came up to store our PSD's in our repository so when a build kicks off we can convert the PSD files to PNG/JPG images. This would be great because we wouldn't be reconverting the same compressed file over and over again and it would also allow us to change the image compression rate without any negative impacts to the final output...meaning we could one day compress at 60% and then go up to 80%.
Does anyone know of a library or way to accomplish this with an ANT taks or Bash?

A: There is actually an image task in ANT. I doubt however that it can handle PSD files though.
Another option is to use an external tool such as convert from the imagemagick package:
<exec executable="convert">
    <arg value="yourfile.psd">
    <arg value="output.png">
</exec>

convert has tons of options for cropping / scaling / setting quality and compression as well, so it should suit your needs.


text:
Q: Issues installing typedb-cti dependency scipy on macOS with M1 chip While following the instructions to install typedb-cti:
cd <path/to/typedb-data-cti>/
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

I got the following errors:
Collecting scipy>=1.8
  Using cached scipy-1.9.1.tar.gz (42.0 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error
...
...
...
Library npymath found: YES
      Library npyrandom found: YES
      Did not find CMake 'cmake'
      Found CMake: NO
      Run-time dependency openblas found: NO (tried pkgconfig, framework and cmake)
      Run-time dependency openblas found: NO (tried framework)

      ../../scipy/meson.build:130:0: ERROR: Pkg-config binary for machine 1 not found. Giving up.

A: What worked for me was (after activating the venv) to first install the latest nightly build from scipy like so:
pip install --pre -i https://pypi.anaconda.org/scipy-wheels-nightly/simple scipy
and then run:
pip install -r requirements.txt


text:
Q: Error Launching Idea. Failed to load JVM DLL C:\Program Files\Java\jdk1.8.0_112 Whenever I open IntelliJ IDEA i get this error:

but I have that defined and I don't know why it wont work:

Any help accepted.

A: To fix I didn't need to touch my environment variables.
I fixed that issue by installing/re-installing the latest PHPStorm version choosing the option to keep old settings, logging out from Windows and logging back in.

A: It could be problem with 32 and 64 version. Maybe you trying to launch 32-bit shortcut on your Desktop. Try to launch 64 version (idea64.exe) inside IDEA folder. This worked for me.

A: I fixed this issue by:

*

*Setting the JAVA_HOME environment variable to the location of the JDK I wanted to use e.g. C:\Program Files\Java\jdk1.8.0_171

*Replacing any paths referring to Java e.g. C:\Program Files (x86)\java\jdk1.8.0_112\jre\bin\server\jvm.dll in Path with %JAVA_HOME%\bin as suggested by DimaSan

*Removing the following from the System variables path C:\ProgramData\Oracle\Java\javapath
The last step was crucial for me, this was overriding JAVA_HOME.

A: Actually i had installed the Android Studio canary version, and created a short cut of 32-bit on 64-bit windows operating system,
resolved by starting 64-bit version of Android Studio

A: Nothing of the other solutions work for me on IntelliJ 2019.2 which starts to use JDK 11 on boot, so I have to resolve it on my own.
Open C:\Users\.IdeaIC2019.2\config\idea64.exe.jdk and edit it to be:
C:\Program Files\Java\jdk1.8.0_131

Restart IDE.
As documented on https://www.jetbrains.com/help/idea/switching-boot-jdk.html
Note: the path on your machine may be different.

A: Change the following value from your Path system variable:
C:\Program Files (x86)\java\jdk1.8.0_112\jre\bin\server\jvm.dll

to:
%JAVA_HOME%\bin

Also make sure there are no any other references to Java folders in the Path variable.

A: In my case, this error appeared after signing in to Microsoft account (I use Windows 10). When I logged out, the error dissapeared.

A: You have to do nothing buddy.
Just use 32 bit version of application or install 64 bit JDK. You installed 32 bit JDK and you are trying to access 64 bit version of that application.

A: I have faced the same problem and in my case, just right click and "Run as administrator", everything works fine.
P.S. I am using Windows 10 in our company's domain.

A: Solved it by running Android studio as admin.
Just Check on that path if the jvm.dll is present just run Android studio as administrator.

A: I have faced same issue after updating android studio version electric eel. it's show error like this.

After many try I found this solution. you can follow this steps.
Step 1 : You can visit this site Official Oracle Java SE Development Kit Site and download particular JDK kit for your pc configuration. I am suggest to download this JDK version Java SE Development Kit 18.0.2.1 and after download you can install in your computer.
Step 2 : After Successfully installed you can go
Stat--> Search--> Edit Environment Variable -->
You can follow this image
1.

Step 3:
Now You can Add JAVA_HOME: C:\Program Files\Java\jdk-18.0.2.1 (install version in your pc) Like this

and also add PATH : C:\Program Files\Java\jdk-18.0.2.1\bin (install version in your pc) Like this

Note : You can only add user variable not system variable.
Step 4 : Last step but main after follow these steps you can restart your pc.

A: If you are installing Intellij Idea on a 32 bit System - the JDK will not come within the bundle.
To fix this issue follow the steps below :
1.Uninstall the installed Intellij IDEA
2.Download and install JDK SE 8 from this link :
https://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html
3.Install Intellij IDEA
Viola !

A: I had the same problem - My solution was slightly different.
I needed to install Microsoft Visual C++ 2010 Redistributable Package (x64)
Hope this helps someone else!

A: I had this issue when trying to start PHPStorm via the command line (add the phpstorm bin folder to your path, and you should be able to do eg phpstorm.exe .) - my local installed worked fine.
see also https://www.jetbrains.com/help/phpstorm/working-with-the-ide-features-from-command-line.html:

Add the path to the PhpStorm  bin folder to the Path environment variable (for example, C:\Program Files\JetBrains\PhpStorm\bin). After you configured the Path environment variable, you can run the PhpStorm commands.

adding the path to the jdk PHPStorm comes bundled with as  JAVA_HOME (setx JAVA_HOME "C:\Program Files (x86)\JetBrains\PhpStorm 2019.1\jre64") doesn't solve the issue as the default phpstorm.exe tries to find a 32-bit jdk
I needed to specifically use the 64-bit phpstorm application
phpstorm64.exe .

A: Can be several reasons:
1). Check that your jdk-byte architecture is the same as your os-byte. So, 32-nit architecture needs 32-bit jdk, 64 bit architecture needs 64 bit jdk.
2). If you're running a 64-bit architecture, use (idea64.exe, phpstorm64.exe, etc.). On the 32-bit architecture use (idea.exe, phpstorm.exe, etc), to launch intelli-j products from the command line or terminal.

A: I had the same issue (JDK 1.8.0_212), but none of the suggested solution worked. I then installed a newer JDK (1.8.0_261) and the problem was solved (obviously, I had to update the JAVA_HOME too).


text:
Q: MSSQL to Oracle I'm having difficulty converting this line of MSSQL:
Union All
Select 1,table_name,3,4,5,6,7,8
from (select top 1 table_name
      from information_schema.tables
      order by 1) as subname
order by 1 desc

to Oracle.
So far I have:
Union All
Select 1,table_name,3,4,5,6,7,8
from
   (select *
    from
      (select table_name
       from all_tables order by 1)
    where rownum <= 1) as subname
order by 1 desc

The error that's thrown is

ORA-00933: SQL command not properly ended

Any help would be appreciated!
Edit:
Solution found, see first comment.
Solution:
Union All Select 1,table_name,3,4,5,6,7,8 from (select * from (select table_name from all_tables order by 1) where rownum <= 1) subname order by 1 desc--

A:     SELECT 1,table_name,3,4,5,6,7,8
    FROM (
       SELECT *
       FROM (
          SELECT table_name
          FROM all_tables
          ORDER BY 1)
       WHERE rownum <= 1) subname
    ORDER BY 1 desc;

In order to name the subquery in Oracle, you do not use the as keyword. Just place the name directly after the parentheses.


text:
Q: cloudflare ssl for staging subdomain: sslv3 alert handshake failure I have the following setup
cloudflare -> aws nlb -> ingress nginx controller (aws eks) -> kubernetes service -> kubernetes pod.
Cloudflare has edge certificates enabled for
*.project.com, project.com and are installed in ingress-nginx as
Cloudflare has origin server ssl cert for
*.staging.project.com, *.project.com, project.com (3 hosts) that I installed inside kubernetes cluster.
extraArgs:
  default-ssl-certificate: ingress-nginx/cloudflare-origin-cert

However I'm unable to connect to argocd.staging.project.com  via HTTPs due to handshake error. It should work as origin server cert has *.project.com and also *.staging.project.com.
Inside cloudflare I have just a single domain "project.com", as it seems cloudflare does not allow me to have a staging hosted zone.
What am I missing or doing wrong?
prod env works just fine with this setup, but not staging. I can change argocd.staging.project.com > /argocd-staging.project.com and everything would work, but I prefer to keep staging subdomain if possible.
DNS is working properly as in http call I get logs in ingress-nginx
✗  curl http://argocd.staging.project.com

<title>308 Permanent Redirect</title>

308 Permanent Redirect

nginx

but in curl https I don't see any logs inside ingress-nginx pod.
curl https://argocd.staging.project.com
curl: (35) error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure

echo | openssl s_client -showcerts -servername argocd.staging.project.com -connect argocd.staging.project.com:443 2>/dev/null | openssl x509 -inform pem -noout -text
unable to load certificate
139926728525632:error:0909006C:PEM routines:get_name:no start line:crypto/pem/pem_lib.c:745:Expecting: TRUSTED CERTIFICATE

cert info
openssl x509 -text -noout -in cloudflare-origin.cert
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            0e:e8:98:22:e2:06:be:6d:18:ba:53:49:ef:ac:3a:ae:2b:a8:d3:e1
        Signature Algorithm: sha256WithRSAEncryption
        Issuer: C = US, O = "CloudFlare, Inc.", OU = CloudFlare Origin SSL Certificate Authority, L = San Francisco, ST = California
        Validity
            Not Before: Dec 28 00:48:00 2021 GMT
            Not After : Dec 24 00:48:00 2036 GMT
        Subject: O = "CloudFlare, Inc.", OU = CloudFlare Origin CA, CN = CloudFlare Origin Certificate
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                RSA Public-Key: (2048 bit)
                Modulus:
                    00:c4:6e:4b:53:c7:bb:a3:7a:e4:52:79:39:20:c7:
                    67:1f:67:06:13:ad:8d:cf:48:ae:56:c0:ab:22:e7:
                    5f:22:1b:bb:35:24:74:62:1a:11:5e:be:c3:a7:70:
                    26:54:65:28:e5:bf:4c:d9:de:cc:1a:55:bf:e4:c4:
                    32:93:84:1f:7c:81:01:bb:20:74:72:e0:c9:f4:cc:
                    47:70:76:5e:e7:ce:43:cd:4f:5e:23:7b:b7:66:ac:
                    e6:ce:3a:1d:8f:1c:c1:5e:61:c2:da:64:46:6c:22:
                    00:4d:8a:97:ab:40:93:a8:dd:35:f0:26:43:a4:af:
                    25:5e:2f:27:d5:29:0a:e5:bf:c7:8f:79:8c:3d:07:
                    66:08:23:f9:a8:72:2b:e5:82:d9:90:a3:56:c5:4c:
                    be:a9:2a:12:90:e4:6c:0b:e4:12:45:9f:a9:e9:7c:
                    4b:66:36:3e:ff:f7:2b:a2:49:5d:6d:ef:7e:f4:3e:
                    5c:cf:7f:d2:70:e9:4f:06:c0:ca:ca:5f:ec:22:f7:
                    06:c0:0e:2d:f5:9f:b3:4c:0c:2f:b2:2e:fc:06:6a:
                    de:07:fa:cc:99:fa:83:35:a3:6d:48:13:da:23:2c:
                    52:9c:2f:30:0e:23:cc:af:e8:d1:31:cd:5d:95:bf:
                    cd:ba:43:91:06:c2:b4:b4:bc:ad:c2:e6:01:83:25:
                    d3:41
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Key Usage: critical
                Digital Signature, Key Encipherment
            X509v3 Extended Key Usage:
                TLS Web Client Authentication, TLS Web Server Authentication
            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Subject Key Identifier:
                13:86:11:20:22:E5:81:ED:B9:8A:5C:04:0F:3F:03:34:E1:86:55:0C
            X509v3 Authority Key Identifier:
                keyid:24:E8:53:57:5D:7C:34:40:87:A9:EB:94:DB:BA:E1:16:78:FC:29:A4

            Authority Information Access:
                OCSP - URI:http://ocsp.cloudflare.com/origin_ca

            X509v3 Subject Alternative Name:
                DNS:*.staging.project.com, DNS:*.project.com, DNS:project.com
            X509v3 CRL Distribution Points:

                Full Name:
                  URI:http://crl.cloudflare.com/origin_ca.crl

    Signature Algorithm: sha256WithRSAEncryption
         63:fd:c0:b0:ad:95:e4:78:d2:d6:ae:62:8c:5d:a2:a6:c9:12:
         c0:56:02:2a:ba:04:fd:b7:74:d4:0d:ad:5e:55:78:67:63:1a:
         79:83:58:91:b4:a9:77:e1:5e:5d:86:ad:e2:5b:03:a1:88:ff:
         88:bb:f4:29:7d:83:96:89:f8:44:a4:4e:79:c3:ab:14:89:15:
         ea:af:a5:66:f4:6a:fe:2a:a5:55:de:0f:36:a5:cb:95:59:ee:
         3a:51:6b:d3:ca:3c:0a:bc:66:60:ff:77:81:91:57:91:3a:a5:
         ea:05:30:aa:69:01:95:48:44:04:e8:78:a7:bf:03:9b:7e:65:
         f7:5d:91:5d:a9:a2:67:5a:3c:c8:7f:9e:4e:3f:3a:2a:2a:5a:
         68:4b:b5:e2:a1:68:a1:ff:6d:d4:39:9d:00:ab:89:c7:34:aa:
         5b:87:fe:ba:61:c2:94:51:5d:59:c5:a0:0a:dc:0c:23:24:19:
         bc:37:ad:1f:8c:bd:71:89:63:b2:a8:a3:24:20:fc:dd:0f:d9:
         15:b4:a2:b8:8f:7a:c6:a6:50:20:a0:fd:de:1a:79:c6:30:86:
         79:bf:ea:46:e3:1b:e6:86:3b:89:67:d2:c5:bf:d8:62:9f:52:
         6c:d2:1f:b5:f6:03:56:2b:23:5e:30:7a:3e:78:39:f7:cd:a0:
         d0:3c:da:69

However for production environment (staging omitted in URL) everything works and handshake is normal.
echo | openssl s_client -showcerts -servername argocd.project.com -connect argocd.project.com:443 2>/dev/null | openssl x509 -inform pem -noout -text
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            0e:2d:db:f3:59:21:a2:91:e4:67:79:17:ff:71:8d:e5
        Signature Algorithm: ecdsa-with-SHA256
        Issuer: C = US, O = "Cloudflare, Inc.", CN = Cloudflare Inc ECC CA-3
        Validity
            Not Before: Jun 15 00:00:00 2021 GMT
            Not After : Jun 14 23:59:59 2022 GMT
        Subject: C = US, ST = California, L = San Francisco, O = "Cloudflare, Inc.", CN = sni.cloudflaressl.com
        Subject Public Key Info:
            Public Key Algorithm: id-ecPublicKey
                Public-Key: (256 bit)
                pub:
                    04:8d:99:4f:55:aa:0c:c2:4d:1b:57:23:e8:73:09:
                    7f:de:d4:ae:50:f8:19:74:0a:23:0f:cc:3e:64:c1:
                    bf:66:56:72:06:4a:c5:0c:13:1f:43:b9:d5:f9:88:
                    e6:f5:4c:4a:02:ee:76:37:9d:ee:e6:26:7d:be:3e:
                    fc:42:a5:97:20
                ASN1 OID: prime256v1
                NIST CURVE: P-256
        X509v3 extensions:
            X509v3 Authority Key Identifier:
                keyid:A5:CE:37:EA:EB:B0:75:0E:94:67:88:B4:45:FA:D9:24:10:87:96:1F

            X509v3 Subject Key Identifier:
                FA:15:4F:CE:7F:3D:C9:27:5A:D3:87:C1:ED:68:A9:FC:CC:BC:E2:84
            X509v3 Subject Alternative Name:
                DNS:*.project.com, DNS:sni.cloudflaressl.com, DNS:project.com
            X509v3 Key Usage: critical
                Digital Signature
            X509v3 Extended Key Usage:
                TLS Web Server Authentication, TLS Web Client Authentication
            X509v3 CRL Distribution Points:

                Full Name:
                  URI:http://crl3.digicert.com/CloudflareIncECCCA-3.crl

                Full Name:
                  URI:http://crl4.digicert.com/CloudflareIncECCCA-3.crl

            X509v3 Certificate Policies:
                Policy: 2.23.140.1.2.2
                  CPS: http://www.digicert.com/CPS

            Authority Information Access:
                OCSP - URI:http://ocsp.digicert.com
                CA Issuers - URI:http://cacerts.digicert.com/CloudflareIncECCCA-3.crt

            X509v3 Basic Constraints: critical
                CA:FALSE
            CT Precertificate SCTs:
                Signed Certificate Timestamp:
                    Version   : v1 (0x0)
                    Log ID    : 46:A5:55:EB:75:FA:91:20:30:B5:A2:89:69:F4:F3:7D:
                                11:2C:41:74:BE:FD:49:B8:85:AB:F2:FC:70:FE:6D:47
                    Timestamp : Jun 15 16:30:55.567 2021 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:46:02:21:00:DD:C3:A2:FE:62:CE:34:30:BF:41:A3:
                                3D:E3:D3:4B:7A:0C:DD:BF:1E:A0:81:B0:5B:63:0E:A3:
                                83:6B:5D:AF:5C:02:21:00:C7:5C:0F:71:C9:61:11:5A:
                                A8:2F:5F:9A:31:A4:2A:C0:83:B6:2A:29:FC:BD:5D:FA:
                                3C:CF:B5:F6:1E:EE:F0:6B
                Signed Certificate Timestamp:
                    Version   : v1 (0x0)
                    Log ID    : 22:45:45:07:59:55:24:56:96:3F:A1:2F:F1:F7:6D:86:
                                E0:23:26:63:AD:C0:4B:7F:5D:C6:83:5C:6E:E2:0F:02
                    Timestamp : Jun 15 16:30:55.564 2021 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:45:02:20:25:E2:6B:36:61:E9:F4:EC:28:DE:1D:E3:
                                18:6F:E2:0A:03:EF:29:45:F3:09:0B:27:45:6F:51:78:
                                D5:3A:2A:83:02:21:00:A4:34:A0:B5:D5:FD:F2:42:13:
                                31:93:DF:C4:AD:3E:A7:48:C6:69:C1:9D:04:7A:EA:C7:
                                27:6E:88:69:9B:B9:BF
                Signed Certificate Timestamp:
                    Version   : v1 (0x0)
                    Log ID    : 51:A3:B0:F5:FD:01:79:9C:56:6D:B8:37:78:8F:0C:A4:
                                7A:CC:1B:27:CB:F7:9E:88:42:9A:0D:FE:D4:8B:05:E5
                    Timestamp : Jun 15 16:30:55.627 2021 GMT
                    Extensions: none
                    Signature : ecdsa-with-SHA256
                                30:45:02:21:00:FA:13:20:B1:07:70:46:F4:C2:AD:F0:
                                1C:10:A7:8D:92:23:2C:8A:34:E0:1C:7F:59:8A:CB:7B:
                                C2:CF:07:95:37:02:20:50:78:FA:DF:8D:A4:9C:B9:73:
                                1F:18:ED:51:06:33:8D:B4:F6:CC:0D:8D:46:69:CB:AB:
                                93:17:D2:64:1F:2D:B3
    Signature Algorithm: ecdsa-with-SHA256
         30:46:02:21:00:fc:1b:7b:6f:de:f2:29:5a:11:0c:92:f8:05:
         31:1b:7c:68:f7:6e:e4:0b:5d:15:67:dd:f4:c9:00:d7:77:ad:
         46:02:21:00:a0:98:25:6a:19:3b:ac:51:68:f5:de:9d:cc:93:
         22:b2:ca:18:c8:e9:ec:06:79:77:01:ba:fb:3a:41:3d:2d:cd

A: Ok found - it's the limitation of universal cloudflare certificate that doesn't cover subdomains :(
from their docs:
Only some of your subdomains return SSL errors
Symptom Cloudflare Universal SSL and regular Dedicated SSL certificates only cover the root-level domain (example.com) and one level of subdomains (*.example.com). If visitors to your domain observe errors accessing a second level of subdomains in their browser (such as dev.www.example.com) but not the first level of subdomains (such as www.example.com), resolve the issue using one of the following methods below.
Resolution

*

*Ensure the domain is at least on a Business plan and upload a Custom SSL certificate that covers dev.www.example.com, or

*purchase a Dedicated SSL certificate with Custom Hostnames that covers dev.www.example.com, or

*if you have a valid certificate for the second level subdomains at your origin web server, click the orange cloud icon beside the dev.www hostname in the Cloudflare DNS app for example.com.

See here: https://support.cloudflare.com/hc/en-us/articles/200170566-Troubleshooting-SSL-errors#h_55e4d315-c60d-4798-9c4c-c75d9baed1b7


text:
Q: How to concatenate data from document.getElementById I have two text fields in an html form with id 'co_addrcheck' and 'usrad_co_addr'. I tried concatenating the two values and copy that to another text field. I tried using the following code but the new text has an 'undefined' value.
var loc = document.getElementById('co_addrcheck');
var home = document.getElementById('usrad_co_addr');

Neither
var post2 = loc  + home;

nor
var post2 = loc.value  + home.value;

works.
Any help would be highly appreciated.

A: Assuming they're text inputs, you should use the "value" property,
var post2 = loc.value  + home.value;

I hope it helps

A: Second one should be working. And best advice is to enclose within try/catch and see the error message.


text:
Q: How to test Terraform files I'm defining my infrastructure in Terraform files. I like Terraform a lot, but I'm having trouble figuring out how to test. I have awspec, which is really nice and runs RSpec-like tests against the result of your build via the AWS API. But is there a way to do unit tests, like on the results of terraform plan? What kind of workflow are others using with Terraform?

A: I'm going to expand on Begin's answer with more information about Kitchen-Terraform.
Kitchen-Terraform is a set of open source plugins that run within Test-Kitchen, these are supposed to go into your Terraform module repository to test that module's functionality before being used in a repository that creates the resources. Please feel free to check the documentation of those two projects for more details, but I will go through my recommendations for integration testing your Terraform code.
Install Ruby, Terraform
For this example, the Terraform module repo will be called: my_terraform_module
mkdir -p my_terraform_module
cd my_terraform_module

mkdir -p test/integration/kt_suite/controls \
         test/fixtures/tf_module/

Create a Gemfile:
source "https://rubygems.org/" do
  gem "kitchen-terraform"
end

Install the necessary components (uses the Gemfile for the dependencies of kitchen-terraform)
gem install bundler
bundle install

Create the Test-Kitchen file .kitchen.yml - this brings together the testing frame, Test-Kitchen and Kitchen-Terraform
---
driver:
  name: terraform
  root_module_directory: test/fixtures/tf_module
  parallelism: 4

provisioner:
  name: terraform

transport:
  name: ssh

verifier:
  name: terraform
  groups:
    - name: basic
      controls:
        - file_check
        - state_file

platforms:
  - name: terraform

suites:
  - name: kt_suite

Your Terraform code should be at the root of the Terraform module repository such as:
my_terraform_module/
  |-- main.tf

Example code that can go in main.tf
resource "null_resource" "create_file" {
  provisioner "local-exec" {
    command = "echo 'this is my first test' > foobar"
  }
}

Then we reference the Terraform module just like we would in Terraform live repos - but in a test fixture instead in this file: test/fixtures/tf_module/main.tf
module "kt_test" {
  source = "../../.."
}

Then from there, you can run Terraform apply, but it's done a little differently with Kitchen-Terraform and Test-Kitchen, you run a converge which helps keep track of state and a couple other items.
bundle exec kitchen converge

Now you've seen your Terraform code do an apply, we need to test it. We can test the actual resources that were created, which would be like an integration test, but we can also test the state file, which is a semi unit test, but I am not aware of anything that can currently do unit tests against the HCL code of Terraform.
Create an inspec default profile file: test/integration/kt_suite/inspec.yml
---
name: default

Create an Inspec control for your integration testing: test/integration/kt_suite/controls/basic.rb - I'm using a test for the example Terraform code I used earlier for the main.tf
# frozen_string_literal: true

control "file_check" do
  describe file('.kitchen/kitchen-terraform/kt-suite-terraform/foobar') do
    it { should exist }
  end
end

And this is an example test of pulling information from the state file and testing if something exists in it. This is a basic one, but you can definitely exand on this example.
# frozen_string_literal: true

terraform_state = attribute "terraform_state", {}

control "state_file" do
  describe "the Terraform state file" do
    subject do json(terraform_state).terraform_version end

    it "is accessible" do is_expected.to match /\d+\.\d+\.\d+/ end
  end
end

Then run Inspec controls with Test-Kitchen and Kitchen-Terraform:
bundle exec kitchen verify

I took a lot of this from the getting started guide and some of the tutorials over here: https://newcontext-oss.github.io/kitchen-terraform/getting_started.html

A: We recently open sourced Terratest, our swiss army knife for testing infrastructure code.
Today, you're probably testing all your infrastructure code manually by deploying, validating, and undeploying. Terratest helps you automate this process:

*

*Write tests in Go.

*Use helpers in Terratest to execute your real IaC tools (e.g., Terraform, Packer, etc.) to deploy real infrastructure (e.g., servers) in a real environment (e.g., AWS).

*Use helpers in Terratest to validate that the infrastructure works correctly in that environment by making HTTP requests, API calls, SSH connections, etc.

*Use helpers in Terratest to undeploy everything at the end of the test.

Here's an example test for some Terraform code:
terraformOptions := &terraform.Options {
  // The path to where your Terraform code is located
  TerraformDir: "../examples/terraform-basic-example",
}

// This will run `terraform init` and `terraform apply` and fail the test if there are any errors
terraform.InitAndApply(t, terraformOptions)

// At the end of the test, run `terraform destroy` to clean up any resources that were created
defer terraform.Destroy(t, terraformOptions)

// Run `terraform output` to get the value of an output variable
instanceUrl := terraform.Output(t, terraformOptions, "instance_url")

// Verify that we get back a 200 OK with the expected text
// It can take a minute or so for the Instance to boot up, so retry a few times
expected := "Hello, World"
maxRetries := 15
timeBetweenRetries := 5 * time.Second
http_helper.HttpGetWithRetry(t, instanceUrl, 200, expected, maxRetries, timeBetweenRetries)

These are integration tests, and depending on what you're testing, can take 5 - 50 minutes. It's not fast (though using Docker and test stages, you can speed some things up), and you'll have to work to make the tests reliable, but it is well worth the time.
Check out the Terratest repo for docs and lots of examples of various types of infrastructure code and the corresponding tests for them.

A: From my research this is a tough issue, since Terraform is not meant to be a full featured programming language and you are declaring what resources you want with Terraform, not how to build them, trying to unit-test doesn't really give you the assurance you are building resources how you'd like without actually running an apply. This makes attempts to unit-test feel more like a linting to me.
However, you could parse your HCL files with something like pyhcl, or parse you're plan files, however from my experience this was a lot of work for little benefit (but I could be missing an easier method!).
Here are some alternatives if you wanted to test the results of your terraform applys:
kitchen-terraform is a tool for writing Test Kitchen specs for your infrastructure.
kitchen-verifier-awspec helps bring together awspec and kitchen-terraform, although I have not used it personally.
If you are using AWS, I have found AWS Config to be able to provide a lot of the same benefits as other infrastructure testing tools, without as much setup/maintenance. Although it is fairly new, and I have not used it extensively.
Also if you are paying for Terraform Premium you get access to Sentinel, which seems to provide a lot of similar benefits to AWS Config, however I have not used it personally.

A: In addition to the answers, I will add my two cents. I was not very happy using GO lang with Terratest although it works perfectly well. It is just that GO is not my favorite programming language. I looked for some frameworks in Java and I found terraform-maven. At first glance, I only found examples in Groovy, but since Groovy run on JVM, it is feasible to implement the same examples in Java.
I translated part of the S3PreProvisionSpec.groovy to Java. It is testing this main.tf file.
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class S3PreProvisionTest {

    private final String TF_CHANGE = "change";
    private final String TF_AFTER = "after";
    private final String TF_TAGS = "tags";
    private final Map<String, String> mandatoryTags = Map.of(
        "application_id", "cna",
        "stack_name", "stacked",
        "created_by", "f.gutierrez@yieldlab.de"
    );
    private Terraform terraform;
    private TfPlan tfplan;

    @BeforeAll
    void setup() {
        terraform = new Terraform().withRootDir("s3_pre_post_demo")
        // .withProperties(Map.of("noColor", "true"))
        ;
        tfplan = terraform.initAndPlan();
    }

    @AfterAll
    void cleanup() {
        terraform.destroy();
    }

    @Test
    void mandatoryTagsForS3Resources() {
        List<Map> s3Bucket = tfplan.getResourcesByType("aws_s3_bucket");
        System.out.println("=========================");

        s3Bucket.forEach(map -> {
            Map tfChangeMap = (Map) map.get(TF_CHANGE);
            Map tfAfterMap = (Map) tfChangeMap.get(TF_AFTER);
            Map tfTagsMap = (Map) tfAfterMap.get(TF_TAGS);

            assertEquals(3, tfTagsMap.size());
            mandatoryTags.forEach((k, v) -> {
                assertEquals(v, tfTagsMap.get(k));
            });

            try {
                JSONObject jsonObject = new JSONObject(map);
                JSONObject jsonChange = jsonObject.getJSONObject(TF_CHANGE);
                JSONObject jsonAfter = jsonChange.getJSONObject(TF_AFTER);
                JSONObject jsonTags = jsonAfter.getJSONObject(TF_TAGS);
                System.out.println(">>>>>>>>>>>>>>>>>>>> " + jsonTags.toString());
                mandatoryTags.forEach((k, v) -> {
                    try {
                        assertEquals(v, jsonTags.getString(k));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        });
    }
}

A: One approach is to output the results to a file using -out=tempfile, then run a script to validate whatever you're trying to do, and if all passes you can pass the file into the apply command.
look at -out here:
https://www.terraform.io/docs/commands/plan.html

A: You can use  github.com/palantir/tfjson to parse a .plan file to json.
There is an issue at the moment that give a "unknown plan file version: 2" error. This is because the vendored version of terraform is too old.
The fix is:
go get github.com/palantir/tfjson
cd $GOPATH/src/github.com/palantir/tfjson
rm -rf vendor
go get -v ./...

There is then an error in ../../hashicorp/terraform/config/testing.go. To fix just change the line
t.Helper()

to
//t.Helper()

Run go get again and then go install
go get -v ./...
go install ./...

You should then be able to do the following which will produce json output.
terraform plan --out=terraform.plan
tfjson terraform.plan


text:
Q: Android SurfaceView Video Overlap In my app, I'm displaying local videos using a SurfaceView. However, I noticed a strange (rare) bug when switching between videos: they both overlap.
Screenshot:

Sometimes the old video (top black video) stays still and sometimes it still continues playing. (with no audio)
How do I fix this?
I was previously using a VideoView and still had this issue. My VideoFragment is recreated everytime I open a new video. I tried releasing the video in the onPause() of the fragment but still no luck.
@Override
public void onPause()
{
    super.onPause();

    if (player != null && Video.getDownloaded())
    {
        if(player.isPlaying())
            player.stop();

        controller.hide();
        player.release();
    }
}

Thanks in Advance,
~Pkmmte Xeleon

A: Simply put, a SurfaceView is a weird "widget". Treat them carefully.
Try reorganizing your UI to have a single SurfaceView (or VideoView if you roll back to that). For example, that could be fixed below your action bar tabs, with the rest of your content inside a fragment beneath it. On a tab change, update the video and replace the main fragment.
Or, if you are only supporting API Level 14+, try TextureView instead.

A: I use a surfaceView as the surface for video or draw something on the surface.
And when I switch the Activity very quickly, e.g. switch to Activity B and switch back very quickly, there are two surface overlap.
dumpsys SurfaceFlinger,there are two surfaceview in the output.
I try to modify the surfaceflinger, when the destroy surface called, evenif it is detached from layerbase, also destroy it.
And this issue dispeared.


text:
Q: Reversing bits in a byte with AVR I am currently working on a problem that wants me to build a subroutine that will reverse the bits in R16.
00000011 => 11000000
or
10101000 => 00010101

For the class we are using the AVR subset and the subroutine needs to work in norfair.
This is what I have so far, any help would be appreciated!
ldi r16,3 ;00000011

A: The naive solution is to loop through the bits with the shift operator and check. But be aware that AVR doesn't have a barrel shifter so it can only shift by 1, any other shift counts need more than 1 instruction. Here's one obvious solution from the famous bithacks page
uint8_t reverse_obvious(uint8_t v)
{
    uint8_t r = v & 1; // r will be reversed bits of v; first get LSB of v
    uint8_t s = sizeof(v) * CHAR_BIT - 1; // extra shift needed at end

    for (v >>= 1; v; v >>= 1)
    {
        r <<= 1;
        r |= v & 1;
        s--;
    }
    r <<= s; // shift when v's highest bits are zero
    return r;
}

The above snippet uses only shifts by 1 except the last r <<= s which needs a loop in AVR. You can avoid that by always running 8 loops
uint8_t reverse(uint8_t x)
{
    uint8_t mask_up = 0x01;
    uint8_t mask_down = 0x80;
    uint8_t result = 0;
    for (; mask_down; mask_down >>= 1, mask_up <<= 1)
    {
        if (x & mask_up)
            result |= mask_down;
    }
    return result;
}

Another alternative that has shift by 2, but I guess it's the best way you can do without a lookup table. AVR has plenty of available ROM for the table so it should be a lot more efficient that way
uint8_t reverse(uint8_t x)
{
    x = (((x & 0xaaU) >> 1) | ((x & 0x55U) << 1));
    x = (((x & 0xccU) >> 2) | ((x & 0x33U) << 2));
    x = (((x & 0xf0U) >> 4) | ((x & 0x0fU) << 4));
    return x;
}

Some compilers also have built-ins to reverse bits. For example Clang has __builtin_bitreverse8() and GCC has __builtin_avr_insert_bits() which can be used to reverse bits:
// reverse the bit order of bits
__builtin_avr_insert_bits (0x01234567, bits, 0)

Unfortunately their outputs are terrible

There are also lots of questions with good answers on SO about reversing bits. Try converting the C code to assembly and compare with the result on compiler explorer

*

*Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

*In C/C++ what's the simplest way to reverse the order of bits in a byte?

A: AVR has swap instruction which allows to swap 4bit nibbles in a register. You can use it to make the code shorter.
mov r17, r16
ror r16  // rotate right, pushing bit 0 out to C flag
rol r17  // rotate left, moving C flag into bit 0 and pushing bit 7 out to C flag
ror r16
rol r17
ror r16
rol r17
ror r16
rol r17
ror r16
andi r16, 0xF0 // isolating bit 4 to 7
andi r17, 0x0F // isolating bit 0 to 3
or r16, r17    // combining
swap r16       // swapping the nibbles

A: You can do that using rol and ror opcodes (rotates left and right through carry).
ldi  r16,0b10101000   // value to reverse
push r17
rol  r16        // this push r16 msb bit in carry in left direction
ror  r17        // this push carry to r17 in right direction
rol  r16
ror  r17
rol  r16
ror  r17
rol  r16
ror  r17
rol  r16
ror  r17
rol  r16
ror  r17
rol  r16
ror  r17
rol  r16
ror  r17       // now r17 is reversed value
mov  r16,r17   // now r16 is reversed value
pop  r17

** not tested, but should work ;-) **
You can also improve this with a loop !


text:
Q: Render high resolution image as thumbnail fast Ruby on Rails 3.2
I have images around 1800 x 1200 pixels that I render to 220 x 180 pixels. The images are in the public directory. They take a little time to render, how would I make them render faster?
My view:
<% @images.each_slice(3) do |slice| %>

                <% slice.each do |image| %>

<%= File.basename(image) %>

                    <% image_path = ["", File.dirname(image).split("public"),"/", File.basename(image)].join('') %>
                    <%= link_to image_tag(image_path), image_path[/\/.*/]%>

        <% end %>

<% end %>

My style making the images thumbnails.
li.span3 img{
    width: 220px;
    max-height: 180px;
}

Any ideas to make them render faster? Maybe in the application controller loading the thumbnails for using app wide or something?

A: Your CSS does not reduce the image size - it renders a massive image, that is what is taking so long, the download and render of a huge image.
It would be faster to resize server-side and download that, the exact method to do that is what you should look into  - a quick google found:
http://www.dzone.com/snippets/easily-generate-thumbnails


text:
Q: How to increase the space between groups and tasks of Gantt Chart (pgfgantt package) I was typing this gantt chart (code below), but I didn't figure out how to increase the space between "WP 1" and "Task 1.1" (please see figure attached). How can I do that? Thanks!
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=2cm]{geometry}
\usepackage{times}
\usepackage{xcolor}
\usepackage{pgfgantt}

\begin{document}

\renewcommand\sfdefault{phv}
\renewcommand\mddefault{mc}
\renewcommand\bfdefault{bc}
\setganttlinklabel{s-s}{START-TO-START}
\setganttlinklabel{f-s}{FINISH-TO-START}
\setganttlinklabel{f-f}{FINISH-TO-FINISH}
\sffamily
\begin{ganttchart}[
    canvas/.append style={fill=none, draw=black!5, line width=.75pt},
    hgrid style/.style={draw=black!5, line width=.75pt},
    vgrid={*1{draw=black!5, line width=.75pt}},
    today=none,
    today rule/.style={
      draw=black!64,
      dash pattern=on 3.5pt off 2.5pt,
      line width=1.5pt
    },
    today label font=\small\bfseries,
    title/.style={draw=none, fill=none},
    title label font=\bfseries\footnotesize,
    title label node/.append style={below=7pt},
    include title in canvas=false,
    bar label font=\mdseries\small\color{black!70},
    bar label node/.append style={left=0cm,align=left,text width=20em},
    bar/.append style={draw=none, fill=black!63},
    bar incomplete/.append style={fill=blue!50},
    bar progress label font=\mdseries\footnotesize\color{black!70},
    group incomplete/.append style={fill=blue},
    group left shift=0,
    group right shift=0,
    group height=.3,
    group peaks tip position=0,
    group label node/.append style={align=left, left=-.5cm, text width=22.5em},
    group progress label font=\bfseries\small,
    link/.style={-latex, line width=1.5pt, red},
    link label font=\scriptsize\bfseries,
    link label node/.append style={below top=2pt and 0pt},
    y unit chart=0.5cm
  ]{1}{13}
  \ganttset{bar height=0.25}
  \gantttitle[
    title label node/.append style={below left=7pt and -2pt}
  ]{MONTHS:\quad1}{1}
  \gantttitlelist{2,4,8,12,16,18,20,24,28,30,32}{1} \\
  \ganttgroup[]{WP 1: Planning}{1}{9} \\
  \ganttbar[]{\textbf{Task 1.1} Task prioritization}{1}{5} \\
  \ganttbar[]{\textbf{Task 1.2} Gantt charts creation}{4}{9} \\
  \ganttgroup[]{Execution}{3}{10} \\
  \ganttbar[]{\textbf{Task 2.1} Synthesis and characterization}{3}{9} \\
  \ganttbar[]{\textbf{Task 2.2} Data Analysis}{4}{10} \\
  \ganttbar[]{\textbf{Task 2.3} Imaging Errors}{5}{10} \\
  \ganttgroup[]{WP3 Conclusion}{4}{12} \\
  \ganttbar[]{\textbf{Task 3.1}  Storytelling of the results}{4}{9} \\
  \ganttbar[]{\textbf{Task 3.2} Presenting}{7}{12}
\end{ganttchart}

\end{document}

A: Perhaps add an extra \\ to the mix, as needed.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=2cm]{geometry}
\usepackage{times}
\usepackage{xcolor}
\usepackage{pgfgantt}

\begin{document}

\renewcommand\sfdefault{phv}
\renewcommand\mddefault{mc}
\renewcommand\bfdefault{bc}
\setganttlinklabel{s-s}{START-TO-START}
\setganttlinklabel{f-s}{FINISH-TO-START}
\setganttlinklabel{f-f}{FINISH-TO-FINISH}
\sffamily
\begin{ganttchart}[
    canvas/.append style={fill=none, draw=black!5, line width=.75pt},
    hgrid style/.style={draw=black!5, line width=.75pt},
    vgrid={*1{draw=black!5, line width=.75pt}},
    today=none,
    today rule/.style={
      draw=black!64,
      dash pattern=on 3.5pt off 2.5pt,
      line width=1.5pt
    },
    today label font=\small\bfseries,
    title/.style={draw=none, fill=none},
    title label font=\bfseries\footnotesize,
    title label node/.append style={below=7pt},
    include title in canvas=false,
    bar label font=\mdseries\small\color{black!70},
    bar label node/.append style={left=0cm,align=left,text width=20em},
    bar/.append style={draw=none, fill=black!63},
    bar incomplete/.append style={fill=blue!50},
    bar progress label font=\mdseries\footnotesize\color{black!70},
    group incomplete/.append style={fill=blue},
    group left shift=0,
    group right shift=0,
    group height=.3,
    group peaks tip position=0,
    group label node/.append style={align=left, left=-.5cm, text width=22.5em},
    group progress label font=\bfseries\small,
    link/.style={-latex, line width=1.5pt, red},
    link label font=\scriptsize\bfseries,
    link label node/.append style={below top=2pt and 0pt},
    y unit chart=0.5cm
  ]{1}{13}
  \ganttset{bar height=0.25}
  \gantttitle[
    title label node/.append style={below left=7pt and -2pt}
  ]{MONTHS:\quad1}{1}
  \gantttitlelist{2,4,8,12,16,18,20,24,28,30,32}{1} \\
  \ganttgroup[]{WP 1: Planning}{1}{9} \\ \\
  \ganttbar[]{\textbf{Task 1.1} Task prioritization}{1}{5} \\
  \ganttbar[]{\textbf{Task 1.2} Gantt charts creation}{4}{9} \\
  \ganttgroup[]{Execution}{3}{10} \\ \\
  \ganttbar[]{\textbf{Task 2.1} Synthesis and characterization}{3}{9} \\
  \ganttbar[]{\textbf{Task 2.2} Data Analysis}{4}{10} \\
  \ganttbar[]{\textbf{Task 2.3} Imaging Errors}{5}{10} \\
  \ganttgroup[]{WP3 Conclusion}{4}{12} \\ \\
  \ganttbar[]{\textbf{Task 3.1}  Storytelling of the results}{4}{9} \\
  \ganttbar[]{\textbf{Task 3.2} Presenting}{7}{12}
\end{ganttchart}

\end{document}


text: Q: Teradata Ansi Mode I read difference of Teradata and Ansi session mode here: Link. I got that why teradata mode is recommended. But I am confused about that where Ansi mode is used? After all it is an option. It must be used in some scenarios. atleast.


text:
Q: TypeScript errors when building because I import extracted .graphql files and the type can't be resolved I have the following file @/graphql/mutations.graphql containing:
mutation addCharacterToUser($userId: ID!, $characterId: ID!) {
    addCharacterToUser(userId: $userId, characterId: $characterId) {
        characterIds
    }
}

mutation newCharacter ($name: String!, $age: Int!) {
    newCharacter(character: {name: $name, age: $age}) {
        id
    }
}

Now I am using it in one of my Vue.js components (I use TypeScript with Vue.js).
However when I run npm run build I receive the following error:
 error  in C:/Development/Project/src/components/character/CharacterCreationDialog.vue

ERROR in C:/Development/Project/src/components/character/CharacterCreationDialog.vue(59,50):
59:50 Cannot find module '@/graphql/character/mutations.graphql' or its corresponding type declarations.
    57 | <script lang="ts">
    58 | import Vue from 'vue'
  > 59 | import { addCharacterToUser, newCharacter } from '@/graphql/character/mutations.graphql'
       |                                                  ^
    60 |
    61 | export default Vue.extend({
    62 |   name: 'CharacterCreationDialog',

I researched some things but I can't really understand what the issue is. I have very little experience with TypeScript.

A: It seems you do not have the required module @/graphql/character/mutations.graphql installed in your project workspace. Can you try checking if you might my missing the module?
Check your dependencies in package.json and ensure you can run npm install with no errors.


text:
Q: make some private members of a class const for some functions I have a class named myClass:
myClass
{
    int myFunction1();
    int myFunction2();

private:
int A;
int B;
};

In myFunction1 A should not change but B can be changed.
In myFunction2 B should not change but A can be changed.
Is there any way to make flexible const for each function?
ie const B for function1 and vice versa.

A: This is not easily possible. You can declare a method const which will make all variables const. You can declare a member mutable so that it can be mutated even in const functions. However, you cannot declare a member mutable to only some methods.
But the question is: Why would you want that? Simply do not alter A in your method. Since the method is in the same file, it should not be too hard to remember that.
If you really need separate encapsulation for A and B even inside a class, then use an own class for them and move the method to the class, e.g.:
class MyClass {
private:
   AContainer A;
   BContainer B;
public:
   void myFunction1(){ B.myFynction1(A.get()); }
   void myFunction2(){ A.myFunction2(B.get()); }

   class BContainer {
       int B;
   public:
       int get(){ return B;}
       myFunction1(int A); // May only change B, A is provided as parameter
   }

   class AContainer {
       int A;
   public:
       int get(){ return A;}
       myFunction2(int B); // May only change A, B is provided as parameter
   }

}

A: If you really need to achieve that behavior you can wrap your ints into classes that will befriend specific functions while providing get/set access, like so (very simplified, lacking all the necessary utilities - just to illustrate the point):
class TIntA{
public:
    TIntA(int _i) : m_data(_i) {}

    // this function will be able to modify the m_data member but other
    // functions will have to use the get()
    friend int myClass::myFunction1();

    int get() const {return m_data;}

private:
    int m_data;
};

I'm sure you can further generalize this approach with templates (can you provide a function as a template parameter? If so you can make this class totally generic)


text:
Q: Unexpected behavior when printing 4-byte integer byte by byte I have this sample code for converting 32 bit integers to ip addresses.

#include <stdio.h>
int main()
{
 unsigned int c ;
 unsigned char* cptr  = (unsigned char*)&c ;
 while(1)
 {
  scanf("%d",&c) ;
  printf("Integer value: %u\n",c);
  printf("%u.%u.%u.%u \n",*cptr, *(cptr+1), *(cptr+2), *(cptr+3) );
 }
}

This code gives incorrect output for input 2249459722 .
But when i replacescanf("%d",&c) ; by scanf("%u",&c) ;
The output comes out to be correct.

P.S : I know about inet_ntop and inet_pton.
 I expect answers other than suggesting those.

A: %d is for signed integers
%u is for unsigned integers
Edit:
Please modify your program as follows to see how your input is really interpreted:
#include <stdio.h>
int main()
{
 unsigned int c ;
 unsigned char* cptr  = (unsigned char*)&c ;
 while(1)
 {
  scanf("%d",&c) ;
  printf("Signed value: %d\n",c);
  printf("Unsigned value: %u\n",c);
  printf("%u.%u.%u.%u \n",*cptr, *(cptr+1), *(cptr+2), *(cptr+3) );
 }
}

What happens when you supply a number greater than INT_MAX is the left-most bit is 1. This indicates that it is a signed integer with a negative value. The number is then interpreted as it's two's complement

A: You are coding 'sinfully' (making a number of mistakes which will hurt you sooner or later - mostly sooner).   First off, you are assuming that the integer is of the correct endian-ness. On some machines, you will be wrong - either on Intel machines or on PowerPC or SPARC machines.
In general, you should show the actual results you get rather than just saying that you get the wrong result; you should also show the expected result.  That helps people debug your expectations.

Here's my modified version of your code - instead of requesting input, it simply assumes the value you specified.
#include <stdio.h>
int main(void)
{
    unsigned int c = 2249459722;
    unsigned char* cptr  = (unsigned char*)&c;
    printf("Integer value:  %10u\n", c);
    printf("Integer value:  0x%08X\n", c);
    printf("Dotted decimal: %u.%u.%u.%u \n", *cptr, *(cptr+1), *(cptr+2), *(cptr+3));
    return(0);
}

When compiled on my Mac (Intel, little-endian), the output is:
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 10.8.20.134

When compiled on my Sun (SPARC, big-endian), the output is:
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 134.20.8.10

(Using GCC 4.4.2 on the SPARC, I get a warning:
xx.c:4: warning: this decimal constant is unsigned only in ISO C90

Using GCC 4.2.1 on Mac - with lots of warnings enabled (gcc -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wstrict-prototypes -Wmissing-prototypes -Werror) - I don't get that warning, which is interesting.)  I can remove that by adding a U suffix to the integer constant.

Another way of looking at the problems is illustrated with the following code and the extremely fussy compiler settings shown above:
#include <stdio.h>

static void print_value(unsigned int c)
{
    unsigned char* cptr  = (unsigned char*)&c;
    printf("Integer value:  %10u\n", c);
    printf("Integer value:  0x%08X\n", c);
    printf("Dotted decimal: %u.%u.%u.%u \n", *cptr, *(cptr+1), *(cptr+2), *(cptr+3));
}

int main(void)
{
    const char str[] = "2249459722";
    unsigned int c = 2249459722;

    printf("Direct operations:\n");
    print_value(c);

    printf("Indirect operations:\n");
    if (sscanf("2249559722", "%d", &c) != 0)
        printf("Conversion failed for %s\n", str);
    else
        print_value(c);
    return(0);
}

This fails to compile (because of the -Werror setting) with the message:
cc1: warnings being treated as errors
xx.c: In function 'main':
xx.c:20: warning: format '%d' expects type 'int *', but argument 3 has type 'unsigned int *'

Remove the -Werror setting and it compiles, but then shows the next problem that you have - the one of not checking for error indications from functions that can fail:
Direct operations:
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 10.8.20.134
Indirect operations:
Conversion failed for 2249459722

Basically, the sscanf() function reports that it failed to convert the string to a signed integer (because the value is too large to fit - see the warning from GCC 4.4.2), but your code was not checking for the error return from sscanf(), so you were using whatever value happened to be left in c at the time.
So, there are multiple problems with your code:

*

*It assumes a particular architecture (little-endian rather than recognizing that big-endian also exists).

*It doesn't compile cleanly when using a compiler with lots of warnings enabled - for good reason.

*It doesn't check that functions that can fail actually succeeded.

Alok's Comment
Yes, the test on sscanf() is wrong.  That's why you have code reviews, and also why it helps to post the code you are testing.
I'm now a bit puzzled - getting consistent behaviour that I can't immediately explain.  With the obvious revision (testing on MacOS X 10.6.2, GCC 4.2.1, 32-bit and 64-bit compilations), I get one not very sane answer.  When I rewrite more modularly, I get a sane answer.
+ cat yy.c
#include <stdio.h>

static void print_value(unsigned int c)
{
    unsigned char* cptr  = (unsigned char*)&c;
    printf("Integer value:  %10u\n", c);
    printf("Integer value:  0x%08X\n", c);
    printf("Dotted decimal: %u.%u.%u.%u \n", *cptr, *(cptr+1), *(cptr+2), *(cptr+3));
}

int main(void)
{
    const char str[] = "2249459722";
    unsigned int c = 2249459722;

    printf("Direct operations:\n");
    print_value(c);

    printf("Indirect operations:\n");
    if (sscanf("2249559722", "%d", &c) != 1)
        printf("Conversion failed for %s\n", str);
    else
        print_value(c);
    return(0);
}

+ gcc -o yy.32 -m32 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wstrict-prototypes -Wmissing-prototypes yy.c
yy.c: In function 'main':
yy.c:20: warning: format '%d' expects type 'int *', but argument 3 has type 'unsigned int *'

+ ./yy.32
Direct operations:
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 10.8.20.134
Indirect operations:
Integer value:  2249559722
Integer value:  0x86158EAA
Dotted decimal: 170.142.21.134

I do not have a good explanation for the value 170.142.21.134; but it is consistent on my machine, at the moment.
+ gcc -o yy.64 -m64 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wstrict-prototypes -Wmissing-prototypes yy.c
yy.c: In function 'main':
yy.c:20: warning: format '%d' expects type 'int *', but argument 3 has type 'unsigned int *'

+ ./yy.64
Direct operations:
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 10.8.20.134
Indirect operations:
Integer value:  2249559722
Integer value:  0x86158EAA
Dotted decimal: 170.142.21.134

Same value - even in 64-bit instead of 32-bit.  Maybe the problem is that I'm trying to explain undefined behaviour, which is more or less by definition unexplainable (inexplicable).
+ cat xx.c
#include <stdio.h>

static void print_value(unsigned int c)
{
    unsigned char* cptr  = (unsigned char*)&c;
    printf("Integer value:  %10u\n", c);
    printf("Integer value:  0x%08X\n", c);
    printf("Dotted decimal: %u.%u.%u.%u \n", *cptr, *(cptr+1), *(cptr+2), *(cptr+3));
}

static void scan_value(const char *str, const char *fmt, const char *tag)
{
    unsigned int c;
    printf("Indirect operations (%s):\n", tag);
    fmt = "%d";
    if (sscanf(str, fmt, &c) != 1)
        printf("Conversion failed for %s (format %s \"%s\")\n", str, tag, fmt);
    else
        print_value(c);
}

int main(void)
{
    const char str[] = "2249459722";
    unsigned int c = 2249459722U;

    printf("Direct operations:\n");
    print_value(c);
    scan_value(str, "%d", "signed");
    scan_value(str, "%u", "unsigned");

    return(0);
}

Using the function argument like this means GCC cannot spot the bogus format any more.
+ gcc -o xx.32 -m32 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wstrict-prototypes -Wmissing-prototypes xx.c

+ ./xx.32
Direct operations:
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 10.8.20.134
Indirect operations (signed):
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 10.8.20.134
Indirect operations (unsigned):
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 10.8.20.134

The results are consistent here.
+ gcc -o xx.64 -m64 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wstrict-prototypes -Wmissing-prototypes xx.c

+ ./xx.64
Direct operations:
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 10.8.20.134
Indirect operations (signed):
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 10.8.20.134
Indirect operations (unsigned):
Integer value:  2249459722
Integer value:  0x8614080A
Dotted decimal: 10.8.20.134

And these are the same as the 32-bit case.  I'm officially bemused.  The main observations remain accurate - be careful, heed compiler warnings (and elicit compiler warnings), and don't assume that "all the world runs on Intel chips" (it used to be "don't assume that all the world is a VAX", once upon a long time ago!).

A: To answer your main question:
scanf("%d", &c);

scanf()'s behavior is undefined when the input being converted can't be represented to the data type.  2249459722 on your machine doesn't fit in an int, so scanf() can do anything, including storing garbage in c.
In C, int type is guaranteed to be able to store values in the range -32767 to +32767.  An unsigned int is guaranteed values between 0 and 65535.  So, as such, 2249459722 need not fit in even an unsigned int.  unsigned long, however, can store values up to 4294967295 (232−1), so you should use unsigned long:
#include <stdio.h>
int main()
{
    unsigned long c ;
    unsigned char *cptr  = (unsigned char*)&c ;
    while(1)
    {
        if (scanf("%lu", &c) != 1) {
            fprintf(stderr, "error in scanf\n");
            return 0;
        }
        printf("Input value: %lu\n", c);
        printf("%u.%u.%u.%u\n", cptr[0], cptr[1], cptr[2], cptr[3]);
    }
    return 0;
}

If you have a C99 compiler, you can #include <inttypes.h> and then use uint32_t instead of unsigned long.  The scanf() call becomes scanf("%" SCNu32, &c);

A: The correct endianness-safe way to write this is
printf("Dotted decimal: %u.%u.%u.%u \n", (c >> 24) & 0xff, (c >> 16) & 0xff, (c >> 8) & 0xff, (c >> 0) & 0xff);


text:
Q: How to get the Joint probability of two dependent continuous random variables I would like to calculate the following probability of :
$$
\begin{equation}
\begin{array}{l}
\displaystyle P_u = \Pr\{x<a_1 , x \geq a_2 \,\,y + a_3\}
\end{array}
\end{equation}
$$
where $x$ and $y$ are independent exponential random variables  with a unit mean and $$a_1 , a_2, a_3 $$ are positive constants.
I tried to use
$$
\begin{equation}
\begin{array}{l}
\displaystyle P_u = \Pr\{x<a ,\,\, x -a_2 \,\,y \geq  a_3\}\\
\displaystyle  \quad \,\,=  \Pr\{x<a , z \geq  a_3\}\\
\end{array}
\end{equation}
$$
where $$z = x-a_2 \, y$$
and
$$
\begin{equation}
\begin{array}{l}
\displaystyle P_u = \int_{x=0}^{a_1}  \int_{z=a_3}^{\infty} f_{xz}(x,z)\, dx\, dz
\end{array}
\end{equation}
$$
I got PDFs of x and z, but since they are not independent , I can not assume :
$$
\begin{equation}
\begin{array}{l}
\displaystyle f_{xz}(x,z)=f_{x}(x)\, f_{z}(z)
\end{array}
\end{equation}
$$
How to complete from here or another alternative at all?

A: The probability will take value $0$ is $\mathsf{P}\left(a_{2}y+a_{3}\geq a_{1}\right)=1$.
So you must take care of suitable conditions on the $a_{i}$.
Let $\left[x<a_{1},x\geq a_{2}y+a_{3}\right]$ denote the function
$\mathbb{R}^{2}\to\mathbb{R}$ that takes value $1$ if $x<a_{1}$
and $x\geq a_{2}y+a_{3}$ are both satisfied and takes value $0$ otherwise.
Then:
$\begin{aligned}\mathsf{P}\left(x<a_{1},x\geq a_{2}y+a_{3}\right) & =\mathsf{E}\left[x<a_{1},x\geq a_{2}y+a_{3}\right]\\
 & =\int\int\left[x<a_{1},x\geq a_{2}y+a_{3}\right]f_{X}\left(x\right)f_{Y}\left(y\right)dxdy\\
 & =\int f_{Y}\left(y\right)\left[a_{2}y+a_{3}<a_{1}\right]\int_{a_{2}y+a_{3}}^{a_{1}}f_{X}\left(x\right)dxdy
\end{aligned}
$
Where $[a_2y+a_3<a_1]$ denotes the function $\mathbb R\to\mathbb R$ that takes value $1$ if $a_2y+a_3<a_1$ is satisfied and takes value $0$ otherwise.
This can further be worked out discerning cases $a_{2}<0$, $a_{2}=0$
and $a_{2}>0$.
In e.g. the last case (i.e. $a_2>0$) we get $\int_{-\infty}^{\frac{a_{1}-a_{3}}{a_{2}}}f_{Y}\left(y\right)\int_{a_{2}y+a_{3}}^{a_{1}}f_{X}\left(x\right)dxdy$.
Note that it will take value $0$ if $a_1\leq a_3$ (then $\mathsf{P}\left(a_{2}y+a_{3}\geq a_{1}\right)=1$)  and simplifies to $\int_{0}^{\frac{a_{1}-a_{3}}{a_{2}}}f_{Y}\left(y\right)\int_{a_{2}y+a_{3}}^{a_{1}}f_{X}\left(x\right)dxdy$ otherwise.

A: If $a_1 \leq 0$ then $P_u = 0$ so, we assume that $a_1 > 0$. For $a_2 = 0$, $P_u$ is straightforward: $ Pu = 0$ if $a_3 < a_1$ else $P_u = \int_{a_1}^{a_3}f_X(x)dx$.
For $a_2 \neq 0$ we can use change of variables
$$\begin{align*}
U &= X \\
V &= X - a_2 Y
\end{align*}$$
The inverse tranformation is
$$\begin{align*}
X &= U \\
Y &= \frac{U-V}{a_2}
\end{align*}$$
The joint pdf of U and V will be
$$f_{U,V}(u,v) = \left. \frac{f_{X,Y}(x,y)}{\left | \frac{\partial(U,V) }{\partial(X,V)} \right | } \right|{}_{x = u \\ y= \frac{u-v}{a_2} }  =
\frac{1}{|a_2|}f_X(u)f_Y \left (\frac{u-v}{a_2} \right)$$
Then
$$ P_u = Pr\{U < a_1, V \geq a_3 \} =
\frac{1}{|a_2|} \iint_{D} f_X(u) f_Y \left (\frac{u-v}{a_2} \right)dvdu $$
Where $D$ is the domain
$$D = \left \{(x,y) \in \Re: 0<u<a_1, v>a_3, \frac{u-v}{a_2}>0 \right \}$$
Now, as @drhab mentions as well in his solution, we have to take two different cases into account:
1) If $a_2>0$ then $a_3 < a_1$ (otherwise the domain $D$ will be empty) and $P_u$ simplifies to
$$ P_u = \frac{1}{a_2} \int_{\max\{0,a_3\}}^{a_1}\int_{a_3}^{u}f_X(u) f_Y \left (\frac{u-v}{a_2} \right)dvdu $$
2) If $a_2<0$ then $P_u$ simplifies to
$$ P_u = -\frac{1}{a_2} \int_{0}^{a_1}\int_{\max\{0,a_3\}}^{\infty}f_X(u) f_Y \left (\frac{u-v}{a_2} \right)dvdu $$
Performing the relevant integration, will give the required result.


text:
Q: Finding averages from strings in a list in Python 3 I have a list of scores like so:
scores = ["Bob Foo - 10 / 20\n",
      "Jim Foo - 5 / 20\n",
      "Bob Foo - 7 / 20\n",
      "Jack T - 6 / 20\n",
      "Jack T - 4 / 20\n",
      "Bob Foo - 9 / 20\n"]

I need to try and find the average score of each person seperately rounded to the nearest integer. The list may vary its scale and names will change but it will always have the format of:
first name last name - score / 20.
I want an output of something like:
>>> Bob Foo - 9
Jim Foo - 5
Jack T - 5

I really don't know what to do here. I know about the sorted function and how you can specify a key but I don't know if that will help here.
The closest I've gotten is:
for score in scores:
    print(re.split(r'[-/]',score))

which isn't even close, because all it does is split up the list and give me this:
>>>
['Bob Foo ', ' 10 ', ' 20\n']
['Jim Foo ', ' 5 ', ' 20\n']
['Bob Foo ', ' 7 ', ' 20\n']
['Jack T ', ' 6 ', ' 20\n']
['Jack T ', ' 4 ', ' 20\n']
['Bob Foo ', ' 9 ', ' 20\n']
>>>

How can I overcome this? Can I just create a function that finds the average score of each person in a list?
Edit:
I could simplify the list of scores to an easier format. For example:
scores = ["Bob Foo 10\n",
      "Jim Foo 5\n",
      "Bob Foo 7\n",
      "Jack T 6\n",
      "Jack T 4\n",
      "Bob Foo 9\n"]

A: I find it useful to divide-and-conquer programming tasks. Divide the complex task into a series of trivially simple tasks. Either you know how to do each one individually, or you can receive more targeted help on the part you are struggling with.
As an example, here is how I would solve this problem:
import re
scores = ["Bob Foo - 10 / 10\n",
          "John Smith - 5 / 10\n",
          "Bob Foo - 7 / 10\n",
          "Jack T - 6 / 10\n",
          "Jack T - 4 / 10\n",
          "Bob Foo - 9 / 10\n"]

# First, split the names and scores up
scores = [re.match('(\S+ \S+) - (\d+)', score).groups() for score in scores]
#print (scores)

# Convert the number string into an integer
scores = [[score[0], int(score[1])] for score in scores]
#print (scores)

# Create a dictionary, keyed by the name
names = set(score[0] for score in scores)
scores = {
    name: [score[1] for score in scores if name == score[0]]
    for name in names
}
# print (scores)

# Compute the average for each name
scores = {
    name: sum(score)/len(score)
    for name, score in scores.items()
}
print (scores)

A: parts = [score.split("-",1) for score in scores]

will break up your data how you demonstrated before except it just seperates it into name,rest , now you just need to save it
data = {}
for name,score in parts:
   try:
       data[name].append(score)
   except KeyError:
       data[name] = [score,]

print data

now you have grouped your scores by name so the now alll you need to do is go through and convert the score to actual int's(or probably better float's)
 and average the score for each name

A: try this .it might help you
import math
scores = ["Bob Foo - 10 / 10\n",
      "John Smith - 5 / 10\n",
      "Bob Foo - 7 / 10\n",
      "Jack T - 6 / 10\n",
      "Jack T - 4 / 10\n",
      "Bob Foo - 9 / 10\n"]
d={}
for i in xrange(len(scores)):
    str=scores[i].split("-");
    try:
        (d[str[0]])[0] +=int((str[1].split("/"))[0])
        (d[str[0]])[1] +=1
    except:
        d[str[0]]=[0,0]
        (d[str[0]])[0]=int((str[1].split("/"))[0])
        (d[str[0]])[1]=1
//store sum and count in a dictionary

for x in d:
    print x,((d[x])[0]/((d[x])[1])*1.0)

and in the last statement apply appropriate function ceil or floor .or round
click here to see the execution


text:
Q: "Use of unresolved identifier" error with ResearchKit code I'm building an app using ResearchKit through the Ray Wenderlich tutorial and the following code continues to give the error message: Use of unresolved identifier 'consentSectionType' which is the current one. Since I didn't write the code, I'm not sure what's wrong with it, and I don't know how to fix it. This is the code:
public var ConsentDocument: ORKConsentDocument {

let consentDocument = ORKConsentDocument()
consentDocument.title = "Consent"

let _: [ORKConsentSectionType] = [
    .overview,
    .dataGathering,
    .privacy,
    .dataUse,
    .timeCommitment,
    .studySurvey,
    .studyTasks,
    .withdrawing
]
var consentSections: [ORKConsentSection] = consentSectionType.map { contentSectionType in
    let consentSection = ORKConsentSection(type: contentSectionType)
    consentSection.summary = "x."
    consentSection.content = "y."
    return consentSection
}

consentDocument.sections = consentSections

Occasionally Xcode will suggest that I change consentSectionType.map to ORKConsentSection.map, but that just brings another error message that says Type 'ORKConsentSection.map' has no member map. This seems to be a case specific problem, as answers to the other questions weren't helpful in this case.

A: Replace this
let _: [ORKConsentSectionType] = [
  .Overview,
  .DataGathering,
  .Privacy,
  .DataUse,
  .TimeCommitment,
  .StudySurvey,
  .StudyTasks,
  .Withdrawing
]

with
let consentSectionType: [ORKConsentSectionType] = [
  .Overview,
  .DataGathering,
  .Privacy,
  .DataUse,
  .TimeCommitment,
  .StudySurvey,
  .StudyTasks,
  .Withdrawing
]


text:
Q: WPF custom Control with custom drawing and ActualWidth I'm trying to create a custom control (deriving from Control) with its own drawing logic. The control is simply drawing a diagonal line from the upper-left corner to the right-bottom corner of the control. This logic is based on the control's ActualWidth and ActualHeight, which are only available when rendering the control (AFAIK).
My question is, what is the proper way to do custom drawing efficiently?
There's not much documentation on this, and I'm afraid I'm doing something stupid or unnecessary, like forcing refreshes/redraws every time OnPropertyChanged is fired...
Here is the control's template:
<Style TargetType="{x:Type local:MyCustomControl}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:MyCustomControl}">
        <Border Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}"
                BorderThickness="{TemplateBinding BorderThickness}">
          <Canvas>
            <Line x:Name="PART_Diagonal"
                  Y1="{Binding Path=DiagonalTop}"
                  Y2="{Binding Path=DiagonalBottom}"
                  X1="{Binding Path=DiagonalLeft}"
                  X2="{Binding Path=DiagonalRight}"
                  Stroke="Red" />
          </Canvas>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

And here is the logic:
public class MyCustomControl : Control, INotifyPropertyChanged
{
  static MyCustomControl()
  {
    DefaultStyleKeyProperty.OverrideMetadata( typeof( MyCustomControl ), new FrameworkPropertyMetadata( typeof( MyCustomControl ) ) );
  }

  public MyCustomControl()
  {
    DataContext = this;
  }

  protected override void OnRenderSizeChanged( SizeChangedInfo sizeInfo )
  {
    base.OnRenderSizeChanged( sizeInfo );

    var margin = 25d;

// These calculations are based on the control's current size.
    DiagonalTop = margin;
    DiagonalBottom = ActualHeight - margin;
    DiagonalLeft = margin;
    DiagonalRight = ActualWidth - margin;

// Is this forcing redraws (i.e. invalidating the layout)?
    OnPropertyChanged( "DiagonalTop" );
    OnPropertyChanged( "DiagonalBottom" );
    OnPropertyChanged( "DiagonalLeft" );
    OnPropertyChanged( "DiagonalRight" );
  }

  public double DiagonalTop { get; private set; }
  public double DiagonalBottom{ get; private set; }
  public double DiagonalLeft { get; private set; }
  public double DiagonalRight { get; private set; }

  public event PropertyChangedEventHandler PropertyChanged;
  protected void OnPropertyChanged(string propertyname)
  {
    if (PropertyChanged != null)
      PropertyChanged.Invoke( this, new PropertyChangedEventArgs( propertyname ) );
  }
}

A: You could do it much easier, without any additional properties. Simply use the Padding property for the inner spacing:
<ControlTemplate TargetType="{x:Type local:MyCustomControl}">
    <Border Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}"
            Padding="{TemplateBinding Padding}">
        <Canvas Name="DrawingCanvas">
            <Line X1="0" X2="{Binding ActualWidth, ElementName=DrawingCanvas}"
                  Y1="0" Y2="{Binding ActualHeight, ElementName=DrawingCanvas}"
                  Stroke="Red" />
        </Canvas>
    </Border>
</ControlTemplate>

Use your control with Padding:
<local:MyCustomControl Padding="25" ... />