text:
Q: Increasing understanding of the formatting in Python with the format() function hilarious = False

joke_evaluation = "Isn't that joke so funny?! {}"

print(joke_evaluation.format(hilarious))

For the following lines of Python code I'm failing to understand a key concept.
A string is assigned to the variable joke_evaluationand include {} to embed another variable within it.
The third line of code has got me stuck, we are saying print the variable joke_evaluation then using the .format() function and passing another variable to it - hilarious which is set as a boolean data type.
Are the {} effectively functioning as placeholders? How does the .format() function know to populate the {} with the variable hilarious?
Please explain in basic terms if possible to increase my understanding, I'm failing to understand how Python populates the curly braces {} as I've mentioned above.

A: Yes, {} acting as placeholders, which is treated by .format method in special way.

How does the .format() function know to populate the {} with the variable hilarious?

If you're providing {} only, it's substituted position-wise, i.e.
>>> 'first: {}, second: {}'.format(1, 2)
'first: 1, second: 2'

For more verbose or re-usable substitution you can use named arguments:
>>> "{actor1} tells {actor2} that he's {actor1}".format(actor1='Bob', actor2='Joel')
"Bob tells Joel that he's Bob"

More on awesome string formatting: pyformat.info
A bit more on formatting, when .format substituting placeholders with some objects, it calls __format__ method on it, which

*

*Accepts formatting spec — which gives you ability to control how it will be converted (for example, '{:.2f}'.format(3.1415)

*Return str, which will actually substitute placeholders

A: Here's my understanding of the the format method:
Any string with curly braces {} will be replaced with the variable you have provided. So, if I have a string say:
myStr = "hello {}"
then doing:
res = myStr.format("user")
print(res) #prints "hello user" without quotes.

Now, doing this:
res = myStr.format(123123)
print(res) #prints "hello 123123" without quotes.

As you might have guessed, the integer 123123 was implicitly converted to string before being included in the string.
Now, coming to the curly {} part:

*

*You can have multiple curly braces and must have the same number of parameters passed to format method. Eg:

myStr = "hello {},{},{}, nice meeting you"
res = myStr.format("abcd",123,"lol")
print(res) #prints "hello abcd,123,lol, nice meeting you"

*You can even put indices in the {} to indicate position like {0} and {1}.

A: Read Python documentation about string: https://docs.python.org/3.6/library/string.html?highlight=formatting
:) Everything you need to know. You can also change Python versions and see the behavior of formatting.
Scroll down to see examples and explanations.


text:
Q: Finish activity I have program with login, main activity and other activities.
First step is login activity(A). If login succeed start main activity(B) and call finish for (A).
working with (B) I'm calling some activities and then back to (B).
When decide to exit - I call logout and try to close (B) calling finish.
This logik works in 70% ot time :(
Unfortunately on 30% after calling finish for (B) - activity(A) appears on screen and start logging me.
Who is starting (B) again? I din't see relation between problem and program usage.
Update:
I put hohistory for (B) and start (B) with FLAG_ACTIVITY_CLEAR_TOP.
UPDATE2: Described behaviour is typical when I set screen orientation mode in code. In manifest  is set portrait. When start activity I'm setting orientation depending on user config. This produced onCreaste twice. I got managed to handle this properly, but this causes problem as described. If I don't set orientation - one onCreate is called and no problem with finish.

A: You can try this when you logout in activity B. The activity displays the home screen.
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);

A: Check the following links, you will get the solution:
Finish parent and current activity in Android
http://developer.android.com/guide/topics/manifest/activity-element.html#clear).You

A: Are you starting your application from an IDE (like eclipse), or from the app installer? If so, you will see this situation if you do the following.

*

*Launch your application from the IDE or after installation from the installer (displays your first activity)

*press the HOME key (takes you back to home screen)

*launch your application again by selecting it from the list of available applications

This sequence will create 2 copies of your first activity, one on top of the other. When you finish the top one, the one underneath it will be shown.
You say this doesn't happen all the time. If you don't launch the app from the IDE, but just from the list of available applications you won't see this behaviour. Also, if you never press the HOME key and relaunch the app using the list of available applications you won't see this behaviour either.

A: When you go from activity A to activity B first time you are supposed to clear your stack top. Otherwise activity A stays in the stack below B and when u finish B, activity B is called again.

A: you should set in manifest file android:noHistory="true" to make your A activity not to stay on android stack.
In case you would like to do it from code in future by using intents  Intent.FLAG_ACTIVITY_NO_HISTORY will do the job for you.. Cheers

A: Using setScreenOrientation made thinks complicated.
It is not enought to set noHistory for activityA and call activityB with FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_NEW_TASK.
When Start app in portrait mode /as declared in manifest/ - It was OK.
But when call setScreenOrientation - have to call finishB 2 times to exit.
/Probably because ot 2 times onCreate for activityB/.
This made thinks to work:
For activityA: android:noHistory="true" and android:launchMode="singleInstance" in manifest.
Start activityB with startActivityForResult and flags FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_NEW_TASK.
In activityA:
1. startActivityForResult(activityB)
2. finishA.
In activityB - when call finish() for B - because of 'singleinstance' system din't start activityA again.
Hope this help.
If anybody know reason which will cause error - please write me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: improve sql query with 2 EXISTS sub queries I have this query (mysql):
 SELECT `budget_items`.*
    FROM `budget_items`
    WHERE (budget_category_id = 4
           AND ((is_custom_for_family = 0)
                OR (is_custom_for_family = 1
                    AND custom_item_family_id = 999))
           AND ((EXISTS
                   (SELECT 1
                    FROM balance_histories
                    WHERE balance_histories.budget_item_id = budget_items.id
                      AND balance_histories.family_id = 999
                      AND payment_date >= '2021-02-01'
                      AND payment_date <= '2021-02-28' ))
                OR (EXISTS
                      (SELECT 1
                       FROM budget_lines
                       WHERE family_id = 999
                         AND budget_id = 188311
                         AND budget_item_id = budget_items.id
                         AND amount > 0))))

It runs multiple times on app start. It takes more than 10 seconds (all of them).
I have indexes on:
balance_histories table: budget_item_id, family_id (tried also payment_date)
budget_lines table: family_id, budget_id, budget_item_id
How can I improve the speed? Query or maybe mysql (8) configuration.
balance_histories table:

budget_lines table:

A: I would start this query in reverse of what you have.  Assuming you COULD have years of data, but your EXISTS query is looking more specifically at a date-range, or specific budget lines, start there, it will probably be much smaller.  Once you have DISTINCT IDs, then go back to the budget items by qualified ID PLUS the additional criteria.
To help optimize the queries, I would have indexes on
table              index
balance_histories  ( family_id, payment_date, budget_item_id )
budget_lines       ( family_id, budget_id, amount )
budget_items       ( id, budget_category_id, is_custom_for_family, custom_item_family_id )

select
        bi.*
    from
        -- pre-query a list of DISTINCT IDs from the balance history
        -- and budget lines that qualify. THEN join to the rest.
        ( select distinct
                bh.budget_item_id id
            from
                balance_histories bh
            where
                    bh.family_id = 999
                AND bh.payment_date >= '2021-02-01'
                AND bh.payment_date <= '2021-02-28'
        UNION
        select
                bl.budget_item_id
            FROM
                budget_lines bl
            WHERE
                    bl.family_id = 999
                AND bl.budget_id = 188311
                AND bl.amount > 0 ) PQ
            JOIN budget_items bi
                on PQ.id = bi.id
                AND bi.budget_category_id = 4
                AND (       bi.is_custom_for_family = 0
                        OR
                            (   bi.is_custom_for_family = 1
                            AND bi.custom_item_family_id = 999 )
                    )

Feedback
As for many SQL queries, there are typically multiple ways to get a solution.  Sometimes using EXISTS works well, sometimes not as much.  You need to consider cardinality of your data, and that is what I was shooting for. Look at what you were asking for first:  Get budget items that are all category for and custom for family is 1 or 0 (which is all), but if family, only those for 999. You were correct on your balance of AND/OR. However, this is going through EVERY RECORD, and if you have millions of rows, that is what you are scanning through.   Only after scanning through every row are you now doing a secondary query (for each record that qualified) against the histories for the specific date range OR family/budget.
My guess is that the number of possible records returned from your two EXISTS queries was going to be very small.  So, by starting by getting a DISTINCT list of just those IDs that are part of that union would be the very small subset. Once that single "ID" if found, it now becomes a direct match to the budget items table and have the final filtering limits of categoryID / Family / Custom Item considerations.
By having indexes better match the context of your query WHERE clause will optimize pulling data.  I have had answers to several other questions with similar resolutions and clarify indexes and why in those... take a look for example, and another here.


text:
Q: PHP function: bring data to normal view I have a function for WordPress:
<?php
function wpcf7_modify_this( $WPCF7_ContactForm ) {
    $comment = "Row_1: " . $_POST['step1'] . ", Row_2: " . $_POST['step2'] . ", Row_3: " . $_POST['step3'] . ", Row_4: " . $_POST['step4'] . ", Row_5: " . $_POST['step51'] . $_POST['step52'] . $_POST['step53'] . $_POST['step54'] . $_POST['step55'] . $_POST['step56'] . ", Row_6: " . $_POST['step61'] . ", " . $_POST['step62'] . ", ". $_POST['step63'];
    $roistatData = array(
      'name'    => isset($_POST['text-14'])    ? $_POST['text-14'] : null,
      'phone'   => isset($_POST['tel-854'])   ? $_POST['tel-854'] : null,
      'comment' => $comment,
   );
   file_get_contents("https://cloud.com/api/add?" . http_build_query($roistatData));
}
add_action("wpcf7_before_send_mail", "wpcf7_modify_this");
?>

The data comes in this form (in one line):

I want like this :)

Please help me bring the data back to normal.
Sorry for my English :)
Thanks for helping.

A: Try this by Adding
 tag.
    <?php
function wpcf7_modify_this( $WPCF7_ContactForm ) {
    $comment = "Row_1: " . $_POST['step1'] . ",\n Row_2: " . $_POST['step2'] . ",\n Row_3: " . $_POST['step3'] . ",\n Row_4: " . $_POST['step4'] . ",\n Row_5: " . $_POST['step51'] . $_POST['step52'] . $_POST['step53'] . $_POST['step54'] . $_POST['step55'] . $_POST['step56'] . ",\n Row_6: " . $_POST['step61'] . ", " . $_POST['step62'] . ", ". $_POST['step63'];
    $roistatData = array(
      'name'    => isset($_POST['text-14'])    ? $_POST['text-14'] : null,
      'phone'   => isset($_POST['tel-854'])   ? $_POST['tel-854'] : null,
      'comment' => $comment,
   );
   file_get_contents("https://cloud.com/api/add?" . http_build_query($roistatData));
}
add_action("wpcf7_before_send_mail", "wpcf7_modify_this");
?>

