text:
Q: How to dynamically add links to a d3 topology? I took the sticky force layout example and tried adding an extra link and updating the layout using enter(), but then all the links disappeared and FireBug shows no error either.
Shouldn't these lines have added a link?
graph.links.push({"source": 0, "target": 11});
link = link.data(graph.links).enter().append("line").attr("class", function(d,i) {console.log(i);return "link";});
Also, the console.log(i) outputs 18 instead of 19. It's like as though it never took into account the increase in size of the graph array.
I checked this example, but even here it seems like using the data() and enter() functions should have been enough.
The code:
<!DOCTYPE html>
<meta charset="utf-8">
<style>

.link {
  stroke: #000;
  stroke-width: 1.5px;
}

.node {
  cursor: move;
  fill: #ccc;
  stroke: #000;
  stroke-width: 1.5px;
}

.node.fixed {
  fill: #f00;
}

</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var graph =
{
  "nodes": [
    {"x": 469, "y": 410},
    {"x": 493, "y": 364},
    {"x": 442, "y": 365},
    {"x": 467, "y": 314},
    {"x": 477, "y": 248},
    {"x": 425, "y": 207},
    {"x": 402, "y": 155},
    {"x": 369, "y": 196},
    {"x": 350, "y": 148},
    {"x": 539, "y": 222},
    {"x": 594, "y": 235},
    {"x": 582, "y": 185},
    {"x": 633, "y": 200}
  ],
  "links": [
    {"source":  0, "target":  1},
    {"source":  1, "target":  2},
    {"source":  2, "target":  0},
    {"source":  1, "target":  3},
    {"source":  3, "target":  2},
    {"source":  3, "target":  4},
    {"source":  4, "target":  5},
    {"source":  5, "target":  6},
    {"source":  5, "target":  7},
    {"source":  6, "target":  7},
    {"source":  6, "target":  8},
    {"source":  7, "target":  8},
    {"source":  9, "target":  4},
    {"source":  9, "target": 11},
    {"source":  9, "target": 10},
    {"source": 10, "target": 11},
    {"source": 11, "target": 12},
    {"source": 12, "target": 10}
  ]
};

var width = 960,
    height = 500;

var force = d3.layout.force()
    .size([width, height])
    .charge(-400)
    .linkDistance(40)
    .on("tick", tick);

var drag = force.drag()
    .on("dragstart", dragstart);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var link = svg.selectAll(".link"),
    node = svg.selectAll(".node");

//d3.json("graph.json", function(error, graph) {

  force.nodes(graph.nodes).links(graph.links).start();
  link = link.data(graph.links).enter().append("line").attr("class", "link");

  node = node.data(graph.nodes)
    .enter().append("circle")
      .attr("class", "node")
      .attr("r", 12)
      .on("dblclick", dblclick)
      .call(drag);
//});

console.log(graph.links.length);
graph.links.push({"source": 0, "target": 11});
console.log(graph.links.length);
link = link.data(graph.links).enter().append("line").attr("class", "link");

function tick() {
  link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

  node.attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });
}

function dblclick(d) {
  d3.select(this).classed("fixed", d.fixed = false);
}

function dragstart(d) {
  d3.select(this).classed("fixed", d.fixed = true);
}

</script>

A: The main problem is
link = link.data(graph.links).enter().append("line").attr("class", "link");

After this, link will contain only the links that were just added to the visualisation as you're using .enter(). This in turn means that only those will be updated during the tick event of the force layout, as you're using the same link variable there. It's the same problem for node.
To fix, set the selection variables to contain all relevant elements after adding the new elements.
link = svg.selectAll(".link");

Complete demo here.


text:
Q: I cannot determine what video driver I am using I have an AMD RX 5700 XT Graphics card and I don't know what driver is being used. When I looked online, people said to do lshw -c video and that the driver is supposed to be on the configuration line.
But sudo lshw -c video outputs this:
  *-display UNCLAIMED
       description: VGA compatible controller
       product: Navi 10
       vendor: Advanced Micro Devices, Inc. [AMD/ATI]
       physical id: 0
       bus info: pci@0000:0b:00.0
       version: c1
       width: 64 bits
       clock: 33MHz
       capabilities: pm pciexpress msi vga_controller cap_list
       configuration: latency=0
       resources: memory:e0000000-efffffff memory:f0000000-f01fffff ioport:f000(size=256) memory:fcd00000-fcd7ffff memory:c0000-dffff

But it is not there. Does this mean that there is no driver installed?

A: It looks like there's no driver used. The *-display section is marked as UNCLAIMED, in short meaning "I couldn't find a fitting driver for this". There can be multiple *-display sections, for example if the machine has multiple graphic cards. Maybe you're looking at the wrong one?

redpajama_set_name: RedPajamaStackExchange


text:
Q: List items in array of objects If I have an array like this:
var arrayData = [
    {"id" : 1, "title" : "a title", "info" : "blah blah"},
    {"id" : 2, "title" : "another title", "info" : "lalala"},
    ...
];

How would I loop through the array and find the value of title?
for (var i=0; i < entries.length; i++) {
    // console.log('title of this post is:')
}

A: for (var i=0; i < entries.length; i++) {
    console.log(entries[i].title);
}

A: If you can use ES5, you can get an array of titles like this:
arrayData.map( function(record) { return record.title; });

A: Each object in the array can be accessed by its index e.g. arrayData[0], and the properties of that object can be accessed in the regular fashion e.g arrayData[0].title, so your loop just needs to use the arrayName and i:
var arrayData = [
    {"id" : 1, "title" : "a title", "info" : "blah blah"},
    {"id" : 2, "title" : "another title", "info" : "lalala"}
];

for (var i=0; i < arrayData.length; i++) {
    console.log('title of this post is: ' + arrayData[i].title)
}

Output:

title of this post is: a title
title of this post is: another title


text:
Q: Set div innerhtml to source that contains table I thought what I was trying to do is quite simple, but apparently nothing related to IE is ever simple.
I'm using this with Javascript and ajax -
document.getElementById("calender").innerText=mypostrequest.responseText

It works fine in Firefox and IE7, but not IE8. I suspect it's because the text contains a table, since I have tested it with other text. I can't replace the table. Is there any way to get around this?

A: Try
document.getElementById("calender").innerHTML=mypostrequest.responseText

A: Switched to jQuery
( $('#calender').html(mypostrequest.responseText) )

It works now.


