text:
Q: Suitable ObservableCollection I am creating a WPF application that displays thousands of records in the datagrid. I'm loading the data coming from external source asynchronously in ObservableCollection and binding it to the datagrid. There will be several addition and updates to the grid all day long.
Performance wise is ObservableCollection suitable for this kind of application or should I look for ObservableDictionary or any other suitable collection?

A: I've used it for real-time display of up to 10,000 records without any problems. Once you start manipulating that many records the bottlenecks tend to be algorithm selection and problems with data virtualization (or lack thereof) rather than which collection class you use. That said, if you're worried about it then there's an article here with a WPF-decoupled ObservableCollection that you could try using instead.

A: DataGrid usses UI virtualization in order to paint only whats visible on the view port area.
This reduces the number of UI elements which created and therefor makes it better in memory and performance.
However, When you are dealing with ObservableCollections which contains thousands of Items you should consider using also Data virtualization techniques.
I would recommend to go KIS (Keep It Simple) and go ahead and try the simplest approch:
Just use the .NET ObservableCollection.
If you are experinced laggy UI during updates you need to consider trying some kind of ObservableCollection which allows blocking UI updates during update phase (In case you need to update the collection in lots of items in short time).
If you are experince laggy UI during scrolling or selcting, or your memory is too high, you need to consider Data virtualization also.
Good luck

A: ObservableCollection notifies View for every item that is added to it, and it does not support AddRange() method. I would recommend and extended class for ObservableCollection that supports AddRange() Method posted in this Answer
This Class get updated for the entire bulk. Instead of each Item. Rest of performance will be responsibility of DataGrid which by default supports Virtual StackPanel


text:
Q: How to make "Load More Articles" button? (similar to Facebook, twitter etc.) I am working on a site where users post their small articles. All articles display on my homepage. I would like to display 20 articles and then have "Load More" button at the bottom that ,when clicked, loads 10 more articles and again when clicked loads 10 more articles and so on.

A: Limit your initial results with a SQL limit (or something similar).
Then attach a click event to your button which triggers an ajax load of the next 10 articles.
(Not the most extensive answer, but then, neither is your question ;)).
(Tip: use jquery, it takes a lot of (event handling / ajax) out of your hands..)
Edit: Okay, try to combine the following:
http://api.jquery.com/click/
http://www.asp.net/ajaxlibrary/jquery_webforms_dynamic_load.ashx
http://weblogs.asp.net/hajan/archive/2011/06/27/ajax-based-data-loading-using-jquery-load-function-in-asp-net.aspx
It's actually pretty basic what you try to do. Try to read some tutorials about jQuery with ASP:)!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How was the first magnet made? An iron ore (natural magnet) in the earth's crust gets magnetized due to another magnet near it which aligns all its domains in one direction. We mine up that ore and use it to make other magnets (artificial magnets). The original magnet that had magnetized the ore had itself got magnetized due to another magnet. This forms a chain. But, how would have the first magnet been made??

A: You don't need a magnet to create another one. That's an incorrect assumption.
Magnets are created by running an electrical current through a material, so there is no need to have a 'first magnet'.
This is happening 'naturally' in the earth core, in the sun, and in other stars.
Check the Maxwell equations, which in a nutshell say that every moving charge creates a magnetic field.

A: Protons, neutrons and electrons are permanent magnets. As far as we know these always existed. When heavier elements were and are aggregated in exploding stars, some of these have permanent magnetic moments as well. During planetary formation these atoms aggregated to make ferromagnetic ores that on planets like Earth were magnetised by the planetary magnetic field.


text:
Q: From Erlang to Python and function overloading in Python Interestingly, do any of the users of stack overflow write in a functional paradigm or not?
I rewrite the program from erlang to python. I can't understand how to do this, given that in python there is no function overload, which is so needed in this code. In general, in python there are not many convenient things that erlang has, for example, passing an empty list [] or a list of [Head | Tail] as function parameters.
I rewrote a bit, but I feel that this is a little like a functional style (except for recursion).
Maybe someone is ready to help me rewrite the code, or at least answer the questions that I asked above?
Erlang code:
-module(dik).
-export([read_graph/1]).
-export([dijkstra/2]).
-export([start/0]).

% The file contains an adjacency list representation of an undirected weighted graph.
% Each row consists of the node tuples that are adjacent to that particular vertex along with the length of that edge.
% Returns a dictionary of VertexNumber -> [Edge]
%   Where Edge is {edge, {vertex, From}, {vertex, To}, Weight}
read_graph(FileName) ->
    {ok, Device} = file:open(FileName, [read]),
    Nodes = dict:new(),
    parse_rows(Device, Nodes).

parse_rows(Device, Nodes) ->
    case io:get_line(Device, "") of
        eof -> Nodes;
        Line -> [VertexNumString | Row] = string:tokens(Line, " \t\n"),
                VertexNum = list_to_integer(VertexNumString),
                case dict:is_key(VertexNum, Nodes) of
                    false -> NewNodes = dict:store(VertexNum, [], Nodes)
                end,
                NewNodes2 = get_edges_from_line(NewNodes, VertexNum, Row),
                parse_rows(Device, NewNodes2)
    end.

parse_edge(Nodes, FromVertexNum, Val) ->
    [VertexString, WeightString] = string:tokens(Val, ","),
    [ToVertexNum, Weight] = [list_to_integer(VertexString), list_to_integer(WeightString)],
    dict:append(FromVertexNum, {edge, {vertex, FromVertexNum}, {vertex, ToVertexNum}, Weight}, Nodes).

get_edges_from_line(Nodes, _, []) ->
    Nodes;

get_edges_from_line(Nodes, VertexNum, [Head | Tail]) ->
    NewNodes = parse_edge(Nodes, VertexNum, Head),
    get_edges_from_line(NewNodes, VertexNum, Tail).

% Performs dijkstras shortest path algorithm on the given graph (Dictionary of VertexNumber -> [Edge]), starting at StartNode.
% Returns a Dictionary of VertexNumber -> Distance.
dijkstra(Nodes, StartNode) ->
    NewNodes = dict:map(fun(Key, Val) -> {if Key == StartNode -> 0; true -> infinity end, not_visited, Val} end, Nodes),
    dict:map(fun(_, {Distance, _, _}) -> Distance end, explore_nodes(NewNodes, StartNode, [StartNode])).

% Closest node returns the node with the lowest distance from the given list of nodes.
closest_node(Nodes, Unvisited) ->
    closest_node(Nodes, Unvisited, none, infinity).

closest_node(_, [], MinNode, _) ->
    MinNode;

closest_node(Nodes, [CurNode|Unvisited], MinNode, Distance) ->
    {CurDistance, Visited, _} = dict:fetch(CurNode, Nodes),
    % Note that any number is < any atom, so 43523452345 < infinity is true.
    if CurDistance < Distance andalso Visited == not_visited ->
        closest_node(Nodes, Unvisited, CurNode, CurDistance);
       true ->
        closest_node(Nodes, Unvisited, MinNode, Distance)
    end.

% Explore the given Nodes starting from NodeNum.
explore_nodes(Nodes, NodeNum, Unvisited) ->
    {NewNodes, NewUnvisited} = explore_node(Nodes, NodeNum, Unvisited),
    NextNode = closest_node(Nodes, NewUnvisited),
    if NextNode == none ->
        Nodes;
       true ->
        explore_nodes(NewNodes, NextNode, NewUnvisited)
    end.

% Convenience function to fetch node from dictionary so we can pattern match on whether it's been visited.
explore_node(Nodes, NodeNum, Unvisited) ->
    explore_node(Nodes, NodeNum, dict:fetch(NodeNum, Nodes), Unvisited).

% Already been visited: Do Nothing.
explore_node(Nodes, _, {_, visited, _}, Unvisited) ->
    {Nodes, Unvisited};

% Go through all the edges of the current node and update the tentative distance of the connected nodes.
% Add any unvisited nodes this node is connected to to the unvisited list.
explore_node(Nodes, NodeNum, {FromDistance, not_visited, [Edge|Edges]}, Unvisited) ->
    {edge, {vertex, NodeNum}, {vertex, ToVertexNum}, Weight} = Edge,
    {ToDistance, ToVisited, ToEdges} = dict:fetch(ToVertexNum, Nodes),
    if (ToDistance == infinity) orelse (Weight + FromDistance < ToDistance) ->
        NewNodes = dict:store(ToVertexNum, {Weight + FromDistance, ToVisited, ToEdges}, Nodes);
       true ->
        NewNodes = Nodes
    end,
    if ToVisited == not_visited ->
        NewUnvisited = [ToVertexNum | Unvisited];
       true ->
        NewUnvisited = Unvisited
    end,
    explore_node(NewNodes, NodeNum, {FromDistance, not_visited, Edges}, NewUnvisited);

% Out of edges, this node has now been visited.
explore_node(Nodes, NodeNum, {FromDistance, not_visited, []}, Unvisited) ->
    % We have looped through all the edges so we need another dictionary fetch to get them back.
    {FromDistance, not_visited, OriginalEdges} = dict:fetch(NodeNum, Nodes),
    % Mark as visited.
    {dict:store(NodeNum, {FromDistance, visited, OriginalEdges}, Nodes), Unvisited}.

% Get the distances of a few nodes from the example graph.
start() ->
    DistanceNodes = [7,37,59,82,99,115,133,165,188,197],
    lists:map(fun(NodeNum) -> dict:fetch(NodeNum, dijkstra(read_graph("dijkstraData.txt"), 1)) end, DistanceNodes).

What I wrote in python:
def read_graph(FileName) -> dict:
    try:
        f, NewNodes = open(FileName), dict()
        return parse_rows(f, NewNodes)
    except FileNotFoundError as ex:
        print(ex)

def parse_rows(f, NewNodes) -> dict:
    Line = f.readline()
    if Line == '':
        return NewNodes
    else:
        test = Line.replace('\n', '').split('\t')
        VertexNum, Row = int(test.pop(0)), test
        if NewNodes.get(VertexNum) is None:
            NewNodes[VertexNum] = []
        get_edges_from_line(NewNodes, VertexNum, Row)
        return parse_rows(f, NewNodes)

def parse_edge(NewNodes, FromVertexNum, Val) -> dict:
    [VertexString, WeightString] = Val.split(',')
    [ToVertexNum, Weight] = [int(VertexString), int(WeightString)]
    return NewNodes.get(FromVertexNum).append((edge, (vertex, FromVertexNum), (vertex, ToVertexNum), Weight))

def get_edges_from_line(NewNodes, VertexNum, Snake) -> dict:
    if not Snake:
       return NewNodes
    Head, Tail = Snake.pop(0), Snake
    parse_edge(NewNodes, VertexNum, Head)
    return get_edges_from_line(NewNodes, VertexNum, Tail)

A: *

*For functional overloading, as you've discovered, it has to be done by hand with if statements and the like.

*As others have commented, the default list type in Python is an array, not a cons-based list, so using head and tail will be inefficient; lists are better handled using either for loops, or list comprehensions.
edges = [parse_edge(s) for s in snake]

*If you do need the head and tail, they're: nodes[0] and nodes[1:]

*For the parse_rows function, it would be more idiomatic to have it accept the lines as an argument; reading input and parsing it are distinct pieces of work, so they should be in separate functions. This also makes it possible to write unit tests for the parse_rows function.

*If you like functional programming, you'll enjoy the itertools module (standard library) and the more-itertools package (from pypi).

*Idiomatically, this code would probably use a class in Python; rather than passing around separate variables for Nodes and Edges, they would be attributes on a single Graph object. Most of the functions would then be methods (with read_graph a classmethod).