A: Use
 or \n :
  <?php
    function wpcf7_modify_this( $WPCF7_ContactForm ) {
        $comment = "Row_1: " . $_POST['step1'] . ",
 Row_2: " . $_POST['step2'] . ",
 Row_3: " . $_POST['step3'] . ",
 Row_4: " . $_POST['step4'] . ",
 Row_5: " . $_POST['step51'] . $_POST['step52'] . $_POST['step53'] . $_POST['step54'] . $_POST['step55'] . $_POST['step56'] . ",
 Row_6: " . $_POST['step61'] . ", " . $_POST['step62'] . ", ". $_POST['step63'];
        $roistatData = array(
          'name'    => isset($_POST['text-14'])    ? $_POST['text-14'] : null,
          'phone'   => isset($_POST['tel-854'])   ? $_POST['tel-854'] : null,
          'comment' => $comment,
       );
       file_get_contents("https://cloud.com/api/add?" . http_build_query($roistatData));
    }
    add_action("wpcf7_before_send_mail", "wpcf7_modify_this");
    ?>


text:
Q: Can I insert a random starting index in this Recursive DFS? This is a homework assignment but the question is not.  Among other things, I need to perform a DFS on a predetermined graph starting with the first element.  My recursiveDFT method does that.
I was just trying to figure out how to modify the algorithm to start with the last index, or a middle one.  It's eluding me.
public void recursiveDFT() {
    for (int i = 0; i < numberOfVertices; i++) {
        if (!vertex[i].getColor().equals("white"))
            vertex[i].setColor("white");
        if (pi[i] != null)
            pi[i] = null;
    }
    time = 0;
    for (int i = 0; i < numberOfVertices; i++) {
        if (vertex[i].getColor().equals("white"))
            recursiveDFTVisit(i);
    }
}//recursiveDFT

public void recursiveDFTVisit(int u) {
    vertex[u].setColor("gray");
    time++;
    d[u] = time;
    vertex[u].visit();
    for (int column = 0; column < numberOfVertices; column++) {
        if(edge[u][column] == 1 && vertex[column].getColor().equals("white")) {
            pi[column] = vertex[u];
            recursiveDFTVisit(column);
        }
    }
    vertex[u].setColor("black");
    f[u] = ++time;
}

A: If you want to start from a different point but still check the whole tree the best way would probably be to reorder your vertex array. To start at a different part of vertex[] you'd simply change the starting value of i in your first for loop. As mentioned though, this might prevent you from walking the whole tree unless you redesign your for loop to ensure it still hits every node. You could for instance, start at length-1 and then decrement i until it goes below zero. That works fine if you just want to start at the end and go in reverse, but if you want to get any more complex ordering you're better off just reordering your vertexes.


text:
Q: D3 transition: duration doesn't work for line path I'm new to javascript and I'm trying to animate my graph with a line that would take 1s to appear (using .transition().duration(1000)).
Unfortunately, I can't get this result. The .duration(1000) seems not to work for the line draw.
Abstract of my
svg.append("path")
            .data([data])
            .transition().duration(1000)
            .attr("class", "line")
            .attr("d", valueline(xy));

If i put a .transition().duration(1000).style("color", "red), the font becomes red in 1s.
My question: why does the duration work for the color but not the line draw?
If you could help me, I would be very very grateful!

I you need my whole code, I but it there:
//VOLCAN FUNCTION
function draw_volcan(url){
    d3.select("svg").remove() // remove the old graph

    // set the dimensions and margins of the graph
    var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

    d3.json(url, function(error, data) { //chargement des data volcans
        if(error) throw ('There was an error while getting geoData: '+error);
        //get in an array the occurance of eruptions
        var volcans_incidence_annee_2018 = new Array(59).fill(0) // on prépare une array avec pour le nombre d'éruptions de volcan par année
        data.forEach(function(d) {
            var single_date_index = d.Date-1960     //année-1960 = index où il faudra ajouter 1 pour l'occurence de l'année
            volcans_incidence_annee_2018[single_date_index] += 1 //ajoute 1 d'occurance à l'année souhaitée
            });
        var volcans_incidence_annee = new Array(56).fill(0)

        for(i in volcans_incidence_annee_2018){ //créé un array volcans_incidence_annee qui contient les données de 1960 à 2015 uniquement
            if(i<56){
                volcans_incidence_annee[i] = volcans_incidence_annee_2018[i]
            };
        };

        var year_array = []
        for(var i = 1960; i<=2015; i++) {year_array.push(i);} //créé un array avec chaque année

        //create array with all the points
        var xy=[];
        for(var i = 0; i < year_array.length; i++ ) {
            xy.push({x: year_array[i], y: volcans_incidence_annee[i]});
        };

        // set the ranges
        var x = d3.scaleLinear().domain([1960, 2015]).range([0, width]);
        var y = d3.scaleLinear().domain([Math.min(...volcans_incidence_annee), Math.max(...volcans_incidence_annee)]).range([height, 0]);

        // create a line function that can convert data[] into x and y points
        var valueline = d3.line()
            .x(function(d) { return x(d.x);})
            .y(function(d) { return y(d.y);});

        // append the svg obgect to the body of the page
        // appends a 'group' element to 'svg'
        // moves the 'group' element to the top left margin
        var svg = d3.select("#graph_draw").append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
            .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");

        // Add the valueline path.
        svg.append("path")
            .data([data])
            .transition().duration(1000)
            .attr("class", "line")
            .attr("d", valueline(xy));

        // Add the X Axis
        svg.append("g")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x));

        // Add the Y Axis
        svg.append("g")
            .call(d3.axisLeft(y));
        //svg.append("g").attr("d", line(+volcans_incidence_annee));
    });

A: In D3, a transition changes a DOM element from an initial state, the source  state, to a final state, the target state.
Everything before creating a transition with selection.transition belongs to the initial state, and everything after it belongs to the desired (target) state.
That said, the issue in your question is quite simple: you cannot interpolate the creation of a class or the definition of the d attribute. As Bostock (D3 creator) once said:

When modifying the DOM, use selections for any changes that cannot be interpolated; only use transitions for animation. For example, it is impossible to interpolate the creation of an element: it either exists or it doesn't.

We can clearly see this in the demos below.
It makes no sense transitioning from having no d attribute to having one:

var d = "M38.8 68.4l37.8 7.9 1.6-7.6-37.8-7.9-1.6 7.6zm5-18l35 16.3 3.2-7-35-16.4-3.2 7.1zm9.7-17.2l29.7 24.7 4.9-5.9-29.7-24.7-4.9 5.9zm19.2-18.3l-6.2 4.6 23 31 6.2-4.6-23-31zM38 86h38.6v-7.7H38V86z";

var d2 = "M84.4 93.8V70.6h7.7v30.9H22.6V70.6h7.7v23.2z";

var svg = d3.select("svg");

var path = svg.append("path")
  .style("fill", "#f48023")
  .transition()
  .duration(1000)
  .attr("d", d)

var path2 = svg.append("path")
  .style("fill", "#bcbbbb")
  .transition()
  .duration(1000)
  .attr("d", d2)
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>

However, we can transition from 0 opacity to 1:

var d = "M38.8 68.4l37.8 7.9 1.6-7.6-37.8-7.9-1.6 7.6zm5-18l35 16.3 3.2-7-35-16.4-3.2 7.1zm9.7-17.2l29.7 24.7 4.9-5.9-29.7-24.7-4.9 5.9zm19.2-18.3l-6.2 4.6 23 31 6.2-4.6-23-31zM38 86h38.6v-7.7H38V86z";

var d2 = "M84.4 93.8V70.6h7.7v30.9H22.6V70.6h7.7v23.2z";

var svg = d3.select("svg");

var path = svg.append("path")
  .style("fill", "#f48023")
  .attr("d", d)
  .style("opacity", 0)
  .transition()
  .duration(1000)
  .style("opacity", 1);

var path2 = svg.append("path")
  .style("fill", "#bcbbbb")
  .attr("d", d2)
  .style("opacity", 0)
  .transition()
  .duration(1000)
  .style("opacity", 1);
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>


text:
Q: Units of measure in C# - almost Inspired by Units of Measure in F#, and despite asserting (here) that you couldn't do it in C#, I had an idea the other day which I've been playing around with.
namespace UnitsOfMeasure
{
    public interface IUnit { }
    public static class Length
    {
        public interface ILength : IUnit { }
        public class m : ILength { }
        public class mm : ILength { }
        public class ft : ILength { }
    }
    public class Mass
    {
        public interface IMass : IUnit { }
        public class kg : IMass { }
        public class g : IMass { }
        public class lb : IMass { }
    }

    public class UnitDouble<T> where T : IUnit
    {
        public readonly double Value;
        public UnitDouble(double value)
        {
            Value = value;
        }
        public static UnitDouble<T> operator +(UnitDouble<T> first, UnitDouble<T> second)
        {
            return new UnitDouble<T>(first.Value + second.Value);
        }
        //TODO: minus operator/equality
    }
}

Example usage:
var a = new UnitDouble<Length.m>(3.1);
var b = new UnitDouble<Length.m>(4.9);
var d = new UnitDouble<Mass.kg>(3.4);
Console.WriteLine((a + b).Value);
//Console.WriteLine((a + c).Value); <-- Compiler says no

The next step is trying to implement conversions (snippet):
public interface IUnit { double toBase { get; } }
public static class Length
{
    public interface ILength : IUnit { }
    public class m : ILength { public double toBase { get { return 1.0;} } }
    public class mm : ILength { public double toBase { get { return 1000.0; } } }
    public class ft : ILength { public double toBase { get { return 0.3048; } } }
    public static UnitDouble<R> Convert<T, R>(UnitDouble<T> input) where T : ILength, new() where R : ILength, new()
    {
        double mult = (new T() as IUnit).toBase;
        double div = (new R() as IUnit).toBase;
        return new UnitDouble<R>(input.Value * mult / div);
    }
}