text:
Q: Calling WCF service method from browser? Since i am new to WCF and Having configured a WCF service endpoint in IIS at Virtual Directory Api ( url goes like
http://localhost/api/taskapi.svc)

i was looking for ways to make request through web browser something like
http://localhost/api/taskapi.svc/GetCompleted

would respond with returnd data .I know this requires the binding of web service with the webHttpBinding  but i don't know how to do it any help would be great ?

A: Use WCFSVGHoST application to test WCF applications. Application enables you to key-in parameters value and execute method of your interest.
Link for the same:
http://msdn.microsoft.com/en-us/library/bb552363.aspx


text:
Q: Struggling with JQuery .each() Function Hopefully this will be a straightforward solution but I can't seem to solve it myself.
The background is I am trying to create a web app that puts all your facebook friends into a jQuery UI auto-complete and posts to their wall when you are finished selecting friends and click a link/button etc.
I had this working fine for one friend but the requirements have changed (as ever) to make this work for multiple friends.
So far I have everything working with multiple friends except when it comes to actually posting to the walls of the user's friends.
Code
I will try to keep this to the code relevant to the question which I believe is as follows:
I have a hidden input which I manage to populate with the ids:
<input id="fbid" type="hidden" value="12345, 567890, ">

I then have a jQuery function which runs when the link is clicked to post to the walls of the friends.


text:
Q: About RadioButton CheckedChanged event Hi there im using a single TextBox for querying differents types of chossings, for example when i select the first RadioButton (Last Name) I search by Client last name, when i choose second RadioButton (Doc. Code) I search by code and so on, please how can i manage or handle exceptions when for example if user choose "Search by Date" and send a string type?
Im using C# 3.5 - Asp.net
I would like to make it with regular expressions and add that in the RadioButton event, so when users changes radio, he could type just some characters in optionA, other more in Option B, and just dates in OptionC ... (regular expression)
Thanks in advances

A: if you are using the asp web control radiobuttonlist then you can make lots of changes when their is a postback. you can set the attribute to SelectIndexChanged,so whenever their is a change it cause a postback and then you can do whatever from their(verifications).
 ex:
   <asp:radioButtonList
     id="radio1" runat="server"
     autoPostBack="true"
     cellSpacing="20"
     repeatColumns="3"
     repeatDirection="horizontal"
     RepeatLayout="table"
     textAlign="right"
     OnSelectedIndexChanged="radio_SelectedIndexChanged">
     <asp:ListItem text="10pt" value="itsMe"/>
     <asp:ListItem text="14pt" value="itsYou"/>
     <asp:ListItem text="16pt" value="Neither"/>
  </asp:radioButtonList>

on the server you should have
protected void radio_SelectedIndexChanged(object sender, EventArgs e)
{
 //do whatever you want by calling the name of the radio id
 //example

  if(radio1.SelectedItem.Value=="(whatever you want to test)"

}


text:
Q: Increasing number of brokers in kafka using KAFKA_ADVERTISED_HOST_NAME I'm new to Kafka and I'm trying to run a Kafka service on my local machine and use it to transfer some data from one .NET project to another.
I'm using docker-compose.yml file to create two docker containers for zookeeper and Kafka from wurstmeister.
In Kafka definition in environment variables there is KAFKA_ADVERTISED_HOST_NAME which I set to 127.0.0.1.
In docker hub of wurstmeister/kafka says I quote
"modify the KAFKA_ADVERTISED_HOST_NAME in docker-compose.yml to match your docker host IP (Note: Do not use localhost or 127.0.0.1 as the host IP if you want to run multiple brokers.)".
When I set my topic to have more than 1 replica and more than 1 partition I get this message
"Error while executing topic command : Replication factor: 2 larger than available brokers: 1.".
What is the right IP address to define in KAFKA_ADVERTISED_HOST_NAME which will allow me to get more than 1 broker?
version: '2'
services:
 zookeeper:
  image: wurstmeister/zookeeper
  ports:
   - "2181:2181"
 kafka:
  image: wurstmeister/kafka
  ports:
   - "9092:9092"
  environment:
   KAFKA_ADVERTISED_HOST_NAME: 127.0.0.1
   KAFKA_CREATE_TOPICS: "simpletalk_topic:2:2"
   KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
  volumes:
   - /var/run/docker.sock:/var/run/docker.sock

A: Note - Running multiple brokers on one machine does not provide true fault tolerance.

use it to transfer some data from one .NET project to another

You only need one broker for this.

First, suggest reading https://github.com/wurstmeister/kafka-docker/wiki/Connectivity
KAFKA_ADVERTISED_HOST_NAME is deprecated. Don't use it.
It has been replaced by KAFKA_ADVERTISED_LISTENERS, which can both contain ${DOCKER_HOST_IP:-127.0.0.1} (or your host IP from ifconfig) since this is the IP your client will use (from the host).
Since brokers are clients of themselves, you also need to advertise the container names. And, if you want to containerize your client, those addresses would also be used by your app.
Beyond Kafka networking configs, KAFKA_BROKER_ID needs to be different between each, and your error is suggesting you need to override all the other replication factor broker configs.
All in all.
version: '3'
services:
 zookeeper:
  image: wurstmeister/zookeeper
 kafka-1:
  image: wurstmeister/kafka
  depends_on: [zookeeper]
  ports:
   - "9092:9092"
  environment:
   KAFKA_BROKER_ID: 1
   KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://${DOCKER_HOST_IP:-127.0.0.1}:9092,PLAINTEXT_INTERNAL://kafka-1:29092
   KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092,PLAINTEXT_INTERNAL://:29092
   KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT_INTERNAL:PLAINTEXT,PLAINTEXT:PLAINTEXT
   KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT_INTERNAL
   KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
   KAFKA_DEFAULT_REPLICATION_FACTOR: 2
   KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 2
   KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 2
 kafka-2:
  image: wurstmeister/kafka
  ports:
   - "9093:9093"
  environment:
   KAFKA_BROKER_ID: 2  # unique
   KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://${DOCKER_HOST_IP:-127.0.0.1}:9093,PLAINTEXT_INTERNAL://kafka-2:29093
   KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9093,PLAINTEXT_INTERNAL://:29093
   KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT_INTERNAL:PLAINTEXT,PLAINTEXT:PLAINTEXT
   KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT_INTERNAL
   KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
   KAFKA_DEFAULT_REPLICATION_FACTOR: 2
   KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 2
   KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 2
   KAFKA_CREATE_TOPICS: "simpletalk_topic:2:2"
  depends_on:  # ensure this joins the other
   - zookeeper
   - kafka-1

I'm trying to run a Kafka service on my local machine

Set bootstrap.servers="localhost:9092,localhost:9093"
Further reading - Connect to Kafka running in Docker
Example usage
Note that topic creation doesn't seem to automatically work. You should ideally be using your application to actually create / check topic existence.
$ kcat -b localhost:9093 -L
Metadata for all topics (from broker -1: localhost:9093/bootstrap):
 2 brokers:
  broker 2 at 127.0.0.1:9093
  broker 1 at 127.0.0.1:9092 (controller)
 0 topics:

producing some data... and consuming it
$ kcat -b localhost:9093 -t test -o earilest
% Auto-selecting Consumer mode (use -P or -C to override)
hello
world
sample
data
of
no
importance

A: it should be ip address of your machine.
Linux: use ifconfig command and your IP will be inet <IP_ADDRESS>
in windows you will get this by using ipconfig


text:
Q: controlled saving in jqgrid cell editing that's about it
Basically what I want to do is control the cell submission with a button or any other control.
Has anyone done this?
Here's some code to help:
$('#users').jqGrid({
      url : base_url + 'administrator/ajaxuser',
      datatype : 'json',
      mtype : 'GET',
      colNames : ['ID', 'E-mail' , 'First Name', 'Last Name','Role' ,'Active', 'Action'],
      colModel : [
          {name: 'id', index: 'id', resizable: false},
          {name: 'email', width: 400, index : 'email', editable:true, editrules : {email:true, required:true, custom:true, custom_func:check_email_exists}},
          {name: 'firstname', index:'firstname'},
          {name:'lastname', index:'lastname'},
          {name:'role', index:'role_id', editable: true, width:180, edittype: 'select', editoptions : {value :'1:administrator;3:special;2:user'}},
          {name:'active', index:'is_active', editable: true, width:180, edittype: 'select', editoptions : {value :'0:Not Active;1:Active'}},
          {name: 'action', index: 'action'}
      ],
      cellEdit : true,
      editurl : base_url + 'administrator/ajaxuseredit',
      cellurl : base_url + 'administrator/ajaxuseredit',
      beforeSaveCell : function(id, cell, value){
          alert(cell);
      },
      pager : '#pager',
      emptyrecords: 'Nothing to display',
      rowNum : 3,
      rowList : [3, 5, 7],
      sortname : 'email',
      viewrecords : true,
      caption : 'Payments Made',
      autowidth: true,
      multiselect : true,
      loadError : function(xhr, st, err){
      }
   }).navGrid('#pager', {edit:false, add:false});

   $('#users').jqGrid('saveCell', 'Row', 'iCol');

A: Use row edit instead of cell edit and look at the "Full control" demo. Then change the row edit config to make only the cell you want editable.


text:
Q: How to create a NetworkPolicy usingt he Fabric8 java client for Kubernetes I am reading the Kubernetes docs here https://kubernetes.io/docs/concepts/services-networking/network-policies/
I would assume there is an equivalent object ofr a NetworkPolicy but I didnt find one in the source code or any examples setting the network policy on groups of pods.
Am I looking at the right place?

A: Here is an example of creating NetworkPolicy using fabric8 kubernetes client.
https://github.com/fabric8io/kubernetes-client/pull/976
To select group of pods you can use PodSelector in NetworkPolicySpec.

A: There's a handler for it in https://github.com/fabric8io/kubernetes-client/blob/master/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/handlers/NetworkPolicyHandler.java, so I guess it's supported. The actual NetworkPolicy class seems to be in a dependency library, kubernetes-model.


text:
Q: Java read line until followstop Actually, I am trying to read file which contain of multiple lines. for this I am using scanner.nextline()
However, I want to read the line until the followstop (dot separator) which usually followed by space or end of line char.
May any body help me in this case ?

A: If you want to search until a period, you can use a Matcher with a Pattern.
//Pattern p = Pattern.compile("[^\\.]*\\.(\\s+)");
Pattern p = Pattern.compile(".*?\\.(\\s+)");  //Anything any amount of times,
                                              //followed by a dot and then some whitespace.

Matcher matcher = p.matcher("firstword. secondword.\n");

while(matcher.find()){
    boolean space = matcher.group(1).charAt(0) == ' ';
    System.out.println(matcher.start() + matcher.group() + "and is space: " + (space ? "TRUE" : "FALSE"));
}

*

*.*? - . will match anything. * matches 0 or more times. ? is the lazy matcher. This matches any number of characters of any type, but it stops before the first period and whitespace (because of the lazy operator).

*\\. - This matches a period. In Java, you have to double escape special characters in regexes.

*(\\s+) - This means match whitespace (\s, which includes new lines) one or more times. It matches one or more whitespace characters. The parentheses "capture" this part of the regex so that every time you get a match on the regex you can just ask it what specific part was matched inside the parentheses. This lets you know if it is a space or a newline.

matcher.group() gets the string that was just matched.
I added in the question mark and commented out the other pattern because it sounded like you could have a period in the middle of some of your data. The question mark does "lazy" matching. By default, matching is greedy and will take the longest matching string. So if there are multiple places in the string with a period followed by a whitespace, it will return all of that as one match. The laziness forces it to stop matching any character (.*) once it reaches the first period and space.

A: Use the read() method and read char by char. If you''re matching the . this is your newline character.
Other solution might be to set the newline character and then use readline(). I did not tried this howeever
or read file in once ans use string.split method

A: FileReader fin = new FileReader("yourfile.txt");
Scanner src = new Scanner(fin);
// Set delimiters to full stop

src.useDelimiter(".");

while (src.hasNext()) {
  // do what you want here
  }

A: Try this,
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null)
        {
            if (line.contains(". ") || line.trim().endsWith("."))
            {
                int length = line.indexOf(". "); // get the index when the line contains dot and space in the middle
                stringBuilder.append(line.trim().endsWith(".") ? line
                        : line.substring(0, length).replace(". ", "." + System.getProperty("line.separator"))); // when the line contains dot at the end or the line may contain the dot with space
                System.out.println("stringBuilder : " + stringBuilder.toString());
                stringBuilder.delete(0, stringBuilder.toString().length());
                if (length != 0)
                {
                    stringBuilder.append(line.substring(length+2, line.length()));
                }
            }
            else
            {
                stringBuilder.append(line.replace(System.getProperty("line.separator"), " "));
            }
        }
        System.out.println("stringBuilder : "+stringBuilder.toString()); // when the last line not end with dot or not contain dot and space


text:
Q: Have an Excel Auto Scroll Macro; is there a way to put a timer on it? So here's what I have for the auto scroll macro:
Sub Macro12()
    Dim lastRow As Long, i As Long
    lastRow = Range("A" & Rows.Count).End(xlUp).Row

    For i = 1 To 23 Step 2
        Cells(i, 1).Select
        ActiveWindow.SmallScroll down:=2
        Application.Wait (Now + TimeValue("0:00:02")) 'Wait two seconds before
        continuing.
        If i = lastRow - 2 Or i = lastRow - 1 Then
            i = 0
            Cells(1, 1).Select
        End If
    Next i
    Debug.Print (i)
End Sub

The issue with this is that it eventually freezes and crashes Excel. What I'm trying to find is a timer code that will tell it to run the macro every 60 - 90 seconds. IE: run Macro12, then don't for 90 seconds, run it again, rinse repeat.
How would I go about this?
EDIT:
This code works:
Sub ReRunMacro()
    Dim xMin As String
    Dim lastRow As Long, i As Long
    lastRow = Range("A" & Rows.Count).End(xlUp).Row

    For i = 1 To 13 Step 2
        Cells(i, 1).Select
        ActiveWindow.SmallScroll down:=2
        Application.Wait (Now + TimeValue("0:00:02"))
        If i = lastRow - 2 Or i = lastRow - 1 Then
            i = 0
            Cells(1, 1).Select
        End If
    Next i
    Debug.Print (i)

    xMin = GetSetting(AppName:="Kutools", Section:="Macro", Key:="min", Default:="")
    If (xMin = "") Or (xMin = "False") Then
        xMin = Application.InputBox(prompt:="Please input the interval time you need to repeat the Macro", Title:="Kutools for Excel", Type:=2)
        SaveSetting "Kutools", "Macro", "min", xMin
    End If

    If (xMin <> "") And (xMin <> False) Then
        Application.OnTime Now() + TimeValue("0:" + xMin + ":0"), "ReRunMacro"
    Else
        Exit Sub
    End If

End Sub

But instead of looping back to the first row (or A1) it just keeps going. Would a simple  Range("A1").Select do the trick to looping back up before running the auto scroll again?


text:
Q: Describe the equivalence relation of the following set with the given partition. Describe the equivalence relation of the following set with the given partition.

$ \Bbb N $ , $ \{\{ 1 \}, \{2,3 \}, \{4,5,6,7\},\{8,9,10,11,12,13,14,15\}....\} . $

What this question has me confused about is what  it wants me to accomplish. Am I supposed to make an equation from this set and analyze if it is reflexive,symmetric, or transitive? Then the part of the partition also throws me off. I know that $p$ is partition of $a$ iff $p$ is a set of subsets of $a$. What I am looking for in this question is a hint in the right direction so that I may produce an answer. I also know that the sets here are restricted so that it must be greater than $0$. Or $\left(x \;\text{ and }\; y \right)$ $\in$ $\Bbb N$. Any hints on how to proceed would be good.
edit
Def: Let  A be nonempty set $. \mathscr P$ is  partition of A iff $. \mathscr P$ is a set of subsets of A such that
$(i) \quad \text{If } X \in \mathscr P, \text{then} \; x\not = \varnothing $
$(ii)\; If  \;x\in \mathscr P \; \text{and} \; y \in \mathscr P, \text{then } x=y  \text{ or } x \cap y = \varnothing$
$(iii) \; \cup_{x \in \mathscr P} X = A$

A: Partition of a set $X$ is a collection of pairwise disjoint subsets of $X$ such that union of all these subsets gives $X$. Any partition naturally sets an equivalence relation and vise versa. The partition in your question can be set by equivalence relation that can be described in many ways. For example like this: we say that $x$ is equivalent to $y$ if $x$ and $y$ have the same number of digits in binary representation. Check, that this an equivalence relation and that classes of equivalence form exactly your partition.


text:
Q: Applying "checked" attribute to radio group using React state. It assigns, but checked input isn't getting styles applied I have a component with four radio inputs in a group. One of them is written as such:

                <input
                  type="radio"
                  id="answer1"
                  name="answer"
                  value="A"
                  checked={this.state.selectedOption === "A"}
                  onChange={this.onValueChange}
                />

The onChange method works to update the state, and I console log the input that is currently checked's value and it shows the value correctly. I have a style applied to radio buttons that are checked, basically changing the border, and it isn't being applied.
The style (just to test) is as such:
input[type="radio"]:checked {
  background-color: rgb(117, 17, 17);
}

Is this because the "checked" attribute is being added dynamically, bypassing CSS's ability to apply styles appropriately?

A: it is not because of dynamic 'checked' attribute. just try to apply the radio button input style using :after pseudo class. It will work.

A: From what I can see your React code seems to be okay... this is a CSS problem with radio button and its problem of accepting a background color change. What can be done with radio buttons is changing the accent-color from what I remember.
This is practically impossible and even if you were able to work something out, chances are it will work on some browsers and not on others.
But still, I think you can try something as simple as the one below.

div {
  margin:10px;
}

.radio-btn:checked + label {
  color: blue;
}

  <input type="radio" class="radio-btn" id="1" value="1" name="radbtn"/> Radio Option 1

<input type="radio" class="radio-btn" id="2" value="2" name="radbtn"/> Radio Option 2

<input type="radio" class="radio-btn" id="3" value="3" name="radbtn"/> Radio Option 3

Take a look and see if it can work for you.

A: Can you try using the computed style property and apply styles accordingly?
For instance

    <input
      className={value ?  'some-checked-class' : ''}
      type="radio"
      id="answer1"
      name="answer"
      value={value}
      checked={this.state.selectedOption === 'A'}
      onChange={this.onValueChange}
    />


text:
Q: How to simplify or rewrite Cosmos Query with LIKE keyword I want to modify a query of something

Select * FROM c WHERE c.id IN (1234, 5678)

to

Select * FROM c WHERE c.id LIKE "1234-%" OR c.id LIKE "5678-%"

the reason is the search keyword is a part of larger concatenated word.I want to simplify/enhance this query .

A: Based on your requirements, you can make use of StartsWith.
Something like:
Select * FROM c WHERE STARTSWITH(c.id, "1234-") or STARTSWITH(c.id, "5678-")

If you want to do a search like %1234-%, then you may want to consider using Contains.
Something like:
Select * FROM c WHERE Contains(c.id, "1234-") or Contains(c.id, "5678-")

A: N explicit ids
Assuming you have a fixed set of explicitly known ids to look for then I wouldn't complicate the query and just pass in the array. It's efficient and most maintainable:
select * from c where ARRAY_CONTAINS(@Ids, c.id)

This will use index and would imho be the preferred option to use. Passing in 100 items is ok, though I believe there is a limit somewhere..
N explicit prefixes
When you don't have a full list known and have to rely on prefixes then you can use the solution from @GauravMantri or your own like-syntax.:
Select * FROM c
WHERE STARTSWITH(c.id, "1234-") or STARTSWITH(c.id, "5678-")

It seems to use index regardless or having the OR clause, the downside is that you'd have to know the number of prefixes to search at compile-time. You could also support any number of prefixes by building a dynamic query in client runtime. Which is slightly dirty, but it works.
Any number of prefixes + don't repeat logic
You don't have to repeat the StartsWith logic nor be limited in how many prefixes to pass in by utilizing joins:
SELECT * FROM c
JOIN prefix in (select value ['1234-', '3456-', '5678-'])
where Startswith( c.id, prefix)

You could also pass in the prefixes by variable and have a compile-time fixed query.
NB! This trick will lose indexing by starts_with field. Usable only when other predicates or top-clause would limit data enough, or your RU will hit the roof.
Unify using Regex
You can also merge the condition into single regex condition. It may be suitable in some cases where you could unify conditions by regex classes, ex \d etc or combinations a la ^(1234|3456)-.
On average case though, that's more of a hassle since in a dynamic case you'd have to build the regex on the fly + I don't think you'd get any indexing..
See: RegexMatch


text:
Q: android studio library of ftp fail to import After i put commons-net3.3 into libs, but i still cannot import
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

is there any step i have missed?

A: Just add into gradle
 dependencies {
    implementation 'org.kie.modules:org-apache-commons-net:6.5.0.Final'
}

A: i solved in this way:
copy commons-net-3.3.jar in libs folder of you app, after
Open File->ProjectStructure->Dependencies, on bottom plus button add "File dependency" and select the library.
Now you should be able to import library class in your activity.java properly


text:
Q: Can NDK include a .lib file? I want to use a C++ library (prebuilt 3rd party) that is distributed as a .lib library object file?  Can this be done.  I see provisions for including .a files, but what i've got is a .lib file.

A: If it is build for ARM you can include it, if not you are out of luck. A .lib file is usually for Windows, so probably the latter. You need to either get the source or get them to build it  with the NDK and send you the object file.


text:
Q: I need a confirm button I am working on a MVC asp.net project and I have a created a button that when click, I need a confirm box to pop up and say "Yes" and "No" and possibly cancel.
My code is below
if (Model.AStatusId == AssetManager.Utility.AMConstants.AssetStatus_Deployed)
{

        <input type="submit" class="btn btn-success" value="Check In"
               onclick="return ValidateCheckInAsset();" />

}

At the moment is displaying an alert label, which I am using for a different button so I know this isn't my solution but I am having problems creating the actual confirm query.
Any help would be very much appreciated.

A: Ok. First of all due to the fact that i can see you are using jQuery i would advise to stop using onclick event on the HTML element.You can search and find out that is depreciated. You can add a different class to the input element in order not to interfere with possible future buttons with the same bootstrap classes.
So your HTML will be

    <input type="submit" class="btn btn-success confirmationBtn" value="Check In" />

And your event listener using the window confirm method
 $(".confirmationBtn").click(function() {
   if (confirm("Are you sure ??")) {

   } else {

  }
 });


text:
Q: Removed BIND9 from Debian Wheezy, Server IP still points to the Domain? I have a Debian Wheezy Server that I installed BIND9 on it. I configured it to work with example.com, but now I wanted to change that to a differnet domain, myOtherDomain.com. I went through the zone file creation and removed all records that I found of example.com. But it still pointed to the same IP. So I went and removed the pacakge of BIND9 by apt-get remove bind9 and apt-get remove --purge bind9 but the IP still points to the domain. What am I missing? How can I change this?

A: It sounds like you still have a PTR record somewhere in DNS (the bind package != DNS) based on

but the IP still points to the domain

There's not enough information in your post to be much more helpful than that. If you want to give actual details, there may be more that we can answer.


text:
Q: Проблема termcolor colored python3 в консоли Я написал такой код на Python  3.7.7

from termcolor import colored

print(colored("lalalala_gagagag", "cyan"))

print(colored("http://google.com", "cyan"))

При запуске её через PyCharm он выдаёт:

(прошу прощения за то, что скрин, при копировании не сохраняется цвет)
Но при запуске через консоль:

[36mlalalala_gagagag[0m
[36mhttp://google.com[0m

colorama тоже не работает.
Я скомпилировал в ехе при помощи PyInstaller. Проблема никуда не делась.

Можете помочь как это исправить. Спасибо.

A: Дело в стандартной кодировке консоли. По умолчанию, она однобайтовая. Вроде бы ASCII. Чтобы появились цвета, нужно изменить ее на двухбайтовую. Такими являются cp1251, unicode, .. . И очень странно, что colorama не изменяет кодировку. Она оборачивает терминал, изменяя его кодировку. Возможно вы не инициализировали ее (colorama.init)?


text:
Q: Error con vue-router Estimados no puedo renderizar la vista por que me dice este error:
Syntax error, unrecognized expression: #/about
Syntax error, unrecognized expression: #/home

Asi es como me queda la url:
http://localhost/cloud/cloud/public/#/home

Estoy usando Laravel + Vuejs + Vue-Router
Links:

        <router-link  to='/home' exact  data-target="#home" class="nav-link" >Inicio</router-link>

        <router-link   to='/about' class="nav-link">Sobre nosotros</router-link>

Precios

Blog

Contacto

app.js
import VueRouter from 'vue-router'
Vue.use(VueRouter)

let routes = [

  {path:'/home',component:require('./components/cloud/homeComponent.vue').default},
  {path:'/about',component:require('./components/cloud/aboutComponent.vue').default}

]

const router =  new VueRouter({
  routes

})

new Vue({
    el: '#app',
    router,

  })

web.php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('app');
});

A: En tu archivo web.php agrega esto
Route::get('/{vue_capture?}', function () {return view('app');})>where('vue_capture', '[\/\w\.-]*');

En tu archivo app.js agrega en tu router  mode: 'history'
const router =  new VueRouter({
   mode: 'history',
   routes
})

En tu app.view o donde tengas el diseño principal, agrega <router-view></router-view> dentro del div con id app

   <router-view></router-view>


text:
Q: C++ overwriting data in a file at a particular position i m having problem in overwriting some data in a file in c++. the code i m using is
 int main(){
   fstream fout;
   fout.open("hello.txt",fstream::binary | fstream::out | fstream::app);
   pos=fout.tellp();
   fout.seekp(pos+5);
   fout.write("####",4);
   fout.close();
   return 0;

}
the problem is even after using seekp ,the data is always written at the end.I want to write it at a particular position.
And if i dont add fstream::app , the contents of the file are erased.
Thanks.

A: You want something like
fstream fout( "hello.txt", fstream::in | fstream::out | fstream::binary );
fout.seek( offset );
fout.write( "####", 4 );

fstream::app tells it to move to the end of the file before each output operation, so even though you explicitly seek to a position, the write location gets forced to the end when you do the write() (that is seekp( 0, ios_base::end );).
cf. http://www.cplusplus.com/reference/iostream/fstream/open/
Another thing to note is that, since you opened the file with fstream::app, tellp() should return the end of the file. So seekp( pos + 5 ) should be trying to move beyond the current end of file position.

A: The problem is with the fstream::app - it opens the file for appending, meaning all writes go to the end of the file. To avoid having the content erased, try opening with fstream::in as well, meaning open with fstream::binary | fstream::out | fstream::in.


text:
Q: Reference request & more: compute vector bundles for homogeneous $G$-varieties We work over the field of complex numbers $\mathbb C$.
Let $G$ be a simple linear algebraic group and let $P,Q$ be standard maximal parabolic subgroups of $G$ containing the same Borel subgroup $B$. It is well-known that also $P \cap Q$ is a parabolic subgroup of $G$. Moreover, the homogeneous $G$-variety $G/P \cap Q$ dominates the generalized Grassmannians $G/P$ and $G/Q$.
$\require{AMScd}$
\begin{CD}
G/P \cap Q @>{q}>> G/Q\\
 @V{p}VV\\
G/P.
\end{CD}
Let $L$ be the generator of the Picard group $\operatorname{Pic}(G/Q) \simeq \mathbb ZL$. I want to describe the vector bundle $p_*q^*L$ over $G/P$ as $P$ varies in the standard maximal parabolic subgroups of $G$.
Example. Let $G \simeq \operatorname{SL}_{n+1}$ and $Q$ be the standard parabolic subgroup associated to the simple root $\alpha_1$ in the root system of the Lie algebra $\mathfrak g \simeq \mathfrak{sl}_{n+1}$, while $P$ is the standard parabolic subgroup associated to the simple root $\alpha_k$ for $1<k\le n$. Then $G/Q \simeq \mathbb P^n$ and $G/P \simeq \operatorname{Gras}(k,n+1)$, the Grassmannian of $k$-planes in a $(n+1)$-vector space. Then $G/P \cap Q \simeq \operatorname{Flag}(1,k;n+1)$ is the flag of lines and $k$-planes in the vector space:
\begin{CD}
\operatorname{Flag}(1,k;n+1) @>{q}>> \mathbb P^n\\
 @V{p}VV\\
\operatorname{Gras}(k,n+1).
\end{CD}
If $L = \mathcal O(1)$ is the dual of the tautological line bundle over the projective space, then it is known that $p_*q^*L$ is the tautological subbundle $S$ appearing in the universal sequence
$$
0 \to S \to \mathcal O^{\oplus (n+1)} \to Q \to 0.
$$
Questions.

*

*How can one compute the vector bundle explicitly in the example?

*More generally, is there a way to compute the rank of $p_*q^*L$?

*How can we compute the weights associated to $p_*q^*L$?

*Once one knows the weights, how can one reconstruct the associated bundle?

I know that this is related to the Borel-Weil-Bott theorem. Everybody seems to know how to compute the bundles, but I cannot find anywhere a reference to learn it.


text:
Q: Targeting JSON internal array data and using RKValueTransformer in RestKit I'm using RestKit on iOS to retrieve some data from kraken.com
I have the following JSON data:
{
    "error":[],
    "result":{
        "XXBTZUSD":{
            "a":["475.00000","1"],
            "b":["465.00639","2"],
            "c":["475.00000","0.01000389"],
            "v":["1.01078477","1.01078477"],
            "p":["475.00008","475.00008"],
            "t":[6,6],
            "l":["475.00000","475.00000"],
            "h":["475.00013","475.00013"],
            "o":"475.00001"
        }
    }
}

My keyPath is @"result.XXBTZUSD" and I'm interested in the first member of the array in each property, i.e. 'a', 'b', 'c', and so on with the exception of 'o' as its value isn't an array. To be clear, an example value I'm interested in would be "475.00000" for 'a'. I am trying to map these values to NSNumber properties in my own data model.
Aside:
I would be doing this dynamically, as I am also getting similar data from other sources but with different structured data.
Also, I don't believe I can use RKObjectMappingMatchers because I don't have an "expected value" for this data.
EDIT:
I've continued working on my RKDynamicMapping and RKBlockValueTransformer logic:
RKDynamicMapping *dynamicMapping = [RKDynamicMapping new];
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation)
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:class];

    if ([url.absoluteString isEqualToString:@"https://api.kraken.com"])
    {
        RKBlockValueTransformer *arrayToNumberValueTransformer = [RKBlockValueTransformer valueTransformerWithValidationBlock:^BOOL(__unsafe_unretained Class inputValueClass, __unsafe_unretained Class outputValueClass) {
            BOOL isTransformableValue = NO;
            if ([inputValueClass isSubclassOfClass:[NSArray class]] && [outputValueClass isSubclassOfClass:[NSNumber class]])
            {
                isTransformableValue = YES;
            }
            return isTransformableValue;
        } transformationBlock:^BOOL(id inputValue, __autoreleasing id *outputValue, __unsafe_unretained Class outputClass, NSError *__autoreleasing *error) {
            RKValueTransformerTestInputValueIsKindOfClass(inputValue, [NSArray class], error);
            RKValueTransformerTestOutputValueClassIsSubclassOfClass(outputClass, [NSNumber class], error);

            *outputValue = [[NSNumber alloc] initWithDouble:[[inputValue objectAtIndex:0] doubleValue]];

            return YES;
        }];

        arrayToNumberValueTransformer.name = @"ArrayToNumberValueTransformer";
        [[RKValueTransformer defaultValueTransformer] insertValueTransformer:arrayToNumberValueTransformer atIndex:0];
    }

    if (sourceKeyPath && [sourceKeyPath length] > 0)
    {
        //  Special case (ignore):
        if ([url.absoluteString isEqualToString:@"http://blockchain.info"])
        {
            [mapping addAttributeMappingsFromDictionary:@{sourceKeyPath:@"currencyCode"}];
        }

        //
        //  The following is useful if you're expecting a set but the service returns a single value
        //[mapping setForceCollectionMapping:YES];    // RestKit cannot infer this information on its own
        //
    }

    //  Where a 'key' is the JSON representation and its value is the internal object representation
    NSDictionary *attributeMappings = [query objectForKey:@"attributeMappings"];
    [mapping addAttributeMappingsFromDictionary:attributeMappings];

    return mapping;
}];

EDIT:
I've got data being mapped now however I'm not sure that I am inserting my RKBlockValueTransformer into the default value transformers list properly? If I insert at 0 will I break something with the functionality of other default value transformers?


text:
Q: How to change the orientation of the iDevice (iPad/iPhone)? It is easy to change orientation of the iPad/iPhone simulators by following: hardware->rotate left or right.
But, how can I change it on iDevice (iPad device or iPhone device?)
please can somebody help me?
should I add some code?

A: Go to you summary tab, scroll down the to go "iPad Deployment Info".
Unselect all the four options in "Supported Interface Orientations".
Then select again, but select Portrait first and remaining after.

Also in View that you are expecting to be in portrait mode, just add
- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    return (orientation == UIInterfaceOrientationMaskAll);
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

Hope this helps.

A: Go to the .plist file in Supporting Files
There you will see Supported interface orientations
Add below keys
Item 0 String Portrait (top home button)
Item 1 String Portrait (bottom home button)
Item 2 String Landscape (left home button)
Item 3 String Landscape (right home button)

A: a call to UIApplication's setStatusBarOrientation will fake a rotation

A: Add Initial interface orientation key/value to your $appName-info.plist file


text:
Q: How to interpret an image histogram and plot histogram3D for an image? I'm really finding many ambiguities in how I really should interpret the histogram of an RGB image? I could understand what the height denotes, but did not understand how the pixels get plotted on a single dimensional x-axis. Also, is it possible to plot the image onto histogram3D? I tried after converting it to separate RGB images but I get an error that says it is not able to calculate the "bins" the diagram.
Thank you

A: The default is to not show any useful labelling, so perhaps it might be easier to do this:
i = ExampleData[{"TestImage", "Mandrill"}];
ImageHistogram[i, FrameTicks -> {True, True},
 Appearance -> "Separated"]

For the 3D aspect of your question, perhaps you want something like this:
{r, g, b} = ColorSeparate[ImageResize[i, 200]]
ListPlot3D[ImageData[r, DataReversed -> True], Mesh -> False,
 ColorFunction -> "GrayTones"]

— this is just the red channel.

A: This might be one more manual way to see Histogram.
image = Import["ExampleData/lena.tif"]
tr = ImageData[image, "Byte"]
tr // Dimensions (*{116,150,3}*)
a = Table[tr[[i, j]] /. {a_, b_, c_} -> a, {i, 116}, {j, 150}](*Similarly for b,c)

Sample Histogram computation is
Histogram[b, 100, ChartBaseStyle -> EdgeForm[None],  ChartStyle -> Green]

Now comparing Histogram for a,b & c with ImageHistogram respectively. we shall see similar results.

We can see both of them resembling.
So, to calculate Histogram3D you need two coordinates which you can extract as,
ab = Table[tr[[i, j]] /. {a_, b_, c_} -> {a,b}, {i, 116}, {j, 150}]
(*Similarly for bc,ca)

My system is old so, I could produce it only once as it took long time. I am not pasting graphics for Histogram3D but you can generate it by Histogram3D[ab].


text:
Q: Why is my tableview property null I have set the delegate and datasource to the File's Owner, the outlet is set properly in the xib file. Now for the .h file:
@interface ProductsViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>{

    IBOutlet UITableView *objTableView;
}

@property(nonatomic,strong)IBOutlet UITableView *objTableView;

In the .m file:
NSLog(@"%@",self.objTableView);
[self.objTableView reloadData];

For the first time, self.objTableView is set properly:
NSLog(@"%@",self.objTableView);
gives:
<UITableView: 0x1d9a5800; frame = (4 54; 532 660); clipsToBounds = YES; autoresize = W+H;

But for next time I got a (null) table view object and so the reloadData doesn't refresh the table view. How to fix that, thanx in advance.
EDIT:
I am using the Afnetworking method JSONRequestOperationWithRequest like the following:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){

    [SVProgressHUD dismiss];
    //Get the response from the server
    //And then refresh the tableview

    [self.objTableView reloadData];//I shouldn't put this here, it should be in the main thread
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response,NSError *error, id JSON){

            [SVProgressHUD dismiss];

            //Alert the error message

}];
[operation start];
[SVProgressHUD showWithStatus:@"Searching for products, please wait.."];

Actually, JSONRequestOperationWithRequestrun asynchronous and so not in the main thread, however it turned that the UI updates should be done in the main thread, so I need to remove [self.objTableView reloadData]; outside that method. But where? how to make sure to run it in the main thread after JSONRequestOperationWithRequest will finish?

A: Are you sure you're looking at self.objTableView (the property's accessor method) and not objTableView (the instance variable you manually defined)? Do you have a @synthesize line? If you omitted your @synthesize line, it would have effectively done @synthesize objTableView = _objTableView; for you, defining an instance variable called _objTableView for your property called objTableView, and thus your manually defined instance variable, objTableView would never have been initialized.
It is recommended that you remove the manually defined instance variable and let the compiler synthesize that for you, and just define the property, thus:
@interface ProductsViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>

// Following lines removed. Do not define the instance variable.
// Let the compiler synthesize it for you.
//
// {
//     IBOutlet UITableView *objTableView;
// }

@property(nonatomic,strong)IBOutlet UITableView *objTableView;

@end

The compiler will generate the instance variable for you, and unless to manually write your own @synthesize line, the compiler will name the instance variable _objTableView. If you ever need to reference the instance variable for your objTableView property (generally only needed in initializer and dealloc methods), remember to include the leading underscore. (The convention of the underscore is to minimize chances that you accidentally refer to the instance variable when you actually intended to use the self.objTableView accessor getter method.

A: Have you tried setting a Watchpoint on objTableView?
In your -viewDidLoad set a breakpoint. When the debugger stops, secondary-click on objTableView in the variable list. Click on "Watch 'objTableView'". It will break anytime the value of objTableView changes.
It should let you know exactly when the value changes.

A: I suggest you create the following method:
- (void)setObjTableView:(UITableView *)tableView {
    _objTableView = tableView;
}

Then set a breakpoint on the _objTableView = tableView line, which should let you know what causes _objTableView to become nil.


text:
Q: Generating Salts, Silex, Charset? I've been researching the best way to generate salts. General advice seems to be to use mcrype_create_iv or openssl_random_pseudo_bytes to generate. T
he problem with this is I have trouble using the values retrieved because of the characters involved. I am using RedBean as an ORM and and Silex as a framework. I have trouble setting and retrieving the generated value with RedBean, and I know Silex also has limitations because I received an error once that the salt can not contain brakets "{}".
What the best way to generate a salt that uses a standard character set. I figured I might be able to md5 the result, but then that results in a much smaller charset.

A: To generate a valid salt, one has to know which algorithm will use this salt. Often you can use the function base64_encode() to retrieve standard characters from a binary salt, it will generate a string with following alphabet:
base64 encoding alphabeth: +/0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
If Silex uses the salt for a BCrypt hash algoritm, it will expect a salt with following alphabet, note the "." instead of "+":
BCrypt hash alphabet: ./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
I think it's best to test out what characters are allowed, or to find out which algorithm will be used, otherwise you will sooner or later generate an invalid salt. An example for generating a BCrypt salt using the function mcrypt_create_iv() could look like this:
/**
 * Generates a random salt for using with the BCrypt algorithm.
 * @param int $length Number of characters the string should have.
 * @return string A random salt.
 */
function sto_generateRandomSalt($length = 22)
{
  if (!defined('MCRYPT_DEV_URANDOM')) die('The MCRYPT_DEV_URANDOM source is required (PHP 5.3).');

  // Generate random bytes, using the operating system's random source.
  // Since PHP 5.3 this also uses the random source on a Windows server.
  // Unlike /dev/random, the /dev/urandom does not block the server, if
  // there is not enough entropy available.
  $randomBinaryString = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);

  // BCrypt expects nearly the same alphabet as base64_encode returns,
  // but instead of the '+' characters it accepts '.' characters.
  // BCrypt alphabet: ./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
  $randomEncodedString = str_replace('+', '.', base64_encode($randomBinaryString));
  return substr($randomEncodedString, 0, $length);
}


text:
Q: How to rotate few images in different angles using Javascript I need to take a list of images (Taken from the DB) and display them on my homepage
in a way that each image is rotated in another angle (finaly it will create half circle)
How can I write it in Javascript and control each the images angles?
Thanks.

A: You might consider using SVG or canvas for this...


text:
Q: best HTML validator/parser? I have a large HTML file, and it looks like some  tags are not closed.  It's hard to find it.  I am using VIM as the editor.
Is there any good way to find it?

A: You can validate your html using http://validator.w3.org/
Just make sure you specify the DOCTYPE correctly and it'll find anything that is invalid.

A: I assume you are on running Linux?! If so, you could try Eclipse
It is a complete IDE, which will help you in many cases and make programming a lot more efficient

A: Just use Notepad++. It is free and light weight code editor, and I already found many unclosed tags in my html with it...

A: HTML Validator (extension for Firefox) has helped me in the past. You need to load the page in the browser to find the errors.

A: If you can put you code online you could try Dr. Watson.

A: Another validator to try is the CSE HTML Validator. The online version is here:
http://www.OnlineWebCheck.com/


text:
Q: How to keep rendering data each time after ajax post? Recently, I have learnt to deal with rendering data. But I am having a trouble to render sent data to ejs file in node.js. I wanted to use sent data for building my html page from server-side with embeded javascript(or jade). So in my code I save sent data in my file, it works pretty well. But problem is that the rendered data keeps being same as it was, even though the file is changed. I guess that the data is changed only once when I run server because my page changes when I rerun server. Please, share your tricks to overcome this kind of problems.
`enter code here`// ----- app.js
app.post('/notes' , function (req , res) {
    var fs = require('fs');
    var data = req.body;
    fs.writeFile("bucket.json" , JSON.stringify(data) , "utf8" , function (){});
});
// ---- routes/bucket
router.get('/', function(req, res, next) {
    var data = require('bucket.json');
    res.render('bucket', {movies:data});
});

A: Modules are cached after the first time they are loaded. See https://nodejs.org/api/modules.html#modules_caching
router.get('/', function(req, res, next) {
    fs.readFile('bucket.json', (err, data) => {
        if(err) {
            return next(err);
        }
        res.render('bucket', {movies:JSON.parese(data)});
    });
});


text:
Q: put $LINE value instead of "$LINE" I have a loop in the script below. It is not working as I want. I need to put the $LINE value in front of each column. While it puts "$LINE" instead of it is value:
cat list | while read LINE ; do
sed 's/^/$LINE\t/g' $LINE.alf > $LINE.joined
done

A: It will not expand variables in side of a single quoted ' string.  Try:
cat list | while read LINE ; do
sed 's/^/'"$LINE"'\t/' $LINE.alf > $LINE.joined
done


text:
Q: Area-preserving diffeomorphisms of sphere to itself Are diffeomorphisms of sphere to itself which preserve area element rotations?

A: No: the group of rotations is finite dimensional, whereas the group of area preserving is not. Here is a concrete example.
If $f$ is a smooth function, let $X$ be the unique vector field such that $i(X).\omega =df$, where $\omega$ is the volume form, then the flow of $X$ preserves the volume form (it is Hamiltonian). One can choose $f$ constant in the north hemisphere, not in the south hemisphere, so its flow is the identity in the north hemisphere and not in the south hemisphere.


text:
Q: jquery toggle triggers display to none I have some weird behavior. I want to trigger event on click on a span tag, let's say #span id. When I run this in my console, to test :
$('#span').toggle(function(){
    console.log('hi');
},function(){
      console.log('hey');
});

The #span display is set to none. I tried to find some code which could interfere but I didn't find any...

A: This version of toggle was removed in jQuery 1.9, so if you are using jQuery >= 1.9 it will toggle the display state
One possible solution to enable the removed functionalities is to add the migration plugin after jQuery
Another will be is to write a toggleClick plugin yourself like the below one from this answer
$.fn.toggleClick = function(){
    var methods = arguments, // store the passed arguments for future reference
        count = methods.length; // cache the number of methods

    //use return this to maintain jQuery chainability
    return this.each(function(i, item){
        // for each element you bind to
        var index = 0; // create a local counter for that element
        $(item).click(function(){ // bind a click handler to that element
            return methods[index++ % count].apply(this,arguments); // that when called will apply the 'index'th method to that element
            // the index % count means that we constrain our iterator between 0 and (count-1)
        });
    });
};

then
$('#span').toggleClick(function(){
    console.log('hi');
},function(){
      console.log('hey');
});

A: Jquery doesn't support toggle(func,func) anymore, toggle() simply toggles the element visible or invisible.

A: http://api.jquery.com/category/deprecated/

.toggle() method signature was deprecated in jQuery 1.8 and removed in
  jQuery 1.9. jQuery also provides an animation method named .toggle()
  that toggles the visibility of elements. Whether the animation or the
  event method is fired depends on the set of arguments passed.

http://api.jquery.com/toggle-event/
you can use .one()
DEMO
function handler1() {
    console.log('hi');
    $(this).one("click", handler2);
}

function handler2() {
    console.log('hey');
    $(this).one("click", handler1);
}
$("#span").one("click", handler1);

A: It has been deprecated and then removed in jQuery 1.9. You'll find some docs here

A: There is no more toggle (in that fashion) in jquery 1.9.
What you can do is this and make your own toggle-like plugin:
$.fn.toggleFn = function(){
    var fns = arguments;
    var fns_length = fns.length;
    var idx = 0;
    this.on('click', function(){
        fns[idx % fns_length].apply(this, arguments);
        idx++;
    });
}

Using it:
$('#span').toggleFn(function(){
    console.log('hi');
},function(){
      console.log('hey');
});


text:
Q: Immersive Injections whose images are Embedded Submanifolds Let $M,N$ be smooth manifolds where the dimension of $M$ is less than or equal to the dimension of $N$.
Suppose that $F: M \rightarrow N$ is an injective immersion and $F(M)$ is an embedded submanifold, is it the case that $F$ is a smooth embedding?
This question came up when I was studying for my differential topology final with some friends. One of my friends is convinced that this is true, I feel strongly that it's not true. But neither of us could prove or disprove it in a satisfactory manner.

A: user8268 is right.  Let me just elaborate a little bit on his argument.
When we talk about the map $F\colon M\to N$, we really mean the composition of maps $M \xrightarrow{G} F(M) \xrightarrow{\iota} N,$ where $G\colon M \to F(M)$ is just the map $F$ with its range restricted, and $\iota\colon F(M) \to N$ is inclusion.
Now, we claim that $G$ is a diffeomorphism and $\iota$ is a smooth embedding, so that $F = \iota \circ G$ is a smooth embedding.

*

*Since $F\colon M\to N$ is an injective immersion, and since $G$ is continuous, we have that $G\colon M\to F(M)$ is a bijective immersion, and so $G$ is a diffeomorphism.

*Since $F(M)$ is embedded, we have that $\iota\colon F(M) \to N$ is a smooth embedding.

Some remarks:
(1) In the case of the Figure 8, what fails is that $\iota$ is not a smooth embedding, but instead an injective immersion.  Note, though, that $G$ is still a diffeomorphism in this case because that is how we define both the smooth structure and topology of the Figure 8.
(2) In the first bullet point, we do need the fact that $G\colon M \to F(M)$ is continuous.  Otherwise, we cannot immediately conclude that $G$ is smooth.
For instance, if the Figure 8 were given some weird topology -- neither the topology inherited from $M$ by declaring $G$ a diffeomorphism, nor the topology inherited from $N$ as a subspace, but instead something really weird -- then the map $G$ may fail to be continuous.
So why is $G$ continuous in our case?  Well, since we were given that $F\colon M\to N$ is continuous, and since $F(M)$ carries the subspace topology (by virtue of being embedded), we can conclude that the restricted map $G$ is in fact continuous.


text:
Q: track twitter hashtags using twit through socket.io I would like to create an if statement in my emit function that says: if the hashtag is x, then send through this ID, if the hashtag is y, then send through that ID. I'm guessing that its best to do this server side. How would I do this? (I think I need to filter the JSON result)
Here is my server side code:
var express = require("express");
var app = express();
var Twit = require('twit');
var T = new Twit({
    consumer_key:         'JBJUBMi6uBz1j4587RHoWVWX9' // Your Consumer Key
  , consumer_secret:      'ChwkS3eXX0obPAGPaw5thpRt8bMr4nbNa7fK3Vc4M8Bieeegr0' // Your Consumer Secret
  , access_token:         '150020683-nztFnojPcUyxUVXllWXFJ9p99JAaTA6MFE6tr5Wx' // Your Access Token
  , access_token_secret:  'jzQMrFnAFjyqMEC7aIDI5hymElWf329Y1dysj0vOAiEGu' // Your Access Token Secret
});

app.use(express.static(__dirname +'/public'));

//routes

app.route('/cool')
    .get(function(req,res){

        res.sendFile(__dirname+'/public/html/404.html');

    });

    var server = app.listen(3000, function(){

console.log(" the server is running on port 3000");

    })

    var socketio = require("socket.io");
    var io = socketio.listen(server);
    var nbOpenSockets = 0;
    var stream = T.stream('statuses/filter', { track: 'liberal, conservative'})

    io.on('connection',function(socket){

console.log('Client connected !');
    if (nbOpenSockets <= 0) {
        nbOpenSockets = 0;
        console.log('First active client. Start streaming from Twitter');
        stream.start();
    }

    nbOpenSockets++;

    socket.on('disconnect', function() {
        console.log('Client disconnected !');
        nbOpenSockets--;

        if (nbOpenSockets <= 0) {
            nbOpenSockets = 0;
            console.log("No active client. Stop streaming from Twitter");
            stream.stop();
        }
    });

        socket.on('changeBackground', function(newColour) {

            console.log(newColour);

            socket.emit('setBackground', newColour);

            socket.broadcast.emit('setBackground', newColour);

        });

        stream.on('tweet', function(tweet) {

socket.emit('info', { tweet: tweet });

});

        socket.emit('initialize', "initialized");

    });

A: By using IndexOf and assigning an ID to that hashtag, I was able to pass the id through to the client:
stream.on('tweet', function(tweet) {

    // console.log(tweet);

    if(tweet.text.indexOf('#war') > -1) {
        console.log("war")

     socket.emit('info', {tweet:"war"});

    }


text:
Q: Extracted XML content from postgres not recognized in R I use a substring query in PostGresql to generate the following output.
I used this in the dbGetQuery in R studio:
dbGetQuery(con, "SELECT substring(response from 11 for       position('</ConsumerEnquiry>'     in response) + 8)  FROM za.scoring_result where id in (334)")

The Output is:
<?xml version="1.0"?>
<ConsumerEnquiry>
 <Session>
  <User_ID>ROCK1</User_ID>
  <FullName>ROCK1</FullName>
  <GroupName>014828</GroupName>
  <Subscriber_ID>14828</Subscriber_ID>
  <Group_ID>014828</Group_ID>
  <RequestType>XML2</RequestType>
  <Environment>PRODUCTION</Environment>
  <Version>1.0.0</Version>
 </Session>
</ConsumerEnquiry>

When I try:
file2 = xmlParse("SA_Data_1")

I get an error:
Error: XML content does not seem to be XML: 'SA_Data_1'
Can someone help me? My first post here.. :)

A: You need to save the output. I'm guessing you really mean to do:
SA_Data_1 = dbGetQuery(con,
   "SELECT substring(response from 11 for  position('</ConsumerEnquiry>' in response) + 8)
    FROM za.scoring_result where id in (334)")

assuming this returns the XML as a character string, then you can do
SA_parsed = xmlParse(SA_Data_1$substring)

to get a parsed version of the XML. Then you can extract bits from it using the rest of the XML package.
file2 = xmlParse("SA_Data_1")

fails because its interpreting "SA_Data_1" as a piece of XML, which it isn't.


text:
Q: How to concatenate strings formatted with printf in bash I need to concatenate several strings in loop and assign result to variable:
Formatted string example:
result=$(printf '| %-15s| %-25s| %-15s| %-15s| %-15s\n' $size $name $visits $inbound $outbound);

From my view it should work like this:
result=''
while read somevar
do
    ...
    outbound=`cat "$www_path/$name/access.log"|grep \`date +"%d/%b/%Y"\`|awk '{ sum+=$11} END {print sum/1024/1024}'`
    result=$(printf '%s| %-15s| %-25s| %-15s| %-15s| %-15s\n' $result $size $name $visits $inbound $outbound);
    ...
done
echo $result

But it doesn't :(
UPD:
Full code listing below:
www_path='/var/www';
result='';
cd /var/www/; ls -d */ | while read i ; do basename "$i" ; done
while read i;
do du -sh "$i"|
        while read size name
        do
                visits=`cat "$www_path/$name/access.log"|grep \`date +"%d/%b/%Y"\`|grep -v "internal dummy connection"|awk -F ' ' '{print $1}'  | sort | uniq | wc -l|tr '\n' '\t'|sed 's/$/\t/'`
                inbound=`cat "$www_path/$name/access.log"|grep \`date +"%d/%b/%Y"\`|grep -v "internal dummy connection"|awk '{ sum+=$10} END {print sum/1024/1024}'|tr '\n' '\t'|sed  's/$/\t\t/'`
                outbound=`cat "$www_path/$name/access.log"|grep \`date +"%d/%b/%Y"\`|grep -v "internal dummy connection"|awk '{ sum+=$11} END {print sum/1024/1024}'`;
                result=$(printf '%s| %-15s| %-25s| %-15s| %-15s| %-15s\n' "$result" "$size" "$name" "$visits" "$inbound" "$outbound")
        done
done
echo $result

A: Your code looks OK. One thing you do need to do, since result will contain whitespace as you add to it, is quote its expansion:
result=$(printf '...' "$result" "$size" "$name" ...)

Quoting the other variables may not be necessary, but it is usually a good idea.
Failing to quote $result shouldn't cause it to be completely blank, however. You might need to post more of the code in your while loop.

A: Use double quotes around $result and all other variables that may contain blanks and other special characters if they are to be used as a single argument to a program or built-in function:
result=$(printf '%s| %-15s| %-25s| %-15s| %-15s| %-15s\n' "$result" "$size" "$name" "$visits" "$inbound" "$outbound")

If you just want to assign the result of printf to a variable (as you did), you can also use
printf -v result '%s| %-15s| %-25s| %-15s| %-15s| %-15s\n' "$result" "$size" "$name" "$visits" "$inbound" "$outbound"

BTW: there also a += assignment operator that just appends to strings (see bash man page, section PARAMETERS).
In the full code listing, a pipe sign is missing after the 'done' before the second 'while read i'.
And when you call
echo $result

the contents of $result is already lost, since the printf is called in a sub process created by the pipe sign after 'do du ...'. The parent processes haven't access to the (environment) variables of the sub process.
I'd rather rewrite the code to something like
result=""
for name in /var/www/* ; do
    read size __ < <(du -sh "$name")
    name=${name##*/}
    #insert the other stuff here and add arguments to printf
    printf -v line '| %-15s| %-25s\n' "$size" "$name"
    result+=$line
done
echo "$result"

The read < <(cmd) expression is similar to cmd | read but the former puts the command in the sub process instead, while the read is executed in the main process. This way, the variables set by read can be used in subsequent commands, too.


text:
Q: Minimum value of $S=\frac{3a}{b+c}+\frac{4b}{a+c}+\frac{5c}{a+b}$ Find Minimum value of Minimum value of $$S=\frac{3a}{b+c}+\frac{4b}{a+c}+\frac{5c}{a+b}$$
My Try:
we have $$S=3 \times \left (\frac{a}{b+c}+\frac{b}{a+c}+\frac{c}{a+b}\right)+\frac{b}{a+c}+\frac{2c}{a+b}$$
By Standard $AM$ $GM$ inequality we know that
$$\frac{a}{b+c}+\frac{b}{a+c}+\frac{c}{a+b} \ge \frac{3}{2}$$
Is it possible to proceed here?

A: For any positive numbers $\alpha, \beta, \gamma$, we have
$$\frac{\alpha^2 a}{b+c} + \frac{\beta^2 b}{c+a} + \frac{\gamma^2 c}{a+b}
= (a+b+c)\left(\frac{\alpha^2}{b+c} + \frac{\beta^2}{c+a} + \frac{\gamma^2}{a+b}\right) - \left(\alpha^2+\beta^2+\gamma^2\right)$$
By Engel's form of Cauchy Schwarz, we have
$$\frac{\alpha^2}{b+c} + \frac{\beta^2}{c+a} + \frac{\gamma^2}{a+b}
\ge \frac{(\alpha+\beta+\gamma)^2}{(b+c)+(c+a)+(c+a)}
= \frac{(\alpha+\beta+\gamma)^2}{2(a+b+c)}
$$
This leads to
$$\frac{\alpha^2 a}{b+c} + \frac{\beta^2 b}{c+a} + \frac{\gamma^2 c}{a+b}
\ge \frac{(\alpha+\beta+\gamma)^2}{2} - \left(\alpha^2 + \beta^2 + \gamma^2\right)$$
and the equality holds when and only when
$$\alpha : \beta : \gamma = b+c : c+a : a+b$$
Subsitute $\alpha,\beta,\gamma$ by $\sqrt{3},\sqrt{4}$ and $\sqrt{5}$
We obtain
$$\frac{3 a}{b+c} + \frac{4 b}{c+a} + \frac{5 c}{a+b}
\ge \frac{(\sqrt{3} + \sqrt{4} + \sqrt{5})^2}{2} - 12
= \sqrt{15} + \sqrt{20} + \sqrt{12} - 6$$
and the equality is achievable when
$$a : b : c = -\sqrt{3}+\sqrt{4}+\sqrt{5} : \sqrt{3} - \sqrt{4} + \sqrt{5} : \sqrt{3}+\sqrt{4} - \sqrt{5}$$
This means the minimum value of $S$ is $\sqrt{15} + \sqrt{20} + \sqrt{12} - 6$.


text:
Q: Multi tenant app that share data (Asp net mvc + Entity Framework + Sql Server) I'm developing a multi tenant app architecture that is quite complex.
.
3 completly different kind of app
Ther is no only one type of application used by many customers; ther are 3 different kind of applications.
APP A, APP B, APP C
.
Each APP is multitenant
Each app has its customers.
APP A
- customer A1
- customer A2
APP B
- customer B1
- customer B2
APP C
- customer C1
- customer C2
.
SHARED INFORMATIONS
Many informations are shared betwen the different apps
"customer A1" need to manipulate or only view data owned by "customer C1"
.
QUESTION
Consider that i'm using Asp net mvc, EF, Sql Server.
Wich is the correct implementation?
One site and many Areas?
Create multiple sites?
Multiple db? Only one db? Filtering? Sql filtered view? ...
Some application example?
EDIT
and... Where to put the business logic?

A: I would recommend that you first build your own multi-tenant engineering stack (Framework) on top of .Net which will handle all the requirements of multi-tenancy in terms of tenant wise data isolation, support for horizontal scaling, filtering of views based on the tenant context and role of the user, tenant wise data model extension, tenant wise UI customization, enforcing access restrictions based on roles,  privileges and data scope - which could be different for different tenants etc.
The business logic can be built on top of this framework. This approach will provide your product a robust and strong engineering foundation.
The other alternative is to buy a ready to use multi-tenant engineering stack off the shelf, install it on Visual Studio and use it as a development template.

A: Ideally in a multi-tenant server with a single app you want physically different databases for each tenant, rather than just a column specifying which tenant the data belongs too
But either way you have to ensure that ALL database functions use the correct database connection or tenant column key. That is the real issue
The way to make sure of this is to have only ONE function per app that makes this decision, and make sure all database functions fail if they have not called this function (directly, or indirectly as below)
e.g. With MVC in the global.asax AuthenticateRequest or BeginRequest function you can validate who the user is and then calculate which database connection they need to use or what tenant column key they must use in EVERY query for that request. This is then stored in a session variable etc
If you have three apps, I would make three separate sites. They can share common classes via a shared project. Life is generally easier if they can be deployed separately

A: This is a concrete answer, but just some some aspects you may consider when designing this.
With regards to shared information, I think the most important part here is to define the relationship between customers and the roles and rights each customer has with respect to other customers. The best approach is to start with is identifying what exactly can be done.
Example:
Read Only|cust1|cust2|cust3
---------+-----+-----+-----
customer1| 1   | 1   | 0
customer2| 0   | 1   | 0
customer3| 1   | 0   | 1

Write    |cust1|cust2|cust3
---------+-----+-----+-----
customer1| 1   | 1   | 0
customer2| 0   | 1   | 0
customer3| 0   | 0   | 1

So in the above, customer1 can read and write(update) customer2's data.
This being said, the main issue is model these relationships i.e. the shared information.  Using @TFD's suggestion, these relationships can be loaded into session for when a customer logs on along with the relevant tenant id's.
(Based on the information provide, my other inclination is that this may be a per application concern and not a customer only  concern. To illustrate this, replace the 'cust' values in the above tables with App.)
Create separate sites for each application since I am assuming that each application has a unique purpose although there is shared functionality.
Maybe  a different Config DB is needed if there are other cross data relationships. The DB would store all the tenant information (incl. relationships to other Apps) for each App.  The reason for this suggestion is that from what I can see, you have three separate multi-tenant apps independent of each other using a shared DB approach - but each App need to interact with another App on some level.
In terms of customers within the DB, I would then suggest that the 'Customers' table be confined to the Config DB. You can then have a content DB based on each applications requirements.

A: My suggestion is to use PRISM with Sliverlight and MVVM design patten. PRISM is designed for such kind of composite application where each application is independent and can also communicate with each other via Events exposed by PRISM.

A: You can have multiple approaches - since the app is data driven, it makes sense to build a database design that secures the data even in case of application bugs.
One way to do this is ensure that there are stored procs for accessing any tables and the security logic is built into the stored procedures. You can ensure that a different db username is used for each customer, and that this db user name is mapped against that tenant id in a mapping table. Then the stored procs can always have a check that the data being requested/modified is actually belonging to the tenant id mapped to the db user who is running the proc (by using context information).
Then you will need some way to ensure that the db connection created by the application uses only the corresponding username that maps to that tenant id. This means you need one more stored proc that gives you this information (with probably username/id as the input) and this stored proc should be executable through a common db username. Remember, this is the only stored proc that needs to have execution priveleges given to this common db user.
This might look like writing a bunch of extra code, but it really helps to know that your db will reject bad requests even due to application bugs. The only place you have be really, really careful is the place where you get the right tenant db username and password for that user id, and that should be quite possible.


text:
Q: Correctly send user to 404 if dynamic content is not found (ASP.NET MVC) I have implemented 404 handling for the general case in ASP.NET MVC 3, for when a controller/view is not found. But how should it be handled inside the controller if the user is trying to access something that can't be found? For example www.foo.bar/Games/Details/randomjunk will call this inside GamesController:
public ActionResult Details(string id) // id is 'randomjunk'
{
  if(DoesGameExist(id) == false)
    // Now what?

I could just do a return Redirect('/Errors/Http404'); but that doesn't seem like the correct way to do it. Should you throw an exception, or something else?
We could have a special view in this case, but to start with we need a good way we can apply to several cases.
Edit: I want to show my friendly 404 page I already have for the general case.

A: You should throw HttpException 404 :
throw new HttpException(404, "Page not Found");

A: EDIT:
Apparently per Darin Dimitrov, what I had before doesn't work even with customErrors.  As Antonio Bakula says in the other answer, you have to do:
throw new HttpException(404, "Not found")

Then the customErrors will work.

There's a built-in helper method called HttpNotFound so you can just do:

    return HttpNotFound();

You could also explicitly return a 404 with HttpStatusCodeResult:

    return new HttpStatusCodeResult(404);

HttpStatusCodeResult is helpful when there's not a specific helper method or class for the code you want.

You should also have this in your Web.config:
<customErrors>
    <error statusCode="404" redirect="~/Custom404Page.html"/>
</customErrors>

You can also have additional lines for other statuses, and a defaultRedirect.

A: You could return a HttpStatusCodeResult.
return new httpStatusCodeResult(404);


text:
Q: How to make Ubuntu 22.04 save screenshot as png and not just place it on clipboard? Ubuntu 22.04 64-bit LTS
I was surprised to see the new screenshot tool throw up a message that I could paste the screenshot into a file. Why should this be required? My old 18.04 setup could do it out of the box. How do I configure this basic function? I could not find anything in settings.

A: Even if I liked the old gnome-screenshot tool, the new tool even improves.
If you just invoke it, PrtScr, you can still do everything: make screenshots of the entire screen, a window or selection, or record the screen. You do not need to think ahead on whether you want a screenshot to file, or one to the clipboard: the new tool just does both.
Make your screenshot, and find the file in ~/Pictures/Screenshots, or paste it in your application. It is your choice.
If you know what you want to capture, then hit Shift+PrtScr to capture the entire screen, or Alt+PrtScr to capture the active window. Again, no need to think ahead: paste the figure or find the file in ~/Pictures/Screenshots: it is your choice.
So also in 22.04, both functions are available, but the mental overhead - do I want output in clipboard or in a file - has been removed.

A: The screenshots should automatically be saved into ~/Pictures/Screenshots or the equivalent if you're using a different language. You can directly navigate to the folder from the message you see when taking a screenshot by hovering your mouse over the dialog.
.


text:
Q: PostgreSql allocate memory for each connection When we configure the memory setting for the Postgres DB what is the recommended memory allocation for each connection ? Is there any formula to apply ?
I know 25% of the memory of the Server should be allocated. But how do we allocate based on the DB connections? How do we know, what is the maximum number of connections should be allocated?
Also in a multi-nodes environment can we allocate more connections for each node (in Postgres-ds.xml max connections) than what is actually allocated in the DB?

A:
When we configure the memory setting for the Postgres DB what is the
  recommended memory allocation for each connection ? Is there any
  formula to apply ?

There is no per-connection pre-allocated memory that a DBA would define. A session will allocate dynamically what is needed, or use the shared memory pre-allocated at server start depending on the kind of usage.
 See Resource consumption in the doc about what can be defined.

I know 25% of the memory of the Server should be allocated. But how do
  we allocate based on the DB connections? How do we know, what is the
  maximum number of connections should be allocated?

The maximum number of client connections (max_connections) is factored into the amount of shared memory that is pre-allocated at server start.
In Managing Kernel Resources, the doc says that its size in bytes is:
(1800 + 270 * max_locks_per_transaction) * max_connections
But memory is not the main factor in deciding the maximum number of connections, it's the raw power and number of cores of the machine, and wether a connection pooler is going to be associated to the server. The point is mostly to avoid too many concurrent active queries provoking the server to halt to a crawl.

Also in a multi-nodes environment can we allocate more connections for
  each node (in Postgres-ds.xml max connections) than what is actually
  allocated in the DB?

If there are multiple client nodes that point to the same PostgreSQL instance, the combined count of their connections cannot outreach max_connections.
However when using a connection pooler, connection as a word becomes ambiguous. You want to know whether it's a connection from the client to the pooler or a connection from the pooler to the database server. Generally there are much more allowed connections to the pool than to the database.


text:
Q: Python ctypes.cdll.LoadLibrary works differently between 2.6.5 and 2.7.1 I've got a system with both Python version 2.6.5 and 2.7.1 and I'm noticing that one LoadLibrary works, the other does not.
Python 2.7.1 (r271:86832, Nov 30 2010, 10:03:07)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import cdll
>>> cdll.LoadLibrary("./mylib.so")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/ctypes/__init__.py", line 431, in LoadLibrary
    return self._dlltype(name)
  File "/usr/local/lib/python2.7/ctypes/__init__.py", line 353, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: ./mylib.so: undefined symbol: compress2

and in working 2.6.5 land:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import cdll
>>> cdll.LoadLibrary("./mylib.so")
<CDLL './mylib.so', handle 98bbd88 at b785c94c>

Does anyone know a good way to figure out why python 2.7.1 is not working?

A: For some reason, Python ctypes gets super anal about library dependencies.  I still have no figured out why 2.6.5 was working above, but doing the following fixes it:
When compiling mylib.so, I needed to specify or link to the zlib library explicity.  Since "compress2" is from the zlib library, I can do it by the following:
g++ blah blah mylib.so blah blah -lz
The -lz links to the zlib library and it will then show up if you do a "ldd mylib.so"  This fixes it and allows "LoadLibrary" to not fail.


text:
Q: x-axis scale in ggplot i have a dataframe
df <-data.frame(apport=c("Min 1", "Min 2", "Org 2017","Org 2017","Org 2017",
                         "Org 2017","Org 2017","Org 2017","Org 2017","Org 2017",
                         "Org 2017","Org 2017"), periode_ap=c("Mai_32","Jui_34",
                          "Avr_30", "Avr_31","Avr_31","Avr_31","Mai_32","Mai_32","Mai_32",
                          "Mai_33","Mai_33","Mai_33"))

I made a ggplot
ggplot(df, aes(x=periode_ap, color=apport))+geom_density()

but i want to have in the x axis a graduation that i have in this list :
list<-c("Jan_0", "Jan_1", "Fev_2", "Fev_3","Mar_4", "Mar_5", "Avr_6", "Avr_7", "Mai_8", "Mai_9", "Jui_10", "Jui_11", "Jul_12", "Jul_13", "Aou_14", "Aou_15", "Sep_16", "Sep_17", "Oct_18", "Oct_19", "Nov_20","Nov_21", "Dec_22", "Dec_23", "Jan_24", "Jan_25", "Fev_26", "Fev_27", "Mar_28", "Mar_29", "Avr_30","Avr_31", "Mai_32", "Mai_33", "Jui_34", "Jui_35", "Jul_36", "Jul_37", "Aou_38",
 "Aou_39", "Sep_40", "Sep_41", "Oct_42", "Oct_43", "Nov_44", "Nov_45", "Dec_46", "Dec_47")

to have a periode from Jan_0 until Dec_47 instead of Avr_30 until Jui_34 that I have in my data, if you can help me , thanks

A: Seems like you're dancing around the answer a bit.  The problem lies in that you cannot use something like xlim('Jan_0','Dec_47') because your x axis scale is discrete and not continuous.  ggplot2 has no idea how your data should be organized, so it is just defaulting to as it exists in the dataframe and does not know how to extrapolate back to "Jan_0" or further out to "Dec_47".  (Incidentally... neither do I...).
The answer to how you expand your chart is therefore twofold:
(1) Tell ggplot2 how your data is organized.  I'm setting df$periode_ap as a factor, and indicating the levels are your list.
lev_periode_ap <- list<-c("Jan_0", "Jan_1", "Fev_2", "Fev_3","Mar_4", "Mar_5", "Avr_6", "Avr_7", "Mai_8", "Mai_9", "Jui_10", "Jui_11", "Jul_12", "Jul_13", "Aou_14", "Aou_15", "Sep_16", "Sep_17", "Oct_18", "Oct_19", "Nov_20","Nov_21", "Dec_22", "Dec_23", "Jan_24", "Jan_25", "Fev_26", "Fev_27", "Mar_28", "Mar_29", "Avr_30","Avr_31", "Mai_32", "Mai_33", "Jui_34", "Jui_35", "Jul_36", "Jul_37", "Aou_38",
        "Aou_39", "Sep_40", "Sep_41", "Oct_42", "Oct_43", "Nov_44", "Nov_45", "Dec_46", "Dec_47")

df$period_ap <- factor(df$periode_ap, levels=lev_periode_ap)

(2) Tell ggplot2 what to do with those levels.  Now that ggplot2 knows that df$periode_ap is ordinal, it can tell what is "highest", what is "lowest", and critically the order of all of those levels.  We need to indicate that we want all levels to be shown via scale_x_discrete(labels=...), but importantly, we want to be sure ggplot2 does not drop any levels where there is no data.  Lucky for us we can use the drop= argument for that. After a bit of theme() element changes, you get this:
ggplot(df, aes(x=period_ap,color=apport))+ theme_bw() +
  geom_density() +
  scale_x_discrete(labels=lev_periode_ap, drop=FALSE) +
  theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=1))

Now, seems we're missing enough datapoints to make showing the colors for "Min 1" and "Min 2" meaningful, but there's the answer to the question you posed.


text:
Q: How to stop socket.io emit from firing more then once I am currently working on making an rpg online using node.js and socket.io. Everything was working fine until I started making a collision detection system. I looked online for a solution and found people that had similar issues but could not understand how to fix my issue. The following is my code.
client side:
function move_character(x){
        //socket.io start
        var collision = io.connect('/collision');
        collision.emit('detection', x);
        collision.on('col', function (msg) {
            if(msg == true) {
                if (x == 'up') {
                    $('#sprite').animate({'top': '-=50px'},150);
                } else if (x == 'down') {
                    $('#sprite').animate({'top': '+=50px'},150);
                } else if (x == 'left') {
                    $('#sprite').animate({'left': '-=50px'},150);
                } else if (x == 'right') {
                    $('#sprite').animate({'left': '+=50px'},150);
                }
            }
        });
        //socket.io end
    }

server side:
var collision = io.of('/collision');
collision.on('connection', function (socket) {
    socket.on('detection', function (x) {
        pool.getConnection(function (err, con) {
            con.query('SELECT class_state FROM gmaps LIMIT 1',
                function (err, result) {
                    if (err) throw err;
                    else {
                        var mapState = result[0].class_state.split(",");
                        var x_coord = 6;
                        var y_coord = 5;

                        var id = ((y_cord -1)*10)+(x_cord -1);
                        var index;
                        if(x == 'up'){
                            index = id-10;
                        }else if(x == 'down'){
                            index = id+10;
                        }else if(x == 'left'){
                            index = id-1;
                        }else if(x == 'right'){
                            index = id+1;
                        }
                        collision.emit('col', true);
                    }
                    });
                con.release();
            });
    });
});

On the server side the emit is always sending true and the coordinates are at a fixed point, I did that to help with the debugging. You may also find code that is not being used right now and I will be using it in the future but I want to fix this bug first.
My actual problem is that when I move the character the 1st time, everything works but the 2nd move does the 1st again followed by the 2nd with the 3rd doing the 1st, 2nd then 3rd move. By the the time I have moved the sprite 10 times, it is repeating the 1st 9 steps before step 10 and it is going all over the screen.
I did try to find the solution myself by changing the code and adding console.log's everywhere. I found that if I emit [true,x] on the server side and fix the client side appropriately, the sprite will move in the direction I want but n number of time with n being the number of moves I tried (1 for 1st move, 4 for 4th move in the same direction). Refreshing does set everything back to normal as it should. I also tried moving io.connect('/collision') outside of the function but that did not work either. It seems the problem is the emit on the server side is keeping a history of past data that has been sent and then resending it each time a call is made. It could also be the collision.on on the client side that is causing the bug.
Also, on the server side, what it does is checks the DB if the tile in question is able to be moved on to, if yes then true and if not then false. It is set to true again because of the bug. When the bug is gone I will finish the server side code.

A: Your issue is that every time you call move_character(x), you create a new socket.io connection with it's associated event handlers.  So, the first time you call it, it connects and sets up an event handler, does the emit('detection', x), then sets up an event handler to listen for the response.
The second time you call move_character(x), you create another socket.io connection and do the same.  Now, when your server gets the message, it does some database work and then broadcasts the response to all connected sockets.  So, now that you have two socket.io connections in the same browser window, each connection gets the response and it gets processed multiple times.
The third time, you set up yet another and so on...

To fix, socket.io works best if you create one socket.io connection and then use it for all your communication to that namespace.  So, move the creation of the socket.io connection and the addition of the event handler outside of your move_character(x) function so it only happens once.
And on the server, I don't quite understand why you are broadcasting the response after your database work to ALL connected clients.  I would think you would want to respond to only the connection that sent the query.  You can do that by changing:
collision.emit('col', true);

to
socket.emit('col', true);


text:
Q: Find rows where they are "similar" and in which columns I'm quite new with SQL Server (2017) and i've this kind of need:
Consider this record:
╔═════════════╦═══════════════╦══════════════╦═══════╗
║   Surname   ║     Name      ║ Day of birth ║ City  ║
╠═════════════╬═══════════════╬══════════════╬═══════╣
║ Rivers Lara ║ Wanda Leticia ║ 07/04/1956   ║ Paris ║
╚═════════════╩═══════════════╩══════════════╩═══════╝

I've to find all the matching records in following list highlighting the type of matching:
╔═════════════╦═══════════════╦══════════════╦════════╗
║   Surname   ║     Name      ║ Day of birth ║  City  ║
╠═════════════╬═══════════════╬══════════════╬════════╣
║ Rivers Lara ║ Wanda Leticia ║ 07/04/1956   ║ London ║
║ Rivers      ║ Leticia       ║ 07/04/1956   ║ Rome   ║
║ Rivers      ║ Leticia       ║ 14/03/1995   ║ Rome   ║
║ Rivers Lara ║ Leticia       ║ 07/04/1956   ║ Paris  ║
║ Rivers Lara ║ Wanda Leticia ║ 08/07/1983   ║ Paris  ║
╚═════════════╩═══════════════╩══════════════╩════════╝

For example:
1st row is matching for Surname+Name+dayofbirth
2nd for Part of Surname+Part of Name+dayofbirth
3rd for Part of Surname+Part of Name
4th for Surname+Part of Name+dayofbirth+City
and so on...
Any ideas on how to approach this type of query will be appreciated considering also that at the moment we have fixed number of possible matching but in the future they could increase (maybe adding more columns like Tax number or other).

A: In addition to Andrew's comment, you can also approach it with a single self-join with an OR-linked condition to each column you want to check:
ON Col1=Col1
OR Col2=Col2
OR Col3=Col3
etc...

Then the extra column you want with the kind of matching would be a massive CASE expression with a WHEN..THEN for every possible combination that you would want to see in this column.
WHEN Col1=Col1 and Col2<>Col2 and Col3<>Col3 THEN 'Col1'
WHEN Col1=Col1 and Col2=Col2 and Col3<>Col3 THEN 'Col1, Col2'
etc...

In the above example, I am assuming none of the columns can contain NULL, but if they can you'll have to handle that in the logic as well.

A: assuming the presentation layer is html and your ok with bits of html in query output, this is a rough idea, though working it's not precisely efficient and no partial matches, only exact. to match partial you'll need to use charindex() or patindex() and split on ' ' with left() or right(), can get convoluted.
one split for left/right word is like, at least this is the way I do splitting still.
--this is only an example on the convoluted nature of string manipulation.
declare @Surname varchar(128) = 'Rivers Lara';
select
     rtrim(iif(charindex(' ',@Surname) = 0,@Surname,Left(@Surname, charindex(' ',@Surname)))) first_part_Surname
    ,ltrim(reverse(iif(charindex(' ',@Surname) = 0,reverse(@Surname),Left(reverse(@Surname), charindex(' ',reverse(@Surname)))))) last_part_Surname

declare @StartRed varchar(50) = ''
       ,@StopRed varchar(50) = '';
select
     case when tm.Surname = tr.Surname then @StartRed + tr.Surname + @StopRed else tr.Surname end Surname
    ,case when tm.Name = tr.Name then @StartRed + tr.Name  + @StopRed else tr.Name end [Name]
    ,case when tm.[Day of Birth] = tr.[Day of Birth] then @StartRed + convert(varchar, tr.[Day of Birth], 1) + @StopRed end [Day of Birth]
    ,case when tm.City = tr.City then @StartRed + tr.City + @StopRed else tr.City end City
from TableMatch tm
inner join TableRecords tr on (tm.Surname = tr.Surname or tm.Name = tr.Name)
    and (tm.[Day of Birth] = tr.[Day of Birth] or tm.City = tr.City)

-- requires either Surname or Name to match and at least 1 of the 2 others to match

additionally, you may be able to use soundex() to find names that sound like other names as a stop-gap without any manipulation. you can also Left() the soundex() value to get broader and broader matches, though you'll end up with all names that start with a the first letter if you goto left(soundex(name),1) matches.


text:
Q: What does the appending zero mean in a C assignment statement? I am writing to inquire a quick question regarding a wired C statement. The following statement is found in libgcrypt 1.7.3, line 680 of mpi/mpi-pow.c.
base_u_size |= (precomp_size[k] & ((mpi_size_t)0 - (k == e0)) );

So the appending 0 after mpi_size_t seems so wired to me. I also show the following assembly code sequence, which corresponds to this source code statement:
              mov    -0x138(%ebp),%eax
              mov    -0x48(%ebp,%eax,4),%edx
              mov    -0x138(%ebp),%eax
              cmp    -0x114(%ebp),%eax  <----- eax = k, -0x114(%ebp) = e0
              jne    80b84b2 <_gcry_mpi_powm+0xeee>
              mov    $0xffffffff,%eax
              jmp   80b84b7 <_gcry_mpi_powm+0xef3>
     80b84b2: mov    $0x0,%eax
     80b84b7: and    %edx,%eax

So somehow the 0 does not lead to any effect here?

A:
So the appending 0 after mpi_size_t

It's called type-casting.
By definition, integer constant values, are of type int. To make is explicitly of type mpi_size_t, you cast the value to the required type.

A: The 0 after mpi_size_t is for typecasting it (0) to the type mpi_size_t

A:
What does the appending zero mean in a C assignment statement?

base_u_size |= (precomp_size[k] & ((mpi_size_t)0 - (k == e0)) );

As well answer by @Sourav Ghosh, it casts the 0 to type mpi_size_t.

To answer why code performs the cast?
In mpi/mpi-pow.c, base_u_size is of type mpi_size_t.
To insure the right side of the assignment is done using at least the rank and width of mpi_size_t math and quiet warnings of mixed signed types.
By including a mpi_size_t on the right side, the subtraction and the & use a width that does not lose information.
With the types of the objects involved as here ( I do not have exactly what OP is using), it is likely to make no difference here.  base_u_size |= precomp_size[k] & -(k == e0); would have been fine - yet bring up persnickety warnings.
OP's code is a common idiom (do right hand math at least as wide as left size and strive for same signnesss) to prevent problems.