text:
Q: C# lists and datagridviews I'm trying to populate a datagrid with info out of a list, and then after pressing a save button it saves the datagrid changes back into the list.
    int pos = MainMenu.myList.FindIndex(x => x.ID == validID);
    var tempStu = MainMenu.myList[pos];
    if (tempStu is DormStudent)
    {
        DormStudent tempDorm = tempStu as DormStudent;
        nameTextBox.Text = tempDorm.Name;
        var blist = new BindingList<Student>(tempDorm.Grades);
        var source = new BindingSource(blist, null);
        gradesDataGridView.DataSource = source;
    }
    else
    {
        nameTextBox.Text = tempStu.Name;
        var blist = new BindingList<Student>(tempStu.Grades);
        var source = new BindingSource(blist, null);
        gradesDataGridView.DataSource = source;
    }

and when you push the save button (i don't have the save part as nice)
    int pos = MainMenu.myList.FindIndex(x => x.ID == validID);
    var tempStu = MainMenu.myList[pos];
    if (tempStu is DormStudent)
    {
        DormStudent tempDorm = tempStu as DormStudent;
        tempDorm.Grades = gradesDataGridView;
        MainMenu.myList[pos] = tempDorm;
    }
    else
    {
        tempStu.Grades = gradesDataGridView;
        MainMenu.myList[pos] = tempStu;
    }

here's the Student class that the grades is in.
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public List<int> Grades;
        public Student()
        {
            ID = 0;
            Name = "No Student";
            Grades = new List<int>();
        }
        public Student(int i, string n)
        {
            ID = i;
            Name = n;
            Grades = new List<int>();
        }
    }

I can't get either the converting the list to the datagrid when the check button is pressed or back when the save button is pressed. can anyone help with that?

A: Looking at your code I see mainly one issue. Note, however, that I am far from being an expert in Data Binding!
I see that you are creating a BindingList<> for type Student. I hope you actually want to display one Student's grades top down.
If instead you really wanted to display all Students top down and their grades in the columns from left to right you would have to do some serious twisting!
Now the BindingList should bind the Grades not a Student, so the first idea would be to change it to BindingList<int>.
However afaik unnamed variables make bad DataMembers. To display them the data should be Properties.
So I created a new class Grade that wraps the integer. For good measure I also added a string Test to hold a description of the the test. Leave it out if you don't want it!
public class Grade
{
    public int Points  { get; set; }
    public string Test { get; set; }

    public Grade()
    { Points = 0; Test = "No Test"; }

    public Grade(int points, string test)
    { Points = points; Test = test; }
}

This calls for changes in the Student class:
public List<Grade> Grades;

and (twice)
Grades = new List<Grade>();

The two lines creating the BindingList now look like this:
var blist = new BindingList<Grade>(tempDorm.Grades);
var blist = new BindingList<Grade>(tempStu.Grades);

The good news is that not only the data now load fine into the DataGridView; there is also no need at all for the save action, as the Data are bound two-way and every change actually happens in the List!
Only in the event of needing an undo function will you need some more coding, but that is another matter..


text:
Q: Why Order() in R don't return the correct order?
*

*I run these simple code in R and I don't know why it doesn't return the correct order.

order(c(4,1,4,3,2))
order(c("R","C","R","I","J"))

*

*This is the results:

[1] 2 5 4 1 3
[1] 2 4 5 1 3

*

*What is the problem?

A: The function order() returns the id (location) of the sorted elements. You could use:
v1 <- c(4,1,4,3,2)
v2 <- c("R","C","R","I","J")

sort(v1)
sort(v2)

#or

v1 <- v1[order(v1)]
v2 <- v2[order(v2)]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disable "a" href tag using code behind(c#) in asp.net 4.0 For certain condition I want to disable my  tag and I have tried following so far
//codebehind
if(condition)
{
    aTag.Disabled.Equals(true);
}

//.aspx page

it's not working, I don't know whats the matter, If anybody know please give me the better solution, thanks.

A: You can use javascript:void(0); to kill the link.
You cannot click me!

if(condition)
{
    aTag.HRef = "javascript:void(0);";
}

A: You could try using the disabled html attribute .. not sure it works for links though.
aTag.Attributes.Add("disabled","disabled");

Update: disabled doesn't work for links
Maybe what you need is to remove the value in the href.
aTag.Attributes["href"]= "#";

Or remove it.
aTag.Attributes.Remove("href");

A: Try setting the href to javascript:void(0)

A: I would just use an <asp:HyperLink Id="aTag" ClientIDMode="Static" Enabled="true" runat="server" />
Set client mode to static if you need to reference aTag in javascript, otherwise you can remove that...
Then check it on server side:  if condition { aTag.Enabled == false } ...


text:
Q: Word for bringing into agreement If there are two points that disagree, is there a word for the act of making them seem as if they are, in fact, in agreement? I've heard "resolve" used in this context, but it doesn't quite work for what I'm looking for.
"Rather than explaining the difference between the two texts, the commentaries seek to ?? them so that they appear to express the same opinion."

A: Reconcile:

[Merriam-Webster]
1 a : to restore to friendship or harmony • reconciled the factions
b : SETTLE, RESOLVE • reconcile differences
2 : to make consistent or congruous • reconcile an ideal with reality

Update: Based on some comments, here is the word inserted into the example sentence that was given:

Rather than explaining the difference between the two texts, the commentaries seeks to reconcile them so that they appear to express the same opinion.

Even if how the opinion expressed is different, they are being analyzed in such a way that seem to be in accord at some level despite that.
In this way, it's the disharmony that's resolved.
This is like political adversaries who can reconcile their differences in order to come together at a summit to discuss mutually acceptable courses of action. Although they still disagree with each other, the conflict that has kept them apart has been reconciled.

Here also is the Collins definition of reconcile:

If you reconcile two beliefs, facts, or demands that seem to be opposed or completely different, you find a way in which they can both be true or both be successful.

A: Perhaps "interpret"?

Rather than explaining the difference between the two texts, the
  commentaries seek to interpret them so that they appear to express
  the same opinion.

You gave no examples so I have invented a simple one.

Text A. People came to the party to meet each other and enjoy the
  food.
Text B. People came to the party to eat their fill of the free food.

These two texts appear to disagree about the reason people came to the party.
If the object is to praise the party, they could be interpreted to mean

There is no doubt that the party served excellent food.

without discussing why they are different.


text:
Q: Why isn't the bool member in struc not taking the user input? I'm creating a function called struct Car, where it takes the user input (in int main) of a couple member values. One of the members is a bool (isElectric), but I can't seem to figure out why the program doesn't allow me to input anything else after I enter "true" or "false". Is there a reason why the output comes out failing?
#include <iostream>
#include <string>

using namespace std;

struct Car {
  string color;
  string model;
  int year;
  bool isElectric;
  double topSpeed;
};

int main() {

Car car1;
cout << "Enter information for Car 1." << endl;
cout << "Car Color?: ";
cin >> car1.color;
cin.ignore();
cout << "Car Model?: ";
getline(cin, car1.model);
cout << "Car Year?: ";
cin >> car1.year;
cout << "Is the car electric?: ";
cin >> car1.isElectric;

Console:
Enter information for Car 1.
Car Color?: Yellow
Car Model?: Model  S
Car Year?: 2020
Is the car electric?: true
Car Top Speed?: Enter information for Car 2.
Car Color?: Car Model?: Car Year?: Is the car electric?: Car Top Speed

A: The default way to input a bool value is the integers 0 (for false) or 1 (for true).
To input the string "true" you need to use the std::boolalpha manipulator:
cin >> boolalpha >> car1.isElectric;


text:
Q: spark-submit process does not terminate after job completion automatically I'm submitting a pyspark job using spark-submit in client mode on yarn.
spark-submit   \
          --name $APP_NAME \
          --master yarn \
          --deploy-mode client \
          --num-executors 16 \
          --executor-cores 1 \
          --driver-memory 6g \
          --executor-memory 2g \

          --py-files myfile.py
            --version 2.3

The job completes successfully and I can verify that in Spark history as well as from Yarn.
Even after Job completion I still see the spark-submit process running and it doesn't terminate.
I wanted to have a job status back from my calling program  which invokes the submit job (Jenkins using publish over ssh plugin). Is there any way to make sure that the spark-submit process terminates with proper exit code after finishing job?
I've tried stopping spark context and putting exit status at the end of python script. This still doesn't work.
sc.stop()
sys.exit(0)

This happens randomly mostly for long running jobs.
I don't see any issue for Cluster mode.

A: You can write unix shell script and then you are able to check starus of command via $?
  spark-submit   \
      --name $APP_NAME \
      --master yarn \
      --deploy-mode client \
      --num-executors 16 \
      --executor-cores 1 \
      --driver-memory 6g \
      --executor-memory 2g \

      --py-files myfile.py
        --version 2.3

then you can check status and add your conditions
   if [ $? -eq 0 ];then
       echo 'Success'
    else
       'fail'
   fi

A: you can change conf --deploy-mode to cluster and try again.


text:
Q: Custom URL value from Gridview to other models yii2 <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        //'company-id',
        //'company-name',
        'department_name',
        'table_title',
        'entry_status',

        ['class' => 'yii\grid\ActionColumn',
         'template' => '{create}',
         'buttons' => [
            'create' => function($url,$model){
                return Html::a('', $url, ['title' => Yii::t('yii', 'Entry Data'),]);
            }]],
              ],
]); ?>

I want to make url in action column which every rows in this gridview has specific link to a specific model. For example: row 1 accessing url create/1 contains a table from a certain model. row 2 accessing url create/2 contains another table from another model. How could I do That?


text:
Q: Why user form submission message is not printing(after stopping confirm form submission alert by browser ) Query to insert the values in database
$query = "select * from logintb WHERE username = '$username'";
$query_run = mysqli_query($con,$query);

if(mysqli_num_rows($query_run)>0){
    echo 'username already exists!!';
}else{
    $query="insert into logintb values('$fullname','$username','$gender','$address','$pnumber','$email','$encrypted_password')";
    $query_run = mysqli_query($con,$query);

    if($query_run){
        echo "Registered successfully!";
        echo("<script>location.href = 'signUp.php';</script>");

    }else{
        echo '<script type="text/javascript"> alert("Error!") </script>';
    }
}