(I would have liked to avoid instantiating objects by using static, but as we all know you can't declare a static method in an interface)
You can then do this:
var e = Length.Convert<Length.mm, Length.m>(c);
var f = Length.Convert<Length.mm, Mass.kg>(d); <-- but not this

Obviously, there is a gaping hole in this, compared to F# Units of measure  (I'll let you work it out).
Oh, the question is: what do you think of this? Is it worth using? Has someone else already done better?
UPDATE for people interested in this subject area, here is a link to a paper from 1997 discussing a different kind of solution (not specifically for C#)

A: You are missing dimensional analysis. For example (from the answer you linked to), in F# you can do this:
let g = 9.8<m/s^2>

and it will generate a new unit of acceleration, derived from meters and seconds (you can actually do the same thing in C++ using templates).
In C#, it is possible to do dimensional analysis at runtime, but it adds overhead and doesn't give you the benefit of compile-time checking. As far as I know there's no way to do full compile-time units in C#.
Whether it's worth doing depends on the application of course, but for many scientific applications, it's definitely a good idea. I don't know of any existing libraries for .NET, but they probably exist.
If you are interested in how to do it at runtime, the idea is that each value has a scalar value and integers representing the power of each basic unit.
class Unit
{
    double scalar;
    int kg;
    int m;
    int s;
    // ... for each basic unit

    public Unit(double scalar, int kg, int m, int s)
    {
       this.scalar = scalar;
       this.kg = kg;
       this.m = m;
       this.s = s;
       ...
    }

    // For addition/subtraction, exponents must match
    public static Unit operator +(Unit first, Unit second)
    {
        if (UnitsAreCompatible(first, second))
        {
            return new Unit(
                first.scalar + second.scalar,
                first.kg,
                first.m,
                first.s,
                ...
            );
        }
        else
        {
            throw new Exception("Units must match for addition");
        }
    }

    // For multiplication/division, add/subtract the exponents
    public static Unit operator *(Unit first, Unit second)
    {
        return new Unit(
            first.scalar * second.scalar,
            first.kg + second.kg,
            first.m + second.m,
            first.s + second.s,
            ...
        );
    }

    public static bool UnitsAreCompatible(Unit first, Unit second)
    {
        return
            first.kg == second.kg &&
            first.m == second.m &&
            first.s == second.s
            ...;
    }
}

If you don't allow the user to change the value of the units (a good idea anyways), you could add subclasses for common units:
class Speed : Unit
{
    public Speed(double x) : base(x, 0, 1, -1, ...); // m/s => m^1 * s^-1
    {
    }
}

class Acceleration : Unit
{
    public Acceleration(double x) : base(x, 0, 1, -2, ...); // m/s^2 => m^1 * s^-2
    {
    }
}

You could also define more specific operators on the derived types to avoid checking for compatible units on common types.

A: Here's my concern with creating units in C#/VB.  Please correct me if you think I'm wrong.  Most implementations I've read about seem to involve creating a structure that pieces together a value (int or double) with a unit.  Then you try to define basic functions (+-*/,etc) for these structures that take into account unit conversions and consistency.
I find the idea very attractive, but every time I balk at what a huge step for a project this appears to be.  It looks like an all-or-nothing deal.  You probably wouldn't just change a few numbers into units; the whole point is that all data inside a project is appropriately labeled with a unit to avoid any ambiguity.  This means saying goodbye to using ordinary doubles and ints, every variable is now defined as a "Unit" or "Length" or "Meters", etc. Do people really do this on a large scale?  So even if you have a large array, every element should be marked with a unit.  This will obviously have both size and performance ramifications.
Despite all the cleverness in trying to push the unit logic into the background, some cumbersome notation seems inevitable with C#.  F# does some behind-the-scenes magic that better reduces the annoyance factor of the unit logic.
Also, how successfully can we make the compiler treat a unit just like an ordinary double when we so desire, w/o using CType or ".Value" or any additional notation?  Such as with nullables, the code knows to treat a double? just like a double (of course if your double? is null then you get an error).

A: Thanks for the idea. I have implemented units in C# many different ways there always seems to be a catch. Now I can try one more time using the ideas discussed above. My goal is to be able to define new units based on existing ones like
Unit lbf = 4.44822162*N;
Unit fps = feet/sec;
Unit hp = 550*lbf*fps

and for the program to figure out the proper dimensions, scaling and symbol to use. In the end I need to build a basic algebra system that can convert things like (m/s)*(m*s)=m^2 and try to express the result based on existing units defined.
Also a requirement must be to be able to serialize the units in a way that new units do not need to be coded, but just declared in a XML file like this:
<DefinedUnits>
  <DirectUnits>
<!-- Base Units -->
<DirectUnit Symbol="kg"  Scale="1" Dims="(1,0,0,0,0)" />
<DirectUnit Symbol="m"   Scale="1" Dims="(0,1,0,0,0)" />
<DirectUnit Symbol="s"   Scale="1" Dims="(0,0,1,0,0)" />
...
<!-- Derived Units -->
<DirectUnit Symbol="N"   Scale="1" Dims="(1,1,-2,0,0)" />
<DirectUnit Symbol="R"   Scale="1.8" Dims="(0,0,0,0,1)" />
...
  </DirectUnits>
  <IndirectUnits>
<!-- Composite Units -->
<IndirectUnit Symbol="m/s"  Scale="1"     Lhs="m" Op="Divide" Rhs="s"/>
<IndirectUnit Symbol="km/h" Scale="1"     Lhs="km" Op="Divide" Rhs="hr"/>
...
<IndirectUnit Symbol="hp"   Scale="550.0" Lhs="lbf" Op="Multiply" Rhs="fps"/>
  </IndirectUnits>
</DefinedUnits>

A: Using separate classes for different units of the same measure (e.g., cm, mm, and ft for Length) seems kind of weird. Based on the .NET Framework's DateTime and TimeSpan classes, I would expect something like this:
Length  length       = Length.FromMillimeters(n1);
decimal lengthInFeet = length.Feet;
Length  length2      = length.AddFeet(n2);
Length  length3      = length + Length.FromMeters(n3);

A: You could add extension methods on numeric types to generate measures.  It'd feel a bit DSL-like:
var mass = 1.Kilogram();
var length = (1.2).Kilometres();

It's not really .NET convention and might not be the most discoverable feature, so perhaps you'd add them in a devoted namespace for people who like them, as well as offering more conventional construction methods.

A: I recently released Units.NET on GitHub and on NuGet.
It gives you all the common units and conversions. It is light-weight, unit tested and supports PCL.
Example conversions:
Length meter = Length.FromMeters(1);
double cm = meter.Centimeters; // 100
double yards = meter.Yards; // 1.09361
double feet = meter.Feet; // 3.28084
double inches = meter.Inches; // 39.3701

A: Now such a C# library exists:
http://www.codeproject.com/Articles/413750/Units-of-Measure-Validator-for-Csharp
It has almost the same features as F#'s unit compile time validation, but for C#.
The core is a MSBuild task, which parses the code and looking for validations.
The unit information are stored in comments and attributes.

A: there is jscience: http://jscience.org/, and here is a groovy dsl for units: http://groovy.dzone.com/news/domain-specific-language-unit-. iirc, c# has closures, so you should be able to cobble something up.

A: Why not use CodeDom to generate all possible permutations of the units automatically? I know it's not the best - but I will definitely work!

A: you could use QuantitySystem instead of implementing it by your own. It builds on F# and drastically improves unit handling in F#. It's the best implementation I found so far and can be used in C# projects.
http://quantitysystem.codeplex.com

A:
Is it worth using?

Yes. If I have "a number" in front of me, I want to know what that is. Any time of the day. Besides, that's what we usually do. We organize data into a meaningful entity -class, struct, you name it. Doubles into coordinates, strings into names and address etc. Why units should be any different?

Has someone else already done better?

Depends on how one defines "better". There are some libraries out there but I haven't tried them so I don't have an opinion. Besides it spoils the fun of trying it myself :)
Now about the implementation. I would like to start with the obvious: it's futile to try replicate the [<Measure>] system of F# in C#. Why? Because once F# allows you to use / ^ (or anything else for that matter) directly on another type, the game is lost. Good luck doing that in C# on a struct or class. The level of metaprogramming required for such a task does not exist and I'm afraid it is not going to be added any time soon -in my opinion. That's why you lack the dimensional analysis that Matthew Crumley mentioned in his answer.
Let's take the example from fsharpforfunandprofit.com: you have Newtons defined as [<Measure>] type N = kg m/sec^2. Now you have the square function that that the author created that will return a N^2 which sounds "wrong", absurd and useless. Unless you want to perform arithmetic operations where at some point during the evaluation process, you might get something "meaningless" until you multiply it with some other unit and you get a meaningful result. Or even worse, you might want to use constants. For example the gas constant R which is 8.31446261815324 J /(K mol). If you define the appropriate units, then F# is ready to consume the R constant. C# is not. You need to specify another type just for that and still you won't be able to do any operation you want on that constant.
That doesn't mean that you shouldn't try. I did and I am quite happy with the results. I started SharpConvert around 3 years ago, after I got inspired by this very question. The trigger was this story: once I had to fix a nasty bug for the RADAR simulator that I develop: an aircraft was plunging in the earth instead of following the predefined glide path. That didn't make me happy as you could guess and after 2 hours of debugging, I realized that somewhere in my calculations, I was treating kilometers as nautical miles. Until that point I was like "oh well I will just be 'careful'" which is at least naive for any non trivial task.
In your code there would be a couple of things I would do different.
First I would turn UnitDouble<T> and IUnit implementations into structs. A unit is just that, a number and if you want them to be treated like numbers, a struct is a more appropriate approach.
Then I would avoid the new T() in the methods. It does not invoke the constructor, it uses Activator.CreateInstance<T>() and for number crunching it will be bad as it will add overhead. That depends though on the implementation, for a simple units converter application it won't harm. For time critical context avoid like the plague. And don't take me wrong, I used it myself as I didn't know better and I run some simple benchmarks the other day and such a call might double the execution time -at least in my case. More details in Dissecting the new() constraint in C#: a perfect example of a leaky abstraction
I would also change Convert<T, R>() and make it a member function. I prefer writing
var c = new Unit<Length.mm>(123);
var e = c.Convert<Length.m>();

rather than
var e = Length.Convert<Length.mm, Length.m>(c);

Last but not least I would use specific unit "shells" for each physical quantity (length time etc) instead of the UnitDouble, as it will be easier to add physical quantity specific functions and operator overloads. It will also allow you to create a Speed<TLength, TTime> shell instead of another Unit<T1, T2> or even Unit<T1, T2, T3> class. So it would look like that:
public readonly struct Length<T> where T : struct, ILength
{
    private static readonly double SiFactor = new T().ToSiFactor;
    public Length(double value)
    {
        if (value < 0) throw new ArgumentException(nameof(value));
        Value = value;
    }

    public double Value { get; }

    public static Length<T> operator +(Length<T> first, Length<T> second)
    {
        return new Length<T>(first.Value + second.Value);
    }

    public static Length<T> operator -(Length<T> first, Length<T> second)
    {
        // I don't know any application where negative length makes sense,
        // if it does feel free to remove Abs() and the exception in the constructor
        return new Length<T>(System.Math.Abs(first.Value - second.Value));
    }

    // You can add more like
    // public static Area<T> operator *(Length<T> x, Length<T> y)
    // or
    //public static Volume<T> operator *(Length<T> x, Length<T> y, Length<T> z)
    // etc

    public Length<R> To<R>() where R : struct, ILength
    {
        //notice how I got rid of the Activator invocations by moving them in a static field;
        //double mult = new T().ToSiFactor;
        //double div = new R().ToSiFactor;
        return new Length<R>(Value * SiFactor / Length<R>.SiFactor);
    }
}

Notice also that, in order to save us from the dreaded Activator call, I stored the result of new T().ToSiFactor in SiFactor. It might seem awkward at first, but as Length is generic, Length<mm> will have its own copy, Length<Km> its own, and so on and so forth. Please note that ToSiFactor is the toBase of your approach.
The problem that I see is that as long as you are in the realm of simple units and up to the first derivative of time, things are simple. If you try to do something more complex, then you can see the drawbacks of this approach. Typing
var accel = new Acceleration<m, s, s>(1.2);

will not be as clear and "smooth" as
let accel = 1.2<m/sec^2>

And regardless of the approach, you will have to specify every math operation you will need with hefty operator overloading, while in F# you have this for free, even if the results are not meaningful as I was writing at the beginning.
The last drawback (or advantage depending on how you see it) of this design, is that it can't be unit agnostic. If there are cases that you need "just a Length" you can't have it. You need to know each time if your Length is millimeters, statute mile or foot. I took the opposite approach in SharpConvert and LengthUnit derives from UnitBase and Meters Kilometers etc derive from this. That's why I couldn't go down the struct path by the way. That way you can have:
LengthUnit l1 = new Meters(12);
LengthUnit l2 = new Feet(15.4);
LengthUnit sum = l1 + l2;

sum will be meters but one shouldn't care as long as they want to use it in the next operation. If they want to display it, then they can call sum.To<Kilometers>() or whatever unit. To be honest, I don't know if not "locking" the variable to a specific unit has any advantages. It might worth investigating it at some point.

A: I would like the compiler to help me as much as possible. So maybe you could have a TypedInt where T contains the actual unit.
    public struct TypedInt<T>
    {
        public int Value { get; }

        public TypedInt(int value) => Value = value;

        public static TypedInt<T> operator -(TypedInt<T> a, TypedInt<T> b) => new TypedInt<T>(a.Value - b.Value);
        public static TypedInt<T> operator +(TypedInt<T> a, TypedInt<T> b) => new TypedInt<T>(a.Value + b.Value);
        public static TypedInt<T> operator *(int a, TypedInt<T> b) => new TypedInt<T>(a * b.Value);
        public static TypedInt<T> operator *(TypedInt<T> a, int b) => new TypedInt<T>(a.Value * b);
        public static TypedInt<T> operator /(TypedInt<T> a, int b) => new TypedInt<T>(a.Value / b);

        // todo: m² or m/s
        // todo: more than just ints
        // todo: other operations
        public override string ToString() => $"{Value} {typeof(T).Name}";
    }

You could have an extensiom method to set the type (or just new):
    public static class TypedInt
    {
        public static TypedInt<T> Of<T>(this int value) => new TypedInt<T>(value);
    }

The actual units can be anything. That way, the system is extensible.
(There's multiple ways of handling conversions. What do you think is best?)
    public class Mile
    {
        // todo: conversion from mile to/from meter
        // maybe define an interface like ITypedConvertible<Meter>
        // conversion probably needs reflection, but there may be
        // a faster way
    };

    public class Second
    {
    }

This way, you can use:
            var distance1 = 10.Of<Mile>();
            var distance2 = 15.Of<Mile>();
            var timespan1 = 4.Of<Second>();

            Console.WriteLine(distance1 + distance2);
            //Console.WriteLine(distance1 + 5); // this will be blocked by the compiler
            //Console.WriteLine(distance1 + timespan1); // this will be blocked by the compiler
            Console.WriteLine(3 * distance1);
            Console.WriteLine(distance1 / 3);
            //Console.WriteLine(distance1 / timespan1); // todo!

A: See Boo Ometa (which will be available for Boo 1.0):
Boo Ometa and Extensible Parsing

A: I really liked reading through this stack overflow question and its answers.
I have a pet project that I've tinkered with over the years, and have recently started re-writing it and have released it to the open source at https://github.com/MafuJosh/NGenericDimensions
It happens to be somewhat similar to many of the ideas expressed in the question and answers of this page.
It basically is about creating generic dimensions, with the unit of measure and the native datatype as the generic type placeholders.
For example:
Dim myLength1 as New Length(of Miles, Int16)(123)

With also some optional use of Extension Methods like:
Dim myLength2 = 123.miles

And
Dim myLength3 = myLength1 + myLength2
Dim myArea1 = myLength1 * myLength2

This would not compile:
Dim myValue = 123.miles + 234.kilograms

New units can be extended in your own libraries.
These datatypes are structures that contain only 1 internal member variable, making them lightweight.
Basically, the operator overloads are restricted to the "dimension" structures, so that every unit of measure doesn't need operator overloads.
Of course, a big downside is the longer declaration of the generics syntax that requires 3 datatypes.  So if that is a problem for you, then this isn't your library.
The main purpose was to be able to decorate an interface with units in a compile-time checking fashion.
There is a lot that needs to be done to the library, but I wanted to post it in case it was the kind of thing someone was looking for.


text:
Q: If, elif, print based on three variables of an input in python HELP! I'm stuck with this python script. So basically I want my program to run the first part of the code when there is an input from recieved from the user for all three variables.
I was trying to basically have if there is . in a, dash in b, and . in c then run these print statements. Else do what's below. NOTE: The first code has different print statements from the others. I want it to run the first part of the code based on a,b,c all having an input. Appreciate the help
code
a = raw_input("Enter ip address: ")
b = raw_input("Enter range: ")
c = raw_input("Enter network: ")

#should print ip adress, range, and network combined
if '.' in a + '-' in b + '.' in c:
  ips = b.split('-')
  print 'config firewall address\n','edit "ip-' + str(a) + '"'
  print 'set subnet ' + str(a) + '/32'
  print 'next'
  print 'edit "ip-' + str(b) + '"'
  print ('set type iprange')
  print ('set start-ip '+ips[0])
  print 'set end-ip '+ips[1]
  print 'next'
  print 'edit "net-' + str(c) + '"'
  print 'set subnet ' + str(c) + ''
  print 'next'
  print 'end'

output
The rest of the code runs based on user input.
#SHOULD print ip adress, range, and network combined
Enter ip address: 10.203.1.10
Enter range: 10.228.50.88-10.228.50.91
Enter network: 172.27.0.0/16
config firewall address
edit "ip-10.203.1.10"
set subnet 10.203.1.10/32
next
end

I don't want the last output to be like that. This is my desired output.
Enter ip address: 10.203.1.10
Enter range: 10.228.50.88-10.228.50.91
Enter network: 172.27.0.0/16
config firewall address
edit "ip-10.203.1.10"
set subnet 10.203.1.10/32
next
edit "ip-10.228.50.88-10.228.50.91"
set type iprange
set start-ip 10.228.50.88
set end-ip 10.228.50.91
next
edit "net-172.27.0.0/16"
set subnet 172.27.0.0/16
next
end

What do I need to do?

A: If you want to check whether multiple conditions are true, instead of:
if '.' in a + '-' in b + '.' in c:
...you should use:
if all(['.' in a, '-' in b, '.' in c]):
...or...
if '.' in a and '-' in b and '.' in c:
You also need to make sure you indent your code properly.


text:
Q: Is polyspace deterministic? We have polyspace analysing our code and we have the feeling that polyspace is not being totally deterministic.
We are finding that some errors/violations on our code are not appearing on one report, and they show up in the next report withouth actually changing the affected code.
It is true that from report to report, the code has changed, but this is normally only adding comments and changing few routines out of the affected code.
At this point, however, we cannot guarantee we are not changing something somewhere else that might affect, although this does not seem to be the reason.
I would like to know if you have ever had this feeling when using polyspace and to know if polyspace might find some errors once, and skip them the next time and vice versa.

A: I did some research and reading. You can find a white paper on PolySpace here: http://subs.emis.de/LNI/Proceedings/Proceedings110/gi-proc-110-048.pdf
That explicitly states:

PolySpace Verifier, as an exhaustive approach,issues checks to prove
  the result of each and every  operation in the source code considering
  the variation domain for the variables involved in the respective
  operation

Basically, that means that your changes on the rest of the code might not seem to affect a specific scope, but they do.
EDIT: I would naively tend to think that static code analysis tools are deterministic, but as pointed out in the comments: some randomness/caching can be used to reduce the complexity. Even tough this shouldn't mean that the tool will randomly find errors/warnings


text:
Q: What makes a programming language fast? Or worded in a more relevant way, what characteristics of a programming language influence the fastness of the corresponding generated executable?
Sure that's the compiler which generate the executable which really matter. You may for example imagine something as advanced as a compilation chain able to infer an executable from a natural language description, asking relevant question with provided suggestions to disambiguate if probability to make a good match with given data is too low.
Now C is famous for enabling developers to get really fast executables, "portable assembler". But is that because the language ease the match between the source and target code, and in the same time, ease the development of optimized compilers? Or is that because the developers using C are more sensitive with how it works under the wood and so code with that in mind? Or some other reason?
When did people first start thinking 'C is portable assembler'?

A: C has remains the 'fastest' language because of its flexibility. It doesn't impose a rigid runtime model. Developers are free to create their own runtime structure, architecture, and data structures.
For example, 20 years ago processors were 'slow' (relative to memory speed) and many optimizations focused on looking up results in large tables of precomputed values. Now, processors are fast and memory is slow. Now, optimizations focus on cache efficiency - since large data tables will blow the cache, they are usually avoided and the tasks are shifting back to the processor.
Many languages are much more than just a language. Most modern languages include heavy runtime frameworks and libraries on which the speed depends. These runtime frameworks usually lock in fundamental data structures and memory management models. When hardware changes, inflexible frameworks become inefficient.
Because C compiles predictibly to native object code, and does not impose a heavy runtime, it has, and will continue to handle major hardware architectural changes and will always be among the fastest languages.

A: less code used for a problem where it took more code to solve in another programming language

A: The predominant characteristic that is considered to make a language fast is how well its data types correspond to machine data types.  Java is considered to be an efficient language because it has primitive data types. Conversely, the performance of anything written in any language which treats all types (even chars and ints) as objects, (as all scripting/untyped languages do,) is bound to suffer.

A: C is fast because there is no language beneath C except Assembly. So this is one reason.
Second, In which language Compiler is written is also matter because if language it self slow then then compiler written in that language is also slow. So, it will produce code but not so fast.
Third, Many time language implementation algorithm also play an important role say how language's datatype is implemented and so on.
Generating optimized code so can it run fast and also take less memory is in NP-Completeness.


text:
Q: Powershell+Sharepoint Online: Recycle Bin Recovery to Target Path Using Powershell, I have found it possible to audit and restore the recycle bin using: Get-PnPRecycleBinItem and Restore-PnpRecycleBinItem. What I cannot find though is how I would go about sending the recovered file to a designated location rather than the original. This particular mass-delete is requiring global action and I'd like to restore everything very carefully into a new sharepoint site and then sort it out from there with the user.
Is it possible to retrieve items from the recycle bin and restore to a target location? I'm willing to script this out - I thought about simply copying it from here and then deleting it to stage2 recycle bin to keep myself organized - that's not bad but I'm not sure how I would engage in a copy from this location.
My only other thought was to restore it, building a list all the while, and then to go through and move it to another location and delete the folder if/when required. Much more complex and way more noise for the sync client of all the users during this ~300k item process...
Thank you for any suggestions

A: No, we cannot move items in the recycle bin to other locations directly.  You have to restore the items in the recycle bin to original location, then move these files/folders to  another location.


text:
Q: How to write a map statement to compare each elements of two lists in haskell? I have two functions both of which return a list:
enter earth = head $ do
  lst <- earth
  return $ map (\x -> if (x == 0) then 2 else x) lst

helper earth = head $ do
  lst <- tail (earth)
  return lst

where earth is another function that returns a list of lists like [[1,2,3],[2,3,4],[4,7,3]]. In the helper function, I am returning the second element of this list of lists, i.e., the head of the tail. And in the enter function, only the head. Now I am writing another function and I want to pass these two functions as arguments to it. I'm doing this:
see :: [Int] -> [Int] -> [Int]
see enter helper = return $ map (\ x y -> if (x == 2) && (y == 0) then 2 else y) enter helper

I'm basically trying to do is to check if the list returned by enter has a 2 and the second list has a zero at that location, then change that 0 to 2 otherwise let the element in the second list be as it is.
What am I doing wrong here?
EDIT:
So, there is an earth function returning like this: [[0,0,1],[1,0,1],[0,0,0]]. The enter function, takes the head of earth(which is [0,0,1] and makes it like this: [2,2,1]. The helper function takes and returns the second element (the head of the tail) of the list of lists returned by earth (which is [1,0,1]). Now the see function, takes these [2,2,1] and [1,0,1] as two arguments, and if an element is 2 in the first list and 0 in the second list (i.e., from this example, the second element in both lists, then that 0 should become 2 in the second list, and what should be returned should be something like this: [1,2,1]

A: zipWith is the function that you're looking for. map only works on one list at a time, so your usage of it will result in a type error. If you just replace map with zipWith in that last line, it should work. Also, you should remove the return. In the context of a list, return only puts something into a singleton list: return x = [x]. Note that return is a function and is not really related to the return in C-influenced languages. I would also suggest not using do notation for lists at this point.
Also, the last function isn't using the other two functions, even though it uses those names. I'm not sure if this is what you want or not though. It is equivalent to a definition of see where you used the names x and y instead of enter and helper.
Here's an example of the behavior of zipWith:
λ> zipWith (*) [2, 3, 4] [10, 100, 1000]
[20,300,4000]

A: It looks like you want something like this:
       xs = [ ...,     1,     2,     0,     1, ... ]
       ys = [ ...,     3,     0,     4,     0, ... ]
zip xs ys = [ ..., (1,3), (2,0), (0,4), (1,0), ... ]
   result = [ ...,     3,     2,     4,     0, ... ]

result is the list ys with the zeros replaced with 2s where there is a 2 in the list xs.
So you can express this logic pretty much directly as a list comprehension:
result = [ r | (x,y) <- zip xs ys, let r = if y == 0 && x == 2 then 2 else y ]

A: map only walks over 1 list, but you try to walk over 2 lists at the same time, and calculate something.
So you need a function which takes a function with 2 parameters, 2 lists and returns a list with the same type of the result of the function: (a -> b -> c) -> [a] -> [b] -> [c]
And hoogle finds a function which has this property: zipWith
So you write a helper function which does what you want:
helper 0 2 = 2
helper _ y = y

now you write the see function and put the helper function in a where clause (you probably don't need that function later):
see a b = zipWith helper a b
    where helper 2 0 = 2
          helper _ y = y

I don't know why you use do but this is not necessary here.


text:
Q: Error when trying to select with comma separated lists I need to get the data shown from a mysql db. The code below I think presents what Im trying to do but the execution is definitely wrong. What do I need to change to get this to work?
SELECT
up.model AS style,
up.list_price AS price,
GROUP_CONCAT(t1.name) AS colorlist,
GROUP_CONCAT(t2.name) AS sizelist,
nr.title,
nr.body AS description,
FROM
uc_products up,
(SELECT c.name FROM uc_attributes a
       JOIN uc_product_options b ON (b.nid = a.nid)
       JOIN uc_attribute_options c ON (c.oid = b.oid AND c.aid = 6)
       WHERE a.nid = up.nid) AS t1,
(SELECT c.name FROM uc_attributes a
       JOIN uc_product_options b ON (b.nid = a.nid)
       JOIN uc_attribute_options c ON (c.oid = b.oid AND c.aid = 9)
       WHERE a.nid = up.nid) AS t2
LEFT JOIN node_revisions nr ON (nr.nid = up.nid)

The Error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM uc_products up, (SELECT c.name FROM uc_attributes a JOIN uc_product_options' at line 8

A: I think the problem is the comma before FROM. Try this:
SELECT
up.model AS style,
up.list_price AS price,
GROUP_CONCAT(t1.name) AS colorlist,
GROUP_CONCAT(t2.name) AS sizelist,
nr.title,
nr.body AS description
FROM
uc_products up,
(SELECT c.name FROM uc_attributes a JOIN uc_product_options b ON (b.nid = a.nid) JOIN uc_attribute_options c ON (c.oid = b.oid AND c.aid = 6) WHERE a.nid = up.nid) AS t1,
(SELECT c.name FROM uc_attributes a JOIN uc_product_options b ON (b.nid = a.nid) JOIN uc_attribute_options c ON (c.oid = b.oid AND c.aid = 9) WHERE a.nid = up.nid) AS t2
LEFT JOIN node_revisions nr ON (nr.nid = up.nid)

A: You have an extra comma after 'AS description' that needs removing.


text:
Q: Implementing a Generic C# class using method in common to others I have the following problem in C#.
I have two classes exposing some common members and methods, for example:
Class myClass01{
   public int a;
   public int b;
   public void method_01(){...}
   public void method_A(){...}
}

and
Class myClass02{
   public int a;
   public int b;
   public void method_01(){...}
   public void method_B(){...}
}

I want to create a new generic class that can use the common attributes/methods of both of them. For example:
Class myGeneric<T>{
   public T element;

   public int sum(){
       return element.a + element.b;
   }

   public void methodGeneric(){
       element.method_01();
    }
}

But with this kind of implementation I receive errors because elements are not accessible. Is there a way to a create a generic class using methods/attributes from different classes but equally defined?

A: The generic class you are making currently does not have a constraint to know from what class the generic type T must be derived from. Thus, it assumes object which does not recognized any customized public/protected fields, properties, and methods you implement.
If you want the generic T to recognize the public/protected fields, properties, and methods you have in common between two classes, you should create an interface which is implemented by both classes and you have the generic type T derived from that particular interface.
For example:
public interface ImyClass { //this is the common interface
    int a { get; set; }
    int b { get; set; }
    void method_01();
}

class myClass01 : ImyClass { //your special interface implementation for myClass01
    public int a { get; set; }
    public int b { get; set; }
    public void method_01() { }
    public void method_A() { }
}

class myClass02 : ImyClass {  //your special interface implementation for myClass02
    public int a { get; set; }
    public int b { get; set; }
    public void method_01() { }
    public void method_B() { }
}

Then in your generic, constraint the generic type with the interface
class myGeneric<T> where T : ImyClass {
    public T element;

    public int sum() {
        return element.a + element.b;
    }

    public void methodGeneric() {
        element.method_01();
    }
}

You could also use abstract or simple base class if the implementation for both methods (both method_01) happen to be exactly the same, for example:
public abstract class myAbstractClass { //this is the common abstract class or base class
    public int a;
    public int b;
    public void method_01(){ } // all your common implementations
}

public class myClass01 : myAbstractClass {
    public void method_A() { } //your special implementation for myClass01
}

public class myClass02 : myAbstractClass {
    public void method_B() { } //your special implementation for myClass02
}

class myGeneric<T> where T : myAbstractClass { //generic specifically from myAbstractClass
    public T element;

    public int sum() {
        return element.a + element.b;
    }

    public void methodGeneric() {
        element.method_01();
    }
}

In any case, a common inheritance is required to recognize the public/protected fields, properties, and methods.

A: Use Interfaces and "where" to get the members accessible. E.g.:
public class SortedList<T> : GenericList<T> where T : System.IComparable<T>

https://msdn.microsoft.com/en-us/library/kwtft8ak.aspx

A: Note that in addition to Ians answer when using an interface, the generic is not necessary anymore you could simple use
class myGeneric {
    public ImyClass element;

    public int sum() {
        return element.a + element.b;
    }

    public void methodGeneric() {
        element.method_01();
    }
}

Although it was not the actual question


text:
Q: AccessViolationException when calling WorkflowInvoker.Invoke I'm trying to run a parallel foreach loop with 32 threads.
This foreach loop is calling a:
WorkflowInvoker.Invoke(new MyWorkflow(), myInputDictionary)

The parallel foreach loop consists of a list of around 65000 items.
At some point, at around 6000 - 6700 items the invocation of WorkflowInvoker.Invoke(new MyWorkflow(), myInputDictionary) throws
an AccessViolationException with the message:
    "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
I have tried different things, like creating an instance of the WorkflowInvoker and passing an instance of MyWorkflow directly to the newly created WorkflowInvoker and then calling the Invoke method on the class.
Also just calling the WorkflowInvoker.Invoke as a static method, but it doesn't make a difference.
The application crashes at the same point every time. Because of the threads it's hard to debug and pinpoint exactly what is causing the trouble.
Of course the problems doesn't occur if I'm doing the calls in a normal foreach loop.
At first we thought the virtual machine was running low on memory, because the application started eating all available memory until it reached a limit of 85% of the total memory (4GB) and then it seemed to crash. So we changed the memory size to 1GB, to see if we could induce the exception earlier in the loop, but instead Windows started garbagecollecting, so in the end the exception still occured at the same point around 6000 - 6700 items.
Any suggestions as to what should be my next move, is much appreciated ;-)
-- EDIT - Added the full stacktrace --
at System.Reflection.Emit.ModuleBuilder.nCreateISymWriterForDynamicModule(Module module, String filename)
at System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternalNoLock(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark)
at System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternal(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark)
at System.Reflection.Emit.AssemblyBuilder.DefineDynamicModule(String name, Boolean emitSymbolInfo)
at System.Activities.Debugger.StateManager.InitDynamicModule(String asmName)
at System.Activities.Debugger.StateManager..ctor(Properties properties, Boolean debugStartedAtRoot)
at System.Activities.Debugger.DebugManager..ctor(Activity root, String moduleNamePrefix, String typeNamePrefix, String auxiliaryThreadName, Boolean breakOnStartup, WorkflowInstance host, Boolean debugStartedAtRoot)
at System.Activities.Debugger.DebugController.EnsureActivityInstrumented(ActivityInstance instance, Boolean primeCurrentInstance)
at System.Activities.Debugger.DebugController.ActivityStarted(ActivityInstance activityInstance)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
at System.Activities.Runtime.ActivityExecutor.ExecuteRootWorkItem.Execute(ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.OnExecuteWorkItem(WorkItem workItem)
at System.Activities.Runtime.Scheduler.Callbacks.ExecuteWorkItem(WorkItem workItem)
at System.Activities.Runtime.Scheduler.OnScheduledWork(Object state)
at System.Runtime.Fx.SendOrPostThunk.UnhandledExceptionFrame(Object state)
at System.Activities.WorkflowApplication.PumpBasedSynchronizationContext.WorkItem.Invoke()
at System.Activities.WorkflowApplication.PumpBasedSynchronizationContext.DoPump()
at System.Activities.WorkflowApplication.Invoke(Activity activity, IDictionary`2 inputs, WorkflowInstanceExtensionManager extensions, TimeSpan timeout)
at System.Activities.WorkflowInvoker.Invoke(Activity workflow, IDictionary`2 inputs, TimeSpan timeout, WorkflowInstanceExtensionManager extensions)
at System.Activities.WorkflowInvoker.Invoke(IDictionary`2 inputs)

-- Extra edit - added the method in question - Obfuscated it a bit to remove businesslogic names --
public MyOutputData InvokeMyWorkflow(MyInputData input)
{
      IDictionary<string, object> wfInput = new Dictionary<string, object>
       {
        { "ArgData", input }
       };
  MyWorkflow myWorkflow = new MyWorkflow();
  try
  {
       WorkflowInvoker invoker = new WorkflowInvoker(myWorkflow);
       IDictionary<string, object> output = invoker.Invoke(wfInput);
       return output["ArgData"] == null ? null : (MyOutputData)output["ArgData"];
  }
  catch (Exception ace)
  {
           Log.Error(ace.StackTrace);
       return null;
  }
 }


text:
Q: Padding changing the size of a div with box-sizing on Firefox I am trying to add a padding to an element inside a DIV. My problem is that it add this padding to the total size of my DIV.
I try to stop this with the following code in my div:
box-sizing: border-box;
ms-box-sizing: border-box;
webkit-box-sizing: border-box;
moz-box-sizing: border-box;

It works fine on Chrome but I still have the problem on Firefox. I can't understand why.
Anyone has an idea on how to fix this?
Many thanks

A: If you want to add extra padding to the width of a div:
div {
    // In this example total div width is 120px
    // box-sizing: content-box is the default style. No need to specify it.
    width: 100px
    padding: 0 10px;
}

Or if you want to make the padding part of the total div width:
div {
    // In this example total div width is 100px
    // support Firefox, WebKit, Opera and IE8+
    -moz-box-sizing: border-box;
    box-sizing: border-box; //always place the standard declaration last, so it overwrites browser specific ones in case they get deprecated
    width: 100px
    padding: 0 10px;
}


text:
Q: How to create a NSPredicate to find entries with leading numerical value? I'm using NSPredicates to fetch entities based on a name attribute. Creating a predicate for names beginning with letters was easy (@"name BEGINSWITH %@", searchLetter), however now I'd like to fetch all entities with a name that begins with a numerical value, or rather a non-alphabetical character.
What would be the appropriate predicate expression here?
Right now I don't want to get too deep into predicate programming, as this is all I need right now and time flies. So, please, don't point me to the Predicate Programming Guide, I just need that expression.. :)
Thanks alot guys!

A: If the MATCHES operator doesn't work with a fetch request, then you'll essentially have to do stuff manually:
NOT(name BEGINSWITH[cd] 'a' OR name BEGINSWITH[cd] 'b' OR ... OR name BEGINSWITH[cd] 'z')

That would get everything that does not start with a letter.  Likewise:
name BEGINSWITH[cd] '0' OR name BEGINSWITH[cd] '1' OR ... OR name BEGINSWITH[cd] '9'

Would get everything that does start with a number.
edit the comment prompted another idea:
If you could extract the first letter of the name, you could do:
NOT(name[0] IN %@), arrayOfLetters

(name[0] being the first character of name, and arrayOfLetters being an NSArray of the alphabetic characters)

A: You can use 'MATCHES' where you can use any regex (e.g. ^[0-9]) to compare. But as far as I know that does not work when dealing with Core Data.
Another soluton would be to use the new (OS X 10.6, iOS 4.0) predicateWithBlock: and check the condition yourself with string methods.


text:
Q: Cache with annotations, Mapkit and regions I have a question about MapKit.
I have to visualize annotations on map and I downloaded these from a server.
I would to implement an efficient cache system.
My idea is this:
I can mantain an array of Regions an when the user make a pan on the map I have to calculate the new region..
If this region is contained into a my regions list I can visualize the annotations otherwise I have to request the new region  to the server.
How can I calculate the region when the user make a pan on the map?
Are there some methods to calculate if the region is contained into other region?
Are there some example project about this idea?

A: There is no API for per-map ID, but there is -[RMTileCache removeAllCachedImagesForCacheKey:]. You can construct a given cacheKey for a tile source if you have a look at how it is made in that tile source's code.


text:
Q: Unit Test of Retrofit 2 api call with Mockito I need some advices on how to mock a rest api. My application is in MVP architecture.
My interface for API:
public interface MyAPI {

    @GET("{cmd}/{userName}/{password}")
    Observable<Response> login(
        @Path("cmd") String cmd,
        @Path("userName") String userName,
        @Path("password") String password
    );

My service:
public class MyService implements IService {

    private static MyService mInstance = new MyService();
    private MyAPI mApi;

    public static MyService getInstance() {
        return mInstance;
    }

    private MyService() {

        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(Config.DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Config.kBaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(httpClientBuilder.build())
            .build();

        this.mApi = retrofit.create(MyAPI.class);
    }

    public void login(
        Subscriber<Response> subscriber,
        String userName,
        String password) {
        mApi.login(Config.kLoginCmd,userName,password)
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(subscriber);
    }

My presenter class:
public class LoginPresenter implements LoginContract.Presenter {

    LoginContract.View mView;
    IService mService;
    ISession mSession;

    public LoginPresenter(LoginContract.View loginView, IService service, ISession session) {
        mView = loginView;
        mService = service;
        mSession = session;
    }

    @Override
    public void login(String email, String password) {

        Subscriber<Response> subscriber = new Subscriber<Response>() {
            @Override
            public void onCompleted() {
                mView.showLoading(false);
            }

            @Override
            public void onError(Throwable e) {
                mView.showError(e.getLocalizedMessage());
            }

            @Override
            public void onNext(Response response) {
                if (response.getResults().getStatus().equalsIgnoreCase(Config.kResultCodeOK)) {
                    mView.loginSuccess();
                } else {
                    mView.showError(response.getResults().getStatus().getErrmsg());
                }
            }
        };

        mView.showLoading(true);
        mService.login(
            subscriber,
            email,
            password);
    }

There is another way to test my presenter by writing a Mock service. But I don't like that so much and I think Mockito could help.
Here is my test class:
public class LoginPresenterMockTest {

    private LoginPresenter mLoginPresenter;

    @Mock
    LoginContract.View view;
    @Mock
    IService service;
    @Mock
    ISession session;

    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        mLoginPresenter = new LoginPresenter(view, service, session);
    }

    @Test
    public void testLoginWithCorrectUserNameAndPassword() throws Exception {
        mLoginPresenter.login("user@email.com","password");
        verify(view).loginSuccess();
    }

}

What I want to do is I mock the response data call loginSuccess() when the response is correct.
Of course my current test will not work. I need some advices on how to mock this? Any idea? Thanks.

A: You can do it in next way:
@Test
public void testLoginWithCorrectUserNameAndPassword() throws Exception {
    // create or mock response object
    when(service.login(anyString(), anyString(), anyString).thenReturn(Observable.just(response));
    mLoginPresenter.login("user@email.com","password");
    verify(view).loginSuccess();
}

@Test
public void testLoginWithIncorrectUserNameAndPassword() throws Exception {
    // create or mock response object
    when(service.login(anyString(), anyString(), anyString).thenReturn(Observable.<Response>error(new IOException()));
    mLoginPresenter.login("user@email.com","password");
    verify(view).showError(anyString);
}

A: Thanks for @Ilya Tretyakov, I came out this solution:
private ArgumentCaptor<Subscriber<Response>> subscriberArgumentCaptor;

@Test
public void testLoginWithCorrectUserNameAndPassword() throws Exception {
    mLoginPresenter.login("user@email.com","password");
    // create the mock Response object
    Response response = ......

    verify(service, times(1)).login(
        subscriberArgumentCaptor.capture(),
        stringUserNameCaptor.capture(),
        stringPasswordCaptor.capture()
    );

    subscriberArgumentCaptor.getValue().onNext(response);
    verify(view).loginSuccess();
}


text:
Q: Solution/Design for distributed database with time-by-time synchronization, solution for PK/FK This question is more about the architecture and idea then about code.
The issue:
Let's have a backend main DBs that stores everything.
Then we have a frontend local database (SQLLite or similar), that stores only the relevant data for user/device.
The user can create data on the frontend. However several users can create the same kind (ie. receipt) at the same time and if we would use a simple int autoincrement PK, there would be collisions on the backend.
The proposed solution is:
we use composite PK, where the PK consists of:
-autoincrement integer
-device ID
-user ID
Now, logicaly, the deviceID and userID should be FK to a table of devices and users, however for several reasons, its not practicable/possible to store all the devices/users on each frontend device, so the FK makes it problematic.
The proposed solution for this would be to ommit the FK req on the fronend and check for data integrity only on the backend, but to be honest i am not sure the risk/gain is worth it.
Has anyone been to this point and/or has some experience after deploying it?
What are your thoughts?
Thank you very much.

A: Vlad,
I think the difficult problem you are trying to address is:  How can a device generate an identifier unique across all devices?  The answer in the past to that question has been to create a "Global Unique IDentifier" (GUID) or a "Universally Unique IDentifier" (UUID) that incorporates uniquely identifying information such as "device id", "timestamp", and random numbers.  The IETF standard for doing such can be found here: RFC4122.
Consequently, most database vendors provide at least a UUID() or GUID() SQL function to return one of these unique identifiers.  BTW, I don't know if SQLLite provides one, but I know that SequelSphereDB does provide a UUID() function. The end result is that you can use these to create unique identifiers for rows.
So, instead of having a combination primary key consisting of a number, a device ID, and a User ID, have a single column CHAR(36) which stores a UUID generated on-the-fly at the time of row creation.
UUID Pros:

*

*Single Column

*Generated at client without the need to contact any other device

*"Guaranteed" to be unique, or at least much more so than the alternate possibilities.

UUID Cons:

*

*Column Storage is big:  CHAR(38).

*Generation is slow in comparison to surrogate key one-up generators.


text:
Q: dynamic drop down box from mysql I got 3 input fields and each field are getting their data from its own tables called Tour type, country and destination respectively as shown
    Tour Type
    <select id="element_11" name="element_11" required>
    <option value="" selected="selected">--Select--</option>
    <?php
        while($row=mysql_fetch_array($sql))
        {
          $tour_type_id=$row['tour_type_id'];
          $name=$row['tour_name'];
          echo "<option value='$tour_type_id'>$name</option>";
        }
        ?>
    </select>

    Country
    <select id="element_12" name="element_12" required>
    <option value="" selected="selected">-- Select --</option>
    <?php
    $sql=mysql_query("Select countries_id,countries_name from countries");
        while($row=mysql_fetch_array($sql))
        {
          $cid=$row['countries_id'];
          $name=$row['countries_name'];

          echo "<option value='$cid'>".$name."</option>";
        }
        ?>
        </select>

    Destination
    <select id="element_13" name="element_13" required>
        <option value="" selected="selected">-- Select --</option>
    <?php
    $sql=mysql_query("Select destination_id,destination_name from destination");

        while($row=mysql_fetch_array($sql))
        {
          $destination_id=$row['destination_id'];
          $name=$row['destination_name'];

          echo "<option value='$destination_id'>".$name."</option>";
        }
        ?>

    </select>

This is what i got as my 3 database tables i.e. tourtype, countries and destination respectively:

I am trying to make each field dependent on each other more like a dependent drop down box. For example if i select a tour type then the 2nd drop down should populate options only relevant to what is selected from the 1st drop down and so on. In this case for e.g if i select culture ,then the 2nd drop down should only show amsterdam and belgium.
Can anyone help me on this.

A: Please go through this link dependent dropdown using jquery ajax
How he maintained the relations among the entities
let me explain you if you want countries based on tour then you need to relate the country table with tour table as you have shown the country table in image it contains only two columns countries_id  and countries_name you have to add one more column  that is tour_type_id when you select any tour you will get the tour_type_id then your query should be
SELECT * FROM `countries`  where `tour_type_id` = 1 //this is the id you will get from the tour_type select box

and this will populate the related countries same case for the destination related this table with country_id
Hope it makes sense

A: There are two ways to sole this.. you can use use php with a page refresh and 2nd way use jQuery ajax to populate fields accordingly.

A: as i am an asp.net developer i can suggest you put your 2nd and 3rd drop down in an update panel(ajax update panels) then in your 2nd drop down query make it like $sql=mysql_query("Select countries_id,countries_name from countries where tour_type_id="+element_11.SelectedItem.Value+""); it will select those values whose tour_type_id is same as you selected in first drop down, same logic can be use in 3rd drop down as well


text:
Q: C++ delete element function in a doubly linked list I'm fairly new to C++ and it's data structures. I've made a few functions for my Doubly Linked List Class but i'm having trouble in the delete functions specifically. I've made a deleteHead() function which delete's the first node in the list, a deleteTail() function which deletes the last node in the list and finally a deleteElement(Item) function which goes over the list and deletes the node which has that the Item in it.
Problem is that whenever I try to delete the only remaining node from the list, the program crashes. i.e If I insert a node and then I call the deleteElement function on the same node (and if the node I inserted is the only node in the list) the program crashes.
here's my code.
template <class T>
void LinkedList<T>::deleteElement(T item)
{
    ListItem<T>* current = head;
    ListItem<T>* temp;
    if (head == NULL) {                         // if list is empty end the function
        return;
    }
    while (current) {
        if (current->value == item) {
            if (current == head) {              // if item is in the head
                deleteHead();
            }
            else if (current == getTail()) {    // if item is in the tail
                deleteTail();
            }
            // if item is between two nodes
            else if (current != head && current != getTail()) {
                temp = current;
                temp->prev->next = temp->next;
                temp->next->prev = temp->prev;
                current->next = NULL;
                current->prev = NULL;
                if (current->next == NULL) {
                    deleteTail();
                }
            }
        }
        current = current->next;
    }
}

// Delete the Head Node
template <class T>
void LinkedList<T>::deleteHead()
{
    if (head != NULL) { // as long as head is not null, delete head
        ListItem<T> *current = head;
        head = head->next;
        current->next = NULL;
        head->prev = NULL;
    } else {return;} // if head is null, end the function without doing anything
}

// Delete Tail Node
template <class T>
void LinkedList<T>::deleteTail()
{
    ListItem<T> *tail = getTail();
    tail = tail->prev;
    tail->next->prev = NULL;
    tail->next = NULL;
}

A: There are several issues in your code. First of all, you're not checking any pointers before you access them. For example, here:
temp = current;
temp->prev->next = temp->next;
temp->next->prev = temp->prev;

If there's only one element in the list, then its next and prev members will presumably be null. That means trying to assign something to temp->prev->next or temp->next->prev will be an access violation.
The same applies elsewhere, including this line at the end of your while loop:
current = current->next;

At that stage, current could hypothetically have been deleted, meaning trying to access its next member should fail. It probably won't fail at the moment though because of another problem...
Very importantly, you're not actually deleting anything. C++ doesn't have a garbage collector, so you can't just set a raw pointer to null and forget about it. You have to call delete on it to destroy and deallocate the object, otherwise it causes a memory leak. You'll need to fix that throughout your code, and then probably revise all your functions. You need to be very careful not to access an object after it's deleted.
With that said, instead of using raw pointers, you should really use smart pointers (i.e. std::shared_ptr). They take care of deleting the object for you when nothing else has a pointer to it. You still need to avoid accessing a deleted object, but it makes coding simpler, and hopefully more modern/robust.

A: Suggestions:
Step #1 - Add member variable ListItem<T>* tail to class ListItem<T>.
Step #2 - Replace all calls to getTail() with tail.
Step #3 - In function deleteElement, you can replace:
else if (current != head && current != tail)

with:
else

Step #4 - In function deleteElement, you should replace:
current->next = NULL;
current->prev = NULL;
if (current->next == NULL)
    deleteTail();

with:
delete current;

Step #5 - Rewrite function deleteHead as follows:
ListItem<T>* current = head;
if (head == tail)
    head = tail = NULL;
else
    head = head->next;
delete current;

Step #6 - Rewrite function deleteTail as follows:
ListItem<T>* current = tail;
if (tail == head)
    tail = head = NULL;
else
    tail = tail->prev;
delete current;

A: Got the answer right. This was a question in my Data Structures assignment. Here's the code I implemented. Yes, i'm aware it has redundancies and inefficiencies but I had to work within the framework of the assignment.
This is my deleteElement() Function:
template <class T>
void LinkedList<T>::deleteElement(T item)
{
    ListItem<T>* current = head;
    ListItem<T>* temp;
    if (head == NULL) {                // if list is empty end the function
        return;
    }
    while (current) {
        if (current->value == item) {
            if (current == head) {              // if item is in the head
                deleteHead();
            }
            else if (current == getTail()) {    // if item is in the tail
                deleteTail();
            }
            else if (current != head && current != getTail()) {
            // if item is between two nodes
                temp = current;
                temp->prev->next = temp->next;
                temp->next->prev = temp->prev;
                current->next = NULL;
                current->prev = NULL;
                if (current->next == NULL) {
                    deleteTail();
                }
            }
        }
        current = current->next;
    }
}


text:
Q: How to encode a not equal to operator to filter a URL? Django I am trying to filter out some values from a Web API and I am encoding my requests into python dictionaries to avoid receiving the complete data set from the URL, however, I want to implement a not equal operator where purchase is not equal to pets. How can I do that?
from django.shortcuts import render
from django.http import JsonResponse

from rest_framework.views import APIView
from rest_framework.response import Response
from collections import Counter
from datetime import datetime, timedelta
import json, urllib.request, dateutil.parser, urllib.parse

url = "http://10.61.202.98:8081/T/ansdb/api/rows/dev/data/tickets"

    #not equal to parameter should be applied here
    parameters = {'user': 'P. J.', 'purchase':'pets'}

    encoded_parameters = urllib.parse.urlencode(parameters)
    encoded_parameters = encoded_parameters.encode('utf-8')
    make_request = urllib.request.Request(url,encoded_parameters)

    with urllib.request.urlopen(make_request, timeout=15) as url:
        complete_data_user = json.loads(url.read().decode())


text:
Q: c# - cpu friendly single thread console app that do something every minute I wrote a c# console application, which should do a task (e.g calling a method) once a minute. The Basic structure is looking like following
while(true)
{
Thread.Sleep(10000)
// Call methodA
}

Sadly that while infinity loop produces a high cpu usage. I've read that Threads are more cost-efficient than infinite while loops. So i wrote that piece of code into my program.cs:
timer.Elapsed += New ElapsedEventHandler(methodA);
timer.Intervall = 10000;
timer.Enabled = True;

After that piece of code my app is shutting down. Even the thread wont be executed anymore and methodA will never be called. So from my point of view, i need to embed that piece of code with a while loop again. I think there are many better ways, e.g. via WaitHandler. But its unclear to me, how i can keep my app alive. May someone can give me a code Example

A: The reason your application closes when you try to use the event might be that it reaches the end of the main method, causing the application to close.
One fairly simple change would be to make your console app use an async main method. That way you should be able to replace the Thread.Sleep with await Task.Delay(...). This will use a timer behind the scene, while still preventing it from closing until it is done.
There might not be any real advantage however for a console application. Task.Sleep should sleep the current thread, and while sleeping it will not use any CPU time. While await Task.Delay will free the thread to do other things, it will not help if there are no other things to do.


text:
Q: LaTeX Beamer Block Title Spacing is different between block types I'm having an issue with the Blocks from the Beamer Package. The spacing below the title in these blocks is different between the different block types, in my case between exampleblock and alertblock. Here's an image that illustrates what I mean:

As you can see, the title in the top example block is closer to the body than the title of the bottom alert block. I would like to have the example block look the same as the alert block. How can I go about this?
Here's a minimal working example of my code:
\documentclass[aspectratio=169,xcolor=dvipsnames]{beamer}
\setbeamertemplate{navigation symbols}{}

\definecolor{blue}{rgb}{0,0.568627,0.862745}
\definecolor{lightblue}{rgb}{0.784313,0.901960,0.980392}
\definecolor{grey}{rgb}{0.713725,0.745098,0.776470}
\definecolor{lightgrey}{rgb}{0.898039,0.909803,0.921568}

\usecolortheme[named=black]{structure}

\setbeamertemplate{blocks}[default]
\setbeamercolor{block title}{bg=blue,fg=white}
\setbeamercolor{block body}{bg=lightgrey}
\setbeamercolor{block title alerted}{bg=white}
\setbeamercolor{block body alerted}{bg=lightblue}
\setbeamercolor{block title example}{fg=blue}
\setbeamercolor{block body example}{bg=lightblue}

\setbeamertemplate{itemize items}[circle]
\setbeamertemplate{itemize item}{\color{blue}$\bullet$}
\setbeamertemplate{itemize subitem}{\color{blue}$\bullet$}

\setbeamertemplate{frametitle}{\vspace*{1.7cm}\textbf{\small\insertframetitle}}

\begin{document}
    \frame {
        \frametitle{Vor-und Nachteile}
        \begin{exampleblock}{Vorteile}
            \begin{itemize}
                \item Vorteil 1
                \item Vorteil 2
            \end{itemize}
        \end{exampleblock}
        \begin{alertblock}{Nachteile}
            \begin{itemize}
                \item Nachteil 1
                \item Nachteil 2
            \end{itemize}
        \end{alertblock}
    }
\end{document}

Compiled with MiKTeX XeTeX on Windows 10

A: The difference between your example and alert blocks is that in one case you set the block title background colour to white, in the other case you don't set it. Beamer uses different margins for empty block backgrounds.
You can avoid the problem by either setting the colour for both cases or leave it empty for both, just be consistent.
\documentclass[aspectratio=169,xcolor=dvipsnames]{beamer}

\definecolor{blue}{rgb}{0,0.568627,0.862745}
\definecolor{lightblue}{rgb}{0.784313,0.901960,0.980392}
\definecolor{grey}{rgb}{0.713725,0.745098,0.776470}
\definecolor{lightgrey}{rgb}{0.898039,0.909803,0.921568}

\setbeamercolor{block title}{bg=blue,fg=white}
\setbeamercolor{block body}{bg=lightgrey}
\setbeamercolor{block title alerted}{bg=white}
\setbeamercolor{block body alerted}{bg=lightblue}
\setbeamercolor{block title example}{fg=blue,bg=white}
\setbeamercolor{block body example}{bg=lightblue}

\begin{document}
    \frame {
        \frametitle{Vor-und Nachteile}
        \begin{exampleblock}{Nachteile}
                    \begin{itemize}
                        \item Nachteil 1
                        \item Nachteil 2
                    \end{itemize}
        \end{exampleblock}
        \begin{alertblock}{Nachteile}
            \begin{itemize}
                \item Nachteil 1
                \item Nachteil 2
            \end{itemize}
        \end{alertblock}
    }
\end{document}


text:
Q: Is this code correct to send email (django)? Test.py
email = EmailMessage()
email['from'] = 'Your Name'
email['to'] = 'name@gmail.com'
email['subject'] = 'Welcome to
Ourr Website!'

email.set_content("Hope You are
doingg great.")

with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
    smtp.ehlo()
    smtp.starttls()
    smtp.login('example@gmail.com', 'password: ********')
    smtp.send_message(email)
    print("Done")

When I execute I'm getting timeout error(10060). Can any one help?

A: For emails, you will need to specify:
EMAIL_HOST
EMAIL_USE_TLS
EMAIL_PORT
EMAIL_HOST_USER
EMAIL_HOST_PASSWORD

(If you're using Gmail for sending Django emails, you will need to allow less secure access. More info on my answer here)
I'm going to paste a block of code that I reuse in all my projects. Feel free to customize it to your benefit.
from django.core.mail import send_mail, EmailMultiAlternatives
from django.template.loader import get_template

def send_email(email, subject, msg, username):
    message = EmailMultiAlternatives(subject=subject, body=msg, from_email='email@gmail.com', to=[email])
    html_templ = get_template("app/email.html").render({'email':email,'username': username})
    message.attach_alternative(html_templ, "text/html")
    message.send()
    print("email sent")


text:
Q: tsql breaking a comma seperated string and then looping i have comma seperated string
a=1,2,3,4

now i want to break this string and then loop through it using 1,2,3 etc in the query in tsql in sql server 2008
set @sql = @sql + ' and  (ClassicStation.int_WheatherTypeId = a[i]) AND (ClassicStation.int_MeasurementId IN (1,2)) or'

A: maybe fn_split is an option check http://odetocode.com/code/365.aspx

A: In your example it looks to me like you can just do this:
set @sql = @sql + 'and  (ClassicStation.int_WheatherTypeId in ('+@a+'))
AND (ClassicStation.int_MeasurementId IN (1,2))'

Otherwise you can split the string with the split function that is located everywhere or
like this
declare @a varchar(max)
set @a ='1,2,3,4' + ','

;with csv (col, pos) as
(
select left(@a, charindex(',', @a) -1),charindex(',', @a)
union all
select substring(@a, pos +1, charindex(',', @a, pos +1) - pos-1),
charindex(',',@a, pos+1) from csv
where pos < len(@a)
)
select * from csv


text:
Q: Why does my gmod server only run locally? I am running Debian on my vServer. I have installed the Garrys Mod server using Steam CMD. I try to run it via
./srcds_run -console -game garrysmod +maxplayers +host_workshop_collection 252617757 -authkey ################################

It seems to start normally, the only thing weird is that it only runs locally. The last line it print while starting is
Network: IP 127.0.1.1, mode MP, dedicated Yes, ports 27015 SV / 27005 CL

Even if I add -host domain.tld or -host 12.34.56.78 it will only run on localhost and cannot be reached by clients.
Can someone help me?

A: The reason was, that it had problems parsing the server.cfg and therefore dind't found a map. You can fix it by either adding '+map ttt_mapname' to the command or 'map ttt_mapname' to the file.


text:
Q: Dynamic execution for procedure sp_dropserver I have the following stored procedure that drops a linked server dynamically according to a passed server name
CREATE PROCEDURE [Common].[sprocServiceConfig_DropLinkedServer]
     (@ServerName NVARCHAR(MAX))
AS
BEGIN
    DECLARE @SQLQuery NVARCHAR(MAX)

    SELECT
        @SQLQuery = N'master.sys.sp_dropserver  ''' + @ServerName+ ''' ,  ''droplogins'' '

    EXECUTE @SQLQuery
END

I can't execute sp_dropserver dynamically. I get the error

Can't find stored procedure sp_dropserver

I can execute it in non-dynamic mode like
EXEC master.sys.sp_dropserver 'Test-PC' , 'droplogins'

Any ideas, please?

A: For the dynamic queries, you need to use sp_executesql.
Try changing from
 @SQLQuery = N'master.sys.sp_dropserver  ''' + @ServerName+ ''' ,  ''droplogins'' '

 EXECUTE @SQLQuery

TO
 @SQLQuery = N'EXEC master.sys.sp_dropserver  ''' + @ServerName+ ''' ,  ''droplogins'' '

 EXECUTE sp_executesql @SQLQuery

A: CREATE PROCEDURE [Common].[sprocServiceConfig_DropLinkedServer]
    (@ServerName VARCHAR(MAX))
AS
BEGIN
    DECLARE @SQLQuery VARCHAR(MAX)

    SELECT @SQLQuery = ''''+@ServerName+ ''' ,  ''droplogins'''

    EXEC master.sys.sp_dropserver  @SQLQuery
END

A: You just need to pass it in braces:
EXECUTE (@SQLQuery)


text:
Q: If loop in jquery is not working i want to add a class to a tag using jquery based on a if condition
the code is
  if ($(".asp:contains('Home')")) {
    $("ul.nav-pills a:contains('Home')").
    parent().addClass('active');
}
else if ($(".asp:contains('List')")) {
    $("ul.nav-pills a:contains('List')").
    parent().addClass('active');
}

am i doing it right?

A: $() returns a jQuery object, always. jQuery objects are not falsey. If you want to see if anything matched, use either .length or [0]
So:
if ($(".asp:contains('Home')")[0]) {
    $("ul.nav-pills a:contains('Home')").parent().addClass('active');
}
else if ($(".asp:contains('List')")[0]) {
    $("ul.nav-pills a:contains('List')").
    parent().addClass('active');
}