text:
Q: What is a good image size for full page background I have a picture, that want to use as full background image in html. I follow the tutorials on https://css-tricks.com/perfect-full-page-background-image/ page but on my site does not look nice at all. My background picture has a size from 1200 x 1200.
My questions are:

*

*What is a good picture size for full background page?

*Which format should I use jpeg or svg?

A: I would recommend svg because it scales up without loss of quality. When using svg the actual size does not matter, because it is a vector image. However it is important to have the same aspect ratio as the screen you are targeting to, most often 16:9.

A: The most screens are 1920x1080, 1024x768.
Maybe you should use media queries?
Check this out: But please note, these statics are for w3schools visitors

A: The method described on css-tricks makes a background that will be resizable to the screen resolution. You'll notice that if you shrink your browser window that the image will get smaller and look 'nicer'.
So, you'll need to find an image with a resolution that supports at least 1080p (1920x1080). Just imagine someone viewing your website on their device at full screen. Some people do have screen that are larger than this, so try your best to support up to 1920x1440, even though 4k screens are becoming popular now.


text:
Q: Why does gnuplot plot this file incorrectly? I have a file that consists of data like this:
0,1566
1,1602
2,1534
3,1505
4,1487
.
.
.
1193,1278
1194,1262
1195,1235

When I plot it with gnuplot (using plot 'data.csv' using 0:1), I get a line from 0,0 to roughly 1200, 1200. Like this:
I don't understand why the plot looks like this. I don't even have any points near (0,0) and the y values should be decreasing with increasing x.

A: column numbering in gnuplot starts with 1, i.e. the first column number is 1. Hence, the correct command would be 'plot 'data.csv' using 1:2' in your example. (the zeroth column is an index, i.e. the number of the lines in the file)

A: Try:
set datafile separator ","
plot 'data.csv' using 1:2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Another why won't my jquery ajax work in ie question Just want to make sure my test code below is proper. I've been reading and it seems html syntax errors renders the jquery ajax unusable in ie?
There are a bunch of includes where this code resides, so is it possible there is something wrong in one of those files, having nothing to do with my ajax code?
$("#checkEmail").blur(function(){
  $.ajax({
    type: "POST",
    url: "adamcheck.php",
    data: "checkit=" + $("#checkEmail").val(),
    success: function(output){
      $("#userCheck").html(output);
    }
  });
});

adamcheck.php
<script type="text/javascript">
$(document).ready(function() {
   alert("FGHFGHGFH");
});
</script>
<?php
if(isset($_POST['checkit'])){
  $email= $_POST['checkit'];
  echo "<p>$email</p>";
}
?>

A: The only possible way in such a situation (where you have doubts on many things) is to debug step by step, entity by entity. First clear your doubt on the AJAX post. Take only this code and the necessary minimum HTML and php code, put them in a separate setup (separate from your project). There is no shortcut to this.
If this works, then move on to the bunch of includes. There
By the way, your AJAX post code looks syntactically correct and it is a very basic and simple.


text:
Q: Convert BitmapImage into Base64String in WinRT I want to convert BitmapImage into base64string in my windows 8.1 apps.
CODE:
protected void UpdateSignatureAsync(BitmapImage bitmapImage, string fileName, long vehicleInsRecID)
{

    WriteableBitmap writimage = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
    using (MemoryStream ms = new MemoryStream())
    {
        WriteableBitmapExtensions.FromStream(writimage, ms);
        Stream s1 = writimage.PixelBuffer.AsStream();
        s1.CopyTo(ms);
        writimage.PixelBuffer.AsStream();
        var ic = new ImageCapture
        {
            ImageBinary = Convert.ToBase64String(ms.ToArray()),/// this line
            CaseServiceRecId = vehicleInsRecID,
            FileName = fileName
        };
        await UpdateImageAsync(ic);
    }

A: I don't have an exact answer for your question, but if you have a StorageFile which is an image, then you can convert this image to a Base64 string using the GetBase64FromImageFile method in the following class:
public static class ImageHash
{
    private static async Task<string> GetBase64FromImageFile(StorageFile file)
    {
        return ComputeHash(await ConvertToByteArray(file));
    }

    private static string ComputeHash(byte[] buffer)
    {
        IBuffer input = buffer.AsBuffer();
        IBuffer hashed = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1).HashData(input);

        return CryptographicBuffer.EncodeToBase64String(hashed);
    }

    public async static Task<byte[]> ConvertToByteArray(StorageFile imageFile)
    {
        byte[] srcPixels;
        RandomAccessStreamReference streamRef =
            RandomAccessStreamReference.CreateFromFile(imageFile);

        using (IRandomAccessStreamWithContentType fileStream =
            await streamRef.OpenReadAsync())
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
            BitmapFrame frame = await decoder.GetFrameAsync(0);

            // I know the parameterless version of GetPixelDataAsync works for this image
            PixelDataProvider pixelProvider = await frame.GetPixelDataAsync();
            srcPixels = pixelProvider.DetachPixelData();
        }

        return srcPixels;
    }
}


text:
Q: onLongClickListener in layout with tabs I followed this tutorial: http://www.android4devs.com/2015/01/how-to-make-material-design-sliding-tabs.html?m=1 to make a layout with 5 tabs. Now I want to put an OnLongClickListener for a button in the first tab to make it share sound1. I have added this code in my MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button1 = (Button) findViewById(R.id.button1);

    button1.setLongClickable(true);
    button1.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View arg0) {
            Intent share = new Intent(Intent.ACTION_SEND);
            share.setType("audio/ogg");

            Uri uri = Uri.parse("android.resource://" + getPackageName()
                    + "/raw/" + R.raw.sound1);
            share.putExtra(Intent.EXTRA_STREAM, uri);
            startActivity(Intent.createChooser(share, "Share Sound File"));

            return true;
        }

    });

But that makes it crash on startup, and the logcat says this:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setLongClickable(boolean)' on a null object reference

A: You are using fragments. You should do that on the Fragment's onCreateView() or onViewCreated() callbacks
public class Tab1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.tab_1,container,false);
        button1 = (Button) v.findViewById(R.id.button1);
        button1.setLongClickable(true);
        ...
        return v;
    }
}


text:
Q: I'm looking for a big book of magic related stories I had it as a kid and lost it in 1978. I don't remember the title but I think it was like the biggest book of magic...
One story was about a guy who invented or found a tube and when he held it up, looked through and blinked, it left a hole in whatever was in view.
Another story (though it might be from a different book) was about a guy who finds clay pebbles in a cave and passed the time tossing them off a cliff. He sticks a couple in his bag and when he gets home from his vacation he discovers that the clay was covering perfect precious gems.

A: The first story is Seven-Day Terror by R. A. Lafferty. First appeared in Worlds of If, March 1962
The second story is The Balls of Clay, from Strangely Enough! by C. B.[Carroll Burleigh] Colby.
I can't find an anthology where they were published together, though.


text:
Q: Another 1045 : Access denied for user 'someone'@'localhost' (using password: YES) As lot of dummies, I cannot connect to MySQL server with user.
This is settings of my USER in DB mysql table user
Host:   %
User: someone
Password: mypassword
Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Create_user_priv: Y
max_questions, max_updates, max_connection, max_user_connections: 0

Connection
Im connecting via localhost console OR phpMyAdmin installed on this machine.
MySQL Server
Information from phpMyAdmin: Server: Localhost via UNIX socket | Server version: 5.0.70-log | Protocol version: 10

*

*When mysql server is running as mysqld_safe --skip-grant-tables & then I can connect to server as any user.

*When mysql server is running normally as /etc/init.d/mysqld start then I cannot an I have error

1045 : Access denied for user 'someone'@'localhost' (using password: YES)

I was spending hours to find solution in google and mysql documentation but without result. Probably it will be some essential settings. Hope you will give me some suggestion. Thanks a lot.

A: You probably need to reset the password for the someone user. It happens often.
Try to start your local server with no password check:
mysqld_safe --skip-grant-tables

And then
set password for 'someone'@'localhost' password('new fancy password')

(notice the '')
See more info in the docs: http://dev.mysql.com/doc/refman/5.0/en/set-password.html
This answer might also help
MySQL - ERROR 1045 - Access denied


text:
Q: Use PayPal (Sandbox) Order ID to open CheckOut via Smart Payment Buttons I have integrated PayPal in my backend to get an Order ID. How can I use this Order ID on the client side via Smart Payment Buttons to open the CheckOut?
The following line has worked recently, but not for a few days since the order ID is accepted as a token. Paypal has changed something.
paypal.Buttons({
  createOrder: (data: any, actions: any) => {
    return myOrderID; (from Server Side)
  },
  onApprove: async (data: any, actions: any) => {
    ...
  },
  onError: (err: any) => {
    console.log(err);
  }
  }).render(
    this.paypalElement.nativeElement
);

Does anyone have a tip for me?
Thanks in advance!

A: Here is an official demo sample that uses a fetch: https://developer.paypal.com/demo/checkout/#/pattern/server
It looks like your (incomplete) code example ought to work , but since it's not complete and hence runnable it can't be tested
I would encourage you to work from the official sample and either build it into your solution or adapt it to be more like the code you want to run and produce a testable sample of your own


text:
Q: Javascript - Accessing another HTML file with window.open(); So basically what I am trying to do is open a window with a local file location (assumed to be in the same directory), and store the body text of that HTML file as a string into the HTML page running the JavaScript, and then close the new window, as if it were never actually opened, so that all it's used for is its text.
The JavaScript is loaded with the body.
function test(){
    var x = document.getElementById("fill");
    var w = window.open('../HTML/HtmlPlaceholder.html');
    var cont = w.document.body.textContent;
    x.innerHTML = cont;
}

but when this happens nothing is actually entered into x (the element with the id of "fill").
Any ideas what I am doing wrong?

A: window.open opens another window which has its own thread and events,
you have two options
-   Either wait for some time to check the contents
try this
function test(){
    var x = document.getElementById("fill");
    var w = window.open('../HTML/HtmlPlaceholder.html');
    setTimeout( function(){

      var cont = w.document.body.textContent;
      x.innerHTML = cont;

      console.log (cont);
    }, 2000);
}

-  or use the window.onload event of the popup itself
inside HtmlPlaceholder.html put
window.onload = function(){

  var x = window.opener.document.getElementById( "fill" );
  x.innerHTML = document.body.innerHTML;
};


text:
Q: Scala Type Mismatch with Nested function call I have this code that I can't seem to get to work. The code is supposed to allow you to determine if the bounding boxes of a circle and rectangle overlap each other.
    abstract class Shape
    case class Circle(r: Double, x: Double, y: Double) extends Shape
    case class Rectangle(llx: Double, lly: Double, w:Double, h:Double) extends Shape

 def boundingBox(s: Shape): Rectangle = s match {
      case Rectangle(llx, lly, w, h) => Rectangle(llx, lly, w, h)
      case Circle(r,x,y) => Rectangle(x-r, y-r, 2*r, 2*r)
    }

    def mayOverlap(s1: Shape, s2: Shape) = overlapRect(boundingBox(s1), boundingBox(s2))

    def overlapRect(r1: Rectangle, r2: Rectangle) = betweenLine(r1.llx, r1.w, r2.llx, r2.w) && betweenLine(r1.lly, r1.h, r2.lly, r2.h)

    def betweenLine(x: Double, l: Double, a: Double, k: Double): Boolean = (a <= x+l) || (a+l <= x+l)