basically i was working on how to prevent the browser confirm form submission alert.Because it causes data to enter twice in database.so i redirect the page to itself.right now it solved my problem but couldn't print the message that user registered successfully because it reloads the page.any solution?

A: you need to place the insert and check into if (isset($_POST['submit-user'])) { } where submit-user is your button
if (isset($_POST['submit-user'])) {

    $query = "select * from logintb WHERE username = '$username'";
    $query_run = mysqli_query($con,$query);

    if (mysqli_num_rows($query_run) > 0) {

        echo 'username already exists!!';

    } else {

        $query="insert into logintb values('$fullname','$username','$gender','$address','$pnumber','$email','$encrypted_password')";
        $query_run = mysqli_query($con,$query);

        if ($query_run) {

            echo "Registered successfully!";

        } else {

            echo '<script type="text/javascript"> alert("Error!") </script>';

        }

    }

}

// HTML <form method="post"></form> goes here...

A: There are two solutions:-
echo "<script>alert('Registered successfully!');</script>";

The above will show the successful message as an alert and after clicking will reload the page . Or otherwise , go for JavaScript / JQuery registration process to make it faster and without reload .


text:
Q: Azure Terraform Web App private Endpoint virtual network I am trying to automate the deployment of an azure virtual network and azure web app.
During the deployment of those resources, everything went just fine and no errors. So I wanted to try to activate the private endpoint on the web app. This is my configuration on terraform.
resource "azurerm_virtual_network" "demo-vnet" {
  name                = "virtual-network-test"
  address_space       = ["10.100.0.0/16"]
  location            = var.location
  resource_group_name = azurerm_resource_group.rg-testing-env.name
}

resource "azurerm_subnet" "front_end" {
  name                 = "Front_End-Subnet"
  address_prefixes     = ["10.100.5.0/28"]
  virtual_network_name = azurerm_virtual_network.demo-vnet.name
  resource_group_name  = azurerm_resource_group.rg-testing-env.name
  delegation {
    name = "testing-frontend"
    service_delegation {
      name    = "Microsoft.Web/serverFarms"
      actions = ["Microsoft.Network/virtualNetworks/subnets/action"]
    }
  }
}

And on the web app itself, I set this configuration
resource "azurerm_app_service_virtual_network_swift_connection" "web-app-vnet" {
  app_service_id = azurerm_app_service.app-test.example.id
  subnet_id      = azurerm_subnet.front_end.id
}

NOTE: On my first deployment, the swift failed because I had not delegation on the virtual network, so I had to add the delegation on the subnet to be able to run terraform.
After setting in place all the configuration, I run my terraform, everything run just smoothly, no errors.
After the completion, I checked my web app Private Endpoint and that was just off.

Can please anyone explain me what am I doing wrong here?. I thought that the swift connection was the block of code to activate the Private endpoint but apparently I am missing something else.
Just to confirm my logic workflow, I tried to do the manual steps in the portal. But surprisingly I was not able because I have the delegation on the subnet, as you can see.

Thank you so much for any help and/or explanation you can offer to solve this issue

A: I have used the below code to test the creation of VNET and Web app with private endpoint.
provider "azurerm" {
    features{}
}

data "azurerm_resource_group" "rg" {
  name     = "ansumantest"
}

# Virtual Network
resource "azurerm_virtual_network" "vnet" {
  name                = "ansumanapp-vnet"
  location            = data.azurerm_resource_group.rg.location
  resource_group_name = data.azurerm_resource_group.rg.name
  address_space       = ["10.4.0.0/16"]
}

# Subnets for App Service instances
resource "azurerm_subnet" "appserv" {
  name                 = "frontend-app"
  resource_group_name  = data.azurerm_resource_group.rg.name
  virtual_network_name = azurerm_virtual_network.vnet.name
  address_prefixes     = ["10.4.1.0/24"]
  enforce_private_link_endpoint_network_policies = true
  }

# App Service Plan
resource "azurerm_app_service_plan" "frontend" {
  name                = "ansuman-frontend-asp"
  location            = data.azurerm_resource_group.rg.location
  resource_group_name = data.azurerm_resource_group.rg.name
  kind                = "Linux"
  reserved            = true

  sku {
    tier = "Premium"
    size = "P1V2"
  }
}

# App Service
resource "azurerm_app_service" "frontend" {
  name                = "ansuman-frontend-app"
  location            = data.azurerm_resource_group.rg.location
  resource_group_name = data.azurerm_resource_group.rg.name
  app_service_plan_id = azurerm_app_service_plan.frontend.id

}
#private endpoint

resource "azurerm_private_endpoint" "example" {
  name                = "${azurerm_app_service.frontend.name}-endpoint"
  location            = data.azurerm_resource_group.rg.location
  resource_group_name = data.azurerm_resource_group.rg.name
  subnet_id           = azurerm_subnet.appserv.id

  private_service_connection {
    name                           = "${azurerm_app_service.frontend.name}-privateconnection"
    private_connection_resource_id = azurerm_app_service.frontend.id
    subresource_names = ["sites"]
    is_manual_connection = false
  }
}

# private DNS
resource "azurerm_private_dns_zone" "example" {
  name                = "privatelink.azurewebsites.net"
  resource_group_name = data.azurerm_resource_group.rg.name
}

#private DNS Link
resource "azurerm_private_dns_zone_virtual_network_link" "example" {
  name                  = "${azurerm_app_service.frontend.name}-dnslink"
  resource_group_name   = data.azurerm_resource_group.rg.name
  private_dns_zone_name = azurerm_private_dns_zone.example.name
  virtual_network_id    = azurerm_virtual_network.vnet.id
  registration_enabled = false
}

Requirements:

*

*As you can see from the above code the Private Endpoint , Private DNS and Private DNS Link block are required for creating the private endpoint and enabling it for the app service.

*The App service Plan needs to have Premium Plan for having Private
endpoint.

*The Subnet to be used by Private Endpoint should have
enforce_private_link_endpoint_network_policies = true set other
wise it will error giving message as subnet has private endpoint network policies enabled , it should be disabled to be used by Private endpoint.

*DNS zone name should only be privatelink.azurewebsites.net as you are creating a private endpoint for webapp.

Outputs:


text:
Q: Jquery PHP - How to handle login callback on same page? Simply, my website allows users to login.
$('#login').click(function() {
    var user = $('#username').val();
    var pass = $('#password').val();
    $.post('authorize.php', { username: user, password: pass }, function(data) {
        //??
    });
});

authorize.php verifies credentials assuring a proper login. But now what? Do I use Jquery to $.show a hidden object, or do I load the new content from a PHP page with $.get or $.load? I'm uneasy on using $.show because elements will be loaded into the DOM regardless of a proper login. All of this takes place on the same page. Which of these two options is better practice? Or is there another?

A: Have authorize.php send the hidden object as data in case of a successful login and then display the data wherever you want.
$.show is not a good practice for the reason you mentioned above.

A: Using ajax request for login it is not good practice. Anyway there are three ways:

*

*You can add some "blank" object into DOM without first, last names and
other dynamic or important information and fill it and show as soon as user
logins.

*Send dom object as response from authrize.php

*Do not use ajax for login :)


text:
Q: HTML hyperlink to a specific page of a pdf file Consider a very simple link to a pdf file in HTML:
Link to pdf

Of course, when the user clicks on the link, the pdf is open and the first page is shown in the browser.
Is there a way create a link to a specific page of the pdf? I was wondering if there is some command like this:
Link to page 11 of the pdf

or some trick based on Javascript.

A: I found answer on adobe forum https://forums.adobe.com/thread/2345594.
After # you should write something like #page=3 for example, to move automatically to page 3.

A: The following should do the trick

You can also do chapters if needed but this needs a correctly formatted PDF.
Thanks


text:
Q: Module not found: Can't resolve 'google-maps-react' in 'C:\Users\USUARIO I am trying to create a project in react that shows a google map with different locations.
I used: $ npm install --save google-map-react from this very simple tutorial that I found online: https://dev.to/jessicabetts/how-to-use-google-maps-api-and-react-js-26c2.
But later I realized that there are 2 similar npm install:

*

*save google-map-react

*save google-maps-react

I am so confused! I always get the same error:
./src/components/MapContainer.js
Module not found: Can't resolve 'google-maps-react' in 'C:\Users\USUARIO\OneDrive\Escritorio\ProyectosGA\react-geek\packyfood\src\components'

I have no idea how to solve it and there is no much info. Could you guys please help me? Here is my code:
MapContainer.js
import React, { Component } from 'react';
import { Map, GoogleApiWrapper } from 'google-maps-react';

const mapStyles = {
  width: '100%',
  height: '100%'
};

export class MapContainer extends Component {
  render() {
    return (
      <Map
        google={this.props.google}
        zoom={4}
        style={mapStyles}
        initialCenter={{
         lat: 6.2518401,
         lng: -75.563591
        }}
      />
    );
  }
}

export default GoogleApiWrapper({
  apiKey: 'AIzaSyDGArUEBa5ns09IA7nt7jP-xfNIUkToFts'
})(MapContainer);

A: Based off the tutorial it looks like you've missed a crucial step.
You need to install google-maps-react dependency in your project.
In your console, navigate to your project root directory and run the following:
npm install --save google-maps-react

Another troubleshooting issue for those who are stuck is to DELETE your node_modules folder and the run npm install in the console.
This will reinstall all the required dependencies for your project.

Note:
Considering you've accidentally installed google-map-react instead of google-maps-react. I recommend uninstalling google-map-react since it's not being used.
Do that by run the following in your console:
npm uninstall --save google-map-react

A: I had the same issue. I fixed it by adding  declare module 'google-map-react'; in file react-app-env.d.ts
Try it out and give a feedback by the way I am using TS with React


text:
Q: How to pass the output of SELECT to a function expecting a table? I have a function that knows to split strings by comma:
SELECT * FROM dbo.SplitStrings('15,29')

Returns
Item
15
29

I also have a function that knows to join strings by comma:
DECLARE @table AS SmallStrings
INSERT INTO @table VALUES ('a'),('b'),('c')
SELECT dbo.JoinStrings(@table) Joined

Returns
Joined
a,b,c

Now I want to split a string, modify each item and join them back. I can do that too:
DECLARE @tmp SmallStrings
INSERT INTO @tmp SELECT dbo.DayOfMonthExprToCron2(Item) Item FROM dbo.SplitStrings('15,29')
SELECT dbo.JoinStrings(@tmp) Result

Returns
Result
15,L

Now I wonder if I can pass the result of SELECT dbo.DayOfMonthExprToCron2(Item) Item FROM dbo.SplitStrings('15,29') directly into dbo.JoinStrings
I tried and failed - my humble attempts do not even compile.
The naive one:
SELECT dbo.JoinStrings(SELECT dbo.DayOfMonthExprToCron2(Item) Item FROM dbo.SplitStrings('15,29')) Result

Results in
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ')'.

Edit
Another attempt (using double parentheses):
SELECT dbo.JoinStrings((SELECT dbo.DayOfMonthExprToCron2(Item) Item FROM dbo.SplitStrings('15,29'))) Result

Results in
Msg 206, Level 16, State 2, Line 1
Operand type clash: nvarchar is incompatible with SmallStrings

I realize that the code is needed, so here it is:
CREATE FUNCTION [dbo].[SplitStrings](@List NVARCHAR(4000))
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN
   (
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM (
        SELECT x = CONVERT(XML, '' + REPLACE(@List, ',', '') + '').query('.')
      ) AS a
      CROSS APPLY x.nodes('i') AS y(i)
   );

CREATE FUNCTION [dbo].[JoinStrings](@strings SmallStrings READONLY)
RETURNS NVARCHAR(4000)
AS
BEGIN
    DECLARE @res NVARCHAR(32)
    SELECT @res = COALESCE(@res + ',', '') + Item
    FROM @strings
    WHERE Item IS NOT NULL
    RETURN @res
END

CREATE TYPE [dbo].[SmallStrings] AS TABLE([Item] [nvarchar](5) NULL)

CREATE FUNCTION [dbo].[DayOfMonthExprToCron2](@dayOfMonthExpr NVARCHAR(32))
RETURNS NVARCHAR(32)
AS
BEGIN
    DECLARE @dayOfMonth INT = CAST(@dayOfMonthExpr AS INT)

    RETURN CASE WHEN @dayOfMonth < 29 THEN @dayOfMonthExpr ELSE 'L' END
END

A: I do not think that is possible.
I poked around the documentation of table value parameters (TechNet) and around the web for any hint.
I also tried using a very simplified set set of functions and couldn't make it work.


text:
Q: Good way to format data in a large DataTable I have a large data.DataTable and some formatting rules to apply.  I'm sure this is not a unique problem.
For example, the LASTNAME column has a value of "Jones" but my formatting rule requires it be 10 characters padded with spaces on the right and uppercase only.  Like: "JONES     "
My initial thought is to loop through each row and generate a string.  But, I wonder if I could accomplish this more efficiently with a DataView, LINQ or something else.
Can someone point me in a direction?

A: It really depends how you display the results. I would say if you display it in a grid, the easiest would be to do a quick loop, no real performance harm there in a datatable.
If you display the records individually you can create an extension method for your string, and simply call it like this for example. LastName.Padded()
public static class StringExtensions
{
   public static string Padded(this string s)
   {
       return s.ToUpper().PadRight(10);
   }
}


text:
Q: How to label the x axis with exact values
I have drawn the bar chart above using the following code:
set terminal jpeg medium
set output "bar.jpeg"  # shall be the name of the chart
set xlabel "full configuration time in msec"
set ylabel "Task rejection rate (%)"
set boxwidth 0.5
set style fill solid
#set autoscale

plot "data.data" using 1:2 with boxes

My file data.data looks like this:
2 9
5 24
7 46
10 66
15 100

I want the exact values 2,5,7,10,15 to appear along the x axis with the corresponding value along the y axis and to use a color other than red. What changes do I have to make to my code? I also need to remove that "data.data" using 1:2 from the top right corner...
Any suggestions?

A: To remove the key, use unset key.
The markers at the bottom of the graph are called xtics. If you want them to appear every 1, rather than every 2, then you could use set xtics 1. Depending on exactly what you wanted to do, you can customise the xtics even more. In gnuplot if you do help xtics there's plenty of information on that.
To change the colour of your boxes, you can use the lc (line colour) property. I have used a hexadecimal #RRGGBB format but you can also use names of colours like green, blue, etc. Look at help linecolor for more info on that.
Incorporating all of those changes into your script:
set xlabel "full configuration time in msec"
set ylabel "Task rejection rate (%)"
set boxwidth 0.5
set style fill solid

unset key
set xtics 1

plot "data.data" using 1:2 with boxes lc rgb '#52bb23'

By the way, I used the pngcairo terminal rather than the jpeg one as I think it looks better. Try set term to see what terminals are available to you.

A: In addition to @TomFenech's answer: If you want to show only the x-values specified in the data file, you can use the xtic function. Note, that in this case the defined x-format has no effect and the value is taken 'as-is':
set xlabel "Full configuration time in msec"
set ylabel "Task rejection rate (%)"
set boxwidth 0.5
set style fill solid
set xtics out nomirror

plot "data.data" using 1:2:xtic(1) with boxes notitle


text:
Q: Terraform Azure Provider 2.x Error: "features": required field is not set I receive the above error, even though I already have the features block, as per the below code extract, however I continue to receive the error when running terraform plan:
provider "azurerm" {
features {}
version = ">=2.0.0"
}

I have also tried pinning the provider version with "=2.0.0"; "=2.1.0"; "=2.2.0"; "=2.3.0"; "=2.4.0", and each time deleting the .terraform directory, and doing a fresh init, and plan each time. but still get same error every time
Normally I've been using ">=2.0.0" ever since the 2.0 AzureRm Provider got released, and I originally added the features block without issue, but now with this error that tells me there is no features block, when in fact I do have a features block - that's why I've been trying all these different version combinations but without luck.
I've also tried all of the above with different versions of terraform.exe (0.12.19; 0.12.21; 0.12.24), also deleting the .terraform directory with each new version.
Error: "features": required field is not set
Any advice would be appreciated. Thank you
Tested all the above on Windows 10 v1809


text:
Q: Is there an option (or a set of patches) to make Redis selectively read-only? I would love to have a means to restrict read/write access to a Redis server to a select list of clients.  For this purpose AUTH and passwords would not be sufficient.  The purpose would be to allow a large number of readers on one side of a Redis server or cluster to fetch/get values while only allowing a smaller number of systems to post new data thereto.
Does anyone know of a set of patches to do this?  Perhaps some "undocumented" or obscure configuration option?  An alternative to Redis which provides similar data structures, operations and synchronization/atomicity features but also offers this?
What would be the best way to suggest this as an enhancement request to Salvatore?

A: Redis is all about simplicity so I doubt such a prominent feature would be undocumented. If you want to contribute, checkout the community page. It's worth a try, but they are very clear that they want to keep Redis simple and that you will find resistance to new features.

A: webdis - 'A fast HTTP interface for Redis' - supports access control.  It provides a REST/JSON API to redis and supports per-command access control by http auth or IP range.
http://webd.is/


text:
Q: Feature structure unification in minikanren How would one define a feature structure unification and subsumption in minikanren if we represent feature structures with lists?
The general behaviour would be something like this (I think):
(run* (q) (unifyo '(a b) '(a b) q))) => (a b)

(run* (q) (unifyo '(x (a b)) '(x (c d)) q)) => (x (a b) (c d)) (x (c d) (a b))

(run* (q) (unifyo '(x (a b)) '(x (a d)) q)) => ()      ; fails because '(a b) is
                                                       ; incompatible with '(a d)
(run* (q)
    (fresh (y) (unifyo '(x (a b)) `(x ,y) q)) => (x (a b)))

(run* (q) (unifyo q '(x (a b)) '(x (a b) (c d)))) => (x (c d))

The following code sort of works, but backwards unification gets stuck when ran with run*:
;; unifies f1 with l2
(define unify-f-with-list°
  (lambda (f1 l2 out)
    (conde
     [(== '() l2) (== `(,f1) out)]
     [(fresh (la ld a2 d2 a1 d1 res)
         (=/= '() l2)
         (== `(,la . ,ld) l2)
         (== `(,a2 . ,d2) la)
         (== `(,a1 . ,d1) f1)
         (conde
          [(== a2 a1)
           (== `(,res . ,ld) out)
           (unify° f1 la res)]
          [(fresh ()
              (=/= a2 a1) ;; if not
              (== `(,la . ,res) out)
              (unify-f-with-list° f1 ld res))]))])))

(define unify-list-with-list°
  (lambda (l1 l2 out)
    (conde
     [(== '() l1) (== l2 out)]
     [(== '() l2) (== l1 out)]
     [(fresh (a1 d1 res)
         (=/= '() l1)
         (== `(,a1 . ,d1) l1)
         (unify-f-with-list° a1 l2 res)
         (unify-list-with-list° d1 res out))])))

(define unify°
  (lambda (f1 f2 out)
    (conde
     [(== f1 f2) (== f1 out)]
     [(fresh (a1 d1 a2 d2)
         (=/= f1 f2)
         (== `(,a1 . ,d1) f1)
         (== `(,a2 . ,d2) f2)
         (== a1 a2)
         (fresh (res)
            (unify-list-with-list° d1 d2 res)
            (== `(,a1 . ,res) out)))])))

A: You can implement this by modifying the code for unification in your minikanren implementation.
I would recommend not using lists to represent feature structures though, instead you could define a new record type than holds a list that always terminates in a fresh variable and one of these would represent a feature structure. Then you can still use lists and other objects as well as having these new objects available.
When the unification code sees two feature structures it would need to unify all the matching keys recursively and extend the 'rest' part of each one to contain the fields unique to the other feature structure (no destructive mutation).


text:
Q: Native ZFS doesn't free up space when deleting files I'm running native ZFS on Ubuntu 11.10 with 2x2 TB drives in a mirrored setup. The ZFS file system is mounted directly in Ubuntu and not through NFS or something like that, the permissions are set too 777.
My problem is that when I delete a file it would disappear as you'd expect but when I type zfs list it's still reporting used space as if the file was still there. I've wait a couple of hours and I'm currently running a scrub to see if that fixes it but that shouldn't be necessary, should it?

A: The answer is pretty ridiculous I guess; it turned out that Ubuntu moved the files to .Trash1000 but wouldn't allow the Recycle Bin to empty the .trash-folders on my ZFS datasets. I'm guessing this is a permissions issue or something since my ZFS datasets are mounted with root and then I ran chmod 777 on all of them to allow for my user to use them.
Anyways, deleting the .Trash1000 folder fixed the "problem".


text:
Q: Action remains in queue in lightning component when launched from timeout function I am actually using lightning components with VF, to allow my user to search for a particular account. According to the client spec, the user will only type their letters and the search result should appear. I'am actually implementing the debounce functionality because i do not what to pin my server at each keypressed letter, using javacript setTimeout function in my JS controller. But my action is stuck in the queue and do not get executed :
cmp codes :
<ui:inputText aura:id="xid-vl" class="slds-input" label="Ville" keyup="{!c.showSearch}" updateOn="keyup"/>

controller codes :
showSearch : function(component, event, helper) {
    console.log("## show search");

    var delay = 1000;
    var timer = component.get('v.timer');

    clearTimeout(timer);
    timer = setTimeout(function(){
        console.log("starting search");
        helper.sendInfo(component);
    }, delay);

    component.set('v.timer', timer);
}

helper codes :
sendInfo: function(component){
    var vl = (component.find("xid-vl").get("v.value"));
    console.log("ville is :" + vl);

    if(vl != null && vl.length > 2){
        console.log("sending to server ");

        var action = component.get("c.getTest");
        //action.setParams({"name": rs,"other": ""});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                console.log("result :", result);
            }
            else console.log('error :',action.getError());
            //component.set("v.showSpinner",false);

        });
        $A.enqueueAction(action);
    }
}

nothing happen, and no error get displayed. When using the salesforce lightning inspector, found that the action remians stucked in the queue with the State = NEW.
Am i missing something when enqueing the action ?

A: The behaviour is mentioned in the docs here

Use $A.getCallback() to wrap any code that modifies a component outside the normal rerendering lifecycle, such as in a setTimeout() call.
The $A.getCallback() call ensures that the framework rerenders the modified component and processes any enqueued actions.

Hence use that in your code like below
 var delay = 1000;
 var timer = component.get('v.timer');
 window.setTimeout(
 $A.getCallback(function() {
 if (component.isValid()) {
    helper.sendInfo(component);
  }}),
  delay);
 component.set('v.timer', timer);
}


text:
Q: How can I expose a public property of a server control in the Properties window? I have an ASP.NET server control with some public properties.
If I drop the server control onto a form, I can access those properties from the code-behind.  But I'd like to set them in the Properties window of the form designer.
The properties are just strings and booleans, not complex types.
I'm using Visual Studio 2010 and .NET 4.0.
How can I expose server control properties to the Properties window in Design mode?

A: Here's an oldie but a goodie. Looks like what you're looking for.
Adding Design-Time Support to ASP.NET Controls
Here's a more recent article: Design-Time Attributes for Components

A: Use the Browsable attribute decorator
//C#
[Browsable(true)]
 public string MyProperty {
    get {

    }
    set {

    }
 }

 'VB
<Browsable(True)> _
Public Property MyProperty() As String
    Get

    End Get
    Set

    End Set
End Property


text:
Q: Is the speed of light through a medium invariant, just like the speed of light through vacuum is invariant? Also, do time dilation etc. still occur? So, we know the speed of light through a vacuum is $c$.
Let us say that both our observers are moving past each other at speed $v$ in a medium in which the speed of light is $c'$.

*

*So, does the usual postulate of relativity apply in this case as well? That is, will the speed of a light beam in that medium be $c'$ in the frame of both the observers irrespective of the speed of source/speed of observer, etc.?

*Will all the relativistic phenomena like length contraction, time dilation, twin paradox etc. apply in this case as well?
If yes, then will the formula for $\gamma$ be modified to use $c'$, or should we still use $c$ to calculate $\gamma$?

A: @IndischerPhysiker has already answered the question, but I would like to bring forward an example of Cherenkov radiation - a phenomenon that occurs when a particle moves through the medium faster than the speed of light (in the medium), and raises precisely the question voiced in the OP:

Cherenkov radiation is electromagnetic radiation emitted when a charged particle (such as an electron) passes through a dielectric medium at a speed greater than the phase velocity (speed of propagation of a wave in a medium) of light in that medium. Special relativity is not violated since light travels slower in materials with refractive index greater than one, and it is the speed of light in vacuum which cannot be exceeded (or reached) by particles with mass.

Update
The way I would answer the question is: the speed of interactions is invariant. In vacuum the speed of light (i.e., the product of the wavelength and the frequency) is the same as the speed of interactions, but not in a medium, because the medium responds to the fields of the electromagnetic wave. But the speed of interaction, e.g., between the wave and the medium is still the speed of light in vacuum. This appears paradoxical only when we treat the medium as continuous, whereas on microscopic level we are still in vacuum. Indeed, refractive index is but a simplification for describing the field that is a superposition of the original light wave and the polarization and magnetization induced by this wave in the environment:
$$
\mathbf{E} = \frac{1}{\epsilon_0}\left(\mathbf{D}-\mathbf{P}\right),\\
\mathbf{B} = \mu_0\left(\mathbf{H}+\mathbf{M}\right).
$$
A related issue is the difference between the phase velocity, $v_{ph}=\lambda\nu=\omega/k$ and the group velocity, $v_g=\partial \omega(k)/\partial$ - the phase velocity can exceed the speed of light in vacuum, but the group velocity cannot - it is the latter that corresponds the the speed with which information propagates. In vacuum or dispersionless medium $\omega(k)=ck$ and the two velocities coinside.

A: The relative speed of light in water was first determined by Fizeau who found experimentally that it depended on the motion of the medium. The combination of Fizeau's result and the null result of the Michelson-Morley experiment was the impetus for the development of special relativity. So the answer to your first question is that the speed of light in a medium does depend on the relative motion of the observer and medium and is not invariant.
The answer to your second question is that we always use the invariant speed $c$ for calculations of the Lorentz transformation. $c$ is usually called "the speed of light", but it's more accurately referred to as "the speed of light in vacuum". It would be even better to call it "the speed of gravity" because that might help to avoid some of the misconceptions around light being special, but for historical reasons "speed of light" seems to have stuck.

A: The short answer to the first question is no. The point is to understand that light does not have to be given the special pedestal we give it while analysing problems such as above. Anything moving at a speed $c$, be it a photon or any other particle would follow the second postulate of relativity. On the other hand  photons which don't travel at $c$ due to being in a medium are just normal particles whose velocities have to be added by relativity-
$$v_x'=\dfrac{v_x-v}{1-vv_x/c^2}$$
The answer to the second problem is yes, they will apply exactly the same way. The second postulate of the special theory says that anything moving at $299,792,458$ m/s moves at that speed irrespective of how you move. The lorentz transformations are normally derived for photons, but any particle moving with a speed $c$ would be enough, since the postulate is about the speed of light, not light itself.
The formula for $\gamma$ = $1/\sqrt{1-v^2/c^2}$ to be used in time dilation / length contraction will still use c and not c'


text:
Q: Android studio location permission issue I made an android application.
I have problem when starting the app because of location permission, when app start I put function to get device location. The problem is sometime when we click "Yes" on the permission it crashed on the first time. It still get the location and have no problem for second and afterwards.
Do you have any idea how to solve this?
How to resolve this issue?

A: do you just ask for permission or do you also search for location data?
Here is an example of a request for permission without seeking the location.
if((ContextCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
) {
return true
}
else{
return false
}


text:
Q: Run the current command and pipe the output to fzf What would be an easy way to bind a key binding from fish to run the current command prompt and pipe it to fzf for easy search/selection?
i.e. a 1 key-press way of accomplishing | fzf (enter)?

A: Seems like a pretty straightforward bind function, if I'm understanding correctly.  At its simplest:
Saved in ~/.config/fish/functions/__append_pipe_fzf.fish:
function __append_pipe_fzf
    set -l cmd (commandline -b)
    commandline -r $cmd" | fzf"
    commandline -f execute
end

And then bind it to a key with something like:
bind -k nul __append_pipe_fzf
nul binds to Ctrl+Space (or ⌘+Space on Mac, which I believe is your case).
Of course, you can make this more robust by checking to see if the current command ends with a process starting with | fzf and remove it if so.  Right now, it could conceivably append the | fzf even when you already have one there.  Also, if you pressed it when the current commandline ended in |, I think it would generate an "or" statement, instead of what you want.


text:
Q: Correct place to read and write from stdin/stderr/stdout of external process which should be terminated within timeout I have the java application which starts external process through process builder.
External application interracts with rest "world" through stdin,stdout,stderr. Also this process should not be executed longer than some timeout.
code looks like this:
ProcessBuilder pb = new ProcessBuilder(parameters);
Process process = pb.start();
OutputStream processOutputStream = process.getOutputStream();
IOUtils.write(inputJson, processOutputStream); // write data to external process
processOutputStream.close(); we don't need pass more arguments

InputStream errorStream = process.getErrorStream();

boolean responseWithinTimeout = process.waitFor(2000, TimeUnit.MILLISECONDS); //app should work not longer than 2 sec
if (process.isAlive()) {
    process.destroyForcibly();
}
String stringFromErrorStream = IOUtils.toString(errorStream, "UTF-8"); //read from external application error stream

My questions:

*

*Does 2000 niliseconds starts sincepb.start() or since  process.waitFor

*Is it correct to read from  errorStream when application already killed or it should be placed before process.destroyForcibly()?

A:
Does 2000 milliseconds starts sincepb.start()

No.

or since process.waitFor()

Yes.

Is it correct to read from errorStream when application already killed

No.

or it should be placed before process.destroyForcibly()?

Yes. Best in a separate thread. You should also consume the process's stdout. Otherwise it can block.


text:
Q: How to make one part of the text Bold in iText I need to get a part of the text bold in my app.  So basically what I am trying to achieve is have something like this:  Address: 123 Street.  Where at the moment i am getting all in bold:  Address: 123 Street
Here is my code I am using:
PdfPTable table2 = new PdfPTable(3);
            table2.setWidthPercentage(100);
            table2.addCell(getCell("Address:  " + SaveString, PdfPCell.ALIGN_LEFT));
            table2.addCell(getCell("Name:  " + SaveStringA, PdfPCell.ALIGN_CENTER));
            table2.addCell(getCell("Last Name:  " + SaveStringB, PdfPCell.ALIGN_RIGHT));
            table2.setSpacingAfter(15);
            doc.add(table2);

public PdfPCell getCell(String text, int alignment) {
    PdfPCell cell = new PdfPCell(new Phrase(text));
    Font bold = FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD);
    Paragraph p1 = new Paragraph(text, bold);
    cell.setPadding(0);
    cell.addElement(p1);
    cell.setHorizontalAlignment(alignment);
    cell.setBorder(PdfPCell.NO_BORDER);

    return cell;

Hoping someone could help please?
Thanks!!

A: You can try using Chunk, something like this:
Font bold = FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD);
Chunk chunkAddress= new Chunk("Address:  ", bold);
Chunk ChunkAddressDetails = new Chunk("123 Street.");

Phrase phrase = new Phrase();
phrase.add(chunkAddress);
phrase.add(ChunkAddressDetails);

Paragraph paragraph= = new Paragraph();
paragraph.add(phrase);

A: SpannableStringBuilder str = new SpannableStringBuilder("Address: 123 Street");
str.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD), 0, "Address:".length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTextView.setText(str);


text:
Q: Using ports on business firewall I have question regarding network architecture with very close view on FW device port usage on business firewalls like Zyxel ATP800.
For example, this FW has 12 customizable ports (WAN,LAN, etc)
I often see that only 2 ports are used:
1xWAN + 1xLAN which goes to managed switch where all VLANs / network separation is configured.
So question:
Is it bad practice to use more ports on ATP800 directly ? For example:
p1- as wan
p3- lan1 (vlan1,2,3,4)
p4- lan2 (vlan 5,6,7,8)
p5- lan3 (vlan6,...)
etc ?
many thanks

A: You can certainly use the other switch ports on the ATP800 if you want. But if you do then you are limited to whatever configuration and features it provides, which may or may not meet your needs. If it doesn't have functionality you need, then you have to use another switch that does, which is generally the reason why you would see only the single LAN port in use.

A: I would add another reason why it can be a bad idea;
The router often do traffic inspection or DPI often they call the module.
As such without knowing it use between the LAN port will cause highter CPU cycle of the router as it will inspect everything. A high load on the port could cause problem with the hardware.


text:
Q: Can you build dynamic libraries for iOS and load them at runtime? Are dynamic libraries supported on iOS (iPhone/iPad)?
In Xcode, I tried to create a New project -> Framework & Library -> Cocoa Library (dynamic). In the project settings, I set the Base SDK to iOS device 4.1 and target to iOS4.1, but it has a build error:

target specifies product type 'com.apple.product-type.library.dynamic', but there's no such product type for the 'iphonesimulator' platform".

The build i selected is Simulator -> Debug -> i386.

A: I'm not really disagreeing with DarkDust's answer, but if I may channel my inner Bill Clinton, it depends on what the meaning of supported is :)
Apple doesn't want you doing this for App Store apps, but the operating system certainly allows it.  Jailbreak apps use this technique all the time.  You basically use a standard UNIX technique to dynamically open a framework/library, and then use stuff in it.  The dlopen function allows you to open the library by passing in the path to that framework, or dylib.  From some docs for building jailbreak apps, here's an example of calling an init() function implemented inside your own, separate dylib:
#include <dlfcn.h>

initWrapper() {
    char *dylibPath = "/Applications/myapp.app/mydylib2.dylib";

    void *libHandle = dlopen(dylibPath, RTLD_NOW);
    if (libHandle != NULL) {
        // This assumes your dylib's init function is called init,
        //    if not change the name in "".
        void (*init)() = dlsym(libHandle, "init");
        if (init != NULL)  {
            init();
        }
        dlclose(libHandle);
    }
}

Furthermore, the default restriction against allowing you to build a dynamic library project for iOS is something in Xcode that you have the ability to override by editing some XCode xml files:
Build and use dylib on iOS
Once you do this, you can build a normal iOS .dylib library, and use it per the sample code above. (yes, you probably will have to unlock this capability again whenever you install a new XCode version).
So, it's not a technical limitation, but an App Store policy limitation.  If you're not limited to the App Store, then you can do it.  Note that this technique does not require jailbreaking, although if the app is sandboxed, it may limit where dylibs can be loaded from.
Edit: in order to make sure this information isn't lost to future link rot, here is the content of the link I provided on how to enable iOS dylibs in Xcode.  (Note: this process still works on Xcode 4, but see comment(s) below for updates to paths, etc.)  Source is the iOS Place blog:

Xcode does not allow you to build dylib for iOS. App will be rejected if it's not single binary. But I have an application that has plug-in architecture to load optional modules. I just want a quick prototype to prove concept before fully port it to iOS. It's faster to do if dylib could simply work. So, this post shows how to build and use dylib but be aware it won't be approved to App Store. (Tested with Xcode 3.2.4 on 10.6.4)
1. Open these files in the Property List Editor: /Developer/Platforms/MacOSX.platform/Developer/Library/Xcode/Specifications/MacOSX Product Types.xcspec and /Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Specifications/iPhone Simulator ProductTypes.xcspec
2. Locate the item in the "MacOSX Product Types.xcspec" that has the product type com.apple.product-type.library.dynamic and drag it to the "iPhone Simulator ProductTypes.xcspec".

3. Open "MacOSX Package Types.xcspec" and "iPhone Simulator PackageTypes.xcspec" found at the same places.
4. Locate the item in the "MacOSX Product Types.xcspec" that has the package type com.apple.package-type.mach-o-dylib and drag it to the "iPhone Simulator PackageTypes.xcspec".

5. Repeat the steps for the "iPhoneOS.platform" and relaunch Xcode if it was running.
Now, lets build a dylib. Start out with the "Cocoa Touch Static Library" Template. That should included the Foundation.framework in the project. Here are the changes I made on top of the template to build dylib.
1. Open the file project.pbxproj (found inside the Xcode project file bundle) in a Text Editor. Search for string "producttype", change it's value to com.apple.product-type.library.dynamic;
Now, open the project with Xcode, go to Project->Edit Project Settings
2. "Installation Directory" set to @executable_path/ because I plan to put the dylib in the same directory as the app's executable.
3. "Mach-O Type" set to Dynamic Library
4. "Executable Extension" set to dylib
5. "Executable Prefix" set to empty
6. Add one or two simple methods to the library and build it.
Now, create an app to test it. This time, I choose the View-based Application. Hook up a UIButton and a UILabel to call the lib and showing return message. You can download the complete project TestApp and play with it.
The Lost knowledge:
Screenshots below are related to links not working now.
Build and use dylib on iOS

A: At the time this question was asked, Dynamic libraries were not supported by iOS and will result in your app getting rejected. Only static libraries are allowed.
However, in iOS8 you can use dynamic libraries and frameworks. It should "just work"

A: Starting from Xcode 11.4.1 dynamic libraries are not allowed (your project won't compile for all destinations). The new way to use libs/frameworks is the create-xcframework from xcodebuild.


text:
Q: How can i loop through an array using innerHTML

From the above code I can only get last digit. Why it is not showing all digits in the array. But When i use innerHTML+=item it is working fine. What is the difference between = and += here. I found that every tutorial explaining that += means x = x + y. But I believe there is a huge logic behind the scenes of += But no any one is expaining about this. It will be very helpfull anyone can explain this. Thanks in advance!

A: What is the difference between = and += here?
= You are assigning the value to something.
+= You are not only assigning but also holding the previous value and also assigning and concatenating the previous value with current value.

A: = and += are not the same
document.getElementById('demo').innerHTML=item;

will set to a single item each time in the loop. So going through three times your would be setting the innerHTML like this:

*

*innerHTML = '1'

*innerHTML = '2'

*innerHTML = '3'
document.getElementById('demo').innerHTML+=item;
will append the item and is the same as
document.getElementById('demo').innerHTML=document.getElementById('demo').innerHTML + item;

So each time through you will be executing:

*

*innerHTML = originalHTML + '1'

*innerHTML = originalHTML + '1' + '2'

*innerHTML = originalHTML + '1' + '2' + '3'


text:
Q: TFS 2013 Custom dashboard widget I have been tasked with creating a custom planning view from TFS.
I have a reasonable amount of experience with the TFS Api but I want to try and avoid having to create and maintain a new application for this.
I have looked at SSRS for TFS but I am unable to access all of the data I need (tags etc.) so this is not an option (as it will invalidate support).
I would ideally like to create a "widget" to appear on one of the TFS dashboards but am not sure where to start. The widget would also need to allow access to the TFS api to gather the data it needs to generate.
Please can someone advise where I may look to start or an alternative approach.

A: You may want to take a look at http://integrate.visualstudio.com where you can find documentation for the TFS API. The REST API works for TFS 2015 and above.
While you can extend the web interface with Extensions (https://marketplace.visualstudio.com/) in Visual Studio Team Services (VSTS), this feature is not yet available in TFS on-premises as of TFS 2015 Update 1.
You can check the published feature timeline for updates, but at this time extensions for TFS are marked as "TBD".

A: If you're working with TFS2013 + Update2 or a higher version of TFS, it is allowed for Team Administrators to customize TFS dashboard via pinning items to the homepage without writing any code.
For example, if you would like to add a chart into the dashboard, you just need to go to the query's Charts page and pin it to the home page. See the following image (quoted from this MSDN article)


text:
Q: Implement smooth transition to emulate car marker moving on the map I want to implement smooth transition to emulate car marker moving on the map. From current postion to selected position.

A: Even if I suppose that you hadn't try anything, I give you a great method to achieve that .. just because I'm in a good mood
public static void animateMarker(final GoogleMap map, final Marker marker, final LatLng toPosition,
                          final boolean hideMarker) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    Projection proj = map.getProjection();
    Point startPoint = proj.toScreenLocation(marker.getPosition());
    final LatLng startLatLng = proj.fromScreenLocation(startPoint);
    final long duration = 500;

    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);
            double lng = t * toPosition.longitude + (1 - t) * startLatLng.longitude;
            double lat = t * toPosition.latitude + (1 - t) * startLatLng.latitude;

            marker.setPosition(new LatLng(lat, lng));

            if (t < 1.0) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            } else {
                if (hideMarker) {
                    marker.setVisible(false);
                } else {
                    marker.setVisible(true);
                }
            }
        }
    });
}

Enjoy it!


text:
Q: undefined method `[]' for nil:NilClass for RoR file upload My model is called Projects, which has a string filename and a string location. I have an upload form that's supposed to take a file as input, upload it to public/data/, and store the filename and path as a new Projects object. When I try to upload a file, I get "undefined method `[]' for nil:NilClass for RoR file upload." The error is in line 86 of my controller file, which is "name = params[:upload][:file].original_filename"
View:
<%= form_tag( { :action => 'upload' }, :multipart => true ) %>
Upload file: <%= file_field( "form", "file" ) %>
<br />
<%= submit_tag( "Upload file" ) %>

Controller:
def upload
    ### THE LINE BELOW IS WHERE THE ERROR OCCURS
    name = params[:upload][:file].original_filename
    directory = "/public/data"
    path = File.join(directory, name)
    File.open(path, "wb") { |f| f.write(params[:upload][:file].read) }
    @project = Project.new({:filename => name, :location => path})

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render json: @project, status: :created, location: @project }
      else
        format.html { render action: "new" }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
end

Can anyone guess what's wrong? I'm a RoR, and Ruby, novice.
Edit: I tried params[:form[:file]] instead of params[:upload][:file], and get the error "can't convert Symbol into Integer" on the same line.

A: In you controller you are trying to get the file using params[:upload][:file], but in your form you created the name as form. So you need to change form to upload. So your code should be,
Upload file: <%= file_field( "upload", "file" ) %>


text:
Q: Difference Between SQL Server Management Studio date filter and Excel/PowerBI date filter I have a SQL query which looks like this:
SELECT *
FROM TABLE
WHERE Date >='2019'

which results in 214.096 rows.
If I copy the results (214.096 rows) into Excel or PowerBI and filter for Date >= 2022, I get 11.460 results for 2022 (in both Excel and Power BI).
However if use the following query:
SELECT *
FROM TABLE
WHERE DATE >= '2022'

I get 13.157 rows.
For the other years I get the following results:
2019

*

*Excel/Power BI: 70.091

*SQL: 70.091
  SELECT *
  FROM TABLE
  WHERE DATE >= '2019' AND DATE < '2020'

2020

*

*Excel/Power BI: 67.645

*SQL : 69.401
  SELECT *
  FROM TABLE
  WHERE DATE >= '2020' AND DATE < '2021'

2021

*

*Excel/Power BI: 64.902
SQL : 69.516
  SELECT *
  FROM TABLE
  WHERE DATE >= '2021' AND DATE < '2022'

2022

*

*Excel/Power BI: 11.460

*SQL : 13.157
  SELECT *
  FROM TABLE
  WHERE DATE >= '2022' AND < '2023'

*That equals in Excel/PowerBI: 214.096

*In SQL for the query with Date >= '2019': 214.096

*If I sum the different queries for the years: 222.165
What am I doing wrong?


text:
Q: How to flash STM32 via Serial Port I have an STM32F102 microcontroller and I want to program it via the Serial Port.
While there is a flasher available for windows, I want to do it on a Linux Machine. I tried doing it with this script
I have set BOOT0 = 1 and BOOT1 = 0, restarted the microcontroller. But it does not work. I get the following output
Can't init. Ensure BOOT0=1, BOOT1=0, and reset device
Traceback (most recent call last):
  File "stm32loader.py", line 552, in <module>
    bootversion = cmd.cmdGet()
  File "stm32loader.py", line 140, in cmdGet
    if self.cmdGeneric(0x00):
  File "stm32loader.py", line 137, in cmdGeneric
    return self._wait_for_ack(hex(cmd))
  File "stm32loader.py", line 88, in _wait_for_ack
    raise CmdException("No response to %s" % info)
__main__.CmdException: No response to 0x0

A: Here are a few tips:

*

*Connect serial cable before resetting / powering up the board. Otherwise some transients can mess the serial bootloader up.

*Make sure you are using a TTL level USB-to-serial converter instead of a RS-232 cable. RS-232 has inverted level, and worse still, its -15V to 15V voltage range can burn your STM32.

*Make sure RX and TX are connected correctly.

*Try using stm32flash instead.

*Most STM32's serial bootloader does not support baud rate higher than 115200 as I remember. The bootloader can detect baud rate automatically, the one I usually use is 57600.

A: Some of these chips are being shipped with locked bootloaders. You will need to use STM32 Flash loader demonstrator to remove the protection. Windows only unfortunately but once it is unlocked you can use any machine.


text:
Q: windows bat file using start cmd /k with doskey not work I tried to use start cmd with custom doskey file, but failed.
1.doskey
ls=dir /b $1

start "title" cmd.exe /k doskey /macrofile=1.doskey && ls .
Prompted
ls command is not recognized

A: Two issues:
Issue 1
The && will be interpreted by the shell you run this command from and not the shell in the window, so you are running doskey /macrofile=1.doskey in the new window but ls . in the old one.
The solution is to surround the whole command that should be passed to the new window with doublequotes:
start "title" cmd.exe /k "doskey /macrofile=1.doskey && ls ."

Alternatively you could escape both & characters with ^:
start "title" cmd.exe /k doskey /macrofile=1.doskey ^&^& ls .

...however, this will just uncover issue 2, so keep reading.
Issue 2
As you can deduce (sort of) from the DOSKEY docs, you cannot run a macro from a command that you didn't type in manually (after all, DOSKEY is a tool to process interactive input from a user):

To run a macro, type the macro name at the command prompt, starting at the first position. If the macro was defined with $* or any of the batch parameters $1 through $9, use a space to separate the parameters. You cannot run a doskey macro from a batch program.

(Emphasis mine.)
This talks only about batch files, but it applies to any non-interactive way of entering a command - and passing it to cmd /c or cmd /k is one of them (since you aren't typing the command into the new shell, it's run automatically on startup of the shell instead).
Based on how you described your intent ("use start with custom doskey file"), I assume you added the ls . only to test whether it works. In that case, just remove the whole && ls . part and try ls . manually in the new window, and you'll see that it does work!
In case that's not what you wanted, and you actually intended to run DOSKEY macros from that "cmd /k" command line or a batch file, you are out of luck - instead, you could call a batch file that contains functions and use that, or create custom batch files instead of macros.


text:
Q: Crystal Reports with SQLite database Can we work with Crystal Reports in Visual Studio with a SQLite database?

A: Well, if the question is just that, yes, it can work.
EDIT:

*

*Introduction to Crystal Reports in .NET

*System.Data.SQLite, ADO.NET provider for SQLite


text:
Q: Ajax call with progress data (non-upload) I am currently working on a project that I would like to send an ajax request that will initiate a database synchronization between a local database and a remote database using PHP.
I was wondering if it is possible to send progress data from the PHP ajax handling script back to the jQuery ajax call to display the synchronization progress to the user.
Here is an example of what I mean:
jQuery.ajax({
    url: ajaxUrl,
    type: post,
    dataType: 'json'
}).done(function(data) {
    // Check for returned progress data
    if (data.complete) {
        // Display "Synchronization complete!" or something similair
    } else {
        // Display progress data such as "Inventory data synchronized..."
    }
});

I'm not even sure if something like this is possible, but I was hoping I could get some help on it.  I did look into xhr briefly, but I was unsure if I could accomplish my goals with it or not.
I know that I could accomplish this with cascading ajax calls, but I would prefer to not need to do it that way as it would be quite a bit more inefficient.

A: You would have to open a socket connection. I'm guessing if you are asking this question you don't know what a socket connection is. But you can google a good socket tutorial for PHP and I'm sure you will come up with something.


text:
Q: Combine IIFEs in grunt/uglify Is there a way in uglify (or another node package if needed) to combine all of my IIFE into a single IIFE?  In my project, we write each file inside of an IIFE and pass the single global into the IIFE as a parameter.
Using the most condensed JS, an IIFE with a "use strict" directive is 31 bytes (a is our single global.)
(function(a){"use strict";/* code here */}());

That means if we have 20 source files, we end up with 600 bytes of wasted space.  If we have 100 source files, it's 3100 bytes wasted... etc.

A:
Is there a way in uglify (or another node package if needed) to
  combine all of my IIFE into a single IIFE?

Yes, but with limitations. You could use grunt-contrib-uglify which comes with two possibilites:

*

*Using wrap

*Using banner and footer (gives you slightly more control of the output)
Configuration in your Gruntfile.js would be:
wrap
uglify: {
    options: {
        wrap: 'foo',
    },
    files: {
       'path/to/output.min.js': ['path/to/input/*.js']
    }
}

The value of wrap would be your export or global variable you want to pass. This should work with multiple IFEE's as your global variable will just be passed to the other IFEE's.
banner and footer
uglify: {
    options: {
        banner: '(function (a) {',
        footer: '})(foo);'
    },
    files: {
       'path/to/output.min.js': ['path/to/input/*.js']
    }
}

Your output will be wrapped within (function (a) { /* your other scripts */ })(foo);. Downside is, at least for my understanding, that you can't write your code in an IIFE as the IIFE will be generated in your output.

Read more in the official documentation.


text:
Q: which signal does gdb send when attaching to a process? Which signal does gdb send when attaching to a process? Does this work the same for different UNIXes. E.g. Linux and Mac OS X?
So far I only found out, that SIGTRAP is used to implement breakpoints. Is it used for attaching aswell?

A: AFAIK it does not need any signals to attach. It just suspends the "inferior" by calling ptrace. It also reads debugged process memory and registers using this calls and it can request instruction single stepping (provided it's implemented on that port of linux), etc.
Software breakpoints are implemented by placing at right location instruction that triggers "trap" or something similar when reached, but debugged process can run full speed until then.
Also (next to reading man ptrace, as already mentioned) see ptrace explanation on wikipedia.


text:
Q: Xamarin forms MVVM Remove the previous VM in my current VM I have a main page : HomeVM.
When the app starts, I use PushModalAsync for RegistrationVM
In my RegistrationVM, I have a button for pushModalAsync -> LoginVM
When the user is connected, I want go back in the VM HomeVM, but impossible, with PopModalAsync, I come back to RegistrationVM.
I would like to close all popmodalasync.
I have tried this
Here in my app.xaml :
var mainPage = (Page)ViewFactory.CreatePage(typeof(HomeVM));
MainPage = new NavigationPage(mainPage)
{
    BarBackgroundColor = (Color)Resources["PrimaryColor"],
    BarTextColor = Color.White,
};
Navigation = MainPage.Navigation;

protected override void OnStart()
{
    var registrationpage = (Page)ViewFactory.CreatePage(typeof(RegistrationVM));
    MainPage.Navigation.PushModalAsync(registrationpage);
}

RegistrationVM :
public RegistrationVM()
{
    Task.Run(async () => await ConnectionAPI());
}

async Task ConnectionAPI()
{
    try
    {
                applicationContext.Device = mydevice;
                await Navigation.PushModalAsync<LoginVM>(async (vm, p) => await vm.InitializeAsync(this));
    }
    catch (Exception e)
    {
        Log.Error(e, "Unhandled exception while loading touch points : {e}", e);
    }
    finally
    {
    }
}

LoginVM :
When the user click on "Login"
PreviousVM = RegistrationVM.
async Task Login()
{
    try
    {
        Log.Information("Logging in");
        applicationContext.User = employe;
        await Navigation.PopModalAsync();
        await Navigation.RemoveAsync(previousVM);
    }
    catch (Exception e)
    {
        Log.Error(e, "Unhandled exception during log in : {e}", e);
    }
    finally
    {
    }
}

I come back to Registration view

A: If you want to just pop all modal windows, you can should be able to keep calling PopModalAsync() until Application.Current.MainPage.Navigation.ModalStack.Count is 0, or you get an ArgumentOutofRangeException.
That said, you might want to consider using a different approach here. Most apps that require a login page don't want to have any other pages loaded while it's displayed. In other words, you don't want the user to be able to back out to your main page unless they are logged in, so you don't want anything else on the stack.
To do this, you can replace the Application.Current.MainPage with your login and/or registration page. When login is complete, you replace it with your app's main navigation page.


text:
Q: Change state in between two animations I am trying to find a way to change text(which is tied to a hook) in between two animations. Essentially I want the sequence of events to go in this order:
fade out -> state change -> fade in
Currently the sequence goes like:
state change -> fade out -> fade in
Another way I was thinking of achieving the same effect would be simply adding a sort of CSS transition time, but I can't find the equivalent for React-Native.
I am quite new to React Native, so any help would be appreciated. Here is my code:
import React, { useState, } from 'react';
import { View, Text, Animated, TouchableOpacity } from 'react-native';

function App() {
  const fadeVal = useState(new Animated.Value(1))[0]

  const texts = ["first", "second", "third", "fourth"]
  const [textID, setTextID] = useState(0)

  const fadeIn =
    Animated.timing(fadeVal, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true
    })

  const fadeOut =
    Animated.timing(fadeVal, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true
    })

  function bothAtOnce() {
      Animated.stagger(500, [fadeOut, fadeIn]).start()
      setTextID(textID + 1)
  }

  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
        <Animated.Text
        style={
          {
            width: 100,
            textAlign: 'center',
            justifyContent: 'center',
            opacity: fadeVal,
            backgroundColor: 'black',
            color: 'white'
          }
        }
        >
          {texts[textID]}
        </Animated.Text>
        <TouchableOpacity onPress={bothAtOnce}>
          <Text>Next</Text>
        </TouchableOpacity>
    </View>
  )
}

export default App;

A: The start function that animations have accepts a callback. So you could totally go
  function bothAtOnce() {
    fadeOut.start(() => {
      setTextID(textID + 1);
      // it happens kinda of instantly so
      // you might want to add a delay?
      fadeIn.start();
    });
  }

link


text:
Q: Hotspot and Internet access together — why not? If I try to set up a hotspot in GNOME, I get the following message:

If you have a connection to the Internet other than wireless, you can use it to share your internet connection with others.
Switching on the wireless hotspot will disconnect you from <network name>.
It is not possible to access the internet through your wireless while the hotspot is active.

What are the technical reasons why I can't set up an Hotspot and be connected to the Internet at the same time?

A: *

*Uses the same antenna.

*Currently most software doesn't allow to be in client and AP mode at the same time.

*Wireless is a half-duplex protocol, except for some really new bleeding edge stuff. The radio can only transmit or receive at one time, it cannot do both at the same time.

Going with point 3, if any software was developed to allow both client and AP mode simultaneously the radio would first need to communicate like a client and then pass the data along as an AP. The latency would be undesirable, and the most likely cause that no one has made software to run both client and AP mode at the same time.

A: it is very possible to use hotspot and browse the internet with the same wifi card at the same time (simultaneously).i have been using it for sometime now.ideapad 100s 141br with card intel dualband 3160,ubuntu.
the most simplest way i found was to use an app called create_ap in github. it works perfectly.
first you need these installed; util-linux, bash, procps or procps-ng, hostapd, iproute2, iw, iwconfig,haveged, dnsmasq, iptables.
install them with:

sudo apt install hostapd iproute2 iw haveged dnsmasq iptables
  procps bash util-linux

. if they are already installed the terminal would inform you, if not it downloads them automatically.
install the app from terminal:
git clone https://github.com/oblique/create_ap
cd create_ap
sudo make install

after it has installed successfully, i created hotspot first before connecting to internet. You can create a hotspot with :
sudo create_ap wlp2s0 wlp2s0 MyAccessPoint
an open AP , where wlp2s0 is my physical wireless card, MyAccessPoint is my hotspot name. The first wlp2s0 is where you want to supply with internet, and the second wlp2s0 is the card connected to the internet (in this case it is the same card). The command would be running it the terminal so tuck it
into the launcher. You can stop the hotspot from terminal with ctrl+c
there is a readme in the installation dir home/create_ap check to out to find out the various hotspots you can create or simply type create_ap in terminal for help.
regards.
source https://github.com/oblique/create_ap


text:
Q: Multiply NSDecimalNumber with NSDecimalNumber return 0 I know this kind of question shouldn't be asked. But, I stuck here for days without any clue. So, I really need help.
I have a core data object, let's say, products.
// Product
NSDecimalNumber *quantity
NSDecimalNumber *price
What I'm trying to do is summarize the price and set it to a label. I search and found some topic here said that NSDecimalNumber can't do standard match operation as it's an object that wrap the actual value. It has to be done through decimalNumberByAdding and decimalNumberByMultiplyingBy. So, I wrote the following code,
NSDecimalNumber *totalPrice = [[NSDecimalNumber alloc] initWithDouble:0.0];
[self.productArray enumerateObjectsUsingBlock:^(Product *product, NSUInteger idx, BOOL *stop) {
    [totalPrice decimalNumberByAdding:[product.price decimalNumberByMultiplyingBy:product.quantity]];
    NSLog(@"%@", totalPrice);
    NSLog(@"%@", totalPrice.doubleValue);
    NSLog(@"%@", totalPrice.decimalValue);
}];

None of those NSLog were showing correct result. They were showing neither 0 or NULL
But, if I NSLog the following code, the correct result can be shown.
[product.price decimalNumberByMultiplyingBy:product.quantity]

Can you help me point out what do I miss here?

A: You are not assigning the return value.
[totalPrice decimalNumberByAdding:[product.price decimalNumberByMultiplyingBy:product.quantity]];

should be:
totalPrice = [totalPrice decimalNumberByAdding:[product.price decimalNumberByMultiplyingBy:product.quantity]];

Since decimalNumberByAdding returns a value, does not update the variable automatically. Because of that, totalPrice is always 0, that's the value you assigned on init.


text:
Q: How to post to twitter with PHP? Hi can anyone help me, I want to be able to post tweets from a PHP script using the twitter API but all the resources i have found and tried so far are old and dont work anymore. anyone have any instructions and/or scripts?
thanks

A: Twitter disabled their HTTP Basic Authentication API some time ago.  You will need to look into OAUTH for PHP which is a token based authentication protocol.  You can find information on this from the OAUTH and Twitter sites as well as any number of tutorials out there.

A: You can use this OAuth library from Abraham Williams. And a nice tutorial is available here

A: Recently, I develop an application to recover the tweets and I found more useful to use the twitter search APIs through AJAX (JSONP for requests out of the domain).
Through the twitter search APIs you can query the twitter database with the same words you use on the twitter web pages and collect the results that can be viewed how do you like.
However, if you prefer the php scripts I suggest you to use the twitter libraries.


text:
Q: Как преобразовать JSON массив в JSON строку Есть JSON массив в таком виде.
[{"id":"1","name":"Name 1"},{"id":"2","name":"Name 2"}]

Раньше эти данные были на отдельной страничке и я получал данные таким способом
$.getJSON("searchshop.php", function(json){
    for (i = 0; i < json.length; i++) {
       alert(json[i].id);
    }
});

Все работало хорошо, но сделал передачу не в файл а напрямую в обработчик то ничего не работает.
пробовал сделать так
respone = '<?php echo $json; ?>';
var obj = jQuery.parseJSON(respone);

Выдает ошибку
VM11773:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 0

Как мне преобразовать $json  в объект javascript ? что бы с ним можно было работать как с массивом.
Подозреваю что причина в том что что бы сработала parseJSON нужна строка json а не объект, но как преобразовать объект в строку не знаю.

A:

response = '<?php echo $json; ?>';
console.log("Type 'response'", typeof response);

try {
  console.log("Length of response", response.length);
} catch(err) {
  console.log("Error", err)
}

Не могли бы вы запустить данный код и показать логи?

A: Попробуйте с использованием этого:
JSON.stringify();

A: Вам необходимо понять что вам приходит в respone, текст или массив. Если там массив, то ничего преобразовывать не надо, а если текст то используйте  JSON.parse();

//Приходит массив
let resp = [{"id":"1","name":"Name 1"},{"id":"2","name":"Name 2"}];

for (i = 0; i < resp.length; i++) {
  console.log(resp[i])
}

//Приходит текст
let respText =  '[{"id":"1","name":"Name 1"},{"id":"2","name":"Name 2"}]'

let respJson = JSON.parse(respText);
for (i = 0; i < respJson.length; i++) {
  console.log(respJson[i])
}


text:
Q: Error when Connection remote mysql database using jpa in Springboot spring boot 1 5 10 RELEASE I'm getting the following error when making a connection to remote mysql database using jpa in Springboot spring boot 1 5 10 RELEASE.
Why am I getting this error?
Parameter 0 of constructor in org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration required a bean of type 'javax.sql.DataSource' that could not be found.
    - Bean method 'dataSource' not loaded because @ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'
    - Bean method 'dataSource' not loaded because @ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'

Action:
Consider revisiting the conditions above or defining a bean of type 'javax.sql.DataSource' in your configuration.


text:
Q: Metricbeat - pod specific endpoints I have X pods configured to work on Y nodes. There are Z (where Z < X) pods that exposes metric via endpoints (based on prometheus text format). So basically some of metricbeat instances must be aware that there are additional endpoints on the machine they are working on and the should constantly retrieve those metrics from these endpoints.
What is the correct approach to collect metrics from those endpoints? I already have configured metricbeat to collect some basic matrics like processor, memory etc. but I also need metric from those endpoints.
Something that might be implicit from my description and I would like to make it clear: some pods might expose those metric endpoints on different ports.
I can think of two approaches:

*

*Add single instance of metricbeat that runs somewhere in the cluster and requests all endpoints

*Configure metricbeat to be aware of for who is working for and be aware that have additional work to do (is it possible?)

how should I do that?


text:
Q: Collections in java - how to choose the appropriate one I'm learning about collections and trying to ascertain the best one to use for my practice exercise.....I've done a lot of reading on them, but still can't find the best approach.....this may sound a bit woolly but any guidance at all would be appreciated....
I need to associate a list of Travellers, with a list of Boarding Passes. Both classes contain a mutable boolean field that will be modified during my programme, else all other fields are immutable. That boolean field must exist. I'll need to create a collection of 10 travellers, and then when all criteria has been met, instantiate a boarding pass, and associate it with them.
There won't be any duplicates of either due to each object having a unique reference variable associated with them, created through an object factory.
From doing some reading I understand that Sets must contain immutable objects, and don't allow duplicate elements, whereas Lists are the opposite.
Because I need to associate them with each other, I was thinking a Map, but I now know that the keys are stored in a set, which would be problematic due to the aforementioned reasons....
Could I override the hashcode() method so that it doesn't taken into consideration the boolean field and therefore as long as all of my other fields are immutable it should be fine? Or is that bad practice?
I also thought about creating a list of Travellers, and then trying to associate a Boarding Pass another way, but couldn't think of how that could be achieved....
Please don't give me any code - just some sort of a steer in the right direction would be really helpful.

A: If you are looking for a best practice, you need to think what you are planning to do with the data now and in the (near) future. When you know
what this is, you need to check which of the methods (list, set and map) works best for you. If you want to compare the three, have a look here

A: You've been mislead about the mutability requirements of set members and map keys.
When you do a lookup in a HashMap, you do it based on the key's hashCode. If you have mutable objects as keys, and mutating the object modifies the hashCode value, then this is a problem.
If a key was inserted into the table when it had a hashCode of 123, but later it's modified to have a hashCode of 345, you won't be able to find it again later since it's stored in the 123 bucket.
If the mutable boolean field does not influence your hashCode values (e.g., you didn't override hashCode or equals on your key class), then there's no issue.
That said, since you say you'll only have one unique instance of each passenger, Boris's suggestion in the comments about using an IdentityHashMap is probably the way to go. The IdentityHashMap gives the same behavior as a HashMap whose keys all use the default (identity-based) implementations for hashCode and equals. This way you'll get the expected behavior whether or not you've overridden equals and/or hashCode for other purposes.
(Note that you need to take equality into account as well as the hashCode.)


text:
Q: I can't to get Label and Buttons components in created window I tryed to learn about GUI and tryed to create the window with two buttons and jne Label on the screen. But I don't understand why I can't see these elements simultaneously. When I comment out lines for buttons I can see the Label element.
Here is my code:
import java.awt.*;
import javax.swing.*;

public class MyWin {

    public static void main(String[] args) {

        JFrame w = new JFrame("My Window");
        w.setSize(1000,800);
        w.setVisible(true);

        JButton b = new JButton("My button");
        b.setVisible(true);
        b.setSize(150, 100);
        b.setLocation(500, 20);

        JButton b2 = new JButton("Second button");
        b2.setVisible(true);
        b2.setSize(150,100);
        b2.setLocation(500, 600);

        JLabel l = new JLabel("My label");
        l.setVisible(true);

        w.getContentPane().add(b);
        w.getContentPane().add(b2);
        w.getContentPane().add(l);
    }
}

A: The default layout for the JFrame is BorderLayout and when you add your JLabel through single parameter add method you add it with a BorderLayour.CENTER constraint as a default, this causes to fill all the available space. So you might want to use layout manager suitable for your needs, then the components won't overlay themselves.
Visual Guide to Layour Managers

A: First of all, JFrame uses BorderLayout as a default layout and just adding the components (w.getContentPane().add(b)) sets them in BorderLayout.CENTER; where they occupy the whole JFrame to fill the empty space. Thus, is recommended to add components in a JPanel. So, you should create first a JPanel, add the components to the JPanel and finally add it to the JFrame.
The setSize(...); statement is not applied due to the default layout (FlowLayout) in JPanels and also is discouraged. (Because it won't work properly in different computers with different screen resolutions)
If you want to change the size of the components you should change the default layout and use instead a customLayout, borderLayout, gridLayout...
If you want to understand deeply how layouts work and all the available layouts in Java check this


text:
Q: Persisting sub-classes with DynamoDB in .NET I have a class hierarchy that I would like to persist with DynamoDB's .NET object persistence model (V2 entry conversion). I would like to persist derived classes to the same table as the base class, and then be able to query all entries in that table and have them deserialize to the appropriate derived types.
In most ORMs, you would be able to specify a type discriminator column that it would use to decide what subtype to deserialize into.
Code example:
public abstract class Animal
{
    [DynamoDBHashKey]
    public string Name { get; set; }
}

[DynamoDBTable("Animal")]
public sealed class Dog : Animal
{
    public double Loyalty { get; set; }
}

[DynamoDBTable("Animal")]
public sealed class Cat : Animal
{
    public int MiceEaten { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var client = new AmazonDynamoDBClient(RegionEndpoint.EUWest1);
        using (var context = new DynamoDBContext(client, new DynamoDBContextConfig {Conversion = DynamoDBEntryConversion.V2}))
        {
            context.Save(new Dog { Name = "Rover", Loyalty = 0.8 });
            context.Save(new Cat { Name = "Felix", MiceEaten = 14 });

            var doggie = context.Load<Animal>("Rover");
            var pussy = context.Load<Animal>("Felix");

            Console.WriteLine(doggie.GetType().Name); // should output Dog
            Console.WriteLine(pussy.GetType().Name); // should output Cat
        }
    }
}

Expected output would be:
Dog
Cat

But actually crashes with the following exception:
Unhandled Exception: System.InvalidOperationException:
Type ConsoleApplication1.Animal is unsupported, it cannot be instantiated

Is there a nice way of persisting this class hierarchy? I am able to make changes to the class model if required, I just want it to feel like idiomatic C#.
I have also tried various combinations of where I put the DynamoDBTable attribute, including just on Animal and on all three classes. If I remove the abstract from Animal, it doesn't throw an exception, but instead it outputs Animal Animal and therefore doesn't deserialize the properties specific to the derived classes.

A: I'm running into the same problem right now.  As far as I can tell, DynamoDB doesn't provide first-class support for mapping row data from a single table to different C# classes.
There's an issue posted in the GitHub aws-sdk-net repository (#245) that shows how one might use a type discriminator approach to deserializing table rows to different C# classes.  That's what I'm going to start investigating... if it works out, I'll update my answer here.
UPDATE #1: Unfortunately, it seems the only way to deserialize DynamoDB data to the appropriate subclass type is type mapping -- that is, build a set of type checks that cast your DynamoDB to the matching concrete type.


text:
Q: Point R is inside the square forming an equilateral triangle ORL having one side equal in length to the side of the square. Find the Angle NRA. The length of the diagonal of a square NOLA is 9√ inches. Point R is inside the square forming an equilateral triangle ORL having one side equal in length to the side of the square. Find the measure of the angle NRA
Can someone tell me the value of angle NRA? I tried divided 180 degrees by 3 since its an equilateral triangle but 60 degrees does not seem to conform with the properties of square since its angle needs to be 45 degrees when you bisect it.


text:
Q: How to implement a click handler with CardService? I need to click a select/deselect all checkboxes using the CardService.
How do I implement an onclick handler function?
I have tried with:
function handlerOfButtonClick(e) {
    var selectAll = CardService.newSelectionInput()
        .setType(CardService.SelectionInputType.CHECK_BOX)
        .setFieldName("select_all")
        .addItem("Select all", "selectAll", false).setOnChangeAction(CardService.newAction()
            .setFunctionName("handleSelectAll"));

    var checkboxGroup = CardService.newSelectionInput()
        .setType(CardService.SelectionInputType.CHECK_BOX)
        .setTitle("A group of checkboxes. Multiple selections are allowed.")
        .setFieldName("checkbox_field")
        .addItem("checkbox one title", "checkbox_one_value", false)
        .addItem("checkbox two title", "checkbox_two_value", true)
        .addItem("checkbox three title", "checkbox_three_value", true);

    var section = CardService.newCardSection().addWidget(selectAll).addWidget(checkboxGroup)
    var card = CardService.newCardBuilder().addSection(section);
    var navigation = CardService.newNavigation().pushCard(card.build());
    var actionResponse = CardService.newActionResponseBuilder().setNavigation(navigation);
    return actionResponse.build();
}

function handleSelectAll(e) {
    //?????
}

A: You can use the method updateCard(card)
This allows you to replace the card you built with a version where all check boxes are checked (that is se to true).
Sample:
function handleSelectAll(e) {

    var checkboxGroup = CardService.newSelectionInput()
        .setType(CardService.SelectionInputType.CHECK_BOX)
        .setTitle("A group of checkboxes. Multiple selections are allowed.")
        .setFieldName("checkbox_field")
        .addItem("checkbox one title", "checkbox_one_value", true)
        .addItem("checkbox two title", "checkbox_two_value", true)
        .addItem("checkbox three title", "checkbox_three_value", true);

    var section = CardService.newCardSection().addWidget(selectAll).addWidget(checkboxGroup)
    var card = CardService.newCardBuilder().addSection(section);

    return CardService.newNavigation().updateCard(card.build());
}