*The naming conventions in Python are snake_case identifiers for variables, functions and methods; CamelCase is used for class names.

*For functional paradigm, look at list comprehensions (and other comprehensions); avoid modifying variables in-place.

A: @Samuel
Below snippet will highlight the issue of function overloading in Python.
In above, they have implemented decorator called overload. This is special case of decorators with arguments. These arguments to decorators are the key elements of function overloading since they specify the type and number of arguments.
Reference for more details
https://medium.com/practo-engineering/function-overloading-in-python-94a8b10d1e08


text:
Q: Why are Inkscape default extensions not working? After perspective
Before perspective
Correct perspective
I am using Inkscape v. 1.0. Here when I am using the perspective extension, it is not likely worked and you see the image after perspective in 2. Actually, the correct perspective is 3. How can I fix this?

A: It's a bug. Please reply to the questions of the bug triage team in the bug tracker to get it fixed (and to find a suggestion about how to fix it for your case).
https://gitlab.com/inkscape/extensions/-/issues/226
For further bug reports, make sure to subscribe, so you will get email notifications.


text:
Q: Angularjs ng-switch not working What I am trying to do is:
When the dropdown toggle is clicked, if Text is clicked, it will show "test_now", if Paragragh Text is click, it will show "text list".
But I tried several times and it still not working, could someone help me on that? thanks so much!
Here is my code:

    <button class="btn btn-default dropdown-toggle">Add item</button>

        {{choice.type}}

        test_now

        test_list

js part:
angular.module('DFS', ['ui.bootstrap']);

function PageCtrl($scope) {

    $scope.items = [
        {
            type: "Text"
        },
        {
            type: "Paragraph Text"
        },
        {
            type: "Multiple Choice"
        },
        {
            type: "Checkboxes"
        },
        {
            type: "Choose from a list"
        }
    ];

    $scope.selection = $scope.items[0].type;

}

A: Here is my example code:

          <button class="btn btn-default dropdown-toggle">Add item</button>

               {{choice.type}}

           test_now

            test_list

      angular.module('myApp', []);
        function PageCtrl($scope) {

    $scope.items = [
        {
            type: "Text"
        },
        {
           type: "Paragraph Text"
        },
        {
        type: "Multiple Choice"
        },
        {
        type: "Checkboxes"
        },
        {
        type: "Choose from a list"
        }
    ];

    $scope.click = function(choice){
        $scope.selection =  choice.type;
    }

    $scope.selection = $scope.items[0].type;

}

or angularjs.org example
http://docs.angularjs.org/api/ng/directive/ngSwitch


text:
Q: Can I have a custom UI for monitoring my microservices registered to Consul? I'm new to using Consul as a service discovery for the SOA. Please clarify whether I can enhance the monitoring web UI that Consul has inbuild to support my needs? Like I wish to monitor the Microservice health (CPU usage, Latency, and Disk space).  TIA

A: Through consul builtin UI there is no feature of getting docker metric like cpu, memory .
Instead you can use tools like
https://github.com/google/cadvisor


text:
Q: Referencing a WP7 border element in tap event I have a WP7 app that is using bing maps and I have pushpins for multiple locations.  On tapping the pushpin I have a tap event that displays a border with some text.  To hide the text I'm using a tap event for the map control which sets the border visibility to collapsed:
private void map_Tap(object sender, GestureEventArgs e)
    {

        this.border.Visibility = Visibility.Collapsed;
    }

Now if I am going to be using multiple borders and texts, I'm going to have to set the visibility multiple times like so:
this.border.Visibility = Visibility.Collapsed;
this.border2.Visibility = Visibility.Collapsed;
this.border3.Visibility = Visibility.Collapsed;

So I created a resource for the border in order to refer to just one border.
<phone:PhoneApplicationPage.Resources>
<Style x:Key="BorderStyle" x:Name="border" TargetType="Border" >
        <Setter Property="Background" Value="Black" />
    </Style>
</phone:PhoneApplicationPage.Resources>

And I set the resource in the pushpin
<my:Pushpin.Content>
                <Border Style="{StaticResource BorderStyle}" >

But now when I refer to the border in the map_Tap event I get a System.Windows.Style does not contain a definition for 'Visibility' because the border is no long referenced as a UIElement(at least that's how I'm understanding this).  How can a make a style for the border element and still reference it as an element?

A: I would like to suggest you this approach and this might help you for some other tasks too.
You use a list of type border and add all the border elements into it. Now whenever you want to manipulate all the elements you can have a foreach loop and access any property you would like example item.Visibility and you can manipulate it as you like. This will even help you sort them out so that you can manipulate any specific border.


text:
Q: Print text of anchor link using BeautifulSoap library | python I am web-scraping a website named pakwheels.com. I want to get year of a car.
https://www.pakwheels.com/used-cars/suzuki-cultus-2018-for-sale-in-lahore-6596122

The year can be get from this part of HTML.

I want to print the text of the anchor link using BeautifulSoap library. Tried different variations of the code but had no success, please help.
my output should be: 2018

A: You can extract the a tag using select_one with the css selector 'span.engine-icon.year + p > a' and then get the text using get_text.
For example, if you were looking at a car from pakwheels.com [the html in your screenshot looks like just like this site's], then
r = requests.get('https://www.pakwheels.com/used-cars/suzuki-cultus-2018-for-sale-in-lahore-6596122')
if r.status_code == 200:
    soup = BeautifulSoup(r.text, 'html.parser')

    hlYear = soup.select_one('span.engine-icon.year + p > a')
    if hlYear is not None:
        print(hlYear.get_text(strip=True))

would print 2018.


text:
Q: Guarded blocks in Java. Where should I update a condition variable? I'd use a volatile condition variable, but I think volatile is redundant. Besides I'm not quite sure I understood this point from https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html#MemoryVisibility correctly:

An unlock (synchronized block or method exit) of a monitor
  happens-before every subsequent lock (synchronized block or method
  entry) of that same monitor. And because the happens-before relation
  is transitive, all actions of a thread prior to unlocking
  happen-before all actions subsequent to any thread locking that
  monitor.

So synchronized blocks are called subsequently. But are results of assignments performed in a synchronized block visible to all the subsequent synchronized blocks?
Here is a sample app.
package sample;

public class Foo {

    private boolean shouldWait;
    private final Object lock = new Object();

    void blockThread() {
        synchronized (lock) {
            shouldWait = true;
            while (shouldWait) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    void notifyThread() {
        synchronized (lock) {
            shouldWait = false;
            lock.notify();
        }
    }
}

Test.
package sample;

public class Main {

    private static Foo foo = new Foo();

    public static void main(String[] args) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                foo.blockThread();
            }
        }).start();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
        new Thread(new Runnable() {

            @Override
            public void run() {
                foo.notifyThread();
            }
        }).start();
    }

}

A:
So synchronized blocks are called subsequently. But are results of assignments performed in a synchronized block visible to all the subsequent synchronized blocks?

Yes. volatile writes have the same relationship.  All actions prior to a volatile write happens-before all subsequent reads.


text:
Q: CakePHP ACL - Not able to access controller although I am Using $this->Auth->allow('index','view') All,
Here I am with CakePHP ACL again. After many headaches, I was able to get Alaxos ACL to work for me. I set group permission, etc, and it works great. However, I am having issue with one controller that does not make sense to me at all...

*

*In this controller articles_controller.php it looks like beforeFilter() has not effect

In my app_controller.php I have
function beforeFilter(){
    ...
    $this->Auth->allow('display') //To make sure all my pages are plublic, like about_us
}

In all my controllers including articles_controller.php I have the following code
...
function beforeFilter(){
    parent::beforeFilter();
    $this->Auth->allow('index','view');
}
....

However, when I access this controller neither the index or view actions works. I get a YOU ARE NOT AUTHORIZED TO ACCESS THAT LOCATION error. The only time that controller works is if I change the $this->Auth->allow('display') to('*') in the app_controller.php's beforeFilter().
I am not sure what to do. Isnt $this->Auth->allow('index','view') making these 2 actions public regardless of ACL says? I am only able to access them when logged in. Same actions in other controllers work just fine. Nothing else is out of the ordinary...
What can I do, or where should I look next. Why?
===========================================================================================
And to add,
I have the following code in my articles_controller.php:
 $this->set('articles',$articles);
 $this->set('topfive_articles',$topfive_articles);
 $this->set('other_articles',$other_articles);
 $this->set('categories',$categories);

If I comment all those out, AUTH now gives me access to the action/view, but it displays undefined variable errors. Also, if I comment out, ie. 3 of 4, nothing happens. I only get thru if I comment out all 4 variables....
I have not idea what is going on...

A: ================================================================================
After many hours of researching and trying I came to a simple conclusion that was so obvious that I am not sure why I missed it.
In articles_controller.php I have other actions besides index, view, edit, delete, admin_xxx. I have among others getArticleComments, mostViewedArticle
I am not sure if it is the correct way, most likely it is not, but I use requestAction to process these actions and most into an ELEMENT which is displayed in the view.
I basically had to tell Auth to allow these actions to be public as well as the index and view.
$this->Auth->allow(
            'index',
            'view',
            'getTotalComments',
            'mostComments',
            'childrenComments',
            'getRelated',
            'getArticleComments',
            'mostViewed'
     );

Voila! As soon as I did that, problem solved... WOW!


text:
Q: WordPress url shortcode I have never written any code in php, but im making a wordpress dashboard that requires a redirect to a page based on the username. I want a button on the homepage that takes the loged in user to the right page, so im making a shortcode(don't know if this is the best solution).
So far, from searching online, i have this code:
function url_sc() {
    $current_user = wp_get_current_user() {
        $username = $current_user->login_user {
            $username_link = "https://testwebpage.no/?username=<?php echo $username; ?>"
        }
    }
    return $username_link;
}

add_shortcode( 'username-url', 'url_sc' );

I don't know if it will work yet, because i get this syntax error:

syntax error, unexpected 'return' (T_RETURN)

Can someone explain to me why i get the error, and possibly how to fix it?

A: Try this code. this will check the user logged in or not and also check you're based on your given username.
function url_sc() {
    $current_user  = wp_get_current_user();
    $username      = $current_user->user_login;
    $username_link = "https://testwebpage.no/?username=".$username;
    return $username_link;
}
add_shortcode( 'username-url', 'url_sc' );

A: That is because you forgot the semicolon after:
$username_link = "https://testwebpage.no/?username=<?php echo $username; ?>"  and forgot to escape the php codethis should be: $username_link = "https://testwebpage.no/?username=". echo $username; ."";
So the complete code looks like:
function url_sc() {
    $current_user = wp_get_current_user() {
        $username = $current_user->login_user {
            $username_link = "https://testwebpage.no/?username=". echo $username; ."";
        }
    }
    return $username_link;
}

add_shortcode( 'username-url', 'url_sc' );

A: I'm no PHP expert, but I do dabble. That whole function block is laid out wrong, try;
function url_sc() {
    $current_user = wp_get_current_user();
    $username = $current_user->user_login;
    $username_link = "https://testwebpage.no/?username=" . $username;
    return $username_link;
}
add_shortcode( 'username-url', 'url_sc' );

You can take this a step further here, and create the button html in this code block, then it will output as a complete linked button with the shortcode.
function url_sc() {
   $current_user = wp_get_current_user();
   $username = $current_user->user_login;
   $username_link = "https://testwebpage.no/?username=" . $username;
   $button = 'Go To My Profile Page';
   return $button;
}
add_shortcode( 'username-url', 'url_sc' );


text:
Q: Continue to next breakpoint I couldn't find any key in rubymine to continue execution till next break point. I can see run to cursor, step into, step over etc.
Can anyone suggest how can I continue to next breakpoint?

A: To proceed to the next breakpoint, click Resume Program on the left toolbar.


text:
Q: C# DatagridView fill with class SingleResponsibility Hi StackOverflow members, I decided to build a library project to improve myself.
I created a class to code Book Operations but i couldn't find out how to fill datagrid via class method.
When i text this method into a button action it didn't work. I found out a solution to make it happen. And here's some code from my BookOperation class;
public void GetBookByName(Yönetici f1)
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("Select * from Kitaplar where Kitap_Adi like '%" + f1.textBox1.Text.Trim() + "%'", conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        f1.dataGridView1.DataSource = dt;
        conn.Close();
    }
    public void GetBookByAuthor(Yönetici f1)
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("Select * from kitaplar where Yazar like '%" + f1.textBox1.Text.Trim() + "%'", conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        f1.dataGridView1.DataSource = dt;
        conn.Close();

    }
    public void GetBookByGenre(Yönetici f1)
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("Select * from kitaplar where Tür like '%" + f1.textBox1.Text.Trim() + "%'", conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        f1.dataGridView1.DataSource = dt;
        conn.Close();
    }

Yönetici is the name of my application screen of book operations.
In the button action, it includes;
Kitap_islemleri ki = new Kitap_islemleri();
ki.GetBookByName(this);

is it okay for single responsibility or is there any different way? Can you please help me?
That's kind of weird using somemethod(this), is it wrong or good for a start? what do you think. How can i get data without using (this)? If there's a way, can you hit it?

A: I suggest you to change your method parameters and return type with what you need. It seems your queries need just 1 criteria.
public DataTable GetBookByName(string bookName)
{
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select * from Kitaplar where Kitap_Adi like '%" + bookName.Trim() + "%'", conn);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    conn.Close();
    return dt;
}

So you won't need all the Yonetici page on your data access layer and with returned DataTable, you can bind it to your gridview on presentation layer.
var bookName = f1.textBox1.Text;
f1.dataGridView1.DataSource = ki.GetBookByName(bookname);

Part 2
public DataTable GetBooks(string filter, string criteria)
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from Kitaplar where " + filter + " like '%" + criteria.Trim() + "%'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
return dt;
}

Usage
GetBooks("Kitap_Adi", "name");
GetBooks("Yazar", "author");
GetBooks("Tür", "kind")


text:
Q: Change a dialog's message while using AsyncTask? I looked at a few other questions regarding a similar issue, and I figured out that I need to use the onProgressUpdate method to change the message of ProgressDialog.
For example, I have code like this that runs in the AsyncTask's doInBackGround (this is just a very small sample):
        byte[] data = getBytesFromFile(image);

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        pictures.dia.setProgress(30);
        pictures.dia.setMessage("Data beginning upload sequence...");

        URL connectURL = new URL(this.base_url);
        HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data, boundary=" + boundary);

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        pictures.dia.setProgress(40);
        pictures.dia.setMessage("Output Stream prepared...");

When I originally run thus, I get a Leaky Window error saying that I can't change dia's message outside of AsyncTask.
So my question is, how do I use onProgressUpdate to set the message of dia when dia's progress reaches a certain number? (i.e., when dia's progress = 30, make it say "Data beginning upload sequence...")
onProgressUpdate must obviously always be checking dia's progress (like a listener, I suppose)[if it doesn't already do this, how can I make it do this?]

A: You need to implement the onProgressUpdate method of AsyncTask. Create a new class that holds the progress percentage and the message only to be the onProgressUpdate method's only parameter.
In the onProgressUpdate, call dia.setProgress and dia.setMessage.
In your doInBackground method, call publishProgress with an instance of your new class that contains the new percentage and message. That will cause the AsyncTask to call onProgressUpdate on the main thread.
For example:
private static class TaskProgress {
    final int percentage;
    final String message;

    TaskProgress(int percentage, String message) {
        this.percentage = percentage;
        this.message = message;
    }
}

In your AsyncTask (replace the ?s with the correct types for your implementation):
public ProgressAsyncTask extends AsyncTask<?, TaskProgress, ?> {

    public void onProgressUpdate(TaskProgress progress) {
         pictures.dia.setProgress(progress.percentage);
         pictures.dia.setMessage(progress.message);
    }

    public ? doInBackground(?... params) {
        // ... your code
        publishProgress(new TaskProgress(30, "A new update"));
        // ... your code
    }

}

A: You're right in that you should put the code for updating the views in dia in the onProgressUpdate method. To ensure that onProgressUpdate is called, though, you need to make calls to publishProgress.  Basically, you call publishProgress from your background thread and then the system, at some undefined time in the future, will invoke onProgressUpdate on the UI thread.


text:
Q: Retain only first occurence of a word in python string I have the below text as a string in python while reading a text line by line. Some lines can have more than 1 alert, some lines can have only 1 and some lines won't even have an alert.
line = process:process_name, Alert:problem with record 44, Alert:problem with record 134, Alert: problem with record 22.

If I have more than 1 alert in a given line, I have to combine all the alerts like below.
Expected output:
new_line = process:process_name, Alert:problem with record 44,problem with record 134,problem with record 22.

Is there a way to do this in python?
I tried using string split and identifying splits starting with Alert. But not sure how to proceed after that.

A: One approach, using re.findall to find all alerts, followed by concatenation to build the output string you want:
inp = "line = process:process_name, Alert:problem with record 44, Alert:problem with record 134, Alert: problem with record 22."
start = inp.split('Alert:', 1)[0]
alerts = re.findall(r'Alert:\s*(problem with record \d+)', inp)
output = start + 'Alert:' + ','.join(alerts)
print(output)

This prints:

line = process:process_name, Alert:problem with record 44,problem with record 134,problem with record 22


text:
Q: NOAA API returning impossible historical temperature values API:
https://www.ncdc.noaa.gov/cdo-web/webservices/v2
Parameters:
CITY:US270013 specifies Minneapolis, MN
datatypeid=TOBS specifies that I want the observed temperature
Python Code
url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/data?datasetid=GHCND&locationid=CITY:US270013&startdate=2016-05-01&enddate=2016-05-31&limit=1000&datatypeid=TOBS'

response = requests.get(url, headers = headers)
response = response.json()
stationData = pd.DataFrame(response['results'])
print(stationData.sort_values(by='station').to_string(index=False))

Results:
attributes datatype                 date            station  value
 ,,7,2400     TOBS  2016-05-01T00:00:00  GHCND:USC00211448     89
 ,,7,2400     TOBS  2016-05-14T00:00:00  GHCND:USC00211448      6
 ,,7,2400     TOBS  2016-05-07T00:00:00  GHCND:USC00211448     61
 ,,7,2400     TOBS  2016-05-16T00:00:00  GHCND:USC00211448    106
 ,,7,2400     TOBS  2016-05-26T00:00:00  GHCND:USC00211448    172
 ,,7,2400     TOBS  2016-05-28T00:00:00  GHCND:USC00211448    161
 ,,7,2400     TOBS  2016-05-17T00:00:00  GHCND:USC00211448     50
 ,,7,2400     TOBS  2016-05-06T00:00:00  GHCND:USC00211448    178

According to that table, May 6th 2015 had an observed temperature of 178 degrees in Minneapolis. This is clearly wrong but there is little documentation on their website. Does their TOBS follow a different scale for temperatures, or is there a different variable I should be using?

A: From the documentation:
ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/daily/readme.txt
TOBS = Temperature at the time of observation (tenths of degrees C)

Divide your results by 10, multiply by 9/5 + 32 to convert to F (or whatever you need to do).
Minneapolis can be freezing in May!


text:
Q: regex: Select all lines that do not end with a specific tag I have this 4 lines, all starting with tag
 and ending with tag
 except the last two.

My mother is at home.

My father is at home.

My sister is at home.<LLbr>

My brother is at home.<AAbr>

So, I want to find all lines with TEXT tag that doesn't ending with

My output result should be

My sister is at home.<LLbr>

My brother is at home.<AAbr>

I made a regex, but is not too good.
(?-s)(.*
.*)(?-s)(?!)
(.*)$

A: *

*Ctrl+H

*Find what:
(?:(?!
)(?!<p).)*(?:<.+?>|\z)

*UNcheck Match case

*check Wrap around

*check Regular expression

*UNCHECK . matches newline

*Search in document
Explanation:

    # literally
(?:                 # start non capture group
  (?!
)          # negative lookahead, make sure we haven't

  (?!<p)            # negative lookahead, make sure we haven't <p
  .                 # any character but newline
)*                  # group may appear 0 or more times
(?:                 # non capture group
   <.+?>            # a tag
 |                  # OR
   \z               # end of string
)                   # end of group

DEMO


text:
Q: bijection between bilinear maps and linear map from tensor product Let $V$, $W$ and $U$ be finite dimensional vector spaces over a field $R$, and let $b:V \times W \to U$ be a bilinear map, and let $\hat b:V \otimes W \to U$ be the linear map defined by $\hat b(v \otimes w)=b(v,w)$, and extended linearly to all elements of $V\otimes W$. The tensor product $V\otimes W$ is defined as a quotient of the vector space whose basis is $V\times W$ by the subspace $\bar S$ whose basis is the set $S$, where $S$ is all terms of the form (1) $(v_1+v_2,w)-(v_1,w)-(v_2,w)$, (2) $(v,w_1+w_2)-(v,w_1)-(v,w_2)$, (3) $r(v,w)-(rv,w)$ and (4) $r(v,w)-(v,rw)$. I don't know how to prove that $\hat b$ is well defined. Namely, if $(v_1, w_1)-(v_2,w_2)\in \bar S$, how do I prove that the bilinearity of $b$ implies that $b(v_1,w_1)=b(v_2,w_2)$. Can somebody please explain in detail how does it follow?

A: $\overline{S}$ is generated by $S$, but $S$ is in general no basis. Let $F(V \times W)$ denote the vector space with basis $V \times W$. Define $b' : F(V \times W) \to U$ as the unique linear map such that $b'(v,w) = b(v,w)$ on the basis $V \times W$. Now verify that $b'(s) = 0$ for all $s \in S$. This implies $\overline{S} \subset ker(b')$ and gives you a unique linear $\hat{b} : V \otimes W = F(V \times W)/\overline{S} \to U$ such that $\hat{b} \circ p = b'$, where $p : F(V \times W) \to V \otimes W$ denotes the quotient map.


text:
Q: How can I call the function clinet.query through the function? I would like to call the client.query through function however it does not work. For example, when the user click a button, I want to call a function named handleClick to get the query The following is an example to how call client.query by the function
class DelayedQuery extends Component {
    state = { dog: null };

    onDogFetched = dog => this.setState(() => ({ dog }));

    handleClick = (client) => {  //<-------I call the function
        async () => {
            const { data } = await client.query({
                query: GET_DOG_PHOTO,
                variables: { breed: "bulldog" }
            });
            this.onDogFetched(data.dog);
        }
    }

    render() {
        return (
            <ApolloConsumer>
                {client => (

                        {this.state.dog && }
                        <button onClick={()=>this.handleClick(client) } > Click me! </button> // <-------I call handleClick

                )}
            </ApolloConsumer>
        );
    }
}

How can I call the function clinet.query through the function?

A: So you have 2 problems.
1. You don't pass the client into your function, so that will be a problem, after the function be work. Do it like this:
 handleClick = client => {...}

2. You don't actual call your inner function in handleClick. You just await the generation of the function. To call it eiter append () after it to call it:
async () => {
        const { data } = await client.query({
            query: GET_DOG_PHOTO,
            variables: { breed: "bulldog" }
        });
        this.onDogFetched(data.dog);
    }();

or separate creation and execution:
 async () => {
        const fetch = client.query({
            query: GET_DOG_PHOTO,
            variables: { breed: "bulldog" }
        });
        const { data } = await fetch();
        this.onDogFetched(data.dog);
    }

or just make the click async:
handleClick = async client => {
   const { data } = await client.query({
            query: GET_DOG_PHOTO,
            variables: { breed: "bulldog" }
        });
        this.onDogFetched(data.dog);
}

Hope this helps. Happy coding.

A: I solve the problem by make the handleClick async
class DelayedQuery extends Component {
    state = { dog: null };

    onDogFetched = dog => this.setState(() => ({ dog }));

    handleClick = async (client) => {
            const { data } = await client.query({
                query: GET_DOG_PHOTO,
                variables: { breed: "bulldog" }
            });
            this.onDogFetched(data.dog);
    }

    render() {
        return (
            <ApolloConsumer>
                {client => (

                        {this.state.dog && }
                        <button onClick={()=>this.handleClick(client) } > Click me! </button>

                )}
            </ApolloConsumer>
        );
    }
}


text:
Q: Visualforce DATEVALUE() function not working after field is used in  This one had me banging my head against the wall for a while today.  It appears that the DATEVALUE() function in Visualforce is unable to parse a Date/Time field after is has been used in an apex:outputField component.
Consider these two examples:
This VF page saves fine:
<apex:page standardController="Account">
{!DATEVALUE(Account.CreatedDate)}
</apex:page>

If we utilize the apex:outputField component to render the CreatedDate field first, DATEVALUE() is no longer able to recognize it as a valid expression.
<apex:page standardController="Account">
  <apex:outputField value="{!Account.CreatedDate}" />
  {!DATEVALUE(Account.CreatedDate)}
</apex:page>

In my case I was trying to use apex:outputField to display a nicely formatted date for the user and then use DATEVALUE() to construct some url parameters for a report link.
Am I crazy for thinking this should work?

A: That is a strange one!
I have a workaround for you: use an apex:variable to store the datevalue for later use:
<apex:page standardController="Account">
  <apex:variable value="{!DATEVALUE(Account.CreatedDate)}" var="dateval"/>
  <apex:outputField value="{!Account.CreatedDate}" />

  -----

  {!dateval}
</apex:page>

Unfortunately I don't know why this strange bug occurs - perhaps someone else will be able to illuminate you.

A: DATEVALUE expects the input of 'YYYY-MM-DD' format as a String. The documentation also says that it accepts DateTime, though I'm not sure why that doesn't work. Another alternative is rendering a Date or DateTime field using the following syntax using outputText with param:
<apex:outputText value="{0, date, dd'/'MM'/'yyyy}">
    <apex:param value="{!Account.CreatedDate}" />
</apex:outputText>


text:
Q: how can I link a list to if else? Flutter I don't understand exactly why I always get an error here. I have built a (if else) statement, in a short version. Whenever the function no longer finds a value, i.e. comes to 3 in the array, I get the error that there is no more data in the array / list. But I did install an (ELSE) and it should display the text ("HELLO"). I don't know exactly where the error is. Maybe someone can help me briefly, thank you.

import 'package:flutter/material.dart';
import 'package:tasktolean/body.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var bodyTextIndex = 0;
  var bodytext = [
    'Hello FIRST Text!',
    'Hello SECOND Text!',
    'Hello THIRD Text!',
  ];

  void buttonPress() {
    setState(() {
      bodyTextIndex = bodyTextIndex + 1;
    });
  }

 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            'TASK',
          ),
        ),
        body: bodyTextIndex <= bodytext.length
            ? Column(
                children: [
                  BodyTextChance(
                    bodytext[bodyTextIndex],
                  ),
                  FlatButton(
                    onPressed: buttonPress,
                    child: Text(
                      'CLICK ME',
                    ),
                  ),
                ],
              )
            : Center(
                child: Text('HELLO'),
              ),
      ),
    );
  }
}

> import 'package:flutter/material.dart';
>
>
> class BodyTextChance extends StatelessWidget {   String bodytext;
>
>   BodyTextChance(this.bodytext);
>
>   @override   Widget build(BuildContext context) {
>     return Text(bodytext);   } }

A: Short Answer
This line uses a wrong comparison operator:
body: bodyTextIndex <= bodytext.length

It should use < operator like so:
body: bodyTextIndex < bodytext.length

A Bit More Details
When bodyTextIndex becomes 3, the condition below is still met:
bodyTextIndex <= bodytext.length

Then it refers to bodytext[3] but the element doesn't exist because it ranges from 0 to 2.


text:
Q: How are you using the pattern matching functionality in ReSharper 5? Resharper 5's new pattern matching seems very powerful, though it takes a bit of tinkering to work out how to use it.
For those who aren't familiar with this feature, it allows you to search for specific patterns within your code.  Instances of such patterns may optionally be replaced with an alternative.  In IntelliJ this was called structural search and replace.  It's much more powerful than simple RegEx search/replace.
I'd like to collect a series of patterns that people are using so that I can learn how to use this feature better.
I propose that each answer include:

*

*a brief introduction of the rationale for the pattern

*an example of what it would match

*an optional example of a replacement

*the XML generated by exporting the pattern so that others can try it out too

A: JetBrains offer a Sample Pattern Catalog for Structural Search and Replace for download containing 17 patterns:

*

*'try/finally' block can be converted to 'using' statement

*Method StringBuilder.Append can be converted to StringBuilder.AppendFormat

*Comparison with true is redundant

*Conditional statement is redundant

*Code is unreachable

*'if' block is never executed

*Identical branches in a conditional statement

*Redundant compound assignment with |= operator

*Redundant compound assignment with &= operator

*Redundant compound assignment with |= operator (alternative case)

*Redundant compound assignment with &= operator (alternative case)

*Redundant initialization to false and condition block

*Redundant initialization to true and condition block

*Method Array.CreateInstance can be replaced with an array creation expression

*Method Array.CreateInstance can be replaced with a two-dimensional array creation expression

*Redundant usage of GetType() == typeof() with a value type

*Method OfType can be used for type-based filtering

A: Remove if envelop around if body.
Example:
This code:
if (ok)
{
  DoNextStep();
}

will be replaced by:
DoNextStep();

So only body of if remains.
The XML:
  <Pattern Severity="HINT">
    <Comment>if</Comment>
    <ReplaceComment>Remove enclosing if</ReplaceComment>
    <ReplacePattern>$body$</ReplacePattern>
    <SearchPattern>if($condition$){$body$}</SearchPattern>
    <Params />
    <Placeholders>
      <StatementPlaceholder Name="body" Minimal="-1" Maximal="-1" />
      <ExpressionPlaceholder Name="condition" ExpressionType="System.Boolean" ExactType="True" />
    </Placeholders>
  </Pattern>

A: Matching a [Flags] enum bit
.NET 4 introduces the System.Enum.HasFlag method which can tidy up your code.
Before:
(myValue & MyFlagsEnum.Foo) == MyFlagsEnum.Foo

After:
myValue.HasFlag(MyFlagsEnum.Foo)

XML:
<CustomPatterns>
  <Pattern Severity="SUGGESTION">
    <Comment>Can condense using 'Enum.HasFlag' method</Comment>
    <ReplaceComment>Replace bit matching with 'Enum.HasFlag'</ReplaceComment>
    <ReplacePattern>$myValue$.HasFlag($target$)</ReplacePattern>
    <SearchPattern><![CDATA[($myValue$ & $target$) == $target$]]></SearchPattern>
    <Params />
    <Placeholders>
      <ExpressionPlaceholder Name="myValue" ExpressionType="System.Enum" ExactType="False" />
      <ExpressionPlaceholder Name="target" ExpressionType="System.Enum" ExactType="False" />
    </Placeholders>
  </Pattern>
</CustomPatterns>

A: Restarting a Stopwatch
.NET 4 introduces the System.Diagnostics.Stopwatch.Restart() method which can tidy up your code.
Before:
stopwatch.Reset();
stopwatch.Start();

After:
stopwatch.Restart();

XML:
<CustomPatterns>
  <Pattern Severity="SUGGESTION">
    <Comment>Use Restart method for System.Diagnostics.Stopwatch</Comment>
    <ReplaceComment>Use Restart method for System.Diagnostics.Stopwatch</ReplaceComment>
    <ReplacePattern>$stopwatch$.Restart();</ReplacePattern>
    <SearchPattern><![CDATA[$stopwatch$.Reset();
$stopwatch$.Start();]]></SearchPattern>
    <Params />
    <Placeholders>
      <ExpressionPlaceholder Name="stopwatch" ExpressionType="System.Diagnostics.Stopwatch" ExactType="True" />
    </Placeholders>
  </Pattern>
</CustomPatterns>

A:
For example, Microsoft recommends (and
  Code Analysis/FxCop generates
  appropriate warnings) if you are doing
  a comparison between a string value
  and an empty string, to use the
  String.IsNullOrEmpty() method.

http://david.gardiner.net.au/2010/02/resharper-5-structural-search-and.html

A: This one's different.  I discovered later in my project that mbunit asserts which compare property values to enums don't render nice messages when using the AssertEx.That syntax.
So I created a pattern to find this:
AssertEx.That(() => myVariable.Status == MyEnum.Ok);

...and replace it with this:
Assert.AreEqual(MyEnum.Ok, myVariable.Status);

Here's the pattern:
<Pattern Severity="WARNING">
<Comment>AssertEx.That asserts for enum values don't give nice error msgs</Comment>
<ReplaceComment>Replace AssertEx.That asserts for enum values with trad Assert.AreEqual for better error msgs</ReplaceComment>
<ReplacePattern>Assert.AreEqual($enum$,$variable$.$property$)</ReplacePattern>
<SearchPattern><![CDATA[AssertEx.That(() => $variable$.$property$ == $enum$]]></SearchPattern>
<Params />
<Placeholders>
  <ExpressionPlaceholder Name="enum" ExpressionType="System.Enum" ExactType="False" />
  <IdentifierPlaceholder Name="variable" Type="" ExactType="False" RegEx="" CaseSensitive="True" />
  <IdentifierPlaceholder Name="property" Type="" ExactType="False" RegEx="" CaseSensitive="True" />
</Placeholders>

A: Remove enclosing braces around a body.
Example:
This code:
    foreach (int i in arr)
    {
      DoNextStep();
    }

will be replaced (by Ctrl+L to remove foreach row and then run this pattern to remove braces) by:
DoNextStep();

So only body of braces remains after typing around two shortcuts.
The XML:
<Pattern Severity="HINT">
  <Comment>Curly braces with body</Comment>
  <ReplaceComment>Remove braces</ReplaceComment>
  <ReplacePattern>$body$</ReplacePattern>
  <SearchPattern>{$body$}</SearchPattern>
  <Params />
  <Placeholders>
    <StatementPlaceholder Name="body" Minimal="-1" Maximal="-1" />
  </Placeholders>

A: To 'as' cast.
Example:
This code:
string s = (string) o;

will be replaced by:
string s = o as string;

So now you have the 'as' cast instead of regular cast.
The XML:
<Pattern Severity="HINT">
  <Comment>Cast</Comment>
  <ReplaceComment>To 'as' cast</ReplaceComment>
  <ReplacePattern>$exp$ as $type$</ReplacePattern>
  <SearchPattern>($type$)$exp$</SearchPattern>
  <Params />
  <Placeholders>
    <TypePlaceholder Name="type" Type="" ExactType="True" />
    <ExpressionPlaceholder Name="exp" ExpressionType="" ExactType="True" />
  </Placeholders>
</Pattern>

A: To regular cast.
Example:
This code:
string s = o as string;

will be replaced by:
string s = (string) o;

So now you have the regular cast instead of 'as' cast.
The XML:
<Pattern Severity="HINT">
  <Comment>Cast (as)</Comment>
  <ReplaceComment>To regular cast</ReplaceComment>
  <ReplacePattern>($type$)$exp$</ReplacePattern>
  <SearchPattern>$exp$ as $type$</SearchPattern>
  <Params />
  <Placeholders>
    <ExpressionPlaceholder Name="exp" ExpressionType="" ExactType="True" />
    <TypePlaceholder Name="type" Type="" ExactType="True" />
  </Placeholders>
</Pattern>


text:
Q: Experimentally proving bias I have a random process of a game (Backgammon) and I have developed two different game agents that can play a game. Now I match these two players against each other in N games. I have a hypothesis that agent A plays better than agent B. So I believe there is a bias towards A. How can I prove (or at lest get some confidence) that agent A plays stronger than agent B based on the outcome of the N games?
I assume there is only win or lose outcome of the games.
This feels like a really simple question, but I think I do it incorrectly.
Here is what I do:
I've played 11000010 games between the two players (N=11000010). Out of these agent A wins 5528841 games and hence agent B wins 5471169 games. I then calculate $\hat\mu$ as $\frac{5528841}{11000010}=0.5026214521623162$.
Then I calculate standard deviation of the experiment $\sigma = N \hat\mu (1-\hat\mu)$. (?) And then $\frac{\hat\mu - 0.5}{\sigma/\sqrt{N}}$ which gives me a really small number that I really don't trust.

A: The null hypothesis $H_0$ is that the $N$ games are independent Bernoulli trials where $B$'s probability of winning is at least $1/2$.  Thus the number $X$ of games $B$ wins is a binomial random variable with parameters $N$ and $p$, with $p \ge 1/2$.  Then $$\mathbb P(X \le x \mid H_0) \le \sum_{k=0}^x {N \choose k} 2^{-N}$$
If $N$ is very large, you might wish to approximate this by a normal distribution, but for reasonable-sized $N$ it is not hard to compute directly.
If you want a test at confidence level $\alpha$, choose $N$ and $x$ such that
$\sum_{k=0}^x {N \choose k} 2^{-N} \le \alpha$.  You will then play the $N$ games, and reject the null hypothesis if you observe $X \le x$.


text:
Q: I'm trying to print from a void function, but it won't compile because it says it isn't defined My code won't compile, but I'm just trying to get my main file to run properly and print the output. I'm also trying to compare if the strings are equal to print. The main errors are in the main file because the header and cpp file compile, but when I try to get some output from the void print function, it crashes and tells me the errors that there's no matching function to call from the parent class. Can you please tell me how to fix this? thank you.
header file:
#include <iostream>
#ifndef BOOK_H
#define BOOK_H

class Book
{

    public:

    Book(std::string title, std::string author, int callNo);

    virtual void print();

    virtual bool equals(std::string book1, std::string book2);

    protected:

    std::string titleBook;
    std::string auth;
    int number;

};

class Journal: public Book
{

    public:

    Journal(int volume);

    void print();

    protected:

    int vol;

};

#endif

cpp file
#include <iostream>
#include "Book.h"
using namespace std;

Book::Book(string title, string author, int callNo)
{

    titleBook = title;
    auth = author;
    number = callNo;

};

void Book::print()
{

    titleBook = "   ";
    auth = "    ";
    number = 0;

};

bool Book::equals(string book1, string book2)
{

    bool printing = false;

    if(book1 == book2) {
        printing = true;
        cout << "Books are a match!";
        print();
    }
    else if (book2 != book1){
        printing = false;
        cout << "Books are not a match, try again.";
    }

};

Journal::Journal(int volume):Book(titleBook, auth, number)
{

    vol = volume;

};

void Journal::print()
{

    vol = 0;

};

main file:
#include <iostream>
#include "Book.h"
using namespace std;

int main()
{

    Book b1("Norton's Star Atlas", "A.P. Norton", 510);
    Book b2("Pocket Sky Atlas", "J. Sinot", 511);

    if (b1.equals(b1, b2)) {

       cout << "The books are the same" << endl;
}

     else {

       cout << "The books are different" << endl;
}

     b1.print();
     b2.print();
    }

    return 0;

}

A: Your issue is that your method signature and the actual call are different. In the  method signature in the Book class, you have the signature written as:
virtual bool equals(std::string book1, std::string book2);

This tells the compiler that Book has a method named equals and takes a std::string and a std::string. But in the main function you call it using two books:
Book b1("Norton's Star Atlas", "A.P. Norton", 510);
Book b2("Pocket Sky Atlas", "J. Sinot", 511);

b1.equals(b1, b2);

When the compile tries to find the equals method in Book, it does not find on which takes two Book instances rather than two std::string causing it to spit out the no matching function for call to 'Book::equals(Book&, Book&)' message.
You can fix this by adding an equals which accepts two Book instances. it should not matter whether you replace the existing function or overload  the current one; however, I doubt that you would ever want to compare books by their string value rather than their actual member properties.

A: Your equal function declared to take two strings, but you have provided two Book objects.
Assuming you want to compare two titles in your Book, your function looks like this;
bool Book::equals(const Book& book1, const Book& book2)
{

    if(book1.titleBook == book2.titleBook)
    {
        cout << "Books are a match!";
        return true;
    }
    else
    {
        cout << "Books are not a match, try again.";
        return false;
    }
};

Your print functions doesn't make sense;
I have modified your print functions, to print object members;
void Book::print()
{

    std::cout << "titleBook: " << titleBook << '\n'
              << "auth: " << auth << '\n'
              << "number: " << number;

};

void Journal::print()
{

    std::cout << "vol: " << vol;

};


text:
Q: Bash expansion of ${@} as command I have a parent script
while read cmd
do
  nohup ./script ${cmd[@]} &>> log &
done < ~/list

that executes this child script
while true
do
  eval "${CMD[@]}"
  #${CMD[@]}
  #./panic
done

with this list of commands
node ~/www/splash/app.js
node ~/www/splash-two/app.js

When the child script calls eval ${CMD[@]} it executes the way I expect running that command with no complaints but when I try to remove the eval and run the command using ${CMD[@]} it throws the error:
Error: Cannot find module '/home/rumplefraggle/SYS/RABBOT/~/www/splash/app.js'

Now I thought possibly this had something to do with the node command so I tried to execute

ls ~

as the command and it throws the error that ~ can not be found.
Echoing ${@} and not running it expands as I would expect it to.
Also manually inserting the command into the child script also works as expected
I don't understand why eval works and simply running the command using ${@} does not. What is causing ${@} to not expand the ~?
Why is node appending the directory name to the command when ${@} is used?

A: This is because of tilde expansion. The eval expands the tilde, which is replaced with the full path to the home directory. Without it, the command gets a literal tilde passed, and tries to use a relative path (that doesn't exist).
$ echo ~
/home/chris
$ echo "~"
~
$ eval 'echo ~'
/home/chris

A: You need quotes: "${cmd[@]}"
Without the quotes, all the elements of the array are smushed up into a single string. With quotes, each element will be properly handled individually.
From the manual:

If the subscript is '@' or '*', the word expands to all members of the array name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, [...] ${name[@]} expands each element of name to a separate word.


text:
Q: Find the inverse of the following matrix: $A$ Find the inverseof the following matrix:
$$A= \begin{bmatrix}
0 & 1 & 0 & 0 &0 \\
1 & 0 & 0 & 0 &0 \\
0 & 0 & 0 & 0&1  \\
0 & 0 & 1 & 0 &0 \\0&0&0&1&0
\end{bmatrix}$$
My attempt :  I think the inverse  will not exist because $\det A=0 $
Is it True ?
Any hints/solution will be appreciated.

A: Note that the given matrix is a so-called permutation matrix, the inverse of it is the permutation matrix associated to the inverse permutation.

Later edit: The matrix $A$ works on a "generic vector" $x$ with components $x_1,\dots, x_5$ as below by mapping it into a vector with components $x_{\sigma(1)}, \dots,x_{\sigma(5)}$ for a particular permutation $\sigma$. Explicitly:
$$
A
\begin{bmatrix}x_1\\x_2\\x_3\\x_4\\x_5\end{bmatrix}
=
\begin{bmatrix}
0 & 1 & 0 & 0 & 0 \\
1 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 1 \\
0 & 0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 & 0
\end{bmatrix}
\begin{bmatrix}x_1\\x_2\\x_3\\x_4\\x_5\end{bmatrix}
=
\begin{bmatrix}x_2\\x_1\\x_5\\x_3\\x_4\end{bmatrix}
$$
The corresponding permutation $\sigma$ (with the inverse $\tau$) is of course
$$
\sigma
=
\binom{12345}{21534}=(12)(354)\ ,
\qquad\text{ with }
\tau:=\sigma^{-1}=
\binom{12345}{21453}=(12)(345)\ .
$$
Now associate in the natural way the permutation matrix for $\tau$...
Note: It is important to see at a glance, that this matrix is a permutation matrix. (Exactly one $1$ entry on each row and/or column.) This is part of a structure. (One has a mapping / a representation of the symmetric group into the general linear group of the corresponding dimension over $\Bbb Z$, or $\Bbb Q$ if we prefer a field.) "Other answers" like writing $A$ as a $(2+3)\times(2+3)$ block matrix, then doing the work in smaller pieces, may also lead to a good end, but for my taste, if i see a structural answer, and a computational one (Gauss scheme, block split, adjoint matrix, etc...) the structural one wins for me.

A: This matrix is a permutation matrix and also orthogonal. What do you know about inverses of orthogonal matrices?

A: The determinant of the matrix is not $0$, the determinant is $1$.
Hint:
Take a look at $A^2, A^3,A^4,\dots$.

A: Note that this matrix is obtained from the identity matrix by exchanging columns (or rows), and that columns (and rows) are still linearly independent, so immediately we have that the determinant is not $0$. Even more precisely, we  immediately have that the determinant is $1$ or $-1$. (Immediately= without doing any calculation)

A: Interchange rows three times ($R_1-R_2, R_3-R_4,R_4-R_5$):
$$\det(A)= \begin{vmatrix}
0 & \color{blue}1 & 0 & 0 &0 \\
\color{red}1 & 0 & 0 & 0 &0 \\
0 & 0 & 0 & 0&\color{green}1  \\
0 & 0 & \color{brown}1 & 0 &0 \\0&0&0&\color{purple}1&0
\end{vmatrix}=(-1)^3\begin{vmatrix}
\color{red}1 & 0 & 0 & 0 &0 \\
0 & \color{blue}1 & 0 & 0 &0 \\
0 & 0 & \color{brown}1 & 0& 0  \\
0 & 0 & 0 & \color{purple}1&0 \\0&0&0&0&\color{green}1
\end{vmatrix}=-1\ne 0.$$
Consider the expanded matrix and perform the same row interchanges:
$$\begin{vmatrix}
0 & \color{blue}1 & 0 & 0 &0 \\
\color{red}1 & 0 & 0 & 0 &0 \\
0 & 0 & 0 & 0&\color{green}1  \\
0 & 0 & \color{brown}1 & 0 &0 \\0&0&0&\color{purple}1&0
\end{vmatrix}\begin{vmatrix}
1 & 0 & 0 & 0 &0 \\
0 & 1 & 0 & 0 &0 \\
0 & 0 & 1 & 0&0  \\
0 & 0 & 0 & 1 &0 \\0&0&0&0&0
\end{vmatrix} \Rightarrow \begin{vmatrix}
\color{red}1 & 0 & 0 & 0 &0 \\
0 & \color{blue}1 & 0 & 0 &0 \\
0 & 0 & \color{brown}1 & 0& 0  \\
0 & 0 & 0 & \color{purple}1&0 \\0&0&0&0&\color{green}1
\end{vmatrix}\begin{vmatrix}
0 & 1 & 0 & 0 &0 \\
1 & 0 & 0 & 0 &0 \\
0 & 0 & 0 & 1&0  \\
0 & 0 & 0 & 0 &1 \\
0 & 0 & 1 & 0 &0
\end{vmatrix} \ \ \ \ $$
Hence, the inverse matrix is:
$$A^{-1}=\begin{vmatrix}
0 & 1 & 0 & 0 &0 \\
1 & 0 & 0 & 0 &0 \\
0 & 0 & 0 & 1&0  \\
0 & 0 & 0 & 0 &1 \\
0 & 0 & 1 & 0 &0
\end{vmatrix}$$


text:
Q: Does Windows have the ln -s or equivalent? I need to link a file to C:\Windows\System32\drivers\etc\hosts
How can I do that with Windows ? Is there a soft link such as ln -s or equivalent in Windows ?

A: Powershell
As long as Microsoft advices to use powershell as a command interpreter since more than 5 years ago and cmd.exe is becoming a legacy application this question lacks an answer in Powershell:
New-Item -path ~\Desktop\hosts -itemType SymbolicLink -target c:\Windows\System32\Drivers\etc\hosts

This works as of Powershell v5.0

A: You are looking for the command "mklink".
Documentation and examples in Microsoft Docs or ss64.com.
Example taken from the link:
// To create a symbolic link named MyDocs from the root directory to the \Users\User1\Documents directory, type:
mklink /d \MyDocs \Users\User1\Documents

A: There are junctions but I don't know if this will do exactly what you need.
edit - oops sorry, junction only applies to directories not files

A: As @inf says, mklink is the solution for Vista and above.
For 2000/XP, you can use fsutil hardlink. Note that, unlike mklink, hardlink doesn't work across drives.

A: Link Shell Extension can create symbolic link (among other things).
Nice context menu integration.
Available for the most recent windows versions and frequently updated.

A: There may be other ways, but the one I'm familiar with is mklink:
C:\>mklink
Creates a symbolic link.

MKLINK [[/D] | [/H] | [/J]] Link Target

        /D      Creates a directory symbolic link.  Default is a file
                symbolic link.
        /H      Creates a hard link instead of a symbolic link.
        /J      Creates a Directory Junction.
        Link    specifies the new symbolic link name.
        Target  specifies the path (relative or absolute) that the new link
                refers to.

A: open the Terminal/CMD
under the android/sdk/tools,type
Terminal** ln -s emulator64-x86 emulator-x86**
CMDmklink emulator64-x86 emulator-x86
this will get created like..
symbolic link created for emulator64-x86 <<===>> emulator-x86


text:
Q: Extjs selectionmodel, getselection bug with nested models I'm having a problem getting selected record, here are my nested Models:
Ext.define('my.Address', {
    extend: 'Ext.data.Model',
    idProperty: '__guid__',
    fields: ['title', 'latitude', 'longitude', '__guid__']
});

Ext.define('my.POS', {
    extend: 'Ext.data.Model',
    idProperty: '__guid__',
    fields: ['__guid__', '__title__', 'password', 'image',
             'contact', 'category', {
                 name: 'address', model: 'my.Address'
             }]
});

Every times I post a record I reload the grid but getting selected record in this way:
   var rec = grid.getSelectionModel().getSelection()[0];

(rec is a my.POS) the address inside the record has guid equal to undefined.
If I look into the store in this way:
  grid.store.data.items[0].data.address[0].__guid__;

guid property is present!
Note that address is an array.
Someone had this problem solved?
Thanks

A: I've got it! the problem is the selection! If I deselect and then select the record it works!
Anyway it seems a bug...


text:
Q: Pandas read_csv from URL and include request header As of Pandas 0.19.2, the function read_csv() can be passed a URL. See, for example, from this answer:
import pandas as pd

url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
c=pd.read_csv(url)

The URL I'd like to use is: https://moz.com/top500/domains/csv
With the above code, this URL returns an error:
urllib2.HTTPError: HTTP Error 403: Forbidden

based on this post, I can get a valid response by passing a request header:
import urllib2,cookielib

site= "https://moz.com/top500/domains/csv"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}

req = urllib2.Request(site, headers=hdr)

try:
    page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print (e.fp.read())

content = page.read()
print (content)

Is there any way to use the web URL functionality of Pandas read_csv(), but also pass a request header to make the request go through?

A: As of pandas 1.3.0, you can now pass custom HTTP(s) headers using storage_options argument:
url = "https://moz.com:443/top500/domains/csv"

hdr = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
    'Accept-Encoding': 'none',
    'Accept-Language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive'
}

domains_df = pd.read_csv(url, storage_options=hdr)

A: I would recommend you using the requests and the io library for your task. The following code should do the job:
import pandas as pd
import requests
from io import StringIO

url = "https://moz.com:443/top500/domains/csv"
headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:66.0) Gecko/20100101 Firefox/66.0"}
req = requests.get(url, headers=headers)
data = StringIO(req.text)

df = pd.read_csv(data)
print(df)

(If you want to add a custom header just modify the headers variable)
Hope this helps


text:
Q: Can I replace the Windows bootloader with GRUB? I recently installed 12.04 via the Windows Installer, and I was wondering if it was possible to install Grub2 and use that instead of the Windows 7 boot-loader?
The Windows boot-loader works fine, however the Windows MSCOFIG application cannot see the partition (as it's code is not designed to detect Linux partition types (ext2, hpfs etc.)
I ran fdisk -l and it returned:
Disk /dev/sda: 750.2 GB, 750156374016 bytes
255 heads, 63 sectors/track, 91201 cylinders, total 1465149168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0x10a444cc

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      206847      102400    7  HPFS/NTFS/exFAT
/dev/sda2          206848  1416081407   707937280    7  HPFS/NTFS/exFAT
/dev/sda3      1416081408  1465147391    24532992   27  Hidden NTFS WinRE

A: Unfortunately, you cannot use GRUB2 to replace NTLDR because GRUB2 cannot load itself from an  NTFS partition.
You should understand that installing Ubuntu via Windows does NOT create it's own partition, but creates a flat file on the NTFS partition which is loop-mounted and then formatted as ext3. Thats why this partition will only be detected by tools running from within the Ubuntu install -- neither Windows nor a LiveUSB/LiveCD will detect it.


text:
Q: Facebook Proxy Loader Security I'm using a PHP proxy script to load images from Facebook into Flash without any sandbox violations.  It is taken from the guide here: http://www.permadi.com/blog/2010/12/loading-facebook-profile-picture-into-flash-swf-using-open-graph-api/.  The relevant PHP code is:
<?php
    $path=$_GET['path'];
    if (stristr($path, "fbcdn.")==FALSE && stristr($path, "facebook.")==FALSE)
    {
        echo "ERROR";
        exit;
    }
    header("Content-Description: Facebook Proxied File");
    header("Content-Type: image");
    header("Content-Disposition: attachment; filename=".$path);
    @readfile($path);
?>

The guide mentions that additional security measures are recommended for a real world application.  What additional measures would be applicable to this?  Maybe some kind of key passed from Flash to PHP?
I realise that there's nothing I can do to completely protect the Flash from being decompiled, but can I prevent the script from being used maliciously?

A: You should restrict the proxy to fetching image files from Facebook. You current "protection" will allow for example this URL: http://virus.provider.com/fbcdn./virus.exe

*

*Make better checks of the domain bname, maybe using the parse_url function.

*Check that you are indeed serving only images. Make sure the filename is ending in a image extension (this helps a lot for Windows clients), but also consider doing more thorough checks of the actual file content.

*Consider adding a check of the $_SERVER['HTTP_REFERER'] to lower the incentives to use your script for hotlinking. If the HTTP_REFERER is non-empty, check that it's actually your site in there. This will mostly protect you from bandwidth thieves.

*Make sure it's actually a remote path. Your current script can be tricked to sending for example your PHP files unparsed, including passwords and other secrets!

*The filname in the Content-Disposition header should be set to a filename, not to the entire path.

Also consider caching the file data on your proxy server to speed up multiple calls to the same file.
These are a few of the things to keep in mind. You may reveal more if you put some thought into it.


text:
Q: Use VS Online "Command Line" task with relative paths I'm trying to use the new VS Online Build process and, specifically, package my app as a NuGet package.
To do so I have to execute something like "nuget pack". My source code is in GitHub and there, under the root folder, I have a folder called .nuget with all necessary to do the packaging.
I've added to my build template a "Command Line" step with this parameters:

*

*tool: C:\a\9ea8689c\myusername\myproject.nuget\nuget.exe

*arguments: pack

Everything else is defaults, included working folder. This works. However when I've tried to replace the absolute path for something like ".nuget/nuget.exe" or .nuget/nuget.exe or even changing the working folder to .nuget and from there just type "nuget.exe" it repeatedly fails because it can't find the tool.
Am I missing something? Should the task work with relative paths?

A: You should use absolute paths leveraging TFS Environment Variables like TF_BUILD_BUILDDIRECTORY.
In a batch file it is something like
echo Launching my own NuGet copy
%TF_BUILD_BUILDDIRECTORY%\myproject.nuget\nuget.exe

A: This worked for me: $(BUILD.SOURCESDIRECTORY)\NuGet.exe.
Notice the dot instead of underscore. I have put my NuGet.exe in the main repository folder, in my case NuGet 3.5 Beta.


text:
Q: Can we monitor a database table read operation row-wise? I want to monitor, using a "read operation" on my one table in my database on SQL Server 2008.
So I want to know which row fetched at what time in that table.
It's not possible for me to do logging in my application.

A: If I understand you correct, you want to know every time your data were "displayed" to the end user? You can use a stored procedure to run your select statement (get data), but as a second statement run an insert into a log table with a timestamp and whatever information you are interested in.
CREATE PROC get_data
AS
BEGIN

    INSERT INTO log_table(timestamp,info1,info2)
    VALUES (GETDATE(), info1, info2)

    SELECT col1,col2
    FROM my_data

END
GO

Something like this.


text:
Q: Tkinter: how to have a button trigger such that it affects another button I am creating a GUI that is meant to emulate an online shop of some sort.
One part of the task is to have a button that will generate a HTML document with images of the user's chosen product category.
Below I have provided my four radio buttons along with their IntVar and commands.
Each of the RadioButton commands do the same thing but extract information from different websites, so for brevity I have only provided the command for the slipper category.
home_hobbies = Tk()

status = IntVar()

def show_slippers():
    #open downloaded file to extract info
    slipperfile = open('slippers.html','r',encoding = 'utf-8').read()
    prices = findall("(.*)", slipperfile) #regex prices
    titles = findall('
\n\s*(.*)', slipperfile) #regex titles
    select_categ.config(state=NORMAL) #make the text box edit-able
    select_categ.delete(1.0, END) #delete any text already in the text box
    #for loop to find first five items and print them
    for i in range(5):
        title = titles[i]
        price = prices[i]
        result = str(i+1) + ". " + title + ' - $' + price + "\n"
        select_categ.insert(END, result) #write list of products
    select_categ.config(state=DISABLED) #make sure the user can't edit the text box

slippers = Radiobutton(home_hobbies, command = show_slippers, indicator = 'off', variable = status, value = 1, text = 'Winter Slippers')
diy = Radiobutton(home_hobbies, command = show_diy, indicator = 'off', variable = status, value = 2, text = "DIY Supplies")
#newstock radiobuttons
sports = Radiobutton(home_hobbies, command = show_sports, indicator = 'off', variable = status, value = 3, text = "Pool Toys")
novelties = Radiobutton(home_hobbies, command = show_novelties, indicator = 'off', variable = status, value = 4, text = "Novelty Items")

select_categ = Text(home_hobbies, wrap = WORD, font = content_font, bg = widgetbg, fg = fontcolour, width = 40)

Above, I also provided the line of code that generates the Text widget as it may help in answering my question (I don't have a very deep understanding of this widget despite reading the effbot page about 20 times over).
I now have a different button whose task is to generate a HTML doc with it's own command, "show_img":
htmlshow = Button(home_hobbies, text = "View Product Images", command = show_img)

I am trying to make the show_img() command work such that I have a preamble of HTML coding, and then, depending on which radibutton has been chosen, the function will replace sections of the code with the corresponding information:
def show_img():
#in this section I write my HTML code which includes replaceable sections such as "image1" and source_url
    if slipper_trig:
        table = table.replace("source_url", ' Etsy - Shop Unique Gifts for Everyone')
        imgfile = open('slippers.html', 'r', encoding = 'utf-8').read()
        images = findall('<img\n*.*image\n*\s*src="(.*)"', imgfile)
        for i in range(5):
            image = images[i]
            table = table.replace("image"+str(i+1), image)

I tried to add BooleanVar into the commands for my Radio Buttons like this:
slipper_trig = False
diy_trig = False
pool_trig = False
novelty_trig = False

#Function for the product category buttons

#
def show_slippers():
    #make selected category true and change all others to false
    slipper_trig = True
    diy_trig = False
    pool_trig = False
    novelty_trig = False

As a way to distinguish between the categories but the GUI clearly doesn't remember the value of "slipper_trig" after its been defined as true in the "show_slippers" function.
Maybe I need to try and integrate the "show_img" command into my original functions that define the RadioButtons? Maybe I should be figuring out how to determine the category chosen by what's shown in the text box?
Any advice would be appreciated.
Thanks!

A: You didn't show minimal working code with your problem so I can only show some minimal example with Button and RadioButton to show how to use these widgets.
I don't know if you used command=function_name in Button.
BTW: it has to be function's name without ()
I don't know if you used .get() to get value from StringVar/Intvar/BooleanVar assigned to RadioButtons.
EDIT I added Checkbutton because probably you may need it instead of Radiobutton
import tkinter as tk

# --- functions ---

def on_click():
    selected = result_var.get()

    print('selected:', selected)

    if selected == 'hello':
        print("add HELLO to html")
    elif selected == 'bye':
        print("add BYE to html")
    else:
        print("???")

    print('option1:', option1_var.get())  # 1 or 0 if you use IntVar
    print('option2:', option2_var.get())  # 1 or 0 if you use IntVar

    if option1_var.get() == 1:
        print("add OPTION 1 to html")

    if option2_var.get() == 1:
        print("add OPTION 2 to html")

# --- main ---

root = tk.Tk()

result_var = tk.StringVar(root, value='hello')
rb1 = tk.Radiobutton(root, text="Hello World", variable=result_var, value='hello')
rb1.pack()
rb2 = tk.Radiobutton(root, text="Good Bye", variable=result_var, value='bye')
rb2.pack()

option1_var = tk.IntVar(root, value=0)
opt1 = tk.Checkbutton(root, text='Option 1', variable=option1_var)
opt1.pack()

option2_var = tk.IntVar(root, value=0)
opt2 = tk.Checkbutton(root, text='Option 2', variable=option2_var)
opt2.pack()

button = tk.Button(root, text='OK', command=on_click)
button.pack()

root.mainloop()

Doc on effbot.org: Button, Radiobutton, Checkbutton


text:
Q: How does one read aloud a birth year with no death year? Eg: John Smith (1994 – ) It is common to notate someone's lifespan using the syntax [year of birth] – [year of death]. When the subject is still living, you simply omit the death year, such as 1994 –.
When reading this aloud, is there a standard way to pronounce the unknown death year?
My hope would be that one is prescribed in a radio broadcast audio style guide, but I cannot locate any.

A: Obligatory "I am not a radio broadcaster" (but I am a native American English speaker)
In all cases, when describing human life spans, I've read and heard this phrase read as:

"Nineteen-ninety-four to present" (or "the present" or "the present day").

Other common options include:

"Born in 1994, currently living"

or

"Born in 1994, not yet deceased"

I would go with the option in bold if I were reading something aloud. Another really common option is simply not to say anything about the death year, implicitly stating that a death has not occurred.


text:
Q: Issue reading input from Java System.in I am trying to write a method that prompts a user for input on the command-line and reads their input as a String from stdin and returns in. The first time I call it, everything works properly. All calls to getInput() afterwards just return nothing.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Prompts the user for input and reads from standard input (stdin).
 * Note: Always check if the return is null!
 *
 * @param description Describes the user input.
 * @return A String of the input, or null when failed.
 */
private String getInput(String description)
{
    System.out.print(description + ": ");
    String input = null;

    InputStreamReader stream = null;
    BufferedReader reader = null;
    try {
        // Open a stream to stdin
        stream = new InputStreamReader(System.in);

        // Create a buffered reader to stdin
        reader = new BufferedReader(stream);

        // Try to read the string
        input = reader.readLine();

        // Exhaust remainder of buffer
        while (reader.skip(1) > 0) {
            // Do nothing
        }

    } catch (IOException e) {
        e.printStackTrace();
        // Error reading input

    } finally {
        // Clean up readers and streams
        try {
            if (reader != null) {
                reader.close();
            }
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
        }
    }

    System.out.print("\n");
    return input;
}

/**
 * Display the login prompt.
 */
private boolean promptLogin()
{
    // prompt for user name and password
    String user = getInput("Enter username");
    String pass = getInput("Enter password");

    if (user == null || pass == null) {
        System.out.println("Invalid login information.");
        return false;
    }
    // ..
     }

A: You must not close the Standard Input Stream; this is the reason it works only the first time
/**
 * Prompts the user for input and reads from standard input (stdin).
 * Note: Always check if the return is null!
 *
 * @param description Describes the user input.
 * @return A String of the input, or null when failed.
 */
private String getInput(String description) {
    System.out.print(description + ": ");
    String input = null;

    InputStreamReader stream = null;
    BufferedReader reader = null;
    try {
        // Open a stream to stdin
        stream = new InputStreamReader(System.in);

        // Create a buffered reader to stdin
        reader = new BufferedReader(stream);

        // Try to read the string
        input = reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return input;
}

/**
 * Display the login prompt.
 */
private boolean promptLogin() {
    // prompt for user name and password
    String user = getInput("Enter username");
    String pass = getInput("Enter password");

    if (user == null || pass == null) {
        System.out.println("Invalid login information.");
        return false;
    }

    return true;
}


text:
Q: Get a list of database tables that contain a specific column field? How to select all tables that contain a specific column?

A: Is this what you expect?
demo: db<>fiddle
SELECT table_name
FROM information_schema.columns
WHERE column_name = 'your_column_name'


text:
Q: TemplateProcessingException: Nested variables, map and foreach loop I have the following models,
public class Shift {
    private UUID id;
    private UUID unit;
    private List employees;
    private Timestamp startTime;
    private Timestamp endTime;

    ...
}

public class Unit {
    private UUID id;
    private String name;

    ...
}

following route,
path("/shift", () -> {
    get("", ShiftController.fetchShifts);
});

following controller,
public static Route fetchShifts = (Request req, Response res) -> {
    Map map = new HashMap<>();
    map.put("shifts", shiftDao.findAllByOrderByUnitAscStartTimeAsc());
    map.put("units", unitDao.findAllByOrderByName().stream().collect(Collectors.toMap(Unit::getId, u -> u)));
    return render(req, map, "shifts");
};

following template,

            unit

which gives me,
ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][qtp1905797065-18] Exception processing template "shifts": Exception evaluating OGNL expression: "units[dd002ece-10c7-11e7-9009-93b58da4760f].name"
...
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating OGNL expression: "units[dd002ece-10c7-11e7-9009-93b58da4760f].name"
...
Caused by: ognl.ExpressionSyntaxException: Malformed OGNL expression: units[dd002ece-10c7-11e7-9009-93b58da4760f].name [ognl.ParseException: Encountered "  "c7 ""
...

and for the death of me I can't figure out the problem. What I want is to iterate through all the shifts and find out the name of the unit for each shift. For this I create a map units in the controller with the ids of units and objects representing them. However, I'm unsuccessful in implementing the map in the template. *{units.get(__${s.unit}__).name} in the template gives similar errors.

A: It should look like this:

You have a few problems with your thymeleaf.
As the error message states, units[dd002ece-10c7-11e7-9009-93b58da4760f].name is not a valid expression.   As far as I know, you can only use the ${map[index]} expression with numbers (which look like map[0]) and strings (which look like map['test']).  Your expression is neither -- to the parser, you have a string missing the containing quotes.
Second, you're misusing __${}__ expressions.  You should really only need to ever use __${}__ when you are defining a th:field expression.  In most other cases, you should be able to do everything without them.


text:
Q: 1D Euler equations (fluid dynamics) with NDSolve Is it possible to accurately solve the 1D Euler equations in Mathematica using NDSolve?
For example, let us consider the Sod shock tube problem. Introduction to this problem can be found in the following links:
http://www.csun.edu/~jb715473/examples/euler1d.htm
https://en.wikipedia.org/wiki/Sod_shock_tube
Using the notation {r, v, e} for $(\rho,v,E)$ we can formulate the problem in Mathematica as:
g = 1.4;
p[x_, t_] := (g - 1) (e[x, t] - r[x, t] v[x, t]^2/2);
eqs = {
    D[r[x, t], t] + D[r[x, t] v[x, t], x] == 0,
    D[r[x, t] v[x, t], t] + D[r[x, t] v[x, t]^2 + p[x, t], x] == 0,
    D[e[x, t], t] + D[v[x, t] (e[x, t] + p[x, t]), x] == 0
};

and initial conditions
r0[x_] := 1.0 Boole[0 < x <= 0.5] + 0.25 Boole[0.5 < x <= 1.0];
v0[x_] := 0.0;
p0[x_] := 1.0 Boole[0 < x <= 0.5] + 0.1 Boole[0.5 < x <= 1.0];

Setting Dirichlet boundary conditions and throwing it into NDSolve:
ppR = 401;
ndsol = NDSolve[Join[eqs, {
    r[x, 0] == r0[x], r[0, t] == r0[0], r[1, t] == r0[1],
    v[x, 0] == v0[x], v[0, t] == v0[0], v[1, t] == v0[1],
    p[x, 0] == p0[x], p[0, t] == p0[0], p[1, t] == p0[1]}],
 {r, v, e}, {x, 0, 1}, {t, 0, 0.1},
 MaxSteps -> 10^3, PrecisionGoal -> 4, AccuracyGoal -> 4,
 Method -> {"MethodOfLines", "Method" -> "StiffnessSwitching",
 "SpatialDiscretization" -> {"TensorProductGrid",
  "DifferenceOrder" -> Pseudospectral, "MaxPoints" -> {ppR},
  "MinPoints" -> {ppR}}}]

Taking the solution and plotting
DensityPlot[Evaluate[First[v[x, t] /. ndsol]], {x, 0, 1}, {t, 0, 0.1}, ColorFunction -> Hue]

We see some nasty numerical errors. Is there anyway to get an accurate solution using NDSolve?
Edit: This paper suggests that the Method of Lines should apply: http://math.lanl.gov/~mac/papers/numerics/H79.pdf

A: Here's a solution by adding a very small viscosity μ to Euler equations (notice Euler equations can be seen as particular Navier–Stokes equations with zero viscosity and zero thermal conductivity):
γ = 1.4;
p[x_, t_] = (γ - 1) (Ε[x, t] - 1/2 ρ[x, t] v[x, t]^2);
eqs = With[{μ = 5 10^-4, ρ = ρ[x, t], v = v[x, t], p = p[x, t], Ε = Ε[x, t]},
   {D[ρ, t] + D[ρ v, x] == 0,
    D[ρ v, t] + D[ρ v^2 + p, x] == μ D[v, x, x](* <- The key point is here *),
    D[Ε, t] + D[v (Ε + p), x] == 0}];

ρ0[x_] = Piecewise[{{0.125, 0.5 < x <= 1}}, 1];
v0[x_] = 0;
p0[x_] = Piecewise[{{0.1, 0.5 < x <= 1}}, 1];

mol[n_Integer, o_: "Pseudospectral"] := {"MethodOfLines",
    "SpatialDiscretization" -> {"TensorProductGrid", "MaxPoints" -> n,
        "MinPoints" -> n, "DifferenceOrder" -> o}}

{solρ, solv, solΕ} =
  NDSolveValue[{eqs,
      {ρ[x, 0] == ρ0[x], ρ[0, t] == ρ0[0], ρ[1, t] == ρ0[1],
       v[x, 0] == v0[x], v[0, t] == v0[0], v[1, t] == v0[1],
       p[x, 0] == p0[x], p[0, t] == p0[0], p[1, t] == p0[1]}},
    {ρ, v, Ε}, {x, 0, 1}, {t, 0, 0.1}, Method -> mol[400, 4]];

μ should be small enough but not too small, or NDSolve will fail again. A dense enough spatial grid is also necessary. Though the warnings eerri and eerr  generated, the obtained solution is in good agreement with the one given in OP's link:
Manipulate[GraphicsRow[
  Plot[#, {x, 0, 1}, PlotRange -> {0, 11/10}] & /@ {solρ[x, t], solv[x, t],
    p[x, t] /. {ρ -> solρ, Ε -> solΕ, v -> solv}}, ImageSize -> 1000], {t, 0, 0.1}]

A: Update-1: The initial conditions in the question were wrong/incomplete. (removed 1/0 errors)
Update-2: The 1D Euler equations were modified to match this source. (ultimately not necessary in V10.4, but is in V8)
Update-3: Method options in NDSolve were modified to produce an accurate result. (ENO schemes are not yet supported, but the proposed answer below is robust enough to tackle a range of Euler fluid dynamic and MHD problems) Problem Solved!
eqs = {D[r[x, t], t] + D[r[x, t] v[x, t], x] == 0,
   D[r[x, t] v[x, t], t] + D[r[x, t] v[x, t]^2 + p[x, t], x] == 0,
   D[r[x, t] e[x, t], t] + D[r[x, t] v[x, t] (e[x, t] + p[x, t]/r[x, t]), x] == 0};

g = 1.4;
p[x_, t_] := (g - 1) r[x, t] (e[x, t] - v[x, t]^2/2);

(*Sod Shock Tube*)
r0[x_] := 1.0 Boole[0 <= x <= 0.5] + 0.125 Boole[0.5 < x <= 1.0];
v0[x_] := 0.0;
p0[x_] := 1.0 Boole[0 <= x <= 0.5] + 0.1 Boole[0.5 < x <= 1.0];

ppR = 400;

ndsol = NDSolve[Join[eqs,
    {r[x, 0] == r0[x], r[0, t] == r0[0], r[1, t] == r0[1],
     v[x, 0] == v0[x], v[0, t] == v0[0], v[1, t] == v0[1],
     p[x, 0] == p0[x], p[0, t] == p0[0], p[1, t] == p0[1]}],
   {r, v, e}, {x, 0, 1}, {t, 0, 0.1},
   MaxSteps -> Infinity, PrecisionGoal -> 1, AccuracyGoal -> 1,
   Method -> {"MethodOfLines",
     "SpatialDiscretization" -> {"TensorProductGrid",
       "MinPoints" -> ppR, "MaxPoints" -> ppR,
       "DifferenceOrder" -> 2},
     Method -> {"Adams", "MaxDifferenceOrder" -> 1}}];

p1 = DensityPlot[
   Evaluate[First[r[x, t] /. ndsol]], {x, 0, 1}, {t, 0, 0.1},
   PlotLabel -> "Density"];
p2 = DensityPlot[
   Evaluate[First[v[x, t] /. ndsol]], {x, 0, 1}, {t, 0, 0.1},
   PlotLabel -> "Velocity"];
GraphicsRow[{p1, p2}, ImageSize -> Large]

Manipulate[
 Plot[Evaluate[First[v[x, t] /. ndsol]], {x, 0, 1},
  PlotRange -> {{0, 1}, {0, 1}}], {t, 0, 0.1, 0.0025}]

A: This is a classical shock-tube problem in which a initially diaphragm separates a hi-pressure, high-density region from one of lower pressure and density. The classical exact solution has multiple discontinuities, a shock wave and a contact-surface (density discontinuity) that propagate to the right, and a continuous rarefaction wave traveling into the high-pressure gas.
The discontinuities cannot be captured by a pseudo spectral scheme,which produces the disastrous oscillations. This also occurs with many other spatial differencing schemes that have too little inherent dissipation. See the book "Difference Methods for Initial Value Problems" by Richtmeyer and Morton (1967), which discusses methods for adding "artificial viscosity" to the Euler equations. This enables the discontinuities to be successfully smeared out over multiple grid points.  There are many more modern methods that accomplish the same purpose. Try Googling the terms "Roe Scheme, ENO Scheme, Flux-Difference Splitting."
In short, Mathematica's NDSolve[] command is not yet able to handle directly the Euler equation flows that have discontinuous solutions, and this includes all mixed subsonic/supersonic flows such as your case. Theoretically, it should be able to handle subsonic flows, which are always continuous. Unfortunately, I have found to my dismay that NDSolve[] is not yet sophisticated enough to permit one to use the type of characteristics-based inflow and outflow boundary conditions that are an absolute necessity for generating stable, accurate subsonic flow solutions. I posted a question on this site two days ago, but the question was Closed Out (removed) by other more senior users who deemed it inappropriate. That question was titled "NDSolve rejects a common non-reflective subsonic outflow boundary condition for the 1-D Euler equations".


text:
Q: Return ID after insert with LINQ to SQL i know there are numerous topics already concerning this, since i googled it already but none of them can fit/work with my code as far as i can see.  I simply want to return an Auto Generated ID form my database after an insert. This is a part of my code:
    using (***LINQDataContext dc = new ***LINQDataContext())
    {
        dc.Users.InsertOnSubmit(new User
        {
            Username = user,
            Password = EncryptPassword(user, pass, 1, null, null),
            Email = email
        });

        dc.SubmitChanges();

        return true;
    }

A: var newUser = new User {
    Username = user,
    Password = EncryptPassword(user, pass, 1, null, null),
    Email = email
};
dc.Users.InsertOnSubmit(newUser);
dc.SubmitChanges();
// any identity / rowversion properties should now have values
var id = newUser.Id;


text:
Q: Nesting Multiple Quotations Inline JS I'm looking to add a bit of inline JS to a certain selection of jQuery (I realize that this is bad practice, but it's fine for a simple userscript, I believe). My code essentially gets me this type of jQuery object:
[text]

to which I then use
*each element of selection*.after('text2');

where definedFunction(param) is a function that takes a single string as an argument and has already been defined in a previous script and is available for my use (I believe?).
My problem is that when I run this code, I get text2 pointing to javascript:definedFunction(. I know I'm not using the escape sequences right, so if someone could please explain to me the proper way of doing that I would appreciate it.
What I'm trying to achieve is the injection of this:
text2

which I know is also missing some escape characters, though again I'm not sure where.
EDIT:
What if I was to replace Argument with a function that returns a string, and/or the name of a string variable?

A: If you do use strings around strings, it can appear ambiguous to javascript. That being said, sometimes it makes sense to do it, and you just need to use different quotes " or ' to ensure it is properly evaluated. TLDR - alternate your strings " and '
you can also escape your quotation marks using "\""


text:
Q: CSV file dump to yaml file in python I'm trying to dump a .csv file into a .yml file and have succedeed.
Only thing is that the syntax in the .yml file is not how I want it.
My .csv file:
NAME,KEYWORDS
Adam,Football Hockey

Where I read the .csv file and dump it into a .yml file:
import csv
import pandas
import yaml

""" Reading whole csv file with panda library """
df = pandas.read_csv('keywords.csv')

""" Dump DataFrame into getData.yml as yaml code """
with open('getData.yml', 'w') as outfile:
    yaml.dump(
        df.to_dict(orient='records'),
        outfile,
        sort_keys=False,
        width=72,
        indent=4
    )

How the .yml output looks:
-   NAME: Adam
    KEYWORDS: Football Hockey

How I want it to look:
-   NAME: Adam
    KEYWORDS: Football, Hockey

I want to have a comma between Football and Hockey. But if I put that in the .csv file it will all look weird because everything is separated by comma from the first place. How can i do this?

A: You have 2 options for that:
In a CSV file, if a comma is within quotes, then it won't be considered as a delimiter during parsing. This way, your CSV file would looks as follows:
NAME,KEYWORDS
Adam,"Football, Hockey"

Alternatively, you can process the KEYWORDS column after reading it. This would add the following to your code:
df = pandas.read_csv('keywords.csv')
df["KEYWORDS"] = df["KEYWORDS"].apply(lambda x: ", ".join(x.split()))

A: I reproduced your dataframe with:
df = pd.read_csv(io.StringIO(
"""
NAME,KEYWORDS
Adam,Football Hockey
"""
), sep=",")

I assume that there can be multiple keywords each separated with a space. To insert commas you can use the apply() method that pandas provides.
df.KEYWORDS = df.KEYWORDS.apply(lambda k: k.replace(" ", ", "))

Then run the rest of your code to produce the desired outcome.

A: The accepted answer is perfectly good.  It seems the task is converting a csv file into yaml.  If that is the case, the pandas library is not really necessary, as the built-in csv module can read csv files.
import csv
import yaml

with open('keywords.csv') as f:
    reader = csv.reader(f)
    next(reader) # skip header
    name_keywords = [ {'NAME': n, 'KEYWORDS': ', '.join(k.split())}
                      for n, k in reader ]

""" Dump DataFrame into getData.yml as yaml code """
with open('getData.yml', 'w') as outfile:
    yaml.dump(
        name_keywords,
        outfile,
        sort_keys=False,
        width=72,
        indent=4
    )