All the function are operating correctly except for mayOverlap. When I load these functions into the interpreter, I get back the following error:
<console>:63: error: type mismatch;
 found   : Rectangle(in object $iw)
 required: Rectangle(in object $iw)
       def mayOverlap(s1: Shape, s2: Shape) = overlapRect(boundingBox(s1), boundingBox(s2))
                                                                     ^
<console>:63: error: type mismatch;
 found   : Rectangle(in object $iw)
 required: Rectangle(in object $iw)
       def mayOverlap(s1: Shape, s2: Shape) = overlapRect(boundingBox(s1), boundingBox(s2))

I'm very new to scala, I'm much more familiar with haskell so it's possible I'm making assumptions of similarity between the two but I've tried to simplify it down and I can't seem to make any nested function calls in mayOverlap at all.

A: I solved the problem by reordering the function declarations so the nested helper functions came first.


text:
Q: Binary Search Homework It's late, I'm tired and forgot I had java homework. Last question is to write a Java program to find the value 45.3 from this list {-3,10,5,24,45.3,10.5} using the binary search method.
Normally I'd be fine but I really don't want to have to rush this in the morning and I'm too tired to think straight so hopefully someone can help at least a little bit.
Here is the code:
public class questionTwelve
{
    public static int binarySearch(int x)
    {
        int low = 0;
        int high = a.length - 1;
        int mid;
        int foundindex;

        while (low <= high)
        {
            mid = (low + high) / 2;
            if (a[mid].compareTo (x) < 0)
                low = mid + 1;
            else if (a[mid].compareTo (x) > 0)
                high = mid - 1;
            else
                foundindex = mid.getIndex;
        }
    }

    public static void main(String[] args)
    {
        int a[];
        a[0] = -3;
        a[1] = 5;
        a[2] = 10;
        a[3] = 10.5;
        a[4] = 24;
        a[5] = 45.3;

        System.out.println("Value 45.3 found at index " + binarySearch(45.3));
    }
}

A: You're trying to store 10.5 and 45.3, which aren't integers, in a list of integers. That's problem one. You're then trying to pass 45.3 (which still isn't an integer) to a method that accepts an integer as an argument.
Inside that method, you're trying to use compareTo on an integer value, just use the standard < and > operators.
You're then trying to use mid.getIndex - not sure what getIndex is, but it's not anything I've ever used with an int. Your method also doesn't return anything. You'll want to return mid when a[mid] == x, and then after the while loop, return -1 (to signify that the number isn't in the list) if it's never hit the other return statement.


text:
Q: sap.ui.unified.FileUploader change http methode / allow post on segw I am working on a file upload in UI5.
I can not use the fileupload via associations since I need the binary before writing in my table.
The problem is sap.ui.unified.FileUploader always uses the POST HTTP method,
this causes an error in the backend system:

405 Methode not allowed

I found this SAP Blog FileUploader - 405 Method Not Allowed in which the problem is solved by extending the control and changing the HTTP method.
My question is there a more standard way to achieve that? I did not find any property in the control to configure the HTTP method.
Options:

*

*Maybe in the XHR Settings?

*Can you allow POST in SEGW or the user exit classes?

A: Upload/Download with SEGW

*

*Step by Step on how to use the SAPUI5 file upload feature

*File Upload/Download through NetWeaver Gateway

*Uploading Files to SAP GW, Downloading Files from SAP GW – New Techniques

*Newest Blog!!: Upload/download File in SAP UI5 Application using Gateway
Binary before Upload: only possible via Deffered & XHR
getBase64Promise: function (file) {
        return new Promise(function (resolve, reject) {
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                var encoded = reader.result.replace("data:", "").replace(/^.*;base64,/, "");
                if ((encoded.length % 4) > 0) {
                    encoded += "=".repeat(4 - (encoded.length % 4));
                }
                resolve(encoded);
            };
            reader.onerror = function () {
                reject("error");
            };
        });
},

fileUploadChange: function (oControlEvent) {
        var that = this;
        var aFiles = oControlEvent.getParameters().files;
        var currentFile = aFiles[0];
        var sUrl = "yourNeeds..";
        this.getBase64Promise(currentFile).then(function (data) {
            that.xhrRequest(data, oView, sUrl);
        });
    },

xhrRequest: function (data, oView, url) {
        var oImage = "data:image/png;base64, " + data;
        oRequest = JSON.stringify(oImage);
        var xhrReadyStateChange = function () {
            if (this.readyState === this.DONE) {
                console.log("200", JSON.parse(this.response));
            }
        };

        var xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.addEventListener("readystatechange", xhrReadyStateChange);
        xhr.open("POST", url, false); // setting request method & API endpoint, the last parameter is to set the calls as synchyronous
        xhr.setRequestHeader("Accept", "application/json"); // adding request headers
        xhr.setRequestHeader("Content-Type", "application/json"); // adding request headers
        xhr.send(oRequest); // sending request
    }
});

A: This may be due to the browser support of UI5.
Under the hood the file uploader is a <div> that contains a <form>.
The file can be uploaded either via XMLHttpRequest (XHR) or by simply submitting the form. Forms only support GET and POST.
If you want to use PUT the first step is setting sendXHR="true".
But XHR does not work in IE9. For some reason the UI5 devs then decided:

If IE9 cannot use PUT then no one should!

So the second step is to create a subclass of the FileUploader, add a new property for the HTTP method and overwrite the _sendFilesWithXHR method.  This is as standard as it gets ;)
Btw this is the line where they hardcoded "POST" which needs to be replaced with a dynamic call of the new property httpMethod.


text:
Q: Yii 'limit' on related model's scope I have a model called Guesses that has_many Comments. I'm making eager queries to this to then pass on as JSON as response to an API call.
The relations are obviously set between the two models and they are correct(one2many <=> belongs2)
I added a scope to Comments called 'api' like this:
public function scopes()
    {
        return array(
            'api' => array(
                'select' => 'id, comment, date',
                'limit'=>3,
                'order'=>'date DESC',
                'together'=>true,
            ),
        );
    }

And I'm running the following one-liner query:
$data = Guesses::model()->with('comments:api')->findAll();

The issue here is that when calling the 'api' scope using a with('relation'), the limit property simply doesn't apply.
I added the 'together'=>true there for another type of scope, plus I hear it might help. It doesn't make a difference.
I don't need all the comments of all Guesses. I want the top 3 (or 5). I am also trying to keep the one-liner call intact and simple, manage everything through scopes, relations and parameterized functions so that the API call itself is clean and simple.
Any advice?

A: There are several methods to achieve this, which i know.
1st. You can add limit to relation, for ex.
    'photos' => array(self::HAS_MANY, 'Photo', 'companyId',
                      'limit'=>3
                )

2nd. You can call limit results when call relation, for ex.
$model->photos(array('limit' => 4));

Maybe there are some other methods, but i don't know them.

A: According to the documentation, that should be ok..
My only suggestions would be:
$data = Guesses::model()->with(
   array('comments'=>array('scopes'=>array('api')))
)->findAll();

or:
$data = Guesses::model()->findAll(array(
  'with'=>array('comments'=>array('scopes'=>array('api')))
));

but that should be the same logic. I don't think together will help you.. it is true by default.
Update
These examples are taken straight from the relational documentation
$posts=Post::model()->with('comments:recently:approved')->findAll();

or since 1.1.7:
$posts=Post::model()->with(array(
    'comments'=>array(
        'scopes'=>array('recently','approved')
    ),
))->findAll();

or since 1.1.7
$posts=Post::model()->findAll(array(
    'with'=>array(
        'comments'=>array(
            'scopes'=>array('recently','approved')
        ),
    ),
));

and lazy-loading:
$approvedComments = $post->comments('comments:approved');

Which suggests that your code should work.. what query is being run in your trace?
Do you have any default scopes that you haven't posted? Are their any extra options defined in your relation? I have had trouble with both of these interfering with named scopes.


text:
Q: Code redirect in javascript from a 302 This code works in Google Chrome but not in IE and Firefox.
The site "somesite.org" send me 302 (redirect).
I want to redirect when it comes from a specific site (somesite.org) to a specific file in my site.
Code:
var url = document.referrer;

if (url.includes("somesite.org")) {
    window.location.href = "http://forthisfile.com/this.html"
}

A: This should work
var url = document.referrer;

    if(url.indexOf("somesite.org") > -1 ){

      window.location = "http://forthisfile.com/this.html" ;
    }

A: IE does not support any form of includes, see MDN reference page.
that said, the alternative is to check the hash:
if(window.location.hash.indexOf("?") >= 0) {
    ...
}

so in your case:
  if(window.location.hash.indexOf("somesite.org") > -1 ){

      window.location = "http://forthisfile.com/this.html" ;
    }


text:
Q: SQL percentage of 1 column display in two columns I have a single column of Male and Female and calculated the percentages and displayed them as such,
Gender      %
M       50.8
F       49.2

How do I calculate the % such that the results is displayed on two separate columns?(Microsoft SQL) such as;
M      F
50.8   49.2

A: Try conditional aggregation using case when expression
select concat(max(case when gender='M' then valueofpercentage end),'%') as 'M',
concat(max(case when gender='F' then valueofpercentage end),'%') as 'F'
from tablename

A: do aggregation
        select Gender,
        max(case when Gender='M' then value end),
        max(case when Gender='F' then value end)
        from table group by Gender

A:     SELECT *
    FROM (
        SELECT
            Gender, %
      from tableName
    ) as s
    PIVOT
    (
        SUM(%)
        FOR Gender IN (M,F)
    )AS pvt

if any issue then tell me.

A: Just use conditional aggregation:
select max(case when gender = 'M' then [%] end) as m,
       max(case when gender = 'F' then [%] end) as f
from t;

A: Looks like the answer from fa06 is the correct logic, but you are having issues with calculating the percentage.
Here is something I just created to teach you how to work out percentages in sql:
declare
@m as decimal,
@f as decimal,
@t as int

set @m = 50
set @f = 40
set @t = @m+@f

select Cast(@m / @t * 100 as decimal(5, 2)) as m, Cast(@f / @t * 100 as decimal(5 ,2)) as f

In this scenario, @m and @f are just dummy numbers and @t is the total number, hence why @m + @f, below is how you'd get the number of count in the table where gender is male - obviously change 'm' to 'f' to get females.
select count(gender) from tablename where gender = 'm' as 'm'

To do the calculation, you'd need to adapt it to something like:
Select Cast(Count(select gender from tablename where gender = 'm') /
Count(select gender from tablename where gender in ('m', 'f')) * 100 as decimal(5,2)
 as 'm' from tablename

Disclaimer - this code was not tested. But the logic is relevant if it doesn't work.
That's just for male and can be simplified far further by looking at fa06's solution, but just for purely working out the %, adapt the logic above - so:

Number of specific gender / total number of records intended for the
  percentage to calculate on * 100

Hope this helps


text:
Q: C# how to open browser using a url and save the loaded page Is there any way in C# to open a browser using a link and save the loaded html page ?? Actually i don't want to inform server that i am using any software or script .
Actually I want data from this link : http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&rt=nc&item=120840650200&si=a8iGAIchyvEbn7KveYFZ5QbEE7o%3D&print=all&category=10363
if I try to download the page using webclient it send me another page not the original one.
when i load the previous url in a browser it is redirected to this link:
http://www.ebay.com/itm/ws/eBayISAPI.dll?ViewItem&rt=nc&item=120840650200&si=a8iGAIchyvEbn7KveYFZ5QbEE7o%3D&print=all&category=10363 which is the original page I want to download
so I just wanted to open the browser using the url and save the loaded page.
Thanks in advance

A: Do you really need to open the browser, or is just (inconspicuously) retrieving the file enough?  If so, you can use System.Net.Webclient or System.Net.HttpWebRequest/HttpWebResponse.  The former option is much easier, but the latter will allow you to set your own user-agent string to one that would match that of common web browsers.

A: Straight from MSDN
WebClient client = new WebClient();
Byte[] pageData = client.DownloadData("http://www.contoso.com");
string pageHtml = Encoding.ASCII.GetString(pageData);
Console.WriteLine(pageHtml);


text:
Q: Completed Proof For Incommensurate Lissajous Curves/Bowditch Curves Are Dense In The Rectangle A Lissajous curve, or a Bowditch curve, is given by the parametric equations
$x(t)=Asin(ω_{x}t + \phi)$
$y(t)=Bsin(ω_{y}t+δ)$,
Now if $\frac{\omega_{x}}{\omega_{y}}$ is irrational, and $\phi$ and $\delta$ are fixed, then the set $\mathcal{L} = (x(t), y(t) | -\infty < t < \infty)$ is supposedly dense in the rectangle $R =[-A,A]$x$[-B,B]$
I have seen:
Show that a Lissajous curve has incommesurate frequencies iff it isdense in a rectangle
But a completed proof was not given. This problem is frequently mentioned in the literature, but a reference to a full proof is never given. Does anyone have such a reference, or could someone provide a proof here?

A: You can write $x$ and $y$ in complex number with the exponentials (easiest way): $\mathbf r\left(t\right)=\left(Ae^{ω_{x}t + \phi},Be^{ω_{y}t + \delta}\right)$. Then proof it by induction, suppose that there is a period $T\neq0$ so that $\mathbf r\left(t\right)=\mathbf r\left(t+T\right)$.


text:
Q: How return a request inside a promise I am using ionic 2 / angular 2.
I need to do a http request, but before I have to get a token using Ionic Storage.
I created a class ApiRequest for that
import {Http, Headers, RequestOptions} from '@angular/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Storage } from '@ionic/storage';

@Injectable()
export class ApiRequest {

    access_token: string;

    constructor(private http: Http, public storage: Storage) {
        this.storage.get('access_token').then( (value:any) => {
            this.access_token = value;
        });
    }

    get(url) {
        let headers = new Headers({
            // 'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.access_token,
            'X-Requested-With': 'XMLHttpRequest'
        });
        let options = new RequestOptions({ headers: headers });

        return this.http.get(url, options)
            .map(res => res.json());

    }

}

Then I can call like that
apiRequest.get(this.URL)
        .subscribe(
            data => {
                this.element= data;
            },
            err => {
                console.log(JSON.stringify(err));
            });

My problem is, this.storage.get is asynchronous, http.get is asynchronous too, and I have to return http.get because I want to call subscribe outside the function.
In this case http.get is called before this.acess token received the value.
How Can I organize my code in that scenario?

A: This might work (not tried myself):
@Injectable()
export class ApiRequest {

    access_token: string;

    constructor(private http: Http, public storage: Storage) {
        this.storagePromise = this.storage.get('access_token').then( (value:any) => {
            this.access_token = value;
        });
    }

    get(url) {
        let headers = new Headers({
            // 'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.access_token,
            'X-Requested-With': 'XMLHttpRequest'
        });
        let options = new RequestOptions({ headers: headers });

        return this.storagePromise.then(
           return token => this.http.get(url, options)
           .map(res => res.json());
        );
    }
}

apiRequest.get(this.URL)
    .then(observable =>
      observable.subscribe(
        data => {
            this.element= data;
        },
        err => {
            console.log(JSON.stringify(err));
        }
      );


text:
Q: Borrar un label y una entrada en tkinter tengo un problema en tkinter, necesito que la función de un Radiobutton ponga en la ventana un label y un entry, eso funciona. Pero necesito que si se seleccione otra opción, los borre. Si alguien me puede decir cómo lo hago le estaré agradecido.
#Marco recepción/despacho
        self.marco_recepcion_despacho=customtkinter.CTkFrame(marco_ticket, border_color=("black"), border_width=2)
        self.marco_recepcion_despacho.grid(column=0, row=5, pady=5, padx=5, columnspan=2)
        def destino():
            if radio.get() == 1:
                pass
            if radio.get() == 2:
                label_destino=customtkinter.CTkLabel(self.marco_recepcion_despacho, text="Despacho :")
                label_destino.grid(column=0, row=1, pady=5, padx=5)
                entry_destino=customtkinter.CTkComboBox(self.marco_recepcion_despacho)
                entry_destino.grid(column=1, row=1, pady=5, padx=5)

        radio=tkinter.IntVar()
        self.radio1=customtkinter.CTkRadioButton(self.marco_recepcion_despacho, text="Recepción", variable=radio, value=1, command=destino)
        self.radio2=customtkinter.CTkRadioButton(self.marco_recepcion_despacho, text="Despacho", variable=radio, value=2, command=destino)
        self.radio1.grid(column=0, row=0, pady=5, padx=5)
        self.radio2.grid(column=1, row=0, pady=5, padx=5)


text:
Q: Quick and simultaneous ajax call I am currently working on add sale for POS using laravel. Here we can use barcode to scan the product code, when barcode is entered it then calls check function, if same product code is found in the cart table then it simply adds the quantity value by 1 else it make an ajax call  which will return the detail of that particular product. My jQuery function looks like this:
 function check() {
     if ($(".product_code").length) {
         var product_code = $("#product_code").val();
         var total = $('#cart_contents tr').length;
         $('#cart_contents tr').each(function(index) {
             var p_code = $(this).find(".product_code").val();
             if (product_code == p_code) {
                 var num = +$(this).find('.product_quantity').val() + 1;
                 $(this).find('.product_discount').val(0);
                 $(this).find('.product_quantity').val(num).keyup();
                 return false;
             } else if (index === total - 1) {
                 populatecart();
             }
         });
     } else {
         populatecart();
         $(".cart_content_area").hide();
     }
 }

 function populatecart() {
     var product_code = $("#product_code").val();
     $.ajax({
         url: "{{ url('getproductdata')}}",
         data: {
             p_id: product_code
         },
         datatype: "JSON",
         type: "get",
         success: function(data) {
             if (data == 'null') {
                 alert('No product code found!');
             } else {
                 $.each(data, function(k, v) {
                    $("#cart_contents").append('
' +
                        ' {!! Form::text('sales_quantity[]', 1, ['class'=>'product_quantity form-control']) !!} 	' +
                        '<input type="text" name="product_code[]" value="' + v["product_code"] + '" class="form-control product_code" readonly/>	' +
                        '<input type="text" name="product_name[]" value="' + v["product_name"] + '" class="form-control product_name" readonly/> 	' +
                        '<input type="text" name="unit_value[]" value="' + v["sell_price"] + '" class="form-control unit_value" readonly/>	' +
                        '{!! Form::text('product_discount[]', 0, ['class'=>'product_discount form-control']) !!}	' +
                        '<input type="text" name="line_total[]" value="' + v["sell_price"] + '" class="form-control line_total" readonly/>	' +
                        '<input name="product_id[]" type="hidden" value="' + v["id"] + '" /><button type="button" class="removebutton" title="Remove this row">X</button>	' +
                        '
');
                     calculateTotalSum();
                 });
             }
         }
     });
 }

However, the problem here is that when I try to scan same product(ie; product having same product code) simultaneously it adds up the quantity but if i try the same thing really quick, the same product is populated into two different rows of the cart table but what I actually want is to have the quantity value of the product be 2 instead of creating 2 rows for same product code.
How can I deal with this problem?

A: rather than use callback based api.
I suggest you use promise based .
the flow goes like this.
var cart = {};
if(cart[product_code] == undefined)
{
    cart[product_code] = $.ajax(url: "{{ url('getproductdata')}}"  ,
                      data:{
                            p_id:product_code
                            },
                      datatype:"JSON",
                      type: "get");
    cart[product_code].done(function(data){
      //do the initialization
    });
}
else
{
   cart[product_code].done(function(){
       //do the update.
   });
}

A: The ajax calls may overlap.
You should probably do the check for existance in the ajax callback only, not already in check();


text:
Q: Setting the ACL when creating a new database via JS in XPages I am creating a new database using JS from an action button. The following sequence happens:

*

*When the database is created the -default- access is set to Manager which it has to be.

*I then create several aclEntries. The first entry created for the current user and set them as a type person and having Manager rights

*I then create several other entries with varying right and save the ACL.

If I open the Db the ACL looks and acts correctly except the -default- has an access level of Manager.
So I tried change my code to set the access level for -default- to Author in various ways, all resulting in an exception:

*

*Change -default- to Author and save

*First save the ACL as above, then change the -default- entry and save

*create the ACL object newly using var newACL = db.getACL(), change and try to save

It seems that it does not recognize me as a manger in the ACL.
Q: How do I change the -default- access away from manager?

A: Probably the easiest way to get a good default ACL is using a template database. All entries in your template that come in square brackets are copied into the new database as ACL entries.
So in your template you would have

*

*[-Default-]=Author and [Anonymous]=No Access which results in

*-Default-=Author and Anonymous=No Access in the new DB

Update
Easier that it looks. You need to make sure to get the entries right...
Use this function:
function makeDB(dbName) {
   var server = database.getServer();
   var you = @UserName();
   var dbDir = session.getDbDirectory(server);
   var db = dbDir.createDatabase(dbName);
   var acl = db.getACL();
   acl.createACLEntry(you,6);
   if (server != "" && server != you) {
      acl.createACLEntry(server,6);
   }
   var def = acl.getEntry("-Default-");
   def.setLevel(3);
   acl.save();
}

Then you call the function using:
makeDB("someFancyDBName");

In the function we make sure that you, who runs the script and the server where it runs are both in the ACL as managers (including the case of a local database, where in the Notes client the server is empty and in the web preview would be your user name).
Works like a charm. If it doesn't work for you, there are a few things to check:

*

*Does it work on local (no server involved)?

*Do you have errors on the console?

*What access level do you have in the server ECL

*Check the "max Internet access" of the database

The previous answer (obsolete):
Other than that it is a little trickier...
You create the new database:
   var db:Database = [... whatever you have todo here ...];
   var acl:Acl = db.getAcl();
   // Do whatever you do, don't touch -Default-
   acl.save();
   acl.recycle();
   var dbURL = db.getUrl(); // <-- off my head might be slightly different name
   db.recycle();

   // Now the real work
   var db2 = session.evaluate(dbUrl);
   var acl2 = db2.getAcl();

   // Change default here;

Typed off my head, contains typos.
This should work. Let us know how it goes


text:
Q: what is the use of string replace method in ruby? i read string methods in ruby. i understood replace will replace the string with the argument passed to it. But the same thing we can do with a short and sweet = oparator also. what is the point of using replace method? its just a personnel choice or it's different from an = operator?
    > a = "hello world"
   => "hello world"
   > a = "123"
   => "123"
   > a.replace("345")
   => "345"

A: This line of code changes the variable a to point to a new string:
a = "new string"

This line of code actually changes the string object that a (and possibly other variables) are pointing to:
a.replace "new string"

A: Using =
str = "cat in the hat"
str.object_id
  #=> 70331872197480

def a(str)
  str = "hat on the cat"
  puts "in method str=#{str}, str.object_id=#{str.object_id}"
end

a(str)
in method str=hat on the cat, str.object_id=70331873031040

str
  #=> "cat in the hat"
str.object_id
  #=> 70331872197480

The values of str outside the method and str inside the method are different objects.
Using String#replace
str = "cat in the hat"
str.object_id
  #=> 70331872931060

def b(str)
  str.replace("hat on the cat")
  puts "in method str=#{str}, str.object_id=#{str.object_id}"
end

b(str)
in method str=hat on the cat, str.object_id=70331872931060

str
  #=> "hat on the cat"
str.object_id
  #=> 70331872931060

The values of str outside the method and str inside the method are the same object.

A: The use case is really just, to achieve something much like pass-by-reference in other languages, where a variable's value can be changed directly. So you could pass a String to a method and that method may entirely change the string to something else.
def bar(bazzer)
  bazzer.replace("reference")
end

bar(baz)

=> It's reference because local assignment is above the food chain , but it's clearly pass-by-reference

This makes sense.


text:
Q: unable to compare strings in mongodb collection I'm a beginner in mongodb and pymongo and I have a mongodb movie database where I store the users
with fields(name,surname,email,category).I am trying to insert a user in my mongodb data using a pymongo and the user key must be a string that is either "Admin" or "Simple". However I am a complete beginner and I do not know how to compare a mongodb collection instance with a string .
I have my code down below :
from pymongo import MongoClient
from flask import Flask , request , Response , jsonify , redirect
from pymongo.errors import DuplicateKeyError
import json

client = MongoClient('mongodb://localhost:27017/')
db = client['MovieFlixDB']

users = db['Users']
movies = db['Movies']

app = Flask(__name__)

@app.route('/insertuser' , methods = ['POST'])
def insert_user():
    data = None
    try:
       data=json.loads(request.data)
    except Exception as e:
        return Response("Bad json content" , status = 500 , mimetype='application/json')
    if data==None:
        return Response("no data has been added" , status = 500 , mimetype='application/json')
    if not "name" in data or not "surname" in data or not "email" in data or not "category" in data:
        return Response("Information incompleted" , status = 500 , mimetype='application/json')
    if data['category']!="admin" and data['category']!="simple":
    return Response("Invalid category." ,status = 500 , mimetype='application/json')

EDIT : I realised that I cannot compare something that has not been inserted in my database and I actually have to compare data["category"] not users.find(...) and I updated my code
I would appreciate your help with this task . Thank you in advance

A: I think you need to use below:
db_data = users.find_one({"email":data["email"]})
if db_data["category"] == data['category']:
    # Do something
else:
    # Do something else

I suggest you to use find_one, instead of find, since you need to find only one document, matching the condition.


text:
Q: Custom annotation image rotates only at the beginning of the Program (Swift- iOS) Please help out a beginner iOS developer here! :) So, I have a timer which gets the latitude and longitude of a bus periodically from a xml sheet which provides real-time locations of the bus. I was able to setup the parser, animate the bus movement and setup a custom (arrow) image for the bus.
However, the problem is, I'm not able to able to rotate the bus-annotation everytime I get new values for the latitude and longitude. The busAnnotation rotates only when the program starts, but not everytime the direction of the bus is updated.
Below is my xml parser function, which calculates the busDirection everytime the location changes. The value of busDirection changes correctly with location changes, but it doesn't apply to the rotation for some reason as the timer goes on. The movement of the annotation is also well-animated, it just doesn't rotate other than when the program is started.
// Some constants
var oldLatitude: Double? = 44.97234
var oldLongitude: Double? = -93.2446329
var busDirection: CLLocationDirection()

func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: NSDictionary!) {
    if (elementName == "vehicle") {
        var latitude = attributeDict["lat"]?.doubleValue            // Get latitude of bus from xml
        var longitude = attributeDict["lon"]?.doubleValue           // Get longitude of bus from xml

        if (oldLatitude == latitude && oldLongitude == longitude) {
            return
        }
        else {  // Update bus location
            busDirection = directionBetweenPoints(MKMapPointForCoordinate(CLLocationCoordinate2DMake(oldLatitude!, oldLongitude!)), destinationPoint: MKMapPointForCoordinate(CLLocationCoordinate2DMake(latitude!, longitude!)))       // Get direction of bus:

            UIView.animateWithDuration(0.5) {
                self.busAnnotation.coordinate = CLLocationCoordinate2DMake(latitude!, longitude!)
                self.mapView(self.map, viewForAnnotation: self.busAnnotation).annotation = self.busAnnotation
                self.map.addAnnotation(self.busAnnotation)
            }

            oldLatitude = latitude
            oldLongitude = longitude
        }
    }
}

Here is the 'viewForAnnotation' that I implemented in order to change the image of the annotation and supposedly rotate it
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    let reuseId = "pin"
    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView

    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView!.image = imageWithImage(UIImage(named:"arrow.png")!, scaledToSize: CGSize(width: 25.0, height: 25.0))       // Set custom image for annotation and resize it
    }
    else {
        pinView!.annotation = annotation
    }

    // Rotate the annotation.
    pinView?.transform = CGAffineTransformRotate(self.map.transform, CGFloat(degreesToRadians(self.busDirection)))
    return pinView
}

These are some of the helper functions that I used in the above methods:
// For rotating bus annotations:
func degreesToRadians(degrees: Double) -> Double { return degrees * M_PI / 180.0 }
func radiansToDegrees(radians: Double) -> Double { return radians * 180.0 / M_PI }

func directionBetweenPoints(sourcePoint: MKMapPoint, destinationPoint : MKMapPoint) -> CLLocationDirection {
    let x : Double = destinationPoint.x - sourcePoint.x;
    let y : Double = destinationPoint.y - sourcePoint.y;

    return fmod(radiansToDegrees(atan2(y, x)), 360.0) + 90.0;
}

Do you guys think I'm missing something here? How would I rotate the bus-annotation everytime the locations are updated? Thanks in advance.

A: The rotation only occurs the first time the map view creates the view for the annotation. Rather than create a new view every time an annotation updates, it simply moves the view. That's much more efficient for the map view to do.
So, what you should do is make the pinView a property, instantiate it in your init method, return that in mapView(, viewForAnnotation:) and apply the rotation directly to that pinView in your animation block.
UIView.animateWithDuration(0.5) {
    self.busAnnotation.coordinate = CLLocationCoordinate2DMake(latitude!, longitude!)
    self.map.addAnnotation(self.busAnnotation)
    if let pv = self.pinView {
        pv.transform = CGAffineTransformRotate(self.map.transform, CGFloat(degreesToRadians(self.busDirection)))
    }
}


text:
Q: Strange behaviour when renaming a column in SQL Server 2008 I need to write some code for renaming a column in SQL Server 2008.
When scripting that in Management Studio I got a double renaming :
NAME1 ==> TEMPNAME ==> NAME2
BEGIN TRANSACTION
GO
EXECUTE sp_rename N'dbo.Table_1.columFirstName', N'Tmp_columSecondName_2', 'COLUMN'
GO
EXECUTE sp_rename N'dbo.Table_1.Tmp_columSecondName_2', N'columSecondName', 'COLUMN'
GO
ALTER TABLE dbo.Table_1 SET (LOCK_ESCALATION = TABLE)
GO
COMMIT

But when I do it in one go, It works just fine.
Why the column first is renamed to a temporary name?  Does it makes sense when  coding a renaming algoritm to do the same?
Thanks!

A: You can swap column names between two columns. Management studio supports that by renaming all columns to temporary names, and then renaming them to the final names.
Blorgbeard: In the Design Window right-click menu, there is a generate change script choice.


text:
Q: Too many constructor arguments in deepest class of inheritance? I want a general solution on how to avoid insanely high number of constructor arguments.
The examples I'm providing here are just examples, and I don't want a specific answer for the exact example here.
That being said, my problem is obviously having too many arguments in my constructor.
I have a base class for any type of person (soldiers, wizards, merchants, etc.) called Person.
My Person class is fairly simple, it implements the basic things common for every person there is.
Let's say I have the following attributes, and my constructor takes an argument for each of these attributes:

*

*string firstName

*string surname

*uint health

*uint maxHealth - we don't want anyone to have 999999999 health...

*uint movementSpeed - and not everyone runs at same speed, right?

So the constructor would look like:
Person::Person(const string &firstName="Missing first name",
               const string &surname="Missing surname",
               const uint health=100,
               const uint maxHealth=100,
               const uint movementSpeed=50) :
    m_firstName(firstName),
    m_surname(surname),
    m_health(health),
    m_maxHealth(maxHealth),
    m_movementSpeed(movementSpeed)
{}

Now imagine a new class, deep down in the inheritance tree, called a Wizard. Most wizards are there for combat, so they can also attack, etc.
Wizard's constructor could look like this:
Wizard::Wizard(const string &firstName="Missing first name",
               const string &surname="Missing surname",
               const string &wizardName="Missing wizard name",
               const uint health=100,
               const uint maxHealth=100,
               const uint mana=100,
               const uint maxMana=100,
               const uint strength=50, // physical damage
               const uint witchcraft=50, // spell damage
               const uint armor=30, // vs. physical damage
               const uint resistance=30, // vs. spell damage
               const uint movementSpeed=50) :
    Warrior(firstName, surName, health, maxHealth, strength, armor, resistance, movementSpeed),
    m_wizardName(wizardName),
    m_mana(mana),
    m_maxMana(maxMana),
    m_witchcraft(witchcraft)
{}

There could be even more arguments, but I suppose you get the point.
That might not even look bad, but imagine looking at a stranger's code and seeing something like this:
Wizard *wiz = new Wizard("Tom", "Valedro", "Lord Voldemort", 300, 400, 200, 200, 10, 500, 30, 400, 300)

Someone might say that "it's still not that bad, you can just read the docs!"
Imo. that is terrible and makes the code insanely hard to read and even write.
Also the order of the arguments gets hard for one to keep track of.
There are few solutions I've thought of, but they have their downsides.
One thing would be to use default constructor and give it no arguments at all, then use setters to do the job:
Wizard *wiz = new Wizard;
wiz->setFirstName("Tom");
wiz->setSurname("Valedro");
...

Of course this would create dozens of extra lines of text, and some people are hardly against getters and setters.
It would get rid of the numbers with no meanings tho, atleast you could read what each number does (wiz->setHealth(100); obviously tells we're setting health here).
Another solution would be to combine some attributes into structs.
I could easily merge firstName, surname and wizardName (even better, use nickname) into a Name class or struct.
This would reduce the number of my arguments in this example, but as I said, I want a general answer for such a problem.
There could still be awfully many arguments even after combining some of them, or you might not be able to combine any cause they're not similar at all.

A: You could use "Fluent Constructors"
See for example this link: http://richarddingwall.name/2009/06/01/fluent-builder-pattern-for-classes-with-long-ish-constructors/

A: Group those arguments into data structures that collect reasonably related information, and let your constructor accepts those data structures.
The trivial solution of grouping everything into one single data structure would make your constructor accept only one argument, but would simply move the problem to the constructor of the data structure (provided you want to define one).
Therefore, you need to find the correct balance so that your constructor will accept a reasonable number of arguments (data structures) - definitely no more than 5 I would say - and each data structure groups together pieces of information that "belong to each other".
Now since you asked for an abstract answer, this is as far as I can go if I want to stay absolutely general. Concerning a concrete example, you could have:
struct name_info
{
    // Constructor(s)...

    const std::string firstName;
    const std::string surname;
    const std::string wizardName;
};

struct health_info
{
    // Constructor(s)...

    const uint health;
    const uint maxHealth;
    const uint mana;
    const uint maxMana;
};

struct fight_info
{
    // You got it...
};

And then your Wizard constructor would look like:
Wizard::Wizard(name info const& ni, health_info const& hi, fight_info const& fi)

A: This is a common problem in unit tests.  A good test is readable, and as you've noted, a string of magic numbers is anything but.  One recommended practice is the introduction of "explanatory variables".  Use the parameter names as local variables in the test class.
string firstName("Tom");
string surname("Valedro");
string wizardName("Lord Voldemort");
uint health=300;
uint maxHealth=400;
uint mana=200;
uint maxMana=200;
uint strength=10; // physical damage
uint witchcraft=500; // spell damage
uint armor=30; // vs. physical damage
uint resistance=400; // vs. spell damage
uint movementSpeed=300;

Wizard *wiz = new Wizard( firstName, surname, wizardName, health, maxHealth,
                          mana, maxMana, strength, witchcraft,
                          armor, resistance, movementSpeed );

Now, when I look at that constructor call, I know exactly what it's testing because it's spelled out in front of me.
And before the premature optimizers complain prematurely, this practice doesn't add anything extra to the production program's size or speed.  Every optimizing compiler out there will optimize this call into a bunch of literals under the covers.  All this coding style does is impact maintainability by making the code clearer and more readable.

A: In addition to what others have suggested, to improve the clarity of your parameters, you may want to try something like below.  The wrappers' explicit constructors will prevent someone from passing int implicitly to the Stats constructor, so that...
Stats a(10, 18, 19); // will not compile
Stats b(Health(10), Health(18), Mana(19)); // will compile

.
// int wrappers
struct Health {
  explicit Health(int v)
  : _val(v)
  {}

  int _val;
};

struct Mana {
  explicit Mana(int v)
  : _val(v)
  {}

  int _val;
};

struct MoveSpeed{
  explicit MoveSpeed(int v)
  : _val(v)
  {}

  int _val;
};

struct Stats{
  Stats(const Health& maxhealth, const Health& curhealth, const Mana& maxmana/*... etc*/)
  : _maxhealth(maxhealth)
  , _curhealth(curhealth)
  , _maxmana(maxmana)
  // ... etc
  {}

  Health _maxhealth;
  Health _curhealth;
  Mana _maxmana ;
  // ... etc
};

class Warrior{
  public:
    Warrior(const Stats& stats /* ... etc */)
    : _stats(stats)
    // ... etc
    {}

  private:
    Stats _stats;
};

A: I think you'll find that if you categorize your arguments and group them into structs based on those categories you won't have many arguments. You can also do this hierarchically if you need to.
struct Stats
{
     uint health;
     uint maxHealth;
     uint mana;
     uint maxMana;
     uint strength;
     uint witchcraft;
     uint armor;
     uint resistance;
     uint movementSpeed;
};

class Wizard
{
public:
    static Stats defaultWizardStats;

    Wizard(Name name, Stats stats = defaultWizardStats)
    : m_Name(name)
    , m_Stats(stats)
    {}

private:
    Name m_Name;
    Stats m_Stats;
};

You can also just store the info in your class using these groups.

A: I always liked the builder pattern for solving this issue, but almost never use it because it can't ensure at compile time that all arguments have been included.
This solution is a bit messy, but gets the job done. It would be a good option especially in cases where code-gen is done.
#include <boost/shared_ptr.hpp>

class Thing
{
    public:

        Thing( int arg0, int arg1 )
        {
            std::cout << "Building Thing with   \n";
            std::cout << "    arg0: " << arg0 << "\n";
            std::cout << "    arg1: " << arg1 << "\n";
        }

        template <typename CompleteArgsT>
        static
        Thing BuildThing( CompleteArgsT completeArgs )
        {
            return Thing( completeArgs.getArg0(),
                          completeArgs.getArg1() );
        }

    public:

        class TheArgs
        {
            public:
                int arg0;
                int arg1;
        };

        class EmptyArgs
        {
            public:
                EmptyArgs() : theArgs( new TheArgs ) {};
                boost::shared_ptr<TheArgs> theArgs;
        };

        template <typename PartialArgsClassT>
        class ArgsData : public PartialArgsClassT
        {
            public:
                typedef ArgsData<PartialArgsClassT> OwnType;

                ArgsData() {}
                ArgsData( const PartialArgsClassT & parent ) : PartialArgsClassT( parent ) {}

                class HasArg0 : public OwnType
                {
                    public:
                        HasArg0( const OwnType & parent ) : OwnType( parent ) {}
                        int getArg0() { return EmptyArgs::theArgs->arg0; }
                };

                class HasArg1 : public OwnType
                {
                    public:
                        HasArg1( const OwnType & parent ) : OwnType( parent ) {}
                        int getArg1() { return EmptyArgs::theArgs->arg1; }
                };

                ArgsData<HasArg0>  arg0( int arg0 )
                {
                    ArgsData<HasArg0> data( *this );
                    data.theArgs->arg0 = arg0;
                    return data;
                }

                ArgsData<HasArg1>  arg1( int arg1 )
                {
                    ArgsData<HasArg1> data( *this );
                    data.theArgs->arg1 = arg1;
                    return data;
                }
        };

        typedef ArgsData<EmptyArgs> Args;
};

int main()
{
    Thing thing = Thing::BuildThing( Thing::Args().arg0( 2 ).arg1( 5 ) );
    return 0;
}


text:
Q: Autofocus does not work in form inside a partial view using MVC3 Razor I am using MVC 3 Razor and I have a simple form in a PartialView [I am showing this as a popup window]. Some of the features are not working properly in PartialView. For example the autofocus attribute.
@Html.TextBoxFor(model => model.Code, new { style = "width:50px", maxlength = 4, autofocus = "" })

I have tried setting the focus through jQuery script but that doesn't work either.
$('#Code').focus();

Am I missing something? Do I have to import some scripts in my partial view for this to work?
Any help is greatly appreciated.
Thanks in Advance.
Update:
I found the problem... I was loading the window and then showing it after a delay of 700ms. I commented out the setTimeout line and it worked. It must be that the focus worked when form loaded but when I actually did the "open()" it lost focus again.
Previous Code
function openWindow(url, title) {
  var window = $("#Window").data("tWindow");
  window.ajaxRequest(url);
  window.title(title);
  setTimeout(showWindow, 700);
}

function showWindow() {
  var window = $("#Window").data("tWindow");
  window.open().center();
}

New Code
function openWindow(url, title) {
  var window = $("#Window").data("tWindow");
  window.ajaxRequest(url);
  window.title(title).open().center();;
//setTimeout(showWindow, 700);
}

Thanks everyone for your replies. Hope it helps someone.

A: Try this code:
function openWindow(url, title) {
  var window = $("#Window").data("tWindow");
  window.ajaxRequest(url);
  window.title(title).open().center();
  //call after the content has been loaded from the Ajax request
  document.getElementById('Code').focus();
}


text:
Q: Passing std::unique_ptr to constructor to take ownership I want to pass a std::unique_ptr to the constructor of a class that will take ownership of the data owned by the std::unique_ptr.
Are there any differences between the approaches foo and bar below in terms of how the compiler handles them that would make one of them preferable?
foo class:
template <class T>
class foo
{
    std::unique_ptr<T> data_;

public:
    foo(std::unique_ptr<T>&& data) :
        data_{ std::forward<std::unique_ptr<T>>(data) }
    {
    }
};

bar class:
template <class T>
class bar
{
    std::unique_ptr<T> data_;

public:
    bar(std::unique_ptr<T> data) :
        data_{ std::move(data) }
    {
    }
};

A: Binding to a reference requires one less move:
void f(std::unique_ptr<T>&& p) { g(std::move(p)); }

f(std::make_unique<T>());  // no move, g binds directly to the temporary

Binding to an object parameter requires one actual move:
void f(std::unique_ptr<T> p) { g(std::move(p)); }

f(std::make_unique<T>());  // p constructed (= moved) from temporary,
                           // g binds to p

The extra move involves one pointer copy, one setting of a pointer to null, and one destructor with a condition check. This is not a big cost, and the question of which style to use depends on the kind of code you're writing:
The more leaf your code is and the less it is used, the more the simple version with by-value passing buys you simplicity. Conversely, the more library your code is and the less you know your users, the more there is value in not imposing avoidable cost, no matter how small.
You decide.


text:
Q: Least squares and null space I want to solve a least squares problem,
$$
\min_x ||y - A x ||^2
$$
with $A \in \mathbb{R}^{m\times n}$. Suppose I were to find two distinct solutions $x_1,x_2$, which solve the problem, so that
$$
||y - A x_1 ||^2 = || y - A x_2 ||^2
$$
Does this imply that $A$ has a non-trivial null space?
Certainly, if $x_2 = x_1 + z$ and $z \in Ker(A)$, then the above condition would hold. But is it possible to have a non-singular $A$ which can have two distinct least squares solutions as above?

A: There is a unique vector in the span of $A$ (the columnspace of $A$) that is closest to $y$, namely the orthogonal projection of $y$ onto the columnspace. Since $Ax_1$ and $Ax_2$ are both "closest" to $y$, then $Ax_1$ and $Ax_2$ are both the orthogonal projection of $y$ onto the columnspace, and therefore $Ax_1=Ax_2$; in particular, $x_1-x_2$ lies in the nullspace of $A$.
An interesting question in this situation is to find the vector $\mathbf{x}_0$ among all vectors for which $\lVert A\mathbf{x}-\mathbf{y}\rVert^2$ is minimal that has least norm. This can be done in two steps using the problem of "minimal solutions", or in a single step by using the pseudoinverse of $A$.

A: If $$\text{the columns of $A$ are linearly independent},$$
then $A^\top A$ is invertible and the solution is uniquely given by $$(A^\top A)^{-1} A^\top y.$$
The above condition is equivalent to
$$\text{$A$ has a trivial nullspace}.$$
(Note that the above conditions include the case where $A$ is non-singular, but are more general since they handle cases where $A$ is not square.)


text:
Q: Connect Python to MySQL DB Can't connect my code to my MySQL DB due to the authentication plugin
I'm trying to connect my code to a newly installed MySQL DB. I am aware that on MySQL 8.X and above, the authentication type is set to sha2 by default and I've read that I need to "force" a different authentication plug-in (auth_plugin='mysql_native_password').
well... I did it but I still get the same error message:
"Authentication plugin '{0}' is not supported".format(plugin_name))
mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported
What else should I do?
Thanks
import mysql.connector as Sql

myDB = Sql.connect(
    host="localhost",
    user="dbadmin",
    password="myPassword",
    auth_plugin="mysql_native_password"
)

print(myDB)

A: This indeed solved my issue:
I had the same problem and passing auth_plugin='mysql_native_password' did not work,
because I accidentally installed mysql-connector instead of mysql-connector-python (via
pip3). Just to leaving this here in case it helps someone.

Authentication plugin 'caching_sha2_password' is not supported


text:
Q: OWL class get equivalent classes I'm trying to get all equivalent classes of an OWL class. I'm using this code but it doesn't work, it returns either empty brackets or the IRI class (I mean the IRI of cls).
I want to get the equivalent classes because I need to mention them as super classes of the given class (in the example the class cls ). So, If cls class is equivalent to the intersection of some other classes, then all those classes are super classes of cls class.
  public static Set<OWLClass> getEquivalentClasses(OWLClassExpression cls) {

        Node<OWLClass> equivalentClasses = reasoner.getEquivalentClasses(cls);
        Set<OWLClass> result = null;
        if (cls.isAnonymous()) {
            result = equivalentClasses.getEntities();
        } else {
            result = equivalentClasses.getEntitiesMinus(cls.asOWLClass());
        }
        return result;
        }


text:
Q: How to sum df when it contains characters? I am trying to prep my data and I am stuck with one issue. Lets say I have the following data frame:
df1
Name    C1    Val1
A       a       x1
A       a       x2
A       b       x3
A       c       x4
B       d       x5
B       d       x6
...

and I want to narrow down the df to
df2
Name    C1     Val
A       a,b,c  x1+x2+x3+x4
B       d      x5+x6
...

while a is a character value and x is numeric value
I have been trying using sapply, rowsum and
df2<- aggregate(df1, list(df1[,1]), FUN= summary)
but it just can't put the character values in a list for each Name.
Can someone help me how to receive df2?

A: m <- function(x) if(is.numeric(x<- type.convert(x)))sum(x) else toString(unique(x))
aggregate(.~Name,df1,m)
  Name      C1 Val1
1    A a, b, c   10
2    B       d   11

where
df1
Name C1 Val1
1    A  a    1
2    A  a    2
3    A  b    3
4    A  c    4
5    B  d    5
6    B  d    6

A: Quick and easy dplyr solution:
    library(dplyr)
library(stringr)
df1 %>%
  mutate(Val1_num = as.numeric(str_extract(Val1, "\\d+"))) %>%
  group_by(Name) %>%
  summarise(C1 = paste(unique(C1), collapse = ","),
            Val1 = paste(unique(Val1), collapse = "+"),
            Val1_num = sum(Val1_num))
#> # A tibble: 2 x 4
#>   Name  C1    Val1        Val1_num
#>   <chr> <chr> <chr>          <dbl>
#> 1 A     a,b,c x1+x2+x3+x4       10
#> 2 B     d     x5+x6             11

Or in base:
df2 <- aggregate(df1, list(df1[,1]), FUN = function(x) {
  if (all(grepl("\\d", x))) {
    sum(as.numeric(gsub("[^[:digit:]]", "", x)))
  } else {
    paste(unique(x), collapse = ",")
  }
})

df2
#>   Group.1 Name    C1 Val1
#> 1       A    A a,b,c   10
#> 2       B    B     d   11

data
df1 <- read.csv(text = "
Name,C1,Val1
A,a,x1
A,a,x2
A,b,x3
A,c,x4
B,d,x5
B,d,x6", stringsAsFactors = FALSE)

A: This is your df, I give it numbers 1 to 6 in Val1
df <-
structure(list(Name = structure(c(1L, 1L, 1L, 1L, 2L, 2L), .Label = c("A",
"B"), class = "factor"), C1 = structure(c(1L, 1L, 2L, 3L, 4L,
4L), .Label = c("a", "b", "c", "d"), class = "factor"), Val1 = 1:6), row.names = c(NA,
-6L), class = "data.frame")

We just use summarise:
df %>%
group_by(Name) %>%
summarise(C1=paste(unique(C1),collapse=","),Val1=sum(Val1))

# A tibble: 2 x 3
  Name  C1     Val1
  <fct> <chr> <int>
1 A     a,b,c    10
2 B     d        11


text:
Q: How to check disk usage for folders containing reflinked files on XFS? XFS supports copy on write (CoW), so it is not entirely clear what du will say if some of the bytes are shared across files. I'd like to find a way to check how much disk space a folder uses, not counting shared bytes multiple times, i.e. the real usage on disk.
Neither xfs_estimate nor du seem to do what I need:
$ mkdir testfolder
$ cd testfolder
$ dd if=/dev/zero of=testfile  bs=1M count=500 status=progress
500+0 records in
500+0 records out
524288000 bytes (524 MB, 500 MiB) copied, 0,158889 s, 3,3 GB/s
$ cp --reflink=always testfile testfile2
$ xfs_estimate .
. will take about 1004,4 megabytes
$ du -hs .
1000M   .

What I expect is that some tool says that this folder uses only 500MB.
df shows that free disk spaces is reduced by 500MB when using a plain cp, but not at all when doing a cp --reflink=always. So reflinking seems to work, but df is not helpful in practice, because the disk is huge and I want to check the real size of a quite small folder.
I assume this might be a valid question for BTRFS too. But in my case, I need a solution which works for XFS.

A: It feels like there should be a tool that does this by default but I don't remember if there is one.
You can query file extents using filefrag (generic, FIEMAP ioctl), or using xfs_bmap (XFS specific). That way you could choose to count shared extents (duplicates) only once (or not at all).
# filefrag -e -k testfile
Filesystem type is: 58465342
File size of testfile is 5242880 (5120 blocks of 1024 bytes)
 ext:     logical_offset:        physical_offset: length:   expected: flags:
   0:        0..    5119:         96..      5215:   5120:             last,shared,eof
testfile: 1 extent found

In this example, filefrag knows and shows that the extent is shared (anywhere in the filesystem, not necessarily within that directory), xfs_bmap does not:
# xfs_bmap -l testfile
testfile:
    0: [0..10239]: 192..10431 10240 blocks

But basically that's the key ingredient you can use to script it on your own.
Show all possible shared extents:
# find . -xdev -type f -exec filefrag -e -k {} + | grep shared
   0:        0..    5119:         96..      5215:   5120:             last,shared,eof
   0:        0..    5119:       5216..     10335:   5120:             last,shared,eof
   0:        0..    5119:         96..      5215:   5120:             last,shared,eof

Shared (duplicate within directory) extents using xfs_bmap:
# find . -xdev -type f -exec xfs_bmap -l {} + | grep 'blocks$' | grep -v ': hole' | sort | uniq -d
0: [0..10239]: 192..10431 10240 blocks

Note that xfs_bmap uses 512 byte per block whereas filefrag uses 1024 bytes (with -k option) or whatever the filesystem blocksize is (like 4096 bytes).
Shared duplicate extents using filefrag:
# find . -xdev -type f -exec filefrag -ek {} + | grep shared | sort | uniq -d
   0:        0..    5119:         96..      5215:   5120:             last,shared,eof

So in this case you'd have to substract 5120 from the du -cks . result.

A: I made a solution for this over on the Veeam community pages:
Inherency:
Since we bill by actual disk usage for our client utilizing (Veeam) CloudConnect, the existing reports are non-functional for reporting and billing (They report pre-deduplication/reflink data).  It took a while to figure out, but there is a way to calculate actual disk space used on a per directory on an immutable repository.
Solution:
Using: https://community.veeam.com/blogs-and-podcasts-57/check-reflink-and-spared-space-on-xfs-repositories-244
I have extrapolated a script that will give the disk usage of each folder (IE: client) on an immutable repo.  This isn't "Data used"; that is what Veeam reports.  This is "Disk Used".  The actual size on disk after reflinks (duplicated data is only counted once).
A note about this script; it appears that the original blog entry is wrong on the size of a block.  They attribute it to 4096... which is true... on disk... but the utility used explicitly gives the information in block sizes of 512:
https://linux.die.net/man/8/xfs_bmap
"units of 512-byte blocks"
To use this script, we use a cron task and pipe the output to a mail client on the repo itself (IE: script.bash 2>&1 | mail -s "Immutable storage report for $HOSTNAME" someemail@email.place)
#!/bin/bash

for clientDir in `find /backups/disk-01/backups/ -mindepth 1 -maxdepth 1 -type d`
do
    echo $clientDir
    clientSpaceUsed=$(find $clientDir/*/* -xdev -type f -exec xfs_bmap -l {} + | awk '{ print $3 " " $4 }' | sort -k 1 | uniq | awk '{ print $2 }' | grep -Eo '[0-9]{1,7}' | paste -sd+ | bc | awk '{print $1*512/1024/1024/1024}')
    #block sizes of 512 bytes.  Divided by 1024 for KB.  Divided by 1024 for MB. Divided by 1024 for GB.
    echo "$clientSpaceUsed GB"
done

To break down how this works:
For each client directory in "/backups/disk-01/backups/"
output the directory being reported on
run xfs_bmap -l (this tells us all about the blocks in question)
Take columns 3 and 4 (now becomes column 1 and 2, the rest are discarded)
sort by column 1
remove duplicate rows of data (reflinks for fast cloning; keeps a single copy of the data for counting purposes)
Select only column 2 (now becomes column 1)
remove anything other than numbers
Add those numbers together
multiple by block size (512)
divide by 1024 (now KB)
divide by 1024 (now MB)
divide by 1024 (now GB)
output text

A: I tried to find out how much space my file really uses and how much is shared with other files. I'm not sure why "total" differs in some bytes compared to du, but finally it seems to return what I need:
file="/mnt/cache/domains/Windows 10/vdisk1-backup.img"

du -h "$file"

mapfile -t fragments < <( filefrag -ek "$file" | tail -n +4 | cut -d ":" -f 4 | grep -oP "[0-9]+" )
sum=$(IFS=+; echo "$((${fragments[*]}))")
sum=$((sum * 1024))
sum=$(echo "$sum" | numfmt --to=iec)
echo "$sum total"

mapfile -t fragments < <( filefrag -ek "$file" | tail -n +4 | grep "shared" | cut -d ":" -f 4 | grep -oP "[0-9]+" )
sum=$(IFS=+; echo "$((${fragments[*]}))")
sum=$((sum * 1024))
sum=$(echo "$sum" | numfmt --to=iec)
echo "$sum shared"

mapfile -t fragments < <( filefrag -ek "$file" | tail -n +4 | grep -v "shared" | cut -d ":" -f 4 | grep -oP "[0-9]+" )
sum=$(IFS=+; echo "$((${fragments[*]}))")
sum=$((sum * 1024))
sum=$(echo "$sum" | numfmt --to=iec)
echo "$sum unique"

Output:
15G     /mnt/cache/domains/Windows 10/vdisk1-backup.img
15G total
8.3G shared
6.8G unique

A: If you just want to know the actual free space similar to df then use xfs_spaceman.
For example:
xfs_spaceman -c 'freesp -s -m4096' /path/to/xfs/mount

It can be slow to calculate this but the reported "total free blocks" is accurate with regards to reflink/deduplicated data and can be multiplied by the block size to get the actual free space in bytes.


text:
Q: How do I change background and font colors of the Items of a ListBox? I created a formatting condition:

*

*If the text contains - Success then the background color is Green, ForeGround color is Black;

*If the text contains - Error" color background Red, foreground is Black;

*Other cases: background color is White, foreground color is Black;

Question.
How do I change background/foreground colors of the ListBox Item that I choose to fulfill Condition 1?
Condition 1. Condition for the selected Item:

*

*background Color.Blue;

*foreground Color.White (or Color.Black);

Problem:
My code does not paint the ListBox Item, which is Color.White.
private SolidBrush reportsForegroundBrushSelected = new SolidBrush(Color.Black);
private SolidBrush reportsBackgroundBrushSelected = new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));

private SolidBrush reportsForegroundBrush = new SolidBrush(Color.Black);
private SolidBrush reportsBackgroundBrush1 = new SolidBrush(Color.LimeGreen);
private SolidBrush reportsBackgroundBrush2 = new SolidBrush(Color.Salmon);
private SolidBrush reportsBackgroundBrush3 = new SolidBrush(Color.White);

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);

    int index = e.Index;
    if (index >= 0 && index < listBox1.Items.Count)
    {
        string text = listBox1.Items[index].ToString();
        Graphics g = e.Graphics;

        //background:
        SolidBrush backgroundBrush;
        if (selected)
        {
            backgroundBrush = reportsBackgroundBrushSelected;
        }
        else
        {
            if (text.Contains("Success"))
            {
                backgroundBrush = reportsBackgroundBrush1;
            }
            else
            {
                backgroundBrush = reportsBackgroundBrush2;
            }
        }

        if (!text.Contains("Success") && !text.Contains("Error"))
        {
            backgroundBrush = reportsBackgroundBrush3;
        }

        g.FillRectangle(backgroundBrush, e.Bounds);

        //text:
        SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush;
        g.DrawString(text, e.Font, foregroundBrush, listBox1.GetItemRectangle(index).Location);
    }
    e.DrawFocusRectangle();
}

A: Even though not explicitly requested, I suggest another way to manage the brushes that may, I think, simplify the ForeColor/BackColor switch and allows a better customization of the ListBox presentation.
Create a class object that contains all the brushes selection/pre-selections and exposes public properties to modify these values if/when needed.
Also, this class provides a method to return the correct combination of brushes, selecting the right ones based on a couple of conditions:

*

*The text content of the current Item

*Its selection Status (Selected/Focused or NotAccelerator/NotFocusedRect)

The class is quite simple.
It has an overloaded constructor that allows to specify default values or specific Color attributes to assign to the standard appearance of the ListBox control.
When using the default (empty) constructor, the default combination of ForeGround/BackGround Colors are set to Color.Black and Color.White:
public ReportsBrushes() : this(Color.White, Color.Black) { }

otherwise, it accepts 2 parameters, to set specific values:
public ReportsBrushes(Color ItemBackColor, Color ItemForeColor)
{
    this.StandardForeground = new SolidBrush(ItemForeColor);
    this.StandardBackground = new SolidBrush(ItemBackColor);
}

This simplifies the ListBox.DrawItem method:
private ReportsBrushes reportsBrushes = new ReportsBrushes();

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    var ctl = sender as ListBox;
    e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
    e.DrawFocusRectangle();

    var itemColors = reportsBrushes.GetItemBrushes(ctl.Items[e.Index].ToString(), e.State.HasFlag(DrawItemState.Selected));

    using (StringFormat format = new StringFormat()) {
        format.LineAlignment = StringAlignment.Center;
        e.Graphics.DrawString(ctl.Items[e.Index].ToString(), ctl.Font, itemColors.ForeColor, e.Bounds, format);
    }
}

private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
    e.ItemHeight = listBox1.Font.Height + 4;
}

The ReportsBrushes class:
internal class ReportsBrushes
{
    public ReportsBrushes() : this(Color.White, Color.Black) { }
    public ReportsBrushes(Color ItemBackColor, Color ItemForeColor)
    {
        this.StandardForeground = new SolidBrush(ItemForeColor);
        this.StandardBackground = new SolidBrush(ItemBackColor);
    }
    public SolidBrush StandardForeground { get; set; }
    public SolidBrush StandardBackground { get; set; }

    public SolidBrush SelectedForeground { get ; set ; } =
        new SolidBrush(Color.FromKnownColor(KnownColor.HighlightText));
    public SolidBrush SelectedBackground { get; set; } =
        new SolidBrush(Color.FromKnownColor(KnownColor.Highlight));
    public SolidBrush SuccessBackground { get; set; } =
        new SolidBrush(Color.LimeGreen);
    public SolidBrush ErrorBackground { get; set; } =
        new SolidBrush(Color.OrangeRed);

    public (SolidBrush ForeColor, SolidBrush BackColor) GetItemBrushes(string ItemText, bool ItemSelected)
    {
        if (ItemSelected) {
            return (this.SelectedForeground, this.SelectedBackground);
        }
        else {
            if (ItemText.Contains("Success")) {
                return (this.StandardForeground, this.SuccessBackground);
            }
            if (ItemText.Contains("Error")) {
                return (this.StandardForeground, this.ErrorBackground);
            }
            return (this.StandardForeground, this.StandardBackground);
        }
    }
}

A: Problem is in your order of if/else.
Set it like this:
if (selected)
{
    backgroundBrush = reportsBackgroundBrushSelected;
}
else
{
    if (text.Contains("Success"))
    {
        backgroundBrush = reportsBackgroundBrush1;
    }
    else if(text.Contains("Error"))
    {
        backgroundBrush = reportsBackgroundBrush2;
    }
    else
    {
        backgroundBrush = reportsBackgroundBrush3;
    }
}


text:
Q: Parallelisation - Why does sleep pause only once? Why do wait only the first goroutine with
func Sleep(d Duration)
http://golang.org/pkg/time
"Sleep pauses the current goroutine for the duration d."
but the rest is execute directly. I think cause the channel c chan string but i dont understand the behaviour between both.
My Example GoPlayground

A: All your go routines are running concurrently so they all sleep for 4 seconds at the same time, hence they all end at the same time.
You called them like this.  The go means that all the getHostName functions run at once.
for i := 0; i < max; i++ {
    go getHostName(haveHost, ipadresse_3, i)
}

And this means that all the sleeps happen at the same time
func getHostName(h chan string, ipAdresse string, n int) {

    //Here!!!
    time.Sleep(4 * time.Second)
    ip := ipAdresse + strconv.Itoa(n)

    //ip, ok := net.LookupAddr(ip)

    if false {
        h <- ip + " - "
    } else {
        h <- "error" + strconv.Itoa(n)
    }
}

So they all finish at the same time.


text:
Q: is count(indexed column) faster than count(*)?
Possible Duplicate:
Performance of COUNT SQL function

Hi all,
I've very large tables and I need to know number of records in each , My question is does it reduce the run time if I run :
select count(indexed column like my PK) from tbTest

instead of
select count(*) from tbTest

A: see Performance of COUNT SQL function
The important thing to note is they are not equivalent

A: Since the question is whether or not there is a performance difference, it would depend on the index.  When you do COUNT(*), it will use the PK column(s) to determine the number of rows.  If you do not have any indexes besides a clustered index on the PK column(s), it will scan the leaf nodes on the clustered index.  That's probably a lot of pages.  If you have a non clustered index that is skinnier than the clustered index, it will choose that instead, resulting in less reads.
So, if the column you select is contained in the smallest possible non-clustered index on the table, the SQL query optimizer will choose that for both count() (if you have a clustered ix that is the PK) and count(indexed_column).  If you choose a count(indexed_col) that is only contained in a wide index, then the count() will be faster if your PK is a clustered index.  The reason this works is that there is a pointer to the clustered index in all non-clustered indexes and SQL Server can figure out the number of rows based on that non-clustered index.
So, as usual in SQL Server, it depends.  Do a showplan and compare the queries to each other.

A: SELECT COUNT(*) may be faster. That is because using * gives the optimizer liberty to choose any column to count on. Say you have a primary key on a INT column, and a non clustered key on a different bigint column. But the primary key is likely the clustered index, and as such it is in fact significantly larger than the nonclustered bigint index (has more pages). So if the optimizer is free to choose the bigint non-clustered index, it can return the response faster. Possible much faster, depending on the table.
So overall is always better to leave it as COUNT(*) and let the optimizer choose.

A: most likely, if the query scans the index instead of the whole table.
it is an easy thing to test, become your own scientist.

A: Both are identical. If you look at the query execution plan for both, both will do an "index scan"


text:
Q: Seeking complete code examnple for JQuery/Ajax Ping with success/fail Since it is asynch and there may be several in parallel I would prefer a solution which supports multiple parallel requests and knows which success/fail belongs to which request - probably using The jqXHR Object as described at http://api.jquery.com/jQuery.post/ (?).
Since I am just learning, a complete code example which I can study and understand would be most welcome.

A: HTML5's Web Workers will allow you to have a multi threaded solution in JS. If you're willing to experiment with them, they're supported in Opera, Chrome and Firefox (haven't tested it on IE yet). Check them out.


text:
Q: Fastest way to copy data from one table to another using linq I have a table on another SQL server which I need to copy from overnight. The structure of the destination table  is very similar so I was just going to use something like the code below.
Source - http://forums.asp.net/t/1322979.aspx/1
I have not tried this yet, but is there a better/quicker way to do this in linq?
    //there exist two table list and listSecond
    DataClassesDataContext dataClass = new DataClassesDataContext(); //create the instance of the DataContext

    var str = from a in dataClass.lists select a;
    foreach (var val in str) // iterator the data from the list and insert them into the listSecond
    {
        listSecond ls = new listSecond();
        ls.ID = val.ID;
        ls.pid = val.pid;
        ls.url = val.url;
        dataClass.listSeconds.InsertOnSubmit(ls);

    }
    dataClass.SubmitChanges();
    Response.Write("success");

A: Using LINQ to insert large amounts of data is not a good idea, except maybe with complicated schemas that need much transformations before being copied. It will create a separate query for each row inserted, in addition to logging them all in the transaction log.
A much faster solution can be found here - it's using SqlBulkCopy, which is a method for inserting large amounts of data in a single query, withouth transaction logging to slow it down. It will be an order of magnitude faster, and I'm telling you this from personal experience with both methods.


text:
Q: error while installing pm2 - node js i am trying to install pm2 (https://github.com/Unitech/pm2)
i get this error :
D:\_Work>npm install pm2
 -g --unsafe-perm
npm WARN `git config --get remote.origin.url` returned wrong result (http://ikt.
pm2.io/ikt.git) undefined
npm WARN `git config --get remote.origin.url` returned wrong result (http://ikt.
pm2.io/ikt.git) undefined
npm ERR! git clone http://ikt.pm2.io/ikt.git undefined
npm ERR! git clone http://ikt.pm2.io/ikt.git undefined
npm WARN optional dep failed, continuing ikt@git+http://ikt.pm2.io/ikt.git#maste
r
npm WARN optional dep failed, continuing fsevents@0.3.5
C:\Users\user\AppData\Roaming\npm\pm2 -> C:\Users\user\AppData\Roaming
\npm\node_modules\pm2\bin\pm2
pm2@0.12.7 C:\Users\user\AppData\Roaming\npm\node_modules\pm2
├── json-stringify-safe@5.0.0
├── cli-table@0.3.1
├── eventemitter2@0.4.14
├── commander@2.6.0
├── pidusage@0.1.1
├── cron@1.0.5
├── async@0.9.0
├── isbinaryfile@2.0.3
├── vizion@0.2.3
├── colors@1.0.3
├── shelljs@0.3.0
├── pmx@0.3.5
├── observe-js@0.4.2
├── debug@2.1.0 (ms@0.6.2)
├── pm2-deploy@0.1.2 (tv4@1.0.18)
├── pm2-multimeter@0.1.2 (charm@0.1.2)
├── pm2-axon-rpc@0.3.6 (commander@1.0.5)
├── moment@2.9.0
├── nssocket@0.5.3 (lazy@1.0.11)
├── coffee-script@1.8.0 (mkdirp@0.3.5)
├── chalk@0.5.1 (ansi-styles@1.1.0, escape-string-regexp@1.0.3, supports-color@0
.2.0, strip-ansi@0.3.0, has-ansi@0.1.0)
├── chokidar@0.12.6 (async-each@0.1.6, readdirp@1.3.0)
├── pm2-axon@2.0.8 (amp-message@0.1.2, escape-regexp@0.0.1, amp@0.3.1, configura
ble@0.0.1, debug@2.0.0)
└── pm2-logs@0.1.1 (blessed@0.0.36, chalk@0.4.0, pm2-interface@1.1.0)

D:\_Work>pm2
fs.js:751
  return binding.mkdir(pathModule._makeLong(path),
                 ^
Error: ENOENT, no such file or directory 'D:\Users\user\.pm2'
    at Error (native)
    at Object.fs.mkdirSync (fs.js:751:18)
    at Object.CLI.pm2Init (C:\Users\user\AppData\Roaming\npm\node_modules\p
m2\lib\CLI.js:37:8)
    at Object.<anonymous> (C:\Users\user\AppData\Roaming\npm\node_modules\p
m2\bin\pm2:20:5)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)

I am having Windows 7 and i tried this by Run as Administrator as well.
I want to install a js file as a windows service or something else so that it runs forever.
Kindly assist

A: It looks like the package is trying to clone a git repo during the install process. Unfortunately the git repo appears to be borked (http://ikt.pm2.io/ikt.git), on http at least.
This could be a transient problem, the maintainer might have misconfigured git or the remote server. I'd raise an issue on the projects github and see what the maintainer says.

A: Check .pm2 folder in D:\Users\user\, if this folder not exist try create and after install.

A: You could try using forever instead of pm2
npm install forever -g
forever start app.js

foreverjs


text:
Q: Find and replace nth instance of text string using python or bash I have a configuration file that I am trying to edit.
For example the file says : listen = 1.1.1.1 and I want it to say listen = 2.2.2.2.
However the word listen occurs in other places in the file. So I want to know how to read in the file and only change the nth instance

A: Assuming "listen = 1.1.1.1" appears on its own line, to change the 4th instance:
awk -v n=4 '/listen = / && ++m == n {$3 = "2.2.2.2"} 1' file > file.changed


text:
Q: How i compute the properties of G/G/1 QueueingProcess? how can i compute the properties of G/G/1 QueueingProcess using Mathematica using the following distributions
QueueProperties[QueueingProcess[ParetoDistribution[k, \[Alpha]], ParetoDistribution[k, \[Alpha]]]]

QueueProperties[QueueingProcess[WeibullDistribution[\[Alpha],\[Beta]], WeibullDistribution[\[Alpha],\[Beta]]]]

QueueProperties[QueueingProcess[ParetoDistribution[k, \[Alpha]], WeibullDistribution[\[Alpha],\[Beta]]]]

A: For some reason the QueueProperties "SummaryTable" property does not like your QueueingProcess.  You many want to report this to WRI.
You can examine your process properties with the following while you wait for an answer from WRI:
Manipulate[
 Column[{
   QueueProperties[qp, prop, "Description"],
   QueueProperties[qp, prop]
   }],
 {{prop, "ArrivalRate", "Property"}, propList},
 Initialization :> {
   qp = QueueingProcess[ParetoDistribution[k, \[Alpha]], ParetoDistribution[k, \[Alpha]]];
   propList = QueueProperties[qp, "Properties"];}
 ]

Hope this helps.


text:
Q: How to escape JSON in Ansible playbook I have the following YAML Ansible playbook file which I intent do use to capture some information from my docker containers:
---
# Syntax check:  /usr/bin/ansible-playbook --syntax-check --inventory data/config/host_inventory.yaml data/config/ansible/docker_containers.yaml
- hosts: hosts
  gather_facts: no
  tasks:
  - name: Docker ps output - identify running containers
    shell: "/usr/bin/docker ps --format '{\"ID\":\"{{ .ID }}\", \"Image\": \"{{ .Image }}\", \"Names\":\"{{ .Names }}\"}'"
    register: docker_ps_output
  - name: Show content of docker_ps_output
    debug:
       msg: docker_ps_output.stdout_lines

But escaping is not working, Ansible gives me the middle finger when I try to run the playbook:
PLAY [hosts] ***********************************************************************************************************************************************************

TASK [Docker ps output - identify running containers] **********************************************************************************************************************************************
fatal: [myhost.com]: FAILED! => {"msg": "template error while templating string: unexpected '.'. String: /usr/bin/docker ps --format ''{\"ID\":\"{{ .ID }}\", \"Image\": \"{{ .Image }}\", \"Names\":\"{{ .Names }}\"}''"}
        to retry, use: --limit @/tmp/docker_containers.retry

PLAY RECAP *****************************************************************************************************************************************************************************************
myhost.com : ok=0    changed=0    unreachable=0    failed=1

The original command I'm trying to run:
/usr/bin/docker ps --format '{"ID":"{{ .ID }}", "Image": "{{ .Image }}", "Names":"{{ .Names }}"}'

A: If you want to avoid templating, you need to cover double-brackets by another double-brackets:
{{ thmthng }}

should look like:
{{ '{{' }} thmthng {{ '}}' }}

Your playbook:
---
- hosts: hosts
  gather_facts: no

  tasks:
  - name: Docker ps output - identify running containers
    shell: "docker ps -a --format '{\"ID\": \"{{ '{{' }} .ID {{ '}}' }}\", \"Image\": \"{{ '{{' }} .Image {{ '}}' }}\", \"Names\" : \"{{ '{{' }} .Names {{ '}}' }}}\"'"
    register: docker_ps_output

  - name: Show content of docker_ps_output
    debug:
       var: docker_ps_output.stdout_lines

A: I would suggest to use a block scalar. Your problem is that {{ .ID }} etc is processed by Ansible's Jinja templating engine when it should not. Probably the most readable way around this is:
---
# Syntax check:  /usr/bin/ansible-playbook --syntax-check --inventory data/config/host_inventory.yaml data/config/ansible/docker_containers.yaml
- hosts: hosts
  gather_facts: no
  tasks:
  - name: Docker ps output - identify running containers
    shell: !unsafe >-
      /usr/bin/docker ps --format
      '{"ID":"{{ .ID }}", "Image": "{{ .Image }}", "Names":"{{ .Names }}"}'
    register: docker_ps_output
  - name: Show content of docker_ps_output
    debug:
       msg: docker_ps_output.stdout_lines

>- starts a folded block scalar, in which you do not need to escape anything and newlines are folded into spaces. The tag !unsafe prevents the value to be processed with Jinja.


text:
Q: sitecore 301 redirect iis 7 We are using IIS 7.5(windows 7 and integrated mode) and SiteCore 6.4. I have installed IIS Url Rewrite Feature to rediect permenetly moved url. I have setup a Test folder inside website root for which we do not have any items on sitecore content tree. I have setup url redirect for this folder using URL Rewrite feature of iis 7.
But for some reason when i browse the Test folder, it is taking me to sitecore 404 page. Ideally it should redirect the page.
Rewrite rule:
<rewrite>
    <rules>
        <rule name="Sitecore_local" stopProcessing="true">
            <match url="/TestUrlRedirect/" />
            <action type="Redirect" url="http://www.google.com" />
        </rule>
    </rules>
</rewrite>

I am trying to access http://localhost/TestUrlRedirect/

A: (updated for actual testing url)
A working regex pattern, for the url you specified, would be configured via this rule.
Try this:
<rule name="Sitecore_local" stopProcessing="true">
    <match url="^TestUrlRedirect/(.*)" />
    <action type="Redirect" url="http://www.ascap.com" />
</rule>

Take a look at this for some starters. http://learn.iis.net/page.aspx/461/creating-rewrite-rules-for-the-url-rewrite-module/
You need to set the url to a regex pattern that matches what you want.

A: Can you please try the line below?
<match url="TestUrlRedirect(.*)" />

A: As we are using IIS 6.0 on sitecore CD server and IIS 7.5 on CM server, i resolve this issue by having my own url rewrite module.

A: You could also try to include your URL in
  <!--  IGNORE URLS
        Set IgnoreUrlPrefixes to a '|' separated list of url prefixes that should not be
        regarded and processed as friendly urls (ie. forms etc.)
  -->
  <setting name="IgnoreUrlPrefixes" value="..."/>

This will tell Sitecore to ignore your folder from processing.