text:
Q: AngularJS ngOptions track by does not set entire object to ngModel Here my json object :
 $scope.todos = [{
    name: 'angular',
    field: ['a', 'b', 'c', 'd'],
    id: 1
  }, {
    name: 'asd',
    field: ['a', 'b', 'c', 'd', 'e'],
    id: 2
  }];

I give select as :
<select ng-model="dashboard.type" ng-options="item as item.name for item in todos track by item.name"></select>

Now when an option is chosen i want another select which iterates upon ngModel of previous select. The next   looks like :
<select ng-model="dashboard.label" ng-options="item as item for item in dashboard.type.field"></select>

It works fine when i choose the option manually but when their is a value in dashboard.type (eg: $scope.dashboard.type.name = 'qwe') in my script, it uses track by to choose the option and save it in dashboard.type, instead of saving the entire object it just saves the value used in track by option.
Value for dashboard.type:

*

*when i choose option manually :
{"name":"qwe","field":["a","b","c","d","f"],"id":3}

*When track by is used :
{"name":"qwe"}
NOTE: I cannot use track by item . It has to be a property of the object item. It can either be name or id.
Here's a plnkr.
Edit :
As pointed out by many, i would like to clarify that I can not initialise the object to any value of todos list. This is because dashboard.type.name value would be different every single time and todos list vary from 10 to 100's of objects. Now I have to iterate the list todos check if todos[index].name==someName and assign the relevant object. I am actively trying to avoid this soution (because there has to be a better way).
NOTE :  I also tried using ng-change and assign the actual object to dashboard.type.name but that works only when option is selected manually ,which already seems to be working fine. It does not assign the object when track by is used.
IMPORTANT: $scope.dashboard.type.name = 'qwe' is just an example. Value of $scope.dashboard.type.name may change every single time the page is loaded.
PS: Also i should have mentioned this earlier.Sorry, My bad!

A: This issue is not because of track by. Setting a default value by doing $scope.dashboard.type.name = 'qwe', causes ng-model to look like $scope.dashboard.type = {name : 'qwe'}. Instead of selecting the default value this way, you should use $scope.dashboard.type = $scope.todos[2];. This will make sure the entire object is set to $scope.dashboard.type.
Edited plunker

A: To initialize the modal by a default value you can use ng-init. For example
 <select ng-init="dashboard.type = todos[2]" ng-model="dashboard.type" ng-options="item as item.name for item in todos track by item.name">
  </select>

A: call this function on ng-init
in html
ng-init ="initialize();"

in js
$scope.dashboard={};//initialize object
$scope.dashboard.type ={}//initialize object

$scope.initialize =function(){

//no need to iterate if it is certain that your Id and index is always same suppose your initial id is 3

//then
var currId =3;//suppose initial id is there
$scope.dashboard.type =$scope.todos[currId]

}

here is codepen for it
http://codepen.io/vkvicky-vasudev/pen/MeexmK


text:
Q: Computing another graph with edges of exactly length l from an unweighted, undirected graph What is a method of making another graph featuring vertices that can be only gotten to with an edge length of l from every vertex V in the original unweighted (assume edges of length 1) and undirected graph G=(V,E). I came up with a solution that just searches through each branch from each V using depth-first search on each vertex until I found all the vertices of path length l from each vertex. This gives a runtime of O(V^(l+1)) so of course, this is not the optimal solution. Can anyone help me find a better solution with a better asymptotic runtime?

A: You could use the Floyd-Warshall algorithm that uses a matrix representation (as @Hammar suggested) but finishes in O(V^3) regardless of l. Instead of l matrix exponentiations, you determine all distances by sequentially inserting nodes and determining the effect on the shortest paths.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add plot markers into legend Bassicaly I work with the points in data and try to find clusters with different distance functions and show them in the grid.But,how can I add the plot markers "OpenMarkers" like with plot legend in the grid plot? Here is what I have done.
data = {{-1.1, 2.6}, {3.9, -0.8}, {4.2, -3.7}, {3.3, 3.5}, {3.9,
    5.2}, {4.1, -4.8}, {3.8, 3.7}, {5.6, 0.1}, {3.1, -5.2}, {-0.9,
    2.3}, {2.9, 4.1}, {-2.3, 3.9}, {-2.5, 3.}, {2.6, -5.5}, {5.2,
    1.9}, {-0.7, 1.3}, {0.9, 2.8}, {-1.5, 3.3}, {3.8,
    1.2}, {2.6, -5.1}, {-0.8, 3.2}, {4.7, 0.7}, {3., 3.}, {3.9,
    3.6}, {4.5, 1.4}, {4.2, 1.3}, {-1.1, 2.6}, {4.8,
    2.4}, {3.3, -3.5}, {3.2, -4.6}, {3.3, -4.9}, {3., 3.5}, {0.7,
    2.1}, {3.2, -4.3}, {-2., 0.5}, {-1.2, 2.}, {-1.6, 1.8}, {-3.5,
    3.7}, {4.8, 0.2}, {3.3, 2.4}, {-0.1, 2.1}, {-1.3, 2.5}, {4.4,
    3.9}, {3.5, 0.2}, {0.1, 2.9}, {-1., 1.6}, {-1.4, 4.5}, {3.2,
    2.5}, {-1.6, 2.4}, {2.6, -5.1}};

Plot1 = ListPlot[
   FindClusters[data, 2, DistanceFunction -> ChebyshevDistance],
   PlotMarkers -> "OpenMarkers", PlotLegends -> Automatic];
Plot2 = ListPlot[
   FindClusters[data, 2,
    DistanceFunction -> SquaredEuclideanDistance],
   PlotMarkers -> "OpenMarkers", PlotLegends -> Automatic];
Plot3 = ListPlot[
   FindClusters[data, 2, DistanceFunction -> EuclideanDistance],
   PlotMarkers -> "OpenMarkers", PlotLegends -> Automatic];

   Legended[Grid[{{Plot1, Plot2}, {Plot3, None}}],
 PointLegend[{ColorData[97, 101],
   ColorData[97, 102]}, {"\[EmptySmallCircle]", "\[EmptyUpTriangle]"}]]

I try to use Legended and PointLegended with the marker symbol but without succes.

A: nc = 2;
labels = {"cluster 1", "cluster 2"};

plots = ListPlot[FindClusters[data, 2, DistanceFunction -> #],
        PlotMarkers -> "OpenMarkers"] & /@
    {ChebyshevDistance, SquaredEuclideanDistance, EuclideanDistance};

legend = PointLegend[97,
    MapThread[Style[##, 16] &, {labels, ColorData[97] /@ Range[Length@labels]}],
    LegendMarkers -> "OpenMarkers"];

Legended[Multicolumn[plots, 2], legend]

or
Legended[Grid @ Partition[plots, 2, 2, 1, {}], legend]

same picture

Use
nc = 3;
labels = {"cluster 1", "cluster 2",, "cluster 3"};

to get

A: If the intent is to have a common legend
Partition[
  Append[
   ListPlot[
      FindClusters[data, 2,
       DistanceFunction -> #],
      PlotMarkers -> "OpenMarkers",
      PlotLabel -> #] & /@
    {ChebyshevDistance,
     SquaredEuclideanDistance,
     EuclideanDistance},
   Column[{
     Style["○  Cluster 1", 16, Bold, ColorData[97][1]],
     Style["△  Cluster 2", 16, Bold,
      ColorData[97][2]]}]], 2] //
 Grid[#, Spacings -> {Automatic, 3}] &

Using Legended
Legended[
 Partition[
   Append[
    ListPlot[
       FindClusters[data, 2,
        DistanceFunction -> #],
       PlotMarkers -> "OpenMarkers",
       PlotLabel -> #] & /@
     {ChebyshevDistance,
      SquaredEuclideanDistance,
      EuclideanDistance}, ""], 2] //
  Grid[#, Spacings -> {Automatic, 3}] &,
 Placed[
  PointLegend[
   ColorData[97] /@ Range[2],
   StringForm["Cluster ``", #] & /@ Range[2],
   LegendMarkers -> {{"○", 16}, {"△", 16}}],
  {0.85, 0.2}]]


text:
Q: PHP login check flow Im having trouble with a php login script (below). I want to redirect to nouser.php if someone enters a username that does not exist and to wrongpass.php if the wrong password (but a valid username) is entered. The below code almost works. If I comment out the entire wrong password section then the nouser section works as expected displaying the nouser page , but if I leave the wrong password section in I get the wrongpass.php page for both nouser and wrong password situations. If I put a valid user in but with wrong password then I get wrong password (correct behavior).
Simply put , how can i make sure that I get redirect to nouser.php if there is nouser of this name and not the wrongpass.php page..
<?php
            $username = $_POST['username'];
$password = $_POST['password'];
//connect to the database here

require_once 'includes/login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());

mysql_select_db($db_database, $db_server)
    or die("Unable to select database: " . mysql_error());

$username = mysql_real_escape_string($username);
$query = "SELECT password, salt
        FROM users
        WHERE username = '$username';";
$result = mysql_query($query);
//wrong user section
if(mysql_num_rows($result) < 1) //no such user exists
{
    header('Location: nouser.php');
}
//wrong password section
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
    header('Location: wrongpass.php');
}
//login successful

?>

A: I think you should add die() to stop the script
if(mysql_num_rows($result) < 1) {
    header('location:nouser.php');
    die();
}

Has not yet test the code.


text:
Q: How can I know if an application reads my hardware fingerprint? I would like to know (for security and privacy reasons) if a certain Windows 7 desktop program actually reads my hardware fingerprint including hard drive serial number, CPU serial number, or any other unique information (Windows product PID, for example) which can be used to identify a given computer. Can Process Monitor do it? If so, how? If not, is there some other program or method I can use to find out?

A: As a programmer myself, I cannot imagine that such a program would, or even could exist. I'll explain why.
There is no single hardware ID; rather, as you said, there are various other unique identifiers that can be used to build a unique profile (much like how online advertisers build a profile by collecting individual bits of information like website visits).
Any program can read any or all of that information (access limitations notwithstanding), and what any given program (or more specifically, its developers) consider sufficiently unique is arbitrary. One developer may consider a Windows PID enough while another (*cough*Microsoft*cough*) will use several. There is really no way to know exactly when a program is taking a hardware fingerprint. There are legitimate reasons that a program may access pretty much any of those bits of information, so it would be difficult to determine whether it is taking a fingerprint or just doing some work.
That said, it could be possible to detect a fingerprint attempt by heuristics. For example, you could detect if a program makes an attempt (or has code) to read multiple pieces of unique data. If so, then you could tell the user about it and let them decide whether it is trying to fingerprint the system or just doing its work (like how anti-malware programs have to allow the user to make a decision about potentially suspect, but not provably guilty software behaviors). Of course even then, the readings could be spread out and thus be even less likely to be detected.
You could manually observe a program, but there are not tools to monitor and log access to every kind of unique information that a program could read (in fact, it is conceivable that it could use a unique piece of uniquely identifying information (i.e., one that is not well known or generally used in that way).
(I can't help but ponder that it might be possible to get a better reading of fingerprinting attempts by using a VM, especially with a custom OS like ReactOS…)
In summary, there is no fool-proof way to know when a program is fingerprinting a system. You can try observing access to common information, but that doesn't guaranteed detection of an attempt to fingerprint by any stretch of the imagination.
If you have concerns about a program, your best bet is simply to research that specific program to see if others have already discovered that it takes a system fingerprint (like how Windows WPA was dissected), or at least to raise the flag so that security experts can disassemble the code, analyze it, and find out.


text:
Q: How do I navigate to a Web Forms ASPX page from my MVC3 application? I find myself having to create a Web Form page in my MVC3 application to host the ReportView control, for displaying rdlc reports for my users. I see quite an abundance of advice on how to go about this all, and it seems pretty simple.
What I would like to know is how do I get from a Razor based view to this report viewer page? Do I simply 'hard-code' a content url to the page, or is there some more polite way?

A: You can do this by adding route in global.asax file.
     routes.MapRoute(
         "ReportRoute",                         // Route name
         "Reports/{reportname}",                // URL
         "~/Reports/{reportname}.aspx"   // File
      );

Check out LeftyX solution with source code.

A: You could use the Url.Content helper:
Show me the report


text:
Q: Vue.js, options for multiple classes on v-bind I need some help trying to figure out how to give the v-bind:class multiple options.
My Uno game, as it loops through your cards, needs to look at the cards color which is in a list of objects ex. ([{ Color: green, Value: 6}] and determine what color of text the card should be.
This is what I have come up with so far:
Vue.js
getClass: function(card){
            var result = [];
            console.log(card);
            if (card.Color == "red"){
                result.push('red');
            }else if (card.Color == "green"){
                result.push('green');
            }else if (card.Color == "blue"){
                result.push('blue');
            }else if(card.Color == "yellow"){
                result.push('yellow');
            }
            console.log(result);
            return result;
        },

HTML

        <button id="myCard" v-for="card in myCards" v-bind:class="getClass(card)"
         @click="playCard(card)">
         {{card.Color}} {{card.Value}}
        </button>

CSS
ul{
    text-align: left;
}
#myCards{
    padding: none;
}
#myCard{
    display: inline-block;
    height: 100px;
    width: 70px;
    border: 1px solid black;
    color: black;
    border: 2px solid black;
    border-radius: 6px;
    background-color: white;
    color: black;
    vertical-align: middle;
    margin: 5px;
}
.red{
    color: red;
}
.green{
    color: green;
}
.blue{
    color: blue;
}
.yellow{
    color: yellow;
}

A: Since there's one property called Color inside the card object you could use style object syntax and you don't need to define classes for each color:

        <button id="myCard" v-for="card in myCards"
         @click="playCard(card)">
         {{card.Color}} {{card.Value}}
        </button>

Vue.config.devtools = false;
Vue.config.productionTip = false;

let app = new Vue({
  el: "#app",

  data() {
    return {
      myCards: [{
          Value: 'card 1',
          Color: 'red'
        },
        {
          Value: 'card 2',
          Color: 'blue'
        },
      ]

    }
  },
  methods: {

  }
})
ul {
  text-align: left;
}

#myCards {
  padding: none;
}

#myCard {
  display: inline-block;
  height: 100px;
  width: 70px;
  border: 1px solid black;
  color: black;
  border: 2px solid black;
  border-radius: 6px;
  background-color: white;
  color: black;
  vertical-align: middle;
  margin: 5px;
}

    <button id="myCard" v-for="card in myCards" :style="{color:card.Color}">
         {{card.Value}}
        </button>


text:
Q: DVC(Data Version Control) keeps stuck at "dvc add xxx" with "Collecting stages from the workspace" in the terminal? I used : dvc[webhdfs]==2.9.3, installed by pip install dvc[webhdfs]
Then the repo is already cloned by git.
I have also typed : dvc remote add -d storage webhdfs://xxx/dvc and git add .dvc/config
But the command dvc add ./assets/xxx/* was still stuck...
The command line window keeps showing : Collecting stages from the workspace


text:
Q: PHP preg_match exact match and get whats inside brackets Lets say I have the following string:
"**link(http://google.com)*{Google}**"

And I want to use preg_match to find the EXACT text **link(http://google.com) but the text inside the brackets changes all the time. I used to use:
preg_match('#\((.*?)\)#', $text3, $match2);

Which would get what is inside the brackets which is good but if I had: *hwh(http://google.com)** it would get whats inside of that. So how can i get whats inside the brackets if, in front of the brackets has **link?

A: Here
preg_match("/\*\*link\((\D+)\)/",$text,$match);

A: ~(?:\*\*link\(([^\)]+)\))~ will match contents in the brackets for all inputs that look like **link(URL) but do not contain extra ) inside URLs. See the example on Regexr: http://regexr.com/3en33 . The whole example:
$text = '"**link(http://google.com)*{Google}**"
**link(arduino.cc)*{official Arduino site}';
$regex = '~(?:\*\*link\((?<url>[^)]+))~';
preg_match_all($regex, $text, $matches);

var_dump($regex, $matches['url']);

A: Use a lookbehind operator ?<=
(?<=\*\*link)\((.*)\) gives you what's inside braces if the text behind is **link
Update:
Here's a PHP example
Here's a regex example


text:
Q: What are the basic principles of experimental electromagnetism? I want to learn about experimental physics in the context of electrodynamics and electrostatics. Basically I'd like to know how we are able to measure different quantities in this field (electric field, potential, etc):

*

*What are the basic measuring devices and principles? For example in Griffiths' book he mentions how measuring the radius of a particle in a particle accelerator can tell us what is the momentum.

*What are some significant milestones in the field? For example Millikan's oil drops experiment.


text:
Q: Loosing DataContext focus when set second DataContext I have class TabItemView.xaml.cs with constructor. I'm setting in it DataContext to MainViewModel because in TabItemView located DataGrid to wich I need to bind data.
public partial class TabItemView : UserControl
{
    public TabItemView()
        {
            InitializeComponent();
            MainViewModel myModel= new MainViewModel();
            this.DataContext = myModel;
        }
    }

In class MainWindow.xaml.cs I also set DataContext to the MainViewModel in the button_Click event. This event adds new Tab on button click
 public partial class MainWindow2 : Window
    {
     //Constructor and some other stuf
                 .....
  private void AddInvoice_Click(object sender, RoutedEventArgs e)
    {
        count++;

        string s = string.Format("Tab {0}", count);
        mainViewModel.Items.Add(new ItemViewModel(s));
        this.DataContext = mainViewModel;
    }
}

This is my MainViewModel
 public class MainViewModel : ViewModelBase
{
    private ObservableCollection<ItemViewModel> items = new ObservableCollection<ItemViewModel>();
    private ObservableCollection<ItemViewModel> invoice_items = new ObservableCollection<ItemViewModel>();

    public ObservableCollection<ItemViewModel> Invoice_Items
    {
        get
        {
            return invoice_items;
        }
        set
        {
            invoice_items = value;
            OnPropertyChanged("Invoice_Items");
        }
    }

    public ObservableCollection<ItemViewModel> Items
    {
        get
        {
            return items;
        }
        set
        {
            items = value;
            OnPropertyChanged("Items");
        }
    }

    private int _selectedTabIndex;

public int SelectedTabIndex
{
    get { return _selectedTabIndex; }
    set { _selectedTabIndex = value; }
}

public MainViewModel()
{
    SelectedTabIndex = 0;
}

}

}
This is markup for MainWindow
Grid>
            <TabControl
        ItemsSource="{Binding Items}" SelectedIndex="{Binding SelectedTabIndex, Mode=TwoWay}">
                <TabControl.ItemTemplate>
                    <DataTemplate>
                        <DockPanel>
                            <TextBlock Text="{Binding TabName}"><TextBlock.Background><SolidColorBrush /></TextBlock.Background></TextBlock>
                            <Button Name="btnDelete" DockPanel.Dock="Right" Margin="5,0,0,0" Padding="0"  CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Name}" BorderBrush="#00000000">
                                <Image Source="/WPF_AccApp;component/Images/11.gif" Height="11" Width="11"></Image>
                            </Button>
                            <DockPanel.Background>
                                <SolidColorBrush />
                            </DockPanel.Background>
                        </DockPanel>
                    </DataTemplate>
                </TabControl.ItemTemplate>
                <TabControl.ContentTemplate>
                    <DataTemplate>
                        <views:TabItemView />
                    </DataTemplate>
                </TabControl.ContentTemplate>
                <TabControl.ItemContainerStyle>
                    <Style TargetType="{x:Type TabItem}">
                        <Setter Property="IsSelected" Value="{Binding IsSelected}" />
                    </Style>
                </TabControl.ItemContainerStyle>
            </TabControl>
        </Grid>

And this is for TabItemView
<UserControl x:Class="WPF_AccApp.Views.TabItemView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="640" d:DesignWidth="800" Focusable="True" IsHitTestVisible="True">
    <Grid Name="grid1" HorizontalAlignment="Stretch" VerticalAlignment="Top" MinWidth="768" MinHeight="446" Focusable="True">
        <Grid.RowDefinitions>
            <RowDefinition MinHeight="43" Height="*" />
            <RowDefinition Height="*" MinHeight="45" />
            <RowDefinition Height="*" MinHeight="45" />
            <RowDefinition Height="*" MinHeight="350" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" MinWidth="100" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBox Text="{Binding Supplier}" Grid.Column="1" Height="27" Name="textBox1" VerticalAlignment="Top" Margin="11,6,0,0" HorizontalAlignment="Stretch" Width="Auto" FontSize="14" HorizontalContentAlignment="Stretch" MinWidth="141" FlowDirection="LeftToRight" DataContext="{Binding}" />
        <Label Content="Supplier" Height="27" Name="label2" VerticalAlignment="Top" FontSize="14" FontFamily="Tahoma" FontWeight="Bold" Margin="21,6,0,0" Width="Auto" IsEnabled="True" HorizontalAlignment="Stretch" Foreground="Black" Background="White" MinWidth="133" HorizontalContentAlignment="Stretch" />
        <TextBox Text="{Binding SupplierBank}" Grid.Column="1" Grid.Row="1" FontSize="14" Height="27" HorizontalAlignment="Stretch" Margin="11,6,0,0" Name="textBox11" VerticalAlignment="Top" Width="Auto" MinWidth="141" />
        <Label Grid.Row="1" Content="Supplier Bank" FontFamily="Tahoma" FontSize="14" FontWeight="Bold" Height="27" Margin="21,6,0,0" Name="label3" VerticalAlignment="Top" Width="Auto" Background="White" MinWidth="133" />
        <TextBox Text="{Binding SupplierAccount}" Grid.Column="1" Grid.Row="2" FontSize="14" Height="27" HorizontalAlignment="Stretch" Margin="11,6,0,0" Name="textBox12" VerticalAlignment="Top" Width="Auto" MinWidth="141" />
        <Label Grid.Row="2" Content="Account Number" FontFamily="Tahoma" FontSize="14" FontWeight="Bold" Height="27" Margin="21,6,0,0" Name="label4" VerticalAlignment="Top" Background="White" MinWidth="133" />
        <TextBox Text="{Binding Buyer}" Grid.Column="4" FontSize="14" Height="27" Margin="11,6,20,0" Name="textBox2" VerticalAlignment="Top" HorizontalAlignment="Stretch" Width="Auto" MinWidth="141" />
        <Label Grid.Column="3" Content="Buyer" FontFamily="Tahoma" FontSize="14" FontWeight="Bold" Height="27" Margin="21,6,0,0" Name="label5" VerticalAlignment="Top" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Background="White" MinWidth="133" />
        <TextBox Text="{Binding BuyerBank}" Grid.Column="4" Grid.Row="1" FontSize="14" Height="27" HorizontalAlignment="Stretch" Margin="11,6,20,0" Name="textBox3" VerticalAlignment="Top" Width="Auto" MinWidth="141" />
        <Label Grid.Column="3" Grid.Row="1" Content="Buyer Bank" FontFamily="Tahoma" FontSize="14" FontWeight="Bold" Height="27" Margin="21,6,0,0" Name="label6" VerticalAlignment="Top" Width="Auto" HorizontalAlignment="Stretch" Background="White" MinWidth="133" />
        <TextBox Text="{Binding BuyerAccount}" Grid.Column="4" Grid.Row="2" FontSize="14" Height="27" HorizontalAlignment="Stretch" Margin="11,6,20,0" Name="textBox4" VerticalAlignment="Top" Width="Auto" MinWidth="141" />
        <Label Grid.Column="3" Grid.Row="2" Content="Account Number" FontFamily="Tahoma" FontSize="14" FontWeight="Bold" Height="27" Margin="21,6,0,0" Name="label7" VerticalAlignment="Top" Width="Auto" HorizontalAlignment="Stretch" Background="White" MinWidth="133" />
    <DataGrid AutoGenerateColumns="False" Grid.ColumnSpan="5" Grid.Row="3"
              Height="104" HorizontalAlignment="Stretch" Margin="55,115,55,0" Name="dataGrid1"
              VerticalAlignment="Top" Width="Auto" CanUserResizeRows="True" ItemsSource="{Binding Invoice_Items}"
              IsReadOnly="False" SelectionUnit="Cell" CanUserAddRows="True">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Item Name" Binding="{Binding Item_Name, Mode=TwoWay}"/>
            <DataGridTextColumn Header="Mesure" Binding="{Binding Mesure, Mode=TwoWay}"/>
            <DataGridTextColumn Header="Quantity" Binding="{Binding Quantity, Mode=TwoWay}"/>
            <DataGridTextColumn Header="Price exc VAT" Binding="{Binding Price_exc_VAT, Mode=TwoWay}"/>
            <DataGridTextColumn Header="VAT" Binding="{Binding VAT, Mode=TwoWay}"/>
            <DataGridTextColumn Header="Price Inc VAT" Binding="{Binding Price_inc_VAT, Mode=TwoWay}"/>
            <DataGridTextColumn Header="Total" Binding="{Binding Total, Mode=TwoWay}"/>
        </DataGrid.Columns>
    </DataGrid>
    <TextBox Grid.ColumnSpan="3" Grid.Row="3" Height="27" HorizontalAlignment="Stretch" Name="textBox5" VerticalAlignment="Top" Grid.Column="1" Margin="11,0,0,0" />
    <Label Background="White" Content="Shipping Address" FontFamily="Tahoma" FontSize="14" FontWeight="Bold" Height="27" Margin="21,0,0,0" MinWidth="133" Name="label1" VerticalAlignment="Top" Grid.Row="3" />
    <Label Background="White" Content="Invoice #" FontFamily="Tahoma" FontSize="14" FontWeight="Bold" Height="27" Margin="78,65,0,0" MinWidth="133" Name="label8" VerticalAlignment="Top" Grid.Column="1" Grid.Row="3" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" />
</Grid>

Now the problem. When I'm setting DataContext only in MainWindow my TextBoxes are reacting normaly and my ObservableCollection Items is notified about changes. When I add new Tab it creates normaly with no text in TextBoxes.
But, when I set DataContext in both MainWindow and TabItemView (like in code which I added) to notify my Invoice_Item ObservableCollection about changes in DataGrid my DataContext for both ObservableCollection's are lost, they are no longer notified about changes. When I add new Tab it dublicates data that I added in previous Tabs in both TextBoxs and DataGrid.
Also when I don't set DataContext in MainWindow and set it only in TabItemView my ObservableCollection Invoice_Items becomes notified about changes in DataGrid, but when I add new Tab, DataGrid's data just dublicates in each added Tab.
Why is this happening, what I'm doing wrong? And how can I fix this issues?
If you need more code or info just say. I'm looking for any help in understanding how to solve my problem. Thank you for the answers.


text: Q: Twitch Bot in Java using 25%+ CPU for select users I am developing a Twitch Bot that is built in C# for the GUI and Java for the logic. I have about 100+ users so far but I have heard complaints from 5 users that the Java process uses 25-30%+ CPU usage. Whereas for me and 95% of the users it never reaches above 5% even when it is being tested very hard. It's not operating system because some of the users use Windows 7, 8.1, and 10. Does anyone have an idea on why there would be such a difference for these select users? I have tried looking into many different aspects but cannot find the problem.


text:
Q: How to inject IServiceContainer when using LighInject? I am using LightInject and now I need to know how to resolve a type myself. I've tried to use IServiceContainer, but when I inject this interface into my class I get an error saying that is an unresolved dependency.
The thing I want te solve is this. At runtime I have a Type that I need a instance from. So I want to do something like SomeResolver.GetInstance(myType).
How can I do this with LightInject?

A: I've got a working solution. Don't know if this is the 'preferred' way, so if anyone has a better idea, please let me know :)
Here's what I use now:
container.Register<ITypeResolver>(s => new LightInjectTypeResolver(s));
And here's the class implementing ITypeResolver:
public class LightInjectTypeResolver : ITypeResolver
{
    private readonly IServiceFactory _serviceFactory;

    public LightInjectTypeResolver(IServiceFactory serviceFactory)
    {
        _serviceFactory = serviceFactory;
    }

    public object GetType(Type entity)
    {
        return _serviceFactory.GetInstance(entity);
    }
}


text:
Q: Create Issue in github through api using nodejs and request: response is undefined I have read this issue: Making a Post request to Github API for creating issue is not working but I am looking for support using the request module. I've read the github documentation, but I'm having a hard time translating their curl examples to javascript.
This is part of a larger attempt at slack/github integration with slash commands. Right now I am just trying to submit a generic request to github. When I log the body of the response, it is 'undefined'.
I would prefer not to use a github wrapper because I would like to understand what I am doing and why it isn't working better.
Any help for this noob is much appreciated.
EDIT: Made changes as suggest in comments
Error is ECONNREFUSED
I'm getting an error when I try to log the response status because response is undefined.
    request({
    "url":"http://api.github.com/repos/user/repo/issues",
    "method":"POST",
    "headers": {"Authorization": "auth token"},
    "body": JSON.stringify({ title: "Found a bug", body: "I'm having a problem  this." })
    }, function(err, response, body) {
        console.log(body);
        if (err) console.log(err);
    });
  });

A: Among the other issues as outlined in the comments (thank you everyone). In my URL I had http instead of https.
DOH


text:
Q: Using the name of a generic type in a class attribute I have a generic class which needs to use the name of one of its type arguments in a class attribute. I don't know how to access the class name in that context
I've tried using typeof(TMsg).Name but VS shows an error saying

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

Currently my code looks like this:
[MessageBase(typeof(TMsg).Name)]
    public abstract class DDSMessageAbstract<TMsg/*, TReader, TWriter, TMsgBase, TSupport*/> : MessageBaseForDDS
    where TMsg : new()
...

My question is, is there a way for me to use the actual name of TMsg or  must I define this attribute for each inheriting class?

A: The short answer might be you could not do that.
First, the generics is for your class instead of your attribute. so you can't use
MessageBase(typeof(TMsg)

The values into attributes are limited to simple types; for example, basic constants (including strings) and typeof.
From ECMA 334v4:

§24.1.3 Attribute parameter types
The types of positional and named
  parameters for an attribute class are
  limited to the attribute parameter
  types, which are:

*

*One of the following types: bool, byte, char,
  double, float, int, long, short, string.

*The type object.

*The type System.Type.

*An enum type, provided it has public accessibility and the
  types in which it is nested (if any)
  also have public accessibility.

*Single-dimensional arrays of the above
  types.

ECMA-334


text:
Q: loadPlaylist function doesn't work in Flash mode of the IFrame player API Name of API affected:
IFrame player API
Issue summary:
loadPlaylist() function doesn't work in Flash mode of the IFrame player API.
Steps to reproduce issue:
Please Visit the demo page I created for this bug:
http://www.gilgoldshlager.com/youtube_bug.html
Expected output:
Be able to load and switch between playlists.
Actual results:
Not able to load and switch between playlists.
Notes:
I wrote all the reproduce steps in the bug demo page I created:
http://www.gilgoldshlager.com/youtube_bug.html
Please let me know if it is a bug or if I'm doing anything wrong.
Thank you, Gil.


text:
Q: How to describe the graph of wedding guests mathematically? I'm working with a particular graph problem and I'm not sure how to describe it. I dug up my algorithms textbook and can't find anything exactly right. I'm trying to plot a path through a weighted undirected complete graph where the weight of the path is defined by the 1-to-1 weights between all vertices.
Here's an example. Imagine I'm making seating charts for a wedding. Some wedding guests are good friends and others... not so much. I used an undirected graph with each guest on the vertices and the 1-to-1 relationships between guests as the edges. Here's a graph of the relationships between the guests Amy, Brent, Charlie, and Donald. I abbreviated their names as A, B, C, and D.

Donald caused some drama and has negative relationships with other guests. To maintain harmony, I want don't want the sum of relationships at any table to be negative. Imagine putting Amy, Brent, and Donald at the same table.

The sum of the edge weights between these three people is 5-5-5=-5, which is less than zero. So I don't want this table arrangement. In the past, I've looked at one weight at a time when constructing paths, so this would be a path from AB (+5) that continues BC (-5), meaning the path ABC would have a weight of 0. Here I want to include the edge weight AC (-5) as well.
Is there a name for a path through a graph like this where you have to count the total 1:1 edge weights instead of just the edges used in a path?

A: If you want to sum the edge weights for all pairs of people who are seated at the same table, you are talking about a complete subgraph, which is called a clique.  You might also be interested in this blog post, where the objective is to minimize the sum across tables of the maximum unhappiness at the table.


text:
Q: Trying to encode multiple audio files and map them to specific channels with FFmpeg I have a video file(V1) and two stereo audio files(A1 & A2). I'm trying to output a movie with the video content and duration from V1, and I want to set A1's audio to the left channel and A2's audio to the right channel, even if those sources are originally stereo.
I've been playing around with the stereotools and pan filters but I'm honestly having trouble deciphering the documentation. Any help is appreciated.

A: I think I've got it or pretty close at least. I still need to figure out how to control the duration but the -shortest flag encodes it at the shortest duration which is actually what I need in this case.
ffmpeg -i video.mov -i audio1.wav -i audio2.wav -filter_complex "[1:a][2:a]amerge=inputs=2,pan=stereo|c0<c0+c1|c1<c2+c3[aout]" -map 0:v -map "[aout]" -shortest output.mp3


text:
Q: Pandas drop_duplicates function not working properly I'm working on building a bridge table between two tables with a many-to-many relationship. Table A contains employee IDs and job assignments (one employee can have more than one assignment). Table B has the same structure. The aim is to build a reconciliation report to find misalignment of job assignments for each employee between Table A and Table B.
To create the bridge table I created a union of Table A and Table B using the concat function. This creates a table with all the employee IDs and the different job assignments. Below is a table showing all the assignments for one employee:
employee_id  job_assignment
001          sales
001          marketing
001          management
001          sales
001          marketing
001          HR

But since this is a bridge table I don't want all these duplicate records. I want the output to look like this:
employee_id  job_assignment
001          sales
001          marketing
001          management
001          HR

I then run bridge.drop_duplicates(inplace = True) to drop all the duplicate records, but it is failing to do so.
The datatype for both of these columns are 'object'
I'm still pretty new to manipulating data and building dataframes in pandas and assistance would be much appreciated.


text:
Q: Как сделать починить фон (из картинки) Да уж, давно тут не появлялся.
Вообщем - у меня есть css фона:
.fon {
    position: relative;
    background-image: url(/assets/mainbg.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    height: 80vh;
    display: flex;
    align-items: center;
    justify-content: center;
}
.fon:before {
    content: " ";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(10, 10, 31, 0.7);
    z-index: 5;
}

<div class="fon"></fon>

но тут же проблема - картинка не встает на задний фон. Тут даже z-index: -1000; не помогает! Перепробовал куча вариантов и никак. Помогите пожалуйста, заранее спасибо


text:
Q: OSGi ( Felix ) extra system.bundle exports Simple experiment -
bundle A needs some com.sun.xml.internal.bind classes to be available to it via it's class loader ( jaxb.. )
I googled my way to the theoretical solution of forcing system.bundle to export com.sun.xml.internal.bind by adding the package to "org.osgi.framework.system.packages.extra" ( a standard framework parameter implemented in felix, documented at http://felix.apache.org/site/apache-felix-framework-configuration-properties.html ) and importing it in my bundle.
By doing so the bundle would not resolve anymore..
Unable to resolve 5.0: missing requirement [5.0] osgi.wiring.package; (osgi.wiring.package=com.sun.xml.internal.bind)

( 5 is the jaxb-using bundle ) Setting "org.osgi.framework.bootdelegation" for "com.sun.xml.internal.bind" and not importing it in the dependent bundle worked as documented.
Am i misinterpreting what system.packages.extra should do? Can i just not resolve imports from system.bundle? I tried explicitly setting system.bundle in the import via bnd at the bottom of my Import-Package directive
com.sun.xml.internal.bind;bundle-symbolic-name="system.bundle",\
*

Which resulted in
Unable to resolve 5.0: missing requirement [5.0] osgi.wiring.package; (&(osgi.wiring.package=com.sun.xml.internal.bind)(bundle-symbolic-name=system.bundle))

ps: i'm using bnd and the -runproperties to define these. My bndrun file has:
-runproperties: osgi.console.enable.builtin=true,\
com.mycompany.manager.confDir=./etc,\
org.osgi.framework.system.packages.extra=com.sun.xml.internal.bind,\
org.osgi.service.http.port=8888

the bundle that needs jaxb defines the following import
Import-Package: com.sun.xml.internal.bind,\
    *

When trying to resolve dependencies in the bndrun editor, i get
    Unable to resolve <<INITIAL>> ver=null: missing requirement (osgi.identity=com.mycompany.configuration.jaxb) [caused by: Unable to resolve com.mycompany.configuration.jaxb ver=0.0.0: missing requirement (osgi.wiring.package=com.sun.xml.internal.bind)]
org.osgi.service.resolver.ResolutionException: Unable to resolve <<INITIAL>> ver=null: missing requirement (osgi.identity=com.mycompany.configuration.jaxb) [caused by: Unable to resolve com.mycompany.configuration.jaxb ver=0.0.0: missing requirement (osgi.wiring.package=com.sun.xml.internal.bind)]
    at org.apache.felix.resolver.Candidates.populateResource(Candidates.java:285)
    at org.apache.felix.resolver.Candidates.populate(Candidates.java:153)
    at org.apache.felix.resolver.ResolverImpl.resolve(ResolverImpl.java:148)
    at biz.aQute.resolve.ResolveProcess.resolveRequired(ResolveProcess.java:34)
    at org.bndtools.core.resolve.ResolveOperation.run(ResolveOperation.java:61)
    at org.bndtools.core.resolve.ResolveJob.run(ResolveJob.java:43)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)

A: I see you are using Bndtools. Good! We have a special property for setting the system packages from the .bndrun file:
-runsystempackages: com.sun.xml.internal.bind

I'm not sure why it didn't work when you put this inside -runproperties... possibly just a typo though I haven't been able to spot it. Anyway it's better to use -runsystempackages because then the Bndrun resolver also knows to add these packages to the system bundle; then you'll be able to resolve in the bndrun editor as well.


text:
Q: Потоки iostream и char* Приведенный код компилирует gcc, но не компилирует Visual C++.
Кто из них неправ в строгом соответствии стандарту? Предполагаю, что это расширение gcc, но в стандарте доказательства не нашел (не нашел >>(char*) - это доказательство?).
#include <iostream>

int main() {
    char* c = new char[200];
    char s[200];
    std::cin >> s;
    std::cin >> c;  // Visual C++ сообщает об ошибке C2679
    std::cout << s;
    std::cout << c;
    }

A: Код перестал быть корректным начиная с C++20.
Если посмотреть вот сюда, видно что в C++20 убрали >> с параметром char *, и заменили его на >> с параметром char (&)[N].
Первый имел тот же недостаток что и gets, поэтому неудивительно что его выпилили вслед за gets.


text:
Q: My "custom model data" textures didn't work with my own file This is my wooden_sword.json, the item/gold is a .png file I added. And it didn't work, only show the error purple/black texture.
{
  "parent": "item/handheld",
  "textures": {
    "layer0": "item/wooden_sword"
  },

  "overrides":[
  {"predicate": {"custom_model_data":1}, "model":"item/iron_ingot"},
  {"predicate": {"custom_model_data":2}, "model":"item/gold"}
  ]
}

The item/iron_ingot is the original file of the pack, and work correctly. I think there are some problems of loading the texture I added

A: I finished it. All I have to do is adding a .json file named [texture name].json in the models file.
{
    "parent": "item/generated",
    "textures": {
        "layer0": "item/[texture name]"
    }
}

After this, it showed the texture of my own files.


text:
Q: Building Prolog (swipl) knowledge base using multiple appends I'm new to Prolog and i'm trying to create a knowledge base consisting of a list through multiple appends. Is it possible?
If from the command line i write:
append([a,b],[c,d],L0), append(L0,[e,f],L1).

the output is:
L0 = [a, b, c, d],
L1 = [a, b, c, d, e, f].

If i write the same code in a .pl file it says:
Full stop in clause-body? Cannot redefine ,/2

Is there a way to tell Prolog to apply the appends and then use L1 as knowledge base?
Edit:
I found a way to do it:
list(L1) :- append([a,b],[c,d],L0), append(L0, [e,f], L1).

But this way, every time i call list(L) it re-creates the list from scratch.
Is there a better way to do it, or this is the way to go?

A: Your edit answers the question, that is in general the way to do it.
However, if you wish to save the result of the predicate for performance reasons (i.e. not having to run the several appends again), you can use the asserta/1 or assertz/1 predicates. For instance, lets say that you have a main predicate that you're running, and you wish to do your append procedure and save that in a saved_list/1 predicate, you can do this:
main :-
    append([a,b],[c,d],L0),
    append(L0,[e,f],L1),
    asserta(saved_list(L1)).

(you can try this out on the command-line if you wish to play around with it)
Now, if you run saved_list(X) later, X will unify with [a, b, c, d, e, f] without having to run the appends. If saved_list/1 is already defined somewhere in the code, you have to declare it as dynamic.
However, a warning: using the various assert and retract predicates is generally discouraged because they are side-effects. If improperly used, they can make code much harder to understand and reason about and can lead to subtle bugs.
In addition, dynamic predicates are not as fast in general as hard-coded ones (i.e. hard-coding the predicate as saved_list([a,b,c,d,e,f]). makes calling it faster than if you have asserted it dynamically). Using it to cache values so that you don't have to calculate them over and over again (i.e. essentially using memoization) is generally ok, but it still should be avoided if possible.
Unless the lists you are appending are huge, I would recommend going with the solution that you provided. Using assert is an unnecessary boondoggle unless doing the appends take a very long time.

A: what do you want? I do not understand.
Your predicate works fine.


text:
Q: how to monitor clicks of child site (added by using iframe) from parent I have a website called A i want to display another website called myFrame through A using iframe  i want to count all the clicks in myFrame and want to display in my website A.myFrame site is in different domain.I did the following code but its not working

Count: 0

A: There are a number of clickjacking exploitation methods that you could explore,  but what you are asking for is not possible because it is a violation of the same origin policy.

A: Cross domain scripting is prohibited in major browsers. But you can disable it (which is very, very dangerous for your security) in Chrome by adding --disable-web-security as the program parameter. I don't how to do it in other browser, though.

A: nah man i think that if is it on other domain it is not possible otherwise if you can get it on the same domain then it is possible by acquiring all the html by load function and then filter all body and check whether any click was attempted on it and update clicks accordingly!


text:
Q: How do I open a view controller that is buried deep into the view hierarchy, directly from tap of a Notification alert Here is the problem I am facing:
I have a UITabBarController as the root view controller. It manages 4 view controllers - A,B,C,D.
C is a navigation controller that has C1 and C2 view controllers in the view hierarchy.
The objective is to open C1 view controller when the user taps on the notification in the notification center.
The problem - When the user taps on the notification, I change the tab selectedIndex to 2 (for C) which loads the view C. And in the ViewDidAppear of C, I push to C1.
Problem with this approach is that for momentarily user sees view C before being transitioned to C1 (because I am doing the transition in viewDidAppear of C). I can't do this transition in viewDidLoad or viewWillAppear of C because runtime throws an error of inconsistency.
If I take an alternative approach of directly pushing C1 from my delegate than the selected tab remains the past one. If I change the selected index of the tab than it loads C again.
Any help will be appreciated.

A: You should use remote notifications in the event of an external push notification requires you to reposition the user within the app. This snippit should help. If not, let me know what else you need.
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //parse notification to get intended_index = x;
    self.tab_controller.selectedIndex = intendex_index;

    [self.tab_controller.selectedViewController.navigationController  popToRootViewControllerAnimated:NO];   //or push. depends on your need
}


text:
Q: seperating rent payments by month in sql I'm not gonna lie, this is for a hw assignment, and I can't figure this part out.
From this query so far, I can get all of the rent revenue from each apartment complex. I just need to be able to separate it by month.
This is my query so far:
SELECT cmplxName AS 'Complex Name', rentTrandate AS 'month' , sum(rentPaid) AS 'Rent Revenue'
FROM complex
INNER JOIN apartment
ON complex.cmplxID = apartment.cmplxID
INNER JOIN lease
ON apartment.aptNumber = lease.aptNumber and apartment.cmplxID = lease.cmplxID
INNER JOIN rent
ON lease.leaseID = rent.leaseID
GROUP BY cmplxName

this is how the data is supposed to look:
complexName     month   rentRevenue
Fox Run         March   1250.00
Oak Meadows     March   1500.00
Oak Meadows     April   700.00
Villa Maria     March   1200.00
Villa Maria     April   600.00

This is how my data looks now:
Fox Run     2015-03-01  1250.00
Oak Meadows 2015-03-01  2200.00
Villa Maria 2015-03-01  1800.00

I appreciate your patience.

A: hi keelsinith This will be done as following
use this SELECT DATENAME(month,rentTrandate)
DATENAME is an SQL method demanding 2 argument DATETIME(interval,YourDateValue)
interval takes  year,dayofweek,month
SELECT cmplxName AS 'Complex Name', SELECT DATENAME(month,rentTrandate) AS 'month' , sum(rentPaid) AS 'Rent Revenue'

FROM complex
INNER JOIN apartment
ON complex.cmplxID = apartment.cmplxID
INNER JOIN lease
ON apartment.aptNumber = lease.aptNumber and apartment.cmplxID = lease.cmplxID
INNER JOIN rent
ON lease.leaseID = rent.leaseID
GROUP BY cmplxName

A: You just need to change the definition of your month field, and change the grouping to group by it as well as the complex name:
SELECT cmplxName AS 'Complex Name', MONTHNAME(rentTrandate) AS 'month' , sum(rentPaid) AS 'Rent Revenue'
FROM complex
INNER JOIN apartment
ON complex.cmplxID = apartment.cmplxID
INNER JOIN lease
ON apartment.aptNumber = lease.aptNumber and apartment.cmplxID = lease.cmplxID
INNER JOIN rent
ON lease.leaseID = rent.leaseID
GROUP BY cmplxName, month

A: I would suggest that you include both the year and the month.  Also, table aliases and qualified column names are highly recommended:
SELECT c.mplxName as Complex_Name, year(r.rentTrandate) as yyyy,
       month(r.rentTrandate) as mm, sum(rentPaid) as Rent_Revenue
FROM complex c INNER JOIN
     apartment a
     ON c.cmplxID = a.cmplxID INNER JOIN
     lease l
     ON a.aptNumber = l.aptNumber and a.cmplxID = l.cmplxID INNER JOIN
     rent r
     ON l.leaseID = r.leaseID
GROUP BY c.cmplxName, year(r.rentTrandate), month(r.rentTrandate)
ORDER BY c.cmplxName, year(r.rentTrandate), month(r.rentTrandate);

This gives the month as a number, but that is more appropriate for sorting the result set anyway.


text:
Q: Como tratar segurança em uma aplicação REST com Spring? Eu gostaria de saber como eu poderia tratar a segurança de uma aplicação stateless REST com o Spring.
Imagine que nenhum usuário possa acessar qualquer conteúdo de /app/content se não tiver identificado primeiramente. Existe como fazer isso sem precisar também fazer o tratamento em todos os métodos?

A: Com Spring, o método de proteção recomendado é configurar o Spring Security para cuidar da autenticação e autorização.
Autenticação
Para a autenticação, há métodos prontos (JDBC, LDAP) ou você pode criar sua própria implementação.
Exemplo de autorização baseada em JDBC:
@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .jdbcAuthentication()
            .dataSource(dataSource)
            .withDefaultSchema()
            .withUser("user").password("password").roles("USER").and()
            .withUser("admin").password("password").roles("USER", "ADMIN");
}

Autorização
Para a autorização, você pode proteger por URL ou método. Na verdade, há outras possibilidades (como usar o paradigma de Orientação a Aspectos), mas as duas apresentadas aqui são as fundamentais.
Proteção por URL
Via código, é possível configurar o acesso por papel às diferentes URLs usando uma instância de HttpSecurity. Exemplo:
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .and()
        .httpBasic();
}

Exemplo mais complexo:
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/resources/**", "/signup", "/about").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/db/**").access("hasRole('ROLE_ADMIN') and hasRole('ROLE_DBA')")
            .anyRequest().authenticated()
            .and()
        // ...
        .formLogin();
}

Via XML, existe a tag <intercept-url>. Exemplo:
<http use-expressions="true">
    <intercept-url pattern="/**" access="authenticated"/>
    <intercept-url pattern="/admin*"
        access="hasRole('admin') and hasIpAddress('192.168.1.0/24')"/>
    <form-login />
    <http-basic />
</http>

Proteção por método via anotação
É possível ativar autorizações via anotação nos beans do Spring com a seguinte configuração:
<global-method-security pre-post-annotations="enabled"/>

A anotação de segurança mais útil e comumente usada é a @PreAuthorize, que verifica se o usuário realmente poderia estar executando aquele método.
Exemplo:
@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);

Aqui a anotação foi incluída numa interface, mas poderia estar também na classe concreta. Isso depende um pouco da arquitetura usada na sua aplicação.
Considerações
Os tópicos mencionados são apenas um resumo muito resumido do Spring Security. Existem vários outros pontos de extensão e customização que podem ser aproveitados dependendo do contexto.
Apenas espero que esta tenha sido uma introdução proveitosa.


text:
Q: How to format time from dd:hh:mm:ss to only hh:mm:ss in SQL server? I found SQL function which get second as input parameter and return seconds in dd:hh:mm:ss format e-g for 93600 seconds it returns 1:02:00:00
it means 1 day 2 hours 0 minutes and 0 seconds.
Function that i used is :
FUNCTION [dbo].[udfTimeSpanFromSeconds]
(
    @Seconds int
)
RETURNS varchar(15)
AS
BEGIN
DECLARE
    --Variable to hold our result
      @DHMS varchar(15)
    --Integers for doing the math
    , @Days int --Integer days
    , @Hours int --Integer hours
    , @Minutes int --Integer minutes
    --Strings for providing the display
    , @sDays varchar(5) --String days
    , @sHours varchar(2) --String hours
    , @sMinutes varchar(2) --String minutes
    , @sSeconds varchar(2) --String seconds

--Get the values using modulos where appropriate
SET @Hours = @Seconds/3600
SET @Minutes = (@Seconds % 3600) /60
SET @Seconds = (@Seconds % 3600) % 60

--If we have 24 or more hours, split the @Hours value into days and hours
IF @Hours > 23
BEGIN
    SET @Days = @Hours/24
    SET @Hours = (@Hours % 24)
END
ELSE
BEGIN
    SET @Days = 0
END

--Now render the whole thing as string values for display
SET @sDays = convert(varchar, @Days)
SET @sHours = RIGHT('0' + convert(varchar, @Hours), 2)
SET @sMinutes = RIGHT('0' + convert(varchar, @Minutes), 2)
SET @sSeconds = RIGHT('0' + convert(varchar, @Seconds), 2)

--Concatenate, concatenate, concatenate
SET @DHMS =  @sDays + ':' + @sHours + ':' + @sMinutes + ':' + @sSeconds

RETURN @DHMS

END

and select command that will retrieve output is
select dbo.udfTimeSpanFromSeconds('93600' )

it shows me result as:

Now i need this output in hh:mm:ss format e-g for current example 26:00:00 it means 26 hours 0 minutes and 0 seconds.
I am using SQL server 2008. Thanks in advance.

A: You can do this with math
DECLARE @sec INT = 93600

SELECT
    CONVERT(VARCHAR(10), (@sec / 3600)) + ':' +
    RIGHT('0' + CONVERT(VARCHAR(2), ((@sec % 3600) / 60)), 2) + ':' +
    RIGHT('0' + CONVERT(VARCHAR(2), (@sec % 60)), 2)

Written as a function:
CREATE FUNCTION udfTimeSpanFromSeconds(
    @sec INT
)
RETURNS VARCHAR(15)
AS
BEGIN
RETURN
    CONVERT(VARCHAR(10), (@sec / 3600)) + ':' +
    RIGHT('0' + CONVERT(VARCHAR(2), ((@sec % 3600) / 60)), 2) + ':' +
    RIGHT('0' + CONVERT(VARCHAR(2), (@sec % 60)), 2)
END

Sample call:
SELECT dbo.udfTimeSpanFromSeconds(360000)

RESULT:
100:00:00

A: If you want you function to return hh:mm:ss then it needs to be as below. This does however limit the total time to be less than 100 hours. You can fix this by increasing the length of the Hours String by changing the right clause and increasing the length of the string returned, as I have now done to illustrate.
(Normally once you have summed your time you usually divide the total by 3600.00 to produce a decimal value for use in further calculations, for example if you are paying by the hour)
FUNCTION [dbo].[udfTimeSpanFromSeconds]
(
    @Seconds int
)
RETURNS varchar(10)
AS
BEGIN
DECLARE
    --Variable to hold our result
      @HMS varchar(15)
    --Integers for doing the math
    , @Hours int --Integer hours
    , @Minutes int --Integer minutes
    --Strings for providing the display
    , @sHours varchar(2) --String hours
    , @sMinutes varchar(2) --String minutes
    , @sSeconds varchar(2) --String seconds

--Get the values using modulos where appropriate
SET @Hours = @Seconds/3600
SET @Minutes = (@Seconds % 3600) /60
SET @Seconds = (@Seconds % 3600) % 60

--Now render the whole thing as string values for display
SET @sHours = RIGHT('0' + convert(varchar(5), @Hours), 3)
SET @sMinutes = RIGHT('0' + convert(varchar(3), @Minutes), 2)
SET @sSeconds = RIGHT('0' + convert(varchar(3), @Seconds), 2)

--Concatenate, concatenate, concatenate
SET @HMS =  @sHours + ':' + @sMinutes + ':' + @sSeconds

RETURN @HMS

END

A: If you want to return 100 hours then you have to use it:-
FUNCTION [dbo].[udfTimeSpanFromSeconds]
(
    @Seconds int
)
RETURNS varchar(8)
AS
BEGIN
DECLARE
--Variable to hold our result
  @HMS varchar(15)
--Integers for doing the math
, @Hours int --Integer hours
, @Minutes int --Integer minutes
--Strings for providing the display
, @sHours varchar(3) --String hours
, @sMinutes varchar(2) --String minutes
, @sSeconds varchar(2) --String seconds

--Get the values using modulos where appropriate

SET @Hours = @Seconds/3600
SET @Minutes = (@Seconds % 3600) /60
SET @Seconds = (@Seconds % 3600) % 60

--Now render the whole thing as string values for display
SET @sHours = RIGHT('0' + convert(varchar, @Hours), 3)
SET @sMinutes = RIGHT('0' + convert(varchar, @Minutes), 2)
SET @sSeconds = RIGHT('0' + convert(varchar, @Seconds), 2)

--Concatenate, concatenate, concatenate
SET @HMS =  @sHours + ':' + @sMinutes + ':' + @sSeconds

RETURN @HMS

END


text:
Q: Adding dynamic controls in `formGroup` is automatically sorting alphabetically I'm creating a dynamic Form using angular formGroup and formcontrols based on a json array like this:
let input = ['name','zip_code' 'address', 'field1', 'custom_field'];

app.component.ts:
public group: FormGroup = this.formBuilder.group({});

  ngOnInit() {
    for(let field in input) {
    this.group.addControl(this.input[field], new FormControl('', []));
  }
  console.log(this.group.controls);
}

console output:
address: FormControl
custom_field: FormControl
field1: FormControl
name: FormControl
zip_code: FormControl

app. component.html
<form autocomplete="off">
  <div *ngFor="let control of group.controls | keyvalue; let i = index">
    <text-field> </text-field>
  </div>
</form>

On the view the form fields are shows in alphabetical order.
Is there any way to disable that alphabetical sorting of fields?
I want to display the fields as same sequence in array.

A: Try using an array of FormGroup with Object.keys() after creating that for ngFor. Something like this:
app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from  '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  public input = ['name','zip_code', 'address', 'field1', 'custom_field'];

  public arrayForm: any[];

  public group: FormGroup

  constructor(private formBuilder: FormBuilder) {
    this.group = this.formBuilder.group({});
    for (let field in this.input) {
       this.group.addControl(this.input[field], new FormControl('', []));
    }
  console.log(this.group.controls);
  this.arrayForm = Object.keys(this.group.controls)
  console.log(this.arrayForm)
  }
}

app.component.html
<form autocomplete="off">
  <div *ngFor="let control of this.arrayForm; let i = index">
    {{control}}
    <input>
  </div>
</form>

I create a sample here on Stackblitz for you.


text:
Q: IE 8 Crashes When Loading Site, Can't Debug - http://bizzocall.com/faq/ - Works well in all other browswers, but when I test it with the developer tools in IE 8 compatibility it just crashes.
I've looked at all the answers and it seems like each person has different problems (I've looked for stray commas, updated jquery, etc).
Any help is much appreciated!
UPDATE
I found a plugin that was calling jquery 1.4 (Dave's WordPress Live Search) and removed it.  Although the code seems cleaner it still pause IE 8.
UPDATE 2
Removing the plugin seemed to be the trick.
Just for those that find this post:  This was running wordpress with thesis installed.

A: It seems that most likely you have a trailing comma, not necessarily a stray one. For example:
{
  "hello":"world",
  "foo":"bar"
}

Would work fine, but if you did:
{
  "hello":"world",
  "foo":"bar",
}

It would totally kill IE. Look for that or maybe give us more hints as to what the error is.

A: It crashes for me too in IE9 with IE8 mode. (see development tools -> F12 ) If you disable javascript, it doesn't crash.. so it's a javascript issue. I see that you are loading 3 different version of jQuery, could be that?
EDIT. I was using the debugger, and got frozen during execution of jQuery 1.44 (You are loading this library in the footer from Google CDN )

A: When comment the script tag of fancybox, IE doesn't crash. But I don't know what is the cause.
You call jquery twice: jquery 1.6 and jquery 1.4.4. Seems this cause the crash. But if you disable jquery 1.4.4, fancybox still causes the crash. Disabling jquery 1.6 avoid the crash.

A: My IE (IE 8.0 @ Windows Server 2003) is not killed when I enter the page.
However the Javascript seems to keep on running forever, because IE offers me to "Stop running script ... causing Internet Explorer to run slowly ... ". There's a Javascript error indication too. It says:
Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; WOW64; Trident/4.0; .NET4.0C; .NET4.0E)
Timestamp: Fri, 13 May 2011 20:08:46 UTC

Message: Permission denied
Line: 133
Char: 374
Code: 0
URI: http://bizzocall.com/faq/wp-includes/js/jquery/jquery.js?ver=1.4.4

You said you've updated JQuery, but 1.4.4 doesn't seem to be the latest version, does it?

UPDATE:
I ran the Developer Tools (F12) to get the call stack and one of the entries in the stack (just in the middle) is:
    //jquery.fancybox-1.3.4.js lines 1040-1045 in the $.fancybox.init
    $('body').append(
        tmp = $('

'),
        loading = $('

'),
        overlay = $('

'),
        wrap = $('

')
    );

UPDATE2:
I give up. My Javascript/JQuery knowledge is too limited. And the minified JQuery code doesn't seem to help either. Debugging through things like this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)}) doesn't seem to be the easiest thing in the world.
I suggest running the same code with a single JQuery instance (one version, it may be 1.4.4 if that's your pick) in development (unminified) version. Problems may arise if the bug doesn't happen then.

A: Dave from "Dave's WordPress Live Search" here. Just wanted to add a few comments:

*

*Dave's WordPress Live Search doesn't "call jQuery 1.4". It tells WordPress to load the version of jQuery it ships with, currently 1.4.4. jQuery 1.6 isn't supported natively by WordPress until version 3.2 ships next month. The preferred way to use an alternate version of jQuery is to "deregister" the included jQuery and register your own version in its place. Adding the following to your theme's functions.php file should take care of it:
if ( !is_admin() ) {
  wp_deregister_script('jquery'); //deregister current jquery
  wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js', false, '1.6', false);
  wp_enqueue_script('jquery');
}

*Someone recently figured out that the jQuery Dimensions plugin included with Dave's WordPress Live Search was causing IE8 to hang. This was needed way back when I first wrote this plugin because WordPress shipped with an ancient (even for the time) version of jQuery. The functionality this jQuery plugin provides was merged into jQuery core a long time ago, and since I've dropped support for WordPress < 2.9, it's not needed anymore. Give Dave's WordPress Live Search v2.1 a spin.

A: Try running IE without add-ons. Often the reason for a full-blown crash is an add-on interfering with something. To do this:
Start > All Programs > Accessories > System Tools > Internet Explorer (No Add-ons)
If you can't find that then go to a run promt (Windows Key + R) and type iexplore.exe -extoff

A: None of the above solutions worked for me. I eventually tracked it down to an out of date version of Modernizr. Mine was at 2.0.6 and can confirm that version 2.5.3 fixed the issue completely.


text:
Q: DBFlow lost the data in String type DBFlow Version:4.2.4
Bug or Feature Request:lost the long string data
Description: i have a long json string,and i inserted the bean without any wrong,but i read it from the database,the value is null.
my string like this as follow:
https://github.com/agrosner/DBFlow/issues/1695
and my code is :
PlotCanvasBean plotCanvasBean = new PlotCanvasBean(plotWithGeo);
                plotCanvasBean.setLoginId(AppManager.getInstance().getUserSession().getUid());
                plotCanvasBean.setCreateTime(new Date());
                plotCanvasBean.setUUID(UUID.randomUUID().toString());
                plotCanvasBean.setPlotId(param.getId());

                plotCanvasBean.insert();

                List<PlotCanvasBean> plotCanvasBeans1 = SQLite.select()
                        .from(PlotCanvasBean.class)
                        .where(PlotCanvasBean_Table.id.isNotNull())
                        .queryList();

and the column declare as a String
enter image description here
screenshot as follow:
the bean insert into the database
the bean read from the database


text:
Q: Observable Collection of Observable collections I want to generate observable collection of type string based on other observable collections.
I have a parent class that contains a property ID. From that class i create two children classes and then create two observable collections, each for one of the children classes. Now I want to create a collection that will only contain the IDs from both children observable collections. I know I can do that by adding the ID to the collection every time i add to the other collections, the problem is with removing. I use WPF DataGrid as the interface to Son and Daughter and want to be able to allow the user to delete inputs using the Delete key.
I have tried using a decostructor for both children components but removing them from the collection doesn't actually make the garbage collector dispose of them.

public class Father
{
        public Father()
        {
        }
        public string ID { get; set; }
}

public class Son
{
    public Son()
    {
    }
    public string Prop1 { get; set; }
}
public class Daughter
{
    public Daughter()
    {
    }
    public string Prop2 { get; set; }
}

public class Main
{
    ObservableCollection<Daughter> daughters = new ObservableCollection<Daughter>();
    ObservableCollection<Son> sons = new ObservableCollection<Son>();

    ObservableCollection<string> IDs = ???

}

What i want to achieve is to have a collection that is always up to date with IDs from both Son and Daughter collections and want to avoid "recreating" the collection every time I add a new children instance.


text:
Q: How can I automate AWS Route53 DNS update based on EC2 instance tag names? I want to implement an automatic way of updating Route53 DNS based on EC2 tags of the instances.
Imagine that I can have a tag name named dns_name which is supposed to document the expected dns name of the machine.
If I shutdown the machine, upgrade it and start it again, I do want to get the DNS updated without having to change anything.
I don't want to install a DNS update service on the machine as this would require me to put AWS credentials on all the VMs, and to deploy this to them.
It seems much easier to use AWS EC2 tags to declare the expected names. A cron job could easily check for changes and update the DNS.
Did anyone implement this?

A: A DNS update service on the machine wouldn't require AWS credentials. You would preferably use AWS IAM instance profiles instead. I've used this method to run a script on server boot to update Route53 records with the latest IP address.
If you want to schedule a cron on a single server that handles updating the Route53 records for all servers, based on instance tags, then that is certainly possible. It would only be a few lines of code.

A: I would highly recommend using Elastic IP's. This is the exact purpose of them. For this implementation, go to EC2 => Network & Security => Elastic IP => Allocate New Address => Actions => Associate Address => (select the instance tag name you're looking for)
Copy the EIP to your clipboard then go to Route53 => Create Hosted Zone => go thought those steps => Go to Record Sets => Create Record Set => For Name: you can have your www. or not => Type: A - IPv4 => Alias: NO => TTL: Whatever you'd like => Value: your EIP address => Save Record Set
If you have an Elastic IP associated to your instance, you can reboot, swap, stop, update, change, shape shift, whatever your want! EIP's wont go anywhere.
Update:
You can make all this automated via the Route53 API.
These are the steps for doing it because you have to know the process in order to do it with the API calls.

A: I was trying to do exactly what I think your attempting to do.
What I've found is this script from this link which is a good starting point.
https://medium.com/@dbclin/a-bash-script-to-update-an-existing-aws-security-group-with-my-new-public-ip-address-d0c965d67f28
#!/bin/bash
# Extract information about the Instance
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id/)
AZ=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone/)
MY_IP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4/)

# Extract tags associated with instance
ZONE_TAG=$(aws ec2 describe-tags --region ${AZ::-1} --filters "Name=resource-id,Values=${INSTANCE_ID}" --query 'Tags[?Key==`AUTO_DNS_ZONE`].Value' --output text)
NAME_TAG=$(aws ec2 describe-tags --region ${AZ::-1} --filters "Name=resource-id,Values=${INSTANCE_ID}" --query 'Tags[?Key==`AUTO_DNS_NAME`].Value' --output text)

# Update Route 53 Record Set based on the Name tag to the current Public IP address of the Instance
aws route53 change-resource-record-sets --hosted-zone-id $ZONE_TAG --change-batch '{"Changes":[{"Action":"UPSERT","ResourceRecordSet":{"Name":"'$NAME_TAG'","Type":"A","TTL":300,"ResourceRecords":[{"Value":"'$MY_IP'"}]}}]}'

A: This has details of the solution suggested by Mark B.  Elastic IP doesn't work if you don't have any available and Amazon allows you only 5.
I used user14441273's pasted script as a starting point.  The provided link for that is dead (redirects you to an article nothing to do with Route53), and the post gives no clue how to set up the required tags ZONE_TAG or NAME_TAG.
Regardless how you do it, you will need to allow the actions to the instance profile role.
Here's the productonlized working script.  I get the instance name from local file system, which is much faster and more reliable than using a network service.  Change the domain to the domain you want to use:
#!/usr/bin/env bash

set -e
shopt -s xpg_echo
set +u

DNS_DOMAIN=yourdomain.com
TTL_S=30  # You want this low or you will have to wait up to this long for changes to propagate

PATH="$PATH:/usr/local/bin"

# Extract information about the Instance
INSTNAME=$(ls -ld /var/lib/cloud/instance | sed 's@.*/@@;')
[ -n "$INSTNAME" ] || {
    echo 'Failed to determine Instance name' 1>&2
    false
}
[ -f /tmp/date.txt ] && {
      echo "date present" 1>&2
    false
}
AWS_REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone  | sed 's/.$//')
[ -n "$AWS_REGION" ] || {
    echo 'Failed to determine AWS Region' 1>&2
    false
}
HOSTNAME=$(aws ec2 describe-tags --region $AWS_REGION --filters Name=resource-type,Values=instance Name=resource-id,Values=$INSTNAME Name=key,Values=Name --query 'Tags[0].Value' --output text)
[ -n "$HOSTNAME" ] || {
    echo 'Failed to determine DNS Hostname to update' 1>&2
    false
}
MY_IP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4/)
[ -n "$MY_IP" ] || {
    echo 'Failed to determine my public IP address' 1>&2
    false
}
ZONE_ID=$(aws route53 --region $AWS_REGION list-hosted-zones-by-name --region $AWS_REGION --dns-name $DNS_DOMAIN --query 'HostedZones[0].Id' --output text)
[ -n "$ZONE_ID" ] || {
    echo 'Failed to determine my Route53 Zone ID' 1>&2
    false
}

aws route53 change-resource-record-sets --hosted-zone-id $ZONE_ID --region $AWS_REGION --change-batch '{"Changes":[{"Action":"UPSERT","ResourceRecordSet":{"Name":"'${HOSTNAME}.$DNS_DOMAIN'","Type":"A","TTL":'$TTL_S',"ResourceRecords":[{"Value":"'$MY_IP'"}]}}]}'
enter code here

Assuming that you're running a late-model Linux variant, here's a working service script.  N.b. I have it configured to run the shell script from /usr/local/sbin which I have NFS mounted:
[Unit]
Description=Update Route53 DNS Service with instance's current public IP addr
RequiresMountsFor=/usr/local

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/updateRoute53.bash
RemainAfterExit=no
StandardOutput=truncate:/var/log/updateRoute53.log

[Install]
WantedBy=multi-user.target


text:
Q: Куда выложить свой исходный код? Необходимо выложить свой исходный код. Пару раз качал с github, только что-то не понимаю как залить туда своё. Есть что нибудь попроще?  Можно без социальных плюшек как у github. Мне они всё равно не нужны. Просто выложить код в открытый доступ и всё. Спасибо.
A: Я бы порекомендовал https://bitbucket.org/ - он поминималистичнее гитхаба и главное - там есть приватные репозитории. Но в гите все равно разбираться придется =)


text:
Q: Ruby on Rails, creating CMS with content types I'm learning RoR nowadays and came up with an idea of creating a very simple content management system. I would like to allow users to create structure of content by adding fields, then the app would create pages to add new items and list all items of given type. I've seen something similar in Drupal where users can define their own content type.
I wonder how to do it:
1.Using relational DB: Should I store content type as (for example) serialized hash of "id => type_of_field" and execute SQL to create db schema in controller after getting it from user? Is there any better way to achieve this? Can it cause problems with future db migrations?
2.How to create views, controllers and routes? Should there be only one controller handling routes to content types by itself without using routes.rb and creating views dynamically from partials? Is there more elegant way to do this?
Thanks for all clues.

A: May be you can fix the layout for basic simple CMS.
like left_side_bar,can_left_side_bar,right_side_bar,top_nav,sub_nav,footer,header,body DB field and checks for displaying content.so basically cut down pages and map to db field,
Checkout various CMS available and go through their architecture it will help you to understand in terms of architecture wise.
List of CMS
https://www.ruby-toolbox.com/categories/content_management_systems


text:
Q: How can I change XSD Path in deployed SSIS Package I am new to SSIS packages. I have an SSIS package Solution in my local machine.
It has an XML Source component which uses an XSD file in my local machine.
When I deploy this on my SQL Server, How can I set the path to a new location on server ?
Thanks

A: Create the XSD path using a Configuration variable. In this case, whenever you will change the configuration it will pick the new path accordingly.

A: I think this guide is what you're looking for:
http://fuzzy-group.blogspot.co.uk/2013/01/ssis-create-dynamic-xsd-source-file-for.html
It allows you to store your xsd in a database where it is configurable, and then loads it dynamically at run time.
I'm not sure exactly how much of an xsd change this can handle, but I think this is the closest you can get without dynamically generating the whole package.


text:
Q: How to re-trigger loading UI in Next 13 using the new app directory? I am working with Next 13's app directory to build a simple website. The route to my main page is /{username}?year={year}&month={month}. When navigating to the page, the main section of this page  triggers the Loading UI from the loading.tsx file because it's making an API request. I have a selector in the page that allows the user to change the year and month. Upon changing these values, they get redirected to the same page, but with the updated date values: /{username}?year={updatedYear}&month={updatedMonth}. Once navigated, the Loading UI does not show again.
My page is a server component and consists of:
const year = searchParams.year;
const month = searchParams.month;

const userData = await getUserInfo(params.username);

return (
<main>
 ...
<Suspense fallback={<Loading />}>
  <GameList {...{
    username: params.username,
    year,
    month,
    }} />
</Suspense>
</main>
);

My <GameList /> component is also a Server Component and is defined as such:
const games = await getUserGames(username, year, month);

return (
 <some game data />
);

I have tried Next's Link to re-route the user to the page with the updated queries, where I used as such:
<Link href={`/${username}?year=${year}&month=${month}`}>component</Link>

I also tried using the useRouter from next/navigation with its push and replace functions:
router.replace(`/${username}?year=${year}&month=${month}`);

I have tried all the different caching strategies for my fetch calls, and that still hasn't changed anything. How can I get my <GameList /> component to go into Loading state again once the date changes (when it makes a new API request to fill with new data)?
Entry point to the page: GitHub repo.


text:
Q: return false but continue in the same scope google

says I can't change the above markup but I want to disable the hyperlink, I do this
$('.google').click(function(){
    return false;
    windows.open('www.gmail.com');
});

I expect after return false my code will work but it doesn't, why?

A: Because after return statement, rest of the code will never be invoked. That is the default behavior of every programming language.  You can prevent the redirection by using event.preventDefault(). For that, use like this
$('.google').click(function (e) {
    e.preventDefault();
    window.open('www.gmail.com');
});

For event.preventDefault() vs return false see event-preventdefault-vs-return-false


text:
Q: numpy: bitwise and on array I'm trying to do an "&" operation across all the values in a simple bool array.  The array I have is as follows:
array([False False True], dtype=bool)

The only thing I've come up with is to slice out the values in the array and use "&" to give a "False" result.  I feel like there must be a better way but I don't know enough about numpy to use it properly.

A: Use arr.all(), which is the same as np.all(arr):
import numpy as np
arr = np.array([False, False, True], dtype=bool)
arr.all()
=> False
np.all(arr)
=> False


text:
Q: How to run multiple versions of Symfony PHP Framework I have several web projects built with Symfony v1.0, but I am excited by the new features in Symfony version 1.4 (Improved security, native email support and improved performance).
How can I continue to develop my 1.0 projects but also create a testing environment for version 1.4?

A: Guide to Installing Multiple versions of Symfony
Thankyou to Guillaume Flandre for pointing it out, there is a fantastic article written by eHabib on SymfonyNerds.com - http://symfonynerds.com/blog/?p=123
Here is the basic outline, read the whole article here.
Step 1 - Un-install Symfony via PEAR
Step 2 - Setup a structure for Symfony: Install symfony in /usr/share/php/symfony
Step 3 - Checkout each Symfony version you need
Use SVN checkout to grab each Symfony version. Put these in a different folder under the base Symfony directory.
Step 4 - Create symbolic links for each version
Create and test symlinks for each version of Symfony. Lets place these in the standard bin directory
Step 5 - Creating a new project
Use the relevant Symfony command. For example, to create a Symfony 1.0 project:

*

*sudo symfony10 init-project test1

*sudo symfony11 generate:project test11

*sudo symfony12 generate:project test12

Step 6 - Check in the project Config to ensure its picked up the right version.

A: This link should be useful: http://symfonynerds.com/blog/?p=123
It points to an article named: Your complete guide to running multiple Symfony versions on the same environment
It's fairly easy to do.

A: As also said in the article, I define it in lib/vendor as svn:externals: symfony http://svn.symfony-project.com/branches/1.2
So there's no symfony to be installed on the server at all and you can use as many versions without influence on other apps.


text:
Q: Is the Meta top bar, resembling Google's design, distinctive enough? Now my meta top bar looks like this:

It remind me too much of google's top bar, with these new grey icons, little "bubbles" and dark background.
On more occasions I saw sites trying to copy ideas from some part of a another site's design (which may be a natural thing to do).
But as a visitor at least my personal experience is, that I like if every site has it's own distinctive look. Either beacuse I just like them as they are, or making them resembling an other site just makes them visually too hard to distinguish (at a glance, for example). The result is that I "forgot" (not really, but have this strange feeling) where am I for a moment, and what do I do here. Or if this place was any different from google. I like if a site has an identity.
My question is is meta's top bar distinctive enough?

edit the argument came up in comments that a top-bar that's looking good on every different site theme is hard to make. But was there anything wrong with having a same-layout, different colors version? The old top-bar doesn't use the same colors, but it uses the same layout, and feel, and, it still manages (at least for me) to make you feel like you are part of the same network - without looking exactly the same. I'd even go as far to say that the variants are refreshing.
edit 2 Benjol points out that for example "in the case of Programmers, [the top bar] is evidently an integral part of the whiteboard" - ie. purposefully not the same as everywhere else. And for a fun reason!
edit 3 Deer Hunter adds that hovering is not an option on a tablet.

A: Well here's the thing: copying off of Google seems OK if you ask me. Google is Gooogle, synonymous with search. A verb, a noun, etc.
But it's hard to say that Meta is doing copypasta, rather they're borrowing the idea of "white on black"
A comparison:

Which isn't trademarked by Google, btw. KhanAcademy has always delivered videos with the white-on-black style.

And how about old-school computers?  My first PC memories were of dark DOS screens on the 486

A: I don't really like the black bar vibe in general. I do like the new functionality (although I miss the direct link to main, but I am getting used to the drop down), but the old look was cozy and distinctive.
The new look reminds me of some random, unpopular blog/aggregate/whatever web site that only really exists to be some web designers portfolio piece. It's cold and bleak. It reminds me of when sadtrombone.com changed their look:
Old Site (Perfect):

New Site (All it needs is one of those crappy tag clouds on the side):

Another example of the vibe I get, Diaspora (supposed to be a Facebook competitor, ultimately another failed social media site):

I don't know. Perhaps I'm being prejudice, but I always associate the full-width, no-margin, black nav bar, white background theme with failed sites in the bleak corners of the internet.
It's sort of the hipster of design themes, tacked on by failing sites at the last minute to try and "look sleak and cool", maybe with a digg button on the side, in a frantic attempt to slow their inevitable slide into becoming a domain name parking site (complete with stock photo of smiling-woman-with-laptop-and-headset) or a Yahoo! portal front-end.
If you keep the black bar, whatever, but please for the love of god promise us you won't add a tag cloud. Those things are like the modern day equivalent of the poorly scaled animated GIF, or <marquee> or that Java applet water reflection text effect (AUUUUGHHHH!).

P.S. Smiling-woman-with-laptop-and-headset, if you are reading this, call me, maybe.

P.P.S. For the ladies.

A: I always liked the easy on the eyes, less is more approach to the style here at stack exchange. There is a lot of contrast which occurs in the new top bar. I like the functionality, but I was kind of hoping for a more gentle color scheme.
Here is what a rollback of styling with the new features looks like. Food for thought...
Name and gravatar

Name only


text:
Q: How do you read X bytes from a file without using Get-Content I want to read X bytes from a binary file via PowerShell, without using Get-Content.
I don't want to use Get-Content as the data is binary, may be large, has no line feeds, and I don't want to read any more of the file than I need to. And from googling it seems that Get-Content uses line feeds to limit how much data it reads, and I've no line feeds.

A:
I don't want to use Get-Content as the data is binary, may be large, has no line feeds, and I don't want to read any more of the file than I need to

Get-Content allows you to read a limited stream of bytes from the start of the file with the -Encoding and -TotalCount parameters:
$numBytes = 10
$bytes = Get-Content .\file.bin -Encoding byte -TotalCount 10

A: The answer I found for this was StreamReader, and in my example below I am reading the first 10 bytes of the file (but it could easily be changed to whatever you want).
NOTE: I am reading the data into a Char array (which is fine for my needs).
    $numBytes = 10 # You'll need to test the file length is valid before reading...
    [char[]]$bytes = new-object Char[] $numBytes
    $streamReader = New-Object System.IO.StreamReader(".\fileyMcFileFile.bin")
    $countBytesGot = $streamReader.Read($bytes, 0, $numBytes)
    $streamReader.Dispose()

(I've answered my own question as it took me ages to work how to do this, couldn't find this solution anywhere, and thought it might help someone else).

A: Update to Mathias' answer for PowerShell 7.0. Instead of -Encoding Byte, you need to use -AsByteStream:
Get-Content -AsByteStream -TotalCount 0x40 output.bin | Format-Hex

Unfortunately, -AsByteStream isn't in turn available in Windows PowerShell 5.0, so if you need your script to be portable, you need to check version and do the following:
$AsByteStream = if ($PSVersionTable.PSVersion.Major -ge 7) { @{ 'AsByteStream' = $True } } else { @{ 'Encoding' = 'Byte' } }
Get-Content @AsByteStream -TotalCount 0x40 output.bin | Format-Hex


text:
Q: Add redirection to PHP script I'm trying to add redirection to a URL to the following script. I can't seem to be able to make it work after clicking the button. Any suggestions for how to make it work? Thanks in advance!
if ($Email=="") {
    echo "

            ×
            Warning! Please enter your email.

    ";
}
elseif ($Name=="" or $PhoneDay=="") {
    echo "

            ×
            Warning! Fill all the required fields.

";
}
else{
    mail($to, $subject, $msg, "From: $_REQUEST[Email]");
    echo "

            ×
            Thank you!

";
    header("Location: http://www.example.com");
}

?>

A: You can't send out a header after you have emitted anything.  So, no echo before the redirect.

A: Here is the documentation for header().
http://www.php.net/manual/en/function.header.php
As PHP puts it, you have to set the headers before you return any output for the user. You have to remove the echo in order for it to work.

A: Try something like this:
 print '';

Make sure you have this on the web page:
");


text:
Q: jQuery detect when user uses SELECT element in form I want to be able to detect when the user has selected an option from a SELECT element in a form. I know what to do from there, but not sure about how to achieve the initial detection.
<select id="mySelect">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

I would like the solution in JQuery if possible.

A: You probably want the .change() handler, like this:
$("#mySelect").change(function() {
  var newVal = $(this).val();
  //do something
});

.val() gets the current value of the dropdown (as a string), just use that to do whatever you want, e.g. alert("The new value is: " + $(this).val());, etc.

A: $("#mySelect").bind("change", function(event){ ... });

A: or just use
$("#mySelect").change(function(){
  //do something here
})

A: $('#mySelect').change(function() {
  alert('Handler for .change() called.');
});

A: jQuery('#mySelect').bind('change',function(e){

        //value of selected item
        var _selectedValues=jQuery(this).val();

        //your codes  here
});

i prefer bind over .change(),. click(), etc: as bind is more generic than others.


text:
Q: Bootstrap v4 popover not updating on state change in React I have a "Nightlife Coordination" app (from the Free Code Camp curriculum) that allows a user to search by city and RSVP to a bar for that night. The app keeps a list of who has RSVP'd and who is going. It is built with React and Bootstrap v4 (and Node on the back end).
I have text under each bar location that, when clicked, allows a user to RSVP or unRSVP. There is also a button that shows how many people have RSVP'd and, if clicked, will display a Bootstrap popover of the list of people who have RSVP'd.
If a user RSVPs (or unRSVPs), I want the list to update. (Currently, the number on the button DOES update, but not the list.)
The following two images show the problem:
Upon initial load, all is correctly functional

When the user RSVPS or unRSVPs, the number on the button correctly updates, but the list does not

Here is my code.
The list is being generated in the data-content attribute in the second anchor tag in the render method.
Can anyone help?
One other hint is that in my React developer tools Chrome extension, it shows the data-content attribute correctly updating upon RSVP and unRSVP. Is it that perhaps Bootstrap saves the contents of the data-content attribute in its JS file upon initial render and does not update it?
const React = require('react');

class Bar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      countMeIn: false, // coming from Mongo
      numberGoing: this.props.user_namesArr.length,
      user_id: this.props.twitter_id,
      user_name: this.props.user_name,
      yelp_id: this.props.yelp_id,
      user_namesArr: this.props.user_namesArr
    };
  }

  componentDidMount() { // need the same for DidMount and DidUpdate, in case user is signed in upon load (from previous session), or signs in after load
    if (this.state.user_namesArr.includes(this.props.user_name) && !this.state.countMeIn) {
      this.setState({
        countMeIn: true
      });
    }

  }

  componentDidUpdate(prevProps, prevState) { // Need both in case user logs in after initial page load
    console.log(this.state.user_namesArr);
    if (this.state.user_namesArr.includes(this.props.user_name) && !prevState.countMeIn) {
      this.setState({
        countMeIn: true
      });
    }
    $('[data-toggle="popover"]').popover();
  }

  rsvp() {
    let url = '/rsvp/?&yelp_id=' + this.props.yelp_id + '&user_id=' + this.props.twitter_id + '&user_name=' + this.props.user_name;
    fetch(url, { method: "POST" })
    .then((res) => res.json())
    .then((json) => {
      let newArr = this.state.user_namesArr;
      newArr.push(this.props.user_name);
      this.setState({
        numberGoing: this.state.numberGoing + 1,
        countMeIn: true,
        user_namesArr: newArr,
      });
    })
  }

  unrsvp() {
    let url = '/unrsvp/?&yelp_id=' + this.props.yelp_id + '&user_id=' + this.props.twitter_id + '&user_name=' + this.props.user_name;
    fetch(url, { method: "POST" })
    .then((res) => res.json())
    .then((json) => {
      let ind = this.state.user_namesArr.indexOf(this.props.user_name);
      let newArr = this.state.user_namesArr;
      newArr.splice(ind, 1);
      this.setState({
        numberGoing: this.state.numberGoing - 1,
        countMeIn: false,
        user_namesArr: newArr,
      });
    })
  }

  render() {
    return (

          { this.props.name }

           { this.props.review_count } reviews { this.props.price }

          { this.props.loc[0] }., { this.props.loc[1] }

           0 ? "popover" : "" } data-trigger="focus" title="Who's In?" data-content={ this.state.user_namesArr }>
            { this.state.numberGoing } going

          {
            this.props.loggedIn ?
            this.state.countMeIn ?
             this.unrsvp() }>You're going! : // if logged in and already RSVP'd
             this.rsvp() }>Count me in! : // if logged in but not yet RSVP'd
             Please log in  // if not logged in
          }

    )
  }

}

module.exports = Bar;

A: Maybe using ref could help ... but why not use reactstrap and more important why not react-popper ...? It's well known (https://github.com/FezVrasta/popper.js/#react-vuejs-angular-angularjs-emberjs-etc-integration) that many libraries doesn't work well with react or any other (virtual) DOM managers.
Do you really need jQuery?
Using react portals you can remove all theese dependencies.

A: It works with Reactstrap. I simply added reactstrap to my package.json file, and used the Reactstrap code.
const React = require('react');
import { Button, Popover, PopoverHeader, PopoverBody } from 'reactstrap';

class Bar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      countMeIn: false, // coming from Mongo
      numberGoing: this.props.user_namesArr.length,
      user_id: this.props.twitter_id,
      user_name: this.props.user_name,
      yelp_id: this.props.yelp_id,
      user_namesArr: this.props.user_namesArr,
      popover: false
    };
    this.toggle = this.toggle.bind(this);
  }

  componentDidMount() { // need the same for DidMount and DidUpdate, in case user is signed in upon load (from previous session), or signs in after load
    if (this.state.user_namesArr.includes(this.props.user_name) && !this.state.countMeIn) {
      this.setState({
        countMeIn: true
      });
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.user_namesArr.includes(this.props.user_name) && !prevState.countMeIn) {
      this.setState({
        countMeIn: true
      });
    }
  }

  rsvp() {
    let url = '/rsvp/?&yelp_id=' + this.props.yelp_id + '&user_id=' + this.props.twitter_id + '&user_name=' + this.props.user_name;
    fetch(url, { method: "POST" })
    .then((res) => res.json())
    .then((json) => {
      let newArr = this.state.user_namesArr;
      newArr.push(this.props.user_name);
      this.setState({
        user_namesArr: newArr,
        numberGoing: this.state.numberGoing + 1,
        countMeIn: true
      });
    })
  }

  unrsvp() {
    let url = '/unrsvp/?&yelp_id=' + this.props.yelp_id + '&user_id=' + this.props.twitter_id + '&user_name=' + this.props.user_name;
    fetch(url, { method: "POST" })
    .then((res) => res.json())
    .then((json) => {
      let ind = this.state.user_namesArr.indexOf(this.props.user_name);
      let newArr = this.state.user_namesArr;
      newArr.splice(ind, 1);
      this.setState({
        user_namesArr: newArr,
        numberGoing: this.state.numberGoing - 1,
        countMeIn: false
      });
    })
  }

  toggle() {
    this.setState({
      popover: !this.state.popover
    });
  }

  render() {
    return (

          { this.props.name }

           { this.props.review_count } reviews { this.props.price }

          { this.props.loc[0] }., { this.props.loc[1] }

          { /* For this to work, id must have leading letters, otherwise throws massive errors. See here: https://stackoverflow.com/questions/23898873/failed-to-execute-queryselectorall-on-document-how-to-fix */ }
          <Button id={ "abc" + this.props.yelp_id } className="btn btn-success" onClick={ this.toggle }>{ this.state.numberGoing } going</Button>
          <Popover placement="right" isOpen={ this.state.popover } target={ "abc" + this.props.yelp_id } toggle={ this.toggle }>
            <PopoverHeader>Who's In?</PopoverHeader>
            <PopoverBody>{ this.state.user_namesArr }</PopoverBody>
          </Popover>
          {
            this.props.loggedIn ?
            this.state.countMeIn ?
             this.unrsvp() }>You're going! : // if logged in and already RSVP'd
             this.rsvp() }>Count me in! : // if logged in but not yet RSVP'd
             Please log in  // if not logged in
          }

    )
  }

}

module.exports = Bar;