text:
Q: Power Source Switching (my first circuit) -- will I blow anything up?
This is my first post and first attempt at electronics and schematics so please go easy!
GOAL: power 1A @ 12v Netgear ethernet switch (in a remote location) from any (or all) of three power supplies, and to failover between them. There is no special requirements other than to keep the switch powered up. Other devices at the location already failover between the three power supplies.  I am trying to rig up the Netgear for redundancy as well.  There is no particular concern about which supply is used... just want continuous operation.
LOGIC: I am trying to come up with a better plan than two DPDT relays stacked. OR-ing would probably be even better but makes me nervous.  So I have designed the circuit below using P-MOSFETS thinking it might be a tiny bit safer to try to keep supplies somewhat isolated. (Is this a bit like being somewhat pregnant?)  Using IRF9540 p-channel MOSFETS circuit is intended to failover from lower to higher numbered supplies.  For example, when Supply1 is active it pulls up M2/M3 gates for Supply2 and Supply3 to disable them.  So only Supply1 will flow. And then Supply2 if enabled similarly disables Supply3.  I thought the logic of P-MOSFETS was most suitable because it hopefully will be simple to use +12v signal from one supply to gates of MOSFETS controlling the others will disable their current flow.
COMPONENTS: Any specific components mentioned are because they are already on hand. Open to other suggestions if any of these are inappropriate.  Working from starter kits of components from Amazon. Parts on hand:
MOSFETS, Component Starter Kit, Shottkey Diodes, and these pre-made MOSFET trigger boards.
DISCUSSION: All of this is because I'm too terrified to try straight OR-ing (does that simply require Schottky diodes on the positive before paralleling them?)  I don't know if I need the flyback diode (or even if I did that correctly) or many other things but just trying to be cautious. I am hoping this switching will "break before make" or that diodes will prevent any "bad things" from happening with switching.
TESTING: This seems to work as desired on the breadboard but I have not yet attempted with 3 independent power supplies.  I will fuse the power supplies just before input into my circuit. I plan to tie all the negatives together and I think they already share a common ground.
OTHER ALTERNATIVES: (1) OR-ing the 3 supplies together with a Schottky diode on each positive. (2) stack DPDT relays that would remain energized most of the time. If power fails on a supply, that de-energizes coils and fails over to remaining supplies. This seems to offer best isolation and switching time is not a problem.
Thanks in advance for your advice and comments.
FURTHER READING:

*

*How to protect circuits from reversed voltage polarity (YouTube)

*Fundamentals of power system ORing (EDN)

A: Answer
Introduction
The OP's question is a bit too broad, and involves a couple of engineering trade offs, cost/risk benefit analysis, and user constraints on knowledge/skills background, learning goal and project developing schedule etc.
Anyway, I suggest to eat the big elephant bite by bite, and I now start brainstorming bites randomly.
First, a reminder: I am a long winded guy and so it might take a long while for me to complete a TLDR answer.
Second, a warning: I am just a friendly hobbyist. No guarantee no nothing won't melt down or blow up.

For the impatient visitors, I would first give a very short, simple solution, which is actually originally proposed by @Russell McMahon and the OP himself.

Design Notes

*

*This circuit is very simple, but beautiful, using one power rectifying diode for each power supply unit (PSU)

*One disadvantage is that all PSUs must be switched on all the time.

*Another disadvantage is that all PSUs are supplying power at the same time.
/ to continue, ...

Discussion, Conclusion, and Suggestions
1. On flyback (freewheeling) diode and rectifying diodes
I recommend 1N5819 for flyback, because it is Schottky and therefore switches fast, with a low voltage drop.
I recommend 1N5408 for power rectification, because it is designed for power supply rectification. Comparing to 1N5819, it can handle larger current, but with larger voltage drop, and switches slower.
Having said that, both can be used for general purpose flyback and rectifying (Well, the marketing guys say so. :)).

2. On preference of PNP/NPN, NMOS/PMOS, Low/High Logical Trigger Level etc
Newbies usually prefer using a High level signal to switch on something, Low level to switch off something.  However, the professional EE guys developing industrial and consumer applications almost always prefer the opposite way, ie, Low level (active, trigger) to switch on or enable something; High level signal to switch off or disable something.  The main reason is electrical efficiency. Google for details.
/ to continue, ...
References
(1) 1N5819 Schottky Barrier Plastic Rectifier (free wheeling, polarity protection, 1A, 0.6V) - Vishay
(2) 1N5408 General Purpose Plastic Rectifier (power supply rectification, freewheeling, 3A, 1.2V) - Vishay
(3) Schottky Diode Forum Discussion - rpi.org.forum 2019
(4) Flyback Diode Selection Notes - rpi.org.forum 2019
(5) AliExpress Power Rectifying Diode Product Sheet
(6) Rpi freezes every now and then, how to fix it with a watchdog? - 2019jun14
(7) Futurlec Power MOSFET Catalog
(8) Vishay N-channel Power MOSFET Guide
(9) Vishay N-channel Power MOSFET (TO220) Catalog
(10) IRL540 N-channel Power MOSFET (100V, 20A, Vgs(th)2Vmax, easy parallel, on chip flyback) Datasheet - Vishay Siliconix
(11) Configuring Netgear Ethernet Switch using Raspberry Pi - Rpi SE 2020mar15
(12) Netgear Gigabit Ethernet Smart Managed Plus Switches Catalog
(13) NetGear GS105E — 5 Port Gigabit Ethernet Smart Managed Plus Switch
(14) Rules and guidelines for drawing good schematics - Community Wiki, EE SE, 2012
(15) Automotive reverse polarity protection - TI 2017apr17
(16) Fundamentals of Power System ORing - 2007 Martin Patoka, TI, 2007mar21
/ to continue, ...

Appendices
Appendix A - Manual / Auto switchable LM2956 / LM2941 PSU
(Ref) Rpi freezes every now and then, how to fix it with a watchdog? - 2019jun14

Appendix B - Ethernet Switch Power

Appendix C - Oring Three PSUs at High Side (5V PSU Example)
Notes
(1) The OP is ORing three 12V PSUs using P-type power MOSFETs. This preliminary design is using N-type power MOSFETs (with built in flash back diode) to OR three 5V PSUs.
(2) The three inputs will be used to switch on/off the PSUs.  For now, 7V (5V + Vgs(th) = 2V max) will switch on, 5V will switch off (need to shift down to perhaps 3V/0V)

Appendix D - Oring Three PSUs at Low Side (5V PSU Example)

/ to continue, ...

End of answer

A: This was more what I meant when I said top to bottom. I did not mean simply to flip everything upside down.

simulate this circuit – Schematic created using CircuitLab
That way you can trust that down is always a lower potential, and up is always a higher potential. You are allowed to cut out the supply symbol and use net names for this so there aren't loops where conventional current is flowing up (which is what happens when you use a supply symbol.)


text:
Q: How to mix PHP in HTML file When I use iframe in HTML file that linked to test.php .. the result is OK
Test.php :
<?php
   $host = "localhost";
   $user = "user";
   $pass = "pass";
   $database = "db";
   $koneksi = mysql_connect ($host,$user,$pass);

   mysql_select_db($database,$koneksi) or die ("error");

   $result = mysql_query("SELECT * FROM pengumuman");
   $i = 0;

   while($row = mysql_fetch_array($result)) {
        echo "
".$row['judul']."
";
        $i++;
   }

   mysql_close($koneksi);
?>

But I do want to separate this test.php, so I mixed it in  my HTML file
<?php
   $host = "localhost";
   $user = "user";
   $pass = "pass";
   $database = "db";
   $koneksi = mysql_connect ($host,$user,$pass);

   mysql_select_db($database,$koneksi) or die ("error");

   $result = mysql_query("SELECT * FROM pengumuman");
   $i = 0;

   while($row = mysql_fetch_array($result)) {
?>

<?php $row['judul'] ?>

<?php
        $i++;
   }
    mysql_close($koneksi);
?>

And the result not OK anymore!
Truly, I'm new in web prog .. Can anyone help me ?

A: This is not possible:
<?php
   while($row = mysql_fetch_array($result)) {
?>

<?php $row['judul'] ?>

<?php
        $i++;
   }
?>

But you can use the code below instead that:
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$database = "db";
$koneksi = mysql_connect($host,$user,$pass);

mysql_select_db($database,$koneksi) or die("error");

$result = mysql_query("SELECT * FROM pengumuman");
$i = 0;
?>

<?php
while($row = mysql_fetch_array($result)) {
    echo "
" . $row['judul'] . "
";
    $i++;
}
?>

<?php mysql_close($koneksi); ?>

But, I didn't check your PHP if it's right, for I'm chillin'.

I think this is want you want!
Create open.php:
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$database = "db";
$koneksi = mysql_connect($host,$user,$pass);

mysql_select_db($database,$koneksi) or die("error");

$result = mysql_query("SELECT * FROM pengumuman");
?>

Create close.php:
<?php mysql_close($koneksi); ?>

And the basename of your web page that included a PHP code must have a .php file extension, such like div.php because commonly, a PHP file must have a .php extension, but sometimes a web host server configured to allow a HTML file to read a PHP code, but it isn't normally. Let say your so called
 HTML is in the div.php file:
<?php include 'open.php'; ?>

<?php
$i = 0;

while($row = mysql_fetch_array($result)) {
    echo "
" . $row['judul'] . "
";
    $i++;
}
?>

<?php include 'close.php'; ?>

A: you probably meant to add an echo before $row['judul']
<?php echo $row['judul']; ?>

simply putting the variable will not output it. Maybe you were thinking of short notation that is disabled by default

A: There are two things you have to take care in this case.
1) Add an echo before $row['judul']
<?php echo $row['judul']; ?>

2) Make sure that the extension of your file is '.php', if your file is test.html then change it to test.php and try.
NB: If you don't want to change your file extension, you must change some server configurations for handling files with .html files. In apache you can achieve this by adding 'AddHandler' in httpd.conf file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Area between two curves, which curve is on top? Given a question like this:
Find the area between ${y = x^2 + 2x - 3}$ and ${y = 2x^2 -5x  -3}$.
I know how to find the area ${\int y_1 - y_2}$ but how can I tell which one is the top curve?  Are there any shortcuts to determining the top curve?

A: First find the points of intersection
$$x^2+2x-3=2x^2-5x-3$$
$$x(x+2)=x(2x-5)$$
$x=0$ or $x+2=2x-5$
$x=0$ or $x=7$
As the curves are continuous, the simplest way is to take any point between $0$ and $7$ and find for which the value of $y$ is greater.
If the curves intersect more than twice, do this for every two consecutive points of intersection.
And finally, it does not matter much, when you are finding between two points with constant value (and if the functions don't intersect more than twice). If you get the order wrong, all that happens is that you get the negative of the actual answer. Taking the modulus will give you the area.

A: Assuming you work only with polynomials and they don't intersect here is a little shortcut:
Find the highest exponent, that is different for both polynomials. The one, with the higher coefficient is on top.


text:
Q: How should I access the underlying entity/model of a ViewModel We're designing a WPF / MVVM application that allows the user to search and manipulate contact records.
We have a MainViewModel that contains an observable collection of ContactViewModel objects, each one of which wraps a Contact entity returned from our business layer. The UI displays these in a list, with the SelectedItem property bound to a corresponding SelectedContact property on the MainViewModel.
We'll also have a button or something where the command is bound to a 'ProcessContact' ICommand exposed by MainViewModel.
ProcessContact needs to takes the selected contact and do something with it, it doesn't really matter what.
My question is: What would be the correct way of getting at the underlying Contact object wrapped by the selected ContactViewModel? I could just expose a Contact property on my view model, but that then means the view could potentially bind to properties directly off the model.
I've found myself passing ViewModel instances around a lot, which feels wrong when what I really want is the entity it's wrapping.
Am I missing something obvious?
Edit: A couple of suggestions thrown around by colleagues:

*

*Expose the entity as a protected property on the ViewModel, which would stop the view binding to it (assuming the view classes are in a separate assembly)

*Stop trying to access the model altogether. If we want to process the underlying entity in some way, we call a method on the ViewModel. In my example we might have a .Process method off ContactViewModel. ( 'SelectedContact.Process()' )
The second option feels like a better solution to me, but not sure if we should be putting that much logic into the ViewModel (but if not there, then where?)

A: Your second suggestion seems more correct to me. I usually wrap my data in a view model which is like a controller anyway... It should be controlling what happens to your data by the user's actions in the view. So i would go with wrapping your data and then attach the appropriate behaviors to your view model. I don't know why you would be worried about adding too much logic to your view model, that is its job!

A: I would suggest to have an observable collection of Contact objects in your MainViewModel. Framework will automatically support the change notification for entity properties and you don't even ned to implement INotifyPropertyChanged in your entity.
In case you have any specific reason for wrapping your Contact entity in viewmodel(I am curious to know them) you will have to expose the Contact object(through a property
) and use it.

A: Do not wrap your Model inside your ViewModel. Atleast do not expose it as a public property.
You can make your Presenter an observer of the Model so that it gets notified when the Model changes. Your Presenter can then call the View and pass it the ViewModel.


text:
Q: What are the main differences between the ed and the ex editor? The ex editor is often touted as an enhancement and simplification of ed. I would like to know what specific enhancements and simplifications it offers. GNU ed, for example, offers extended regular expressions. So, besides these, what advantages come with ex? I am thinking specifically of the original ex editor by Bill Joy, not later incarnations in Vim.

A: As a very rough first approximation we can say that ed doesn't show what has been modified (until asked to print) and ex could (additionally) work as a full screen editor. Using a very old description from the the posix spec:

*

*ed

The ed utility is a line-oriented text editor that uses two modes: command mode and input mode. In command mode the input characters shall be interpreted as commands, and in input mode they shall be interpreted as text.

*

*ex

The ex utility is a line-oriented text editor. There are two other modes of the editor-open and visual-in which screen-oriented editing is available.

Both programs have been extended, modified and improved over the years and now the list of differences is much longer and impossible to fully list on a short answer of this site.
That full-screen capability has lead to the development of vi (a visual editor), and then to vim (visual improved).


text:
Q: Alpha correction in a family of tests Suppose that one runs 8 correlation analyses but in two separate batches: Would the alpha-correction apply to all 8 tests as a family or each of the 4 tests as a family?
For example, if there are two research questions and both require correlation analysis, the researcher conducts the first 4 tests (for research question 1) and then conducts the second 4 tests (for research question 2).
In this case, should the alpha be corrected for a family of 4 tests or for a family of 8 tests?
(Note that the same statistical test--Pearson's $r$--is used in both cases.)
I understand there isn't a consensus on this matter (as with many other matters in statistics as I am learning fast!) but some broad guidelines would be most helpful.

A: I'd say that it depends on your research questions. Are the two research questions related to the same data set? Are they completely independent from eachother? Would a false negative be worse than a false positive for either of these questions? If you have jellybeans type questions, correct for all of them. If your first question is about the link between smoking and cancer and your second question is about the link between a father's length and his son's length, correct for 4 in each batch. If you're somewhere in between, I don't think that there is a "right answer" to this.
You could correct for all 8 tests. But then again, you could correct for all 400 tests that you run this year, to get at most a 5 % (say) risk of making a type I error in 2012. You have to draw the line somewhere...
Also, as you run multiple correlation tests, it sounds like you might have multivariate data. Have you considered using some multivariate generalization of Pearson's correlation coefficient, such as canonical correlations?


text:
Q: Google Analytics Add On in Google Spreadsheet Giving Server Error Message This morning on 7/12/2018, when I was running my daily Analytics report using Google Analytics Add On in Google Spreadsheet, I got this message: "Exception: We're sorry, a server error occurred. Please wait a bit and try again." Anybody seeing this message, I am seeing it for the first time. Tried to run the reports intermittently, still getting the same error. Want to know if its a system wide problem or is there anything off with my setting, which I have not changed at all.

A: It's happening to me as well, as of this afternoon.


text:
Q: Haskell duplicate element at certain position I want to duplicate the n-th elemnt of a list and my knowledge of haskell is very limited.
I tried splitting the list in two parts, then getting the last element of the first part and just pasting it between those parts:
dupl n (x:xs) = (take n (x:xs)) ++ ( (x:xs) !! n) ++ (drop n (x:xs))

But I always get the error:
Prelude> :l f.hs
[1 of 1] Compiling Main             ( f.hs, interpreted )

f.hs:5:39:
   Occurs check: cannot construct the infinite type: a0 = [a0]
   In the first argument of `(:)', namely `x'
   In the first argument of `(!!)', namely `(x : xs)'
   In the first argument of `(++)', namely `((x : xs) !! n)'
Failed, modules loaded: none.

Could someone tell me what I am doing wrong?

A: list !! n returns a list element, not a list. ++ can only concatenate lists; you can't add a list element to a list with ++.
To put it more formally, !! has a type of:
(!!) :: [a] -> Int -> a

which means that it accepts a list of as and an Int, and returns an a. ++, on the other hand, has a type of:
(++) :: [a] -> [a] -> [a]

which means that it accepts two lists of as and returns a new list of as. So you can see that ++ accepts lists, but !! doesn't return lists, so you're not allowed to chain them together like that.

How do we fix this? You need to put the element list !! n into a list, in order to concatenate it to the other two lists without the type checker throwing a hissy fit.
This should do the trick:
dupl n l = (take n l) ++ [l !! n] ++ (drop n l)

Equivalently, add the chosen element to the right-hand list, and concatenate that to the other half of the original list:
dupl n l = (take n l) ++ ((l !! n):(drop n l))

Caveat lector: both of the above functions, unlike @Marimuthu's suggestion, will raise an exception if n is an out-of-bounds index. The exception comes from !!.

A: Caveat emptor if you pick a bad index, but—
dupN n xs = let (first, x:rest) = splitAt (n-1) xs in first ++ x:x:rest

A: You can also use splitAt:
dupl n xs = first ++ take 1 rest ++ rest where (first, rest) = splitAt (n - 1) xs

This will not break if n is out of bounds.


text:
Q: MySql Form query for filters or Ignore WHERE clause for column value in NodeJS I'm trying to fetch a user list where gender, region, and status are the mandatory filters in my app. Filtering works fine when gender is either 0 or 1. The problem is when I need both. Scenario is same for all 3 filters.
API: https://website.com/api/getUsers?gender=0&region=1&status=1 to get filter results.
APPROACH 1: I want to pass something for those api params for eg. gender=#$%, so that it ignores its WHERE clause when passing it on queryInputs below.
module.exports.getMatches = ({offset, gender, status, region}, callback) => {
var dbQuery = 'SELECT * from `users` WHERE `gender` = ? AND `status` = ? AND `region` = ? LIMIT ? OFFSET ?';
var queryInputs = [parseInt(gender), parseInt(status), parseInt(region), 10, parseInt(offset)];

db.query(dbQuery, queryInputs, function(err, result) {
    //code goes here
});
}

APPROACH 2: I'm passing empty params to validate to fetch all data for particular filters for eg. https://website.com/api/getUsers?gender=&region=1&status=
I'm trying to avoid WHERE clause if I pass empty params in api. This almost worked for me if it weren't for last AND before LIMIT in the query.
module.exports.getMatches = ({offset, gender, status, region}, callback) => {
var dbQuery = 'SELECT * from `users`';
if( gender != '' || status!= '' || region != '') dbQuery += ' WHERE'
if(gender != ''){
    dbQuery += ' `gender` = '+ db.escape(parseInt(gender))+' AND';
}
if(status != ''){
    dbQuery += ' `status` = '+ db.escape(parseInt(status))+' AND';
}
if(region != ''){
    dbQuery += ' `region` = '+ db.escape(parseInt(region))+' AND';
}
dbQuery += ' LIMIT 10 OFFSET ' + db.escape(parseInt(offset));

db.query(dbQuery, queryInputs, function(err, result) {
    //code goes here
});
}

Among these two Approches solution for anyone works for me.

A: Here is an edit for your second approach. This should allow you to put "AND" before your query additions so you avoid your stated error.
module.exports.getMatches = ({offset, gender, status, region}, callback) => {
var dbQuery = 'SELECT * from `users` WHERE 1=1 ';
//if( gender != '' || status!= '' || region != '') dbQuery += ' WHERE'
if(gender != ''){
    dbQuery += 'AND `gender` = '+ db.escape(parseInt(gender));
}
if(status != ''){
    dbQuery += 'AND `status` = '+ db.escape(parseInt(status));
}
if(region != ''){
    dbQuery += 'AND `region` = '+ db.escape(parseInt(region));
}
dbQuery += ' LIMIT 10 OFFSET ' + db.escape(parseInt(offset));

db.query(dbQuery, queryInputs, function(err, result) {
    //code goes here
});
}

A: as per best practices, if you want to fetch all the users, you may follow the approach given below:
1: Create a new API (/allUsers) with pagination obviously and create a separate SQL statement for this API, where you don't need to add a filter clause.
OR
2: Add a validation check in existing API, if there is no param then don't apply filters otherwise apply as usual.


text:
Q: _.cloneDeep is not a function? I am working on one small JavaScript, jQuery project. It is Tic Tac Toe game. I want the computer to play hard against the human. For that sake, I used minmix function, which is a very popular function for a game I think.
Here is my HTML code

Tic Tac Toe Game

            <button id="restart">Restart</button>

I am using very long process, but I will add the minmax function here.
function minmax(newGrid, depth, player) {
  const gameState= gameOver(newGrid);

  if (gameState === false){
    const values= [];

    for (var i=0; i<3; i++) {
      for (var j = 0; j<3;j++){
        const gridCopy = _.cloneDeep(newGrid);
        if (gridCopy[i][j]!=='') continue;
        gridCopy[i][j]=player;
        const value = minmax(gridCopy,depth+1,(player===PLAYER_TOKEN)?COMPUTER_TOKEN:PLAYER_TOKEN);
        values.push({
        cost:value,
      cell: {
        i:i,
        j:j
      }
    });
      }
    }

    if (player === COMPUTER_TOKEN) {
      const max = _.maxBy(values, (v) => {
        return v.cost;
      });
      if (depth === 0) {
        return max.cell;
      }
      else {
        return max.cost;
      }
    }
    else {
      const min = _.minBy(values, (v) => {
        return v.cost;
      });
      if (depth === 0) {
        return min.cell;
      }
      else {
        return min.cost;
      }
    }
  }
  else if (gameState === null){
    return 0;
  }
  else if (gameState===PLAYER_TOKEN) {
    return depth - 10;
  }
  else if (gameState===COMPUTER) {
    return 10 - depth;
  }
}

function computerMove(){
  return minmax(grid,0,COMPUTER_TOKEN);
}

I am getting an error in the console, which I do not understand.
Uncaught TypeError: _.cloneDeep is not a function

I added Underscore JS also but not working


text:
Q: Selecting posts from wordpress db with thumbnail or intro images I have been trying to fetch posts from a wordpress site's mysql db to my own script for a few days.
<?php

 $querystr = "
    SELECT DISTINCT $wpdb->posts.*
    FROM $wpdb->posts, $wpdb->postmeta
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
    AND $wpdb->postmeta.meta_key = 'tag'
    AND $wpdb->postmeta.meta_value = 'email'
    AND $wpdb->posts.post_status = 'publish'
    AND $wpdb->posts.post_type = 'post'
    AND $wpdb->posts.post_date < NOW()
    ORDER BY $wpdb->posts.post_date DESC
 ";

 $pageposts = $wpdb->get_results($querystr, OBJECT);

 ?>

I can see thumbnail images on the original site but I could not figure out where to get that image location data in the db.
What would be the enhancements on my query in order to have image information with current ones?

A: You need to dive into your wp_postmeta table. This is where you will find everything. You can get the thumbnail ID with the following query:
SELECT * FROM 'wp_postmeta' WHERE post_id=**ID_HERE** AND meta_key='_thumbnail_id'

You will get a thumbnail ID from which you will be able to get your real thumbnail with the following query:
SELECT * FROM 'wp_postmeta' WHERE post_id=**PREVIOUSLY_OBTAINED_ID**

This will actually give you two rows :

*

*One for the URL of your image (meta_key="_wp_attached_file")

*One for the image info like its dimensions, its title etc... (meta_key="_wp_attachment_metadata")

A: Try this code:
<?php echo get_the_post_thumbnail($page->ID, 'thumbnail'); ?>

More details here: http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail


text:
Q: How to make ng-if to interrupt css transition I have 2 buttons which substitute each other regarding to its ng-if context. (like button A will show if VAR is true, and button B otherwise)
My problem is, since these buttons have been applied with css-transitions (actually only their background-color properties)
When I changed VAR from true to false, the button did not disappear suddenly.
And when I removed the css-transitions, the problem disappeared.
I would like to keep the css-transitions.
Anyone can suggest me a way to solve this ?


text:
Q: Get the dynamic alloccated port of a IPEndPoint How is it possible to get the dynamically assigned port of a IPEndPoint, when you create it with 0 as port:
var endpoint = new IPEndPoint(Dns.GetHostAddresses(localhost).FirstOrDefault(), 0);

If I look at the endpoint.Port, it is 0 (any), even tho the underlaying Socket must have an designated port already?

A: FYI:
Socket.RemoteEndPoint
Socket.LocalEndPoint


text:
Q: How to determine if MySQL install is Community or Enterprise without root password? I have taken over a production Linux RHEL server which has a MySQL install on it. I need to find out which version of MySql is installed.
Apparently this is easy information to determine which it says here on mysql.com but unfortunately no one can remember the root password and no one knows what version of MySQL it is.
I am assuming it is Enterprise but I need to know for sure.
I tried 2 different commands:
mysql --version

Output:
mysql  Ver 14.14 Distrib 5.6.13, for Linux (x86_64) using  EditLine wrapper

and
file /usr/sbin/mysqld

Output:
/usr/sbin/mysqld: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, not stripped

Both of these commands provided me with useful information but I still need to figure out if the server has the Community or Enterprise edition.

A: No , you can't. You need to login to mysql to get this info.
Can use commands like,
SHOW VARIABLES LIKE "%version%";

A: You can get the details using status command in the mysql command prompt. Don't use the windows cmd prompt to execute the command.
mysql > Status


text:
Q: Demonstrate an inequality $|(x+y+z+a^2xyz)|\ /\ |1+a^2(xy+xz+yz)|<1/a$ For $a>0, x,y,z\in\mathbb{R}$
$$|x|<a,\ |y|<a, \ |z|<a$$
Demonstrate this inequality:
$$\frac{|(x+y+z+a^2xyz)|}{|1+a^2(xy+xz+yz)|}<{1\over a}$$

A: The inequality cannot be demonstrated, because there are counter-examples: For $x=1$, $y=0$, $z=0$, and all $a > 1$, we have
$$\frac{|(x+y+z+a^2xyz)|}{|1+a^2(xy+xz+yz)|} = 1 > \frac{1}{a} \cdot $$


text:
Q: Adding/removing classes with jquery I am trying to change the font size of a webpage. I have specified three sizes:

*

*Small

*Medium

*Large

Based on what the user clicks the html font size should become the size he chooses.
#small, #med, #large are three paragraph elements.
medium, small, large are three classes for CSS.
My code is:
enter code here

<script>
                $(document).ready(function(){
                    $("#small").click(function(){
                        if($("p").hasClass('large'))
                        {
                         $("p").removeClass("large").addClass("small");
                        }
                        else
                        {
                            $("p").removeClass("medium").addClass("small");
                        }
                        });
                    $("#med").click(function(){
                        if($("p").hasClass('small'))
                        {
                            $("p").removeClass("small").addClass("medium");

                        }
                        else
                        {
                            $("p").removeClass("large").addClass("medium");
                        }

                    });

                    $("#large").click(function(){
                        if($("p").hasClass('small'))
                        {
                            $("p").removeClass("small").addClass("large");
                        }
                        else
                        {
                            $("p").removeClass("medium").addClass("large");
                        }

                    });

                });
            </script>

I don't think its working perfectly. So if anyone could show where i am going wrong will be of great help.

A: You are a bit verbose, for each click there is no need for any decision, you always have to remove any of the other two classes and add the one from the button you pressed
$(document).ready(function(){
    $("#small").click(function(){
        $("p").removeClass("medium").removeClass("large").addClass("small");
    });
    $("#med").click(function(){
        $("p").removeClass("small").removeClass("large").addClass("medium");
    });
    $("#large").click(function(){
        $("p").removeClass("small").removeClass("medium").addClass("large");
    });
});

You could probably "compress" that further by using the id as a variable using something like the following (note that the click-able element is "#med" and the class is "medium", so that would need additional work)
$(document).ready(function(){
    $("#small,#med,#large").click(function(this){
        $("p").removeClass().addClass($(this).attr("id"));
    });
});

A: A bit more compact way would be to combime the classes as below:
$(document).ready(function(){
    $("#small").click(function(){
        $("p").removeClass("medium large").addClass("small");
    });
    $("#med").click(function(){
        $("p").removeClass("small large").addClass("medium");
    });

    $("#large").click(function(){
        $("p").removeClass("small medium").addClass("large");
    });
});


text:
Q: mysql list in one column result of another select I have a very huge table where I need to find duplicate rows. In order to find them I run:
SELECT firstcolumn, count(*) AS c FROM invoice GROUP BY firstcolumn HAVING c > 1 ORDER BY c DESC

This works as expected: I get a table with firstcolumn in one column and the  total number of rows that holds firstcolumn's duplicate value.
Now, I need to add a new column to this result table: a new column "ids" which lists all the ids of the rows that have the same firstcolumn's value. So for instance, if my original table has 3 rows with the same  firstcolumn value (eg. "somerandomstring") and this 3 rows have 11,32,356 as ids, I should end up with a result table like this:
"somerandomstring",3,"11,32,356"

So, how can I modify my  query so that I  can have the list of ids in my third column ?
I tried modifying my query as such:
SELECT firstcolumn, count(*) AS c, (SELECT secondid FROM invoice AS so WHERE so.firstcolumn = si.firstcolumn) AS secondcolumn
FROM invoice AS si
WHERE firstcolumn != ""
GROUP BY firstcolumn HAVING c > 1 ORDER BY c DESC

but it doesn't work. No error  appear and the query just keeps loading

A: GROUP_CONCAT to the rescue:
SELECT firstcolumn,
       count(*) AS c,
       group_concat(secondid) as ids
FROM invoice AS si
WHERE firstcolumn != ""
GROUP BY firstcolumn
HAVING c > 1
ORDER BY c DESC


text:
Q: Is there a way to fetch data from sqlite3 database into list using python more efficiently? I have a list of words (100k+ elements). In database each word has corresponding id. I want to get these id-s into list as well.
I'm using following function, but it is very slow:
def fetch_id(word_list, cursor):

   for word in word_list:
       cursor.execute('SELECT id FROM entries_table WHERE word = ?',(word,))
   data = cursor.fetchone()
   if data is not None:
       return data[0]
   else: return None

Is there a way to make function faster?

A: cursor.execute("SELECT id FROM entries_table WHERE word in {}".format(str(tuple(word_list))))


text:
Q: Wii Fit Plus: any way to choose which pet belongs to which person? In Wii Fit Plus I have two Miis and two pets. For some reason it binds the "wrong" pet to the "wrong" Mii. Essentially I'm playing with my girlfriend's dog, and she's playing with mine.
Is there anything I can do about this?

A: After playing the game for a few weeks, I am under the strong impression that it is not possible.


text:
Q: Cross field validation in jsf h:datatable using p:calendar I noticed this question was asked, but it has not been answered correctly.
I have a datatable that has two columns start date and end date. Both contain primefaces p:calendar controls in them. I need to ensure that for each row that the date in column1 is not after the date in column2. I would like to tie this into the JSF validation framework, but I'm having trouble.
i've tried marking the datatable  rowStatePreserved="true" , this allows me to get the values, but something is still wrong as when it fails, all the values in the first row overwrite all the other values. What am I doing wrong, or should I be using a completely different strategy?
xhtml code
    <h:form>
 <f:event type="postValidate" listener="#{bean.doCrossFieldValidation}"/>
       <p:dataTable id="eventDaysTable" value="#{course.courseSchedules}" var="_eventDay" styleClass="compactDataTable"
                                 >
                        <p:column id="eventDayStartColumn">
                            <f:facet name="header">
                                Start
                            </f:facet>
                            <p:calendar id="startDate" required="true"  value="#{_eventDay.startTime}" pattern="MM/dd/yyyy hh:mm a"/>
                        </p:column>
                        <p:column id="eventDayEndColumn">
                            <f:facet name="header">
                                End
                            </f:facet>
                            <p:calendar id="endDate" required="true"  value="#{_eventDay.endTime}" pattern="MM/dd/yyyy hh:mm a"/>
                        </p:column>
                    </p:dataTable>
        </h:form>

validationCode
 public void doCrossFieldValidation(ComponentSystemEvent cse) {

        UIData eventsDaysStable = (UIData) cse.getComponent().findComponent("eventDaysTable");

        if (null != eventsDaysStable && eventsDaysStable.isRendered()) {

            Iterator<UIComponent> startDateCalendarIterator = eventsDaysStable.findComponent("eventDayStartColumn").getChildren().iterator();
            Iterator<UIComponent> endDateCalendarIterator = eventsDaysStable.findComponent("eventDayEndColumn").getChildren().iterator();

            while (startDateCalendarIterator.hasNext() && endDateCalendarIterator.hasNext()) {
                org.primefaces.component.calendar.Calendar startDateComponent = (org.primefaces.component.calendar.Calendar) startDateCalendarIterator.next();
                org.primefaces.component.calendar.Calendar endDateComponent = (org.primefaces.component.calendar.Calendar) endDateCalendarIterator.next();

                Date startDate = (Date) startDateComponent.getValue();
                Date endDate = (Date) endDateComponent.getValue();

                if (null != startDate && null != endDate && startDate.after(endDate)) {
                    eventScheduleChronologyOk = false;
                    startDateComponent.setValid(false);
                    endDateComponent.setValid(false);
                }

            }

            if (!eventScheduleChronologyOk) {
                showErrorMessage(ProductManagementMessage.PRODUCT_SCHEDULE_OUT_OF_ORDER);
            }

        }

    }

A:
What am I doing wrong

Performing validation outside the context of the datatable in a non-standard JSF way. The row data is only available while you're (or JSF is) iterating over the datatable. There's physically only one <p:calendar> component in every column which has multiple different states depending on the current datatable iteration round. Those states are not available when you're not iterating over the datatable. You'll only get null as value then.
Technically, with your different validation approach so far, you should be invoking visitTree() method on the UIData component and performing the job in the VisitCallback implementation. This will iterate over the datatable.
For example,
dataTable.visitTree(VisitContext.createVisitContext(), new VisitCallback() {
    @Override
    public VisitResult visit(VisitContext context, UIComponent component) {
        // Check if component is instance of <p:calendar> and collect its value by its ID.

        return VisitResult.ACCEPT;
    }
});

This is only clumsy. This gives you every single row, you'd need to maintain and check the row index youself and collect the values. Note that calling UIInput#setValid() should also be done inside the VisitCallback implementation.

or should I be using a completely different strategy?

Yes, use a normal Validator the standard JSF way. You can pass the one component as an attribute of the other component.
E.g.
<p:column>
    <p:calendar binding="#{startDateComponent}" id="startDate" required="true"  value="#{item.start}" pattern="MM/dd/yyyy hh:mm a"/>
</p:column>
<p:column >
    <p:calendar id="endDate" required="true"  value="#{item.end}" pattern="MM/dd/yyyy hh:mm a">
        <f:validator validatorId="dateRangeValidator" />
        <f:attribute name="startDateComponent" value="#{startDateComponent}" />
    </p:calendar>
</p:column>

with
@FacesValidator("dateRangeValidator")
public class DateRangeValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (value == null) {
            return; // Let required="true" handle.
        }

        UIInput startDateComponent = (UIInput) component.getAttributes().get("startDateComponent");

        if (!startDateComponent.isValid()) {
            return; // Already invalidated. Don't care about it then.
        }

        Date startDate = (Date) startDateComponent.getValue();

        if (startDate == null) {
            return; // Let required="true" handle.
        }

        Date endDate = (Date) value;

        if (startDate.after(endDate)) {
            startDateComponent.setValid(false);
            throw new ValidatorException(new FacesMessage(
                FacesMessage.SEVERITY_ERROR, "Start date may not be after end date.", null));
        }
    }

}

As both components are in the same row, the startDateComponent will "automagically" give the right value back on getValue() everytime this validator is invoked. Note that this validator is also reuseable outside the datatable while your initial approach isn't.
Alternatively, you can use OmniFaces <o:validateOrder> as a complete solution. Its showcase example even shows off this specific use case of <p:calendar> components inside a <p:dataTable>.


text:
Q: Number of series of this form whose product is 2 $I_n$ is the $n^\text{th}$ member of the series $I$ of length $k$. The first member of the series is of the form $2^\frac{m}{12}\mid m\in\Bbb Z\text{ and } 0\le m\le12$. If $k$ is larger than $1$ and $m$ for the first member is odd, the last member of the series will also follow that form. The rest of the members, if there are any, are of the form $2^\frac{2m}{12}\mid m\in\Bbb Z\text{ and } 0 < m\le6$. How many series are there that the following holds true?
$$\prod_{n=1}^k I_n = 2$$
The insight into this starts with auditory frequencies. If we have a 'root' frequency, $f$, its octave is $2f$. In music theory, we divide the octave into twelve notes, and the logarithmic nature of sound frequencies means that each interval between adjacent notes, or each 'semitone', is $2^\frac{1}{12}$. So if you want to move $m$ semitones, the interval is $2^\frac{m}{12}$. I want to know the number of symmetrical scales available in this tuning system. Our point of symmetry is the tritone, $\sqrt{2}$. For our purposes, we will notate this as $2^\frac{6}{12}$.
For the visualization, I see each interval as being divided in half. One half will climb from the tritone up to the octave while the other half will climb down to the root. If our first interval is an even number of semitones, it can easily be divided in half. However, if it is an odd number, we will need one more interval of an odd number of semitones to compensate. This is why the last member of the series is specified as being of the same form. It must compensate if we have an odd first interval. From there on, all intervals will be doubled, one interval traveling down towards the root and one up towards the octave.
That is why the rest of the series members are the way they are. A member representing $2m$ semitones is actually representing $m$ upwards and $m$ downwards. So if there are any ways that this can be made more clear to the mathematically-minded, please let me know and if not, then I believe this is a relatively simple combinatorics problem. I just don't know enough about it to do it myself.

A: Following Arthur's comment, you are looking for sequences $m_1,\ldots, m_k$ where all $m_n$ are $\in\{1,\ldots,6\}$ except $m_1,m_k\in\{0,\ldots,12\}$, and $m_1+2m_2+\ldots+2m_{k-1}+m_k=12$.
Via $(m_1,m_2,\ldots, m_k)\mapsto (m_1-1,m_2,\ldots,m_k+1)$, the solutions with odd start/end are in bijection with the purely even solutions.
The even solutions with all numbers positive are counted by a simple stars-and-bars argument: There are $2^5$ ways to write $6$ as sum of natural numbers.
If we account for solutions with possibly an initial and/or terminal $0$, we arrive at $4\cdot 2^5$ purely even solutions, hence a total of $2\cdot 4\cdot 2^5=256$ solutions in total.


text:
Q: Change language from an activity that reflects in previously created activities as well I am using two buttons to change the language in my app. There are two activities and both of them have the language changing buttons.
The problem is that when I move to the second activity from the first then change the language the first one is still in the old language. The onCreate is not called since it was not killed.
I am going to make more activities as well, I do not want to finish and start acitivities while moving within the app to call the onCreate. How do change the language without having to recreate the activity

A: You can try calling onConfigurationChanged "manually" from your activity:
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = newLocale;
res.updateConfiguration(conf, dm);
onConfigurationChanged(conf);

Also declare in AndroidManifest for your activity:
android:configChanges="locale"


text:
Q: Wifi freezes on ubuntu 16.04 My wifi freezes randomly on Ubuntu 16.04. It recovers either on reconnect or by restarting the iwlwifi, i.e.
sudo modprobe -r iwlwifi && sudo modprobe iwlwifi

Depending on the position of starts it might freeze again after a random period from a couple of seconds to hours.
sudo dmesg | grep wifi

gives
[   11.998788] iwlwifi 0000:08:00.0: loaded firmware version 29.1044073957.0 op_mode iwlmvm
[   12.138269] iwlwifi 0000:08:00.0: Detected Intel(R) Dual Band Wireless AC 7265, REV=0x210
[   12.158953] iwlwifi 0000:08:00.0: base HW address: 5c:e0:c5:40:7e:d2
[   15.407862] iwlwifi 0000:08:00.0 wlp8s0: renamed from wlan0
[  336.819378] iwlwifi 0000:08:00.0: loaded firmware version 29.1044073957.0 op_mode iwlmvm
[  336.845631] iwlwifi 0000:08:00.0: Detected Intel(R) Dual Band Wireless AC 7265, REV=0x210
[  336.872297] iwlwifi 0000:08:00.0: base HW address: 5c:e0:c5:40:7e:d2
[  336.943626] iwlwifi 0000:08:00.0 wlp8s0: renamed from wlan0
[ 1101.338499] iwlwifi: unknown parameter 'wd_disable' ignored
[ 1101.341003] iwlwifi 0000:08:00.0: loaded firmware version 29.1044073957.0 op_mode iwlmvm
[ 1101.359871] iwlwifi 0000:08:00.0: Detected Intel(R) Dual Band Wireless AC 7265, REV=0x210
[ 1101.384760] iwlwifi 0000:08:00.0: base HW address: 5c:e0:c5:40:7e:d2
[ 1101.453981] iwlwifi 0000:08:00.0 wlp8s0: renamed from wlan0

I tried to track /var/log/kern.log and /var/log/syslog to see if a specific message is printed before freezing however nothing was printed related to wifi. I disabled Ipv6 for my wifi connection. I also modified my /etc/modprobe.d/iwlwifi.conf so now it looks like
# /etc/modprobe.d/iwlwifi.conf
# iwlwifi will dyamically load either iwldvm or iwlmvm depending on the
# microcode file installed on the system.  When removing iwlwifi, first
# remove the iwl?vm module and then iwlwifi.
remove iwlwifi \
(/sbin/lsmod | grep -o -e ^iwlmvm -e ^iwldvm -e ^iwlwifi | xargs /sbin/rmmod) \
&& /sbin/modprobe -r mac80211

options iwlwifi 11n_disable=1
options iwlwifi wd_disable=1
options iwlwifi 11n_disable=8

with various combinations of the last 3 lines commented.
Hardware: HP Envy m6 laptop
OS: Ubuntu 16.04
UPD: The problem disappears when I turn off the bluetooth.

A: If this problem disappears after you disable bluetooth, I think this can be solved by turning of bluetooth coexistence.
Run in a terminal
sudo tee /etc/modprobe.d/iwlwifi-opt.conf <<< "options iwlwifi bt_coex_active=N"

and reboot.


text:
Q: Как вывести значение по id из базы данных django мне нужно, чтобы при нажатии на кнопку найти у меня открывался пдф файл, по id из бд(id вводится по input) попробовал сделать через js но не работает, подскажите как сделать?

let a
btn.onclick = function(e) {
    e.preventDefault();
    document.getElementById('form').style.display = 'none'
    document.getElementById('pdf').style.display = 'block'
    a = document.getElementById('floatingInput').value
}
html,
body {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #f5f5f5;
}

.form-signin {
  max-width: 330px;
  padding: 15px;
}

.form-signin .form-floating:focus-within {
  z-index: 2;
}

.form-signin input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

.img-block {
  display: flex;
  justify-content: center;
  justify-items: center;
  align-items: center;
  width: 250px;
  height: 150px;
}

.logo {
  height: 100%;
  width: auto;
}
{% load static %}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.104.2">
    <link rel="canonical" href="https://getbootstrap.com/docs/5.2/examples/sign-in/">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <link href="{% static 'css/style.css' %}" rel="stylesheet">

    <link href="{% static 'css/style.css' %}" rel="stylesheet">

<embed src="{{  }}" class="pdf" id="pdf"/>

    <form id="form" action="" method="POST">
            {% csrf_token %}

            <input type="text" class="form-control" id="floatingInput" placeholder="name@example.com">
            Номер задания

          <button class="w-100 btn btn-lg btn-primary mt-4" type="submit" id="btn">найти</button>
    </form>

from django.db import models

class Numbers(models.Model):
    abstract = models.FileField(upload_to="synopsisFiles/")
from django.shortcuts import render, redirect
from .models import Numbers
def index(request):
    return render(request, 'main/index.html')

A: В вашей функции сначала нужно получить объект по из базы данных по ID, а потом передать его в шаблон:
def index(request, your_id):
  numbers_object = Numbers.object.get(id=your_id)
  context = {'pdf': numbers_object}
  return render(request, 'main/index.html', contex)

для вывода в шаблоне нужно что-то типа:
{{ pdf.abstract.url }}


text:
Q: My NSTextField highlights text when I press Enter.? I just want "enter" to place a "NewLine" character in the field so that I can continue typing I just want "enter" to place a "NewLine" character in the field so that I can continue typing.
thx
- (void)someAction:(id)sender
{
    NSString *s = [tf1 stringValue];
    [tf1 setStringValue:[NSString stringWithFormat:@"%@%@",s, @"\nEnter\n" ]];
}

- (void)myRun:(NSButton*)btn
{
    NSString *s = [tf1 stringValue];
    [tf1 setStringValue:[NSString stringWithFormat:@"%@%@",s, @"hello\nthere" ]];
}

- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
    [super windowControllerDidLoadNib:aController];
    // Add any code here that needs to be executed once the windowController has loaded the document's window.

    //[aController.window setFrame:CGRectMake(10,10,1000,600) display:TRUE];
    [aController.window setFrame:NSMakeRect(10,10,1000,600) display:TRUE];
    [aController.window setBackgroundColor:[NSColor grayColor]];

    //NSButton *b1 = [[NSButton alloc] initWithFrame:CGRectMake(10, 530, 100, 30)];
    NSButton *b1 = [[NSButton alloc] initWithFrame:NSMakeRect(10, 530, 100, 30)];
    [b1 setTitle:@"Run"];
    [b1 setAction:@selector(myRun:)];
    [aController.window.contentView addSubview:b1];

    tf1 = [[NSTextField alloc] initWithFrame:NSMakeRect(10, 10, 600, 500)];
    [aController.window.contentView addSubview:tf1];
    [tf1 setTarget:self];
    [tf1 setAction:@selector(someAction:)];

}

A: Technical Q&A QA1454: How to make NSTextField accept tab, return and enter keys


text:
Q: gpg2 - no option to select aes block cipher and outdated use agent? With OpenSSL, I can select a what type of block cipher to use for encrypting a file.
For example, if I want to encrypt a file with AES256 CBC block cipher mode:
openssl aes-256-cbc -a -salt -pass pass:MYPASSWORD -in secrets.txt -out secrets.txt.enc

In gpg2, I try to encrypt a file with the following:
gpg2 --cipher-algo AES256 -a --no-use-agent --passphrase MYPASSWORD -c secrets.txt

There are two problems I could get some help with:

*

*There is no option to specify what cipher block to use. What if I want AES256 CTR or XTS instead of CBC? What cipher block does --cipher-algo AES256 use and how do I specify something specific?

*The command completely fails if I don't enter the passphrase in the gnu password agent (I'm trying to supply the passphrase in the command with --passphrase and --no-use-agent, for possible automation on a trusted machine):
gpg: WARNING: "--no-use-agent" is an obsolete option - it has no effect
gpg: problem with the agent: Invalid card
gpg: error creating passphrase: Operation cancelled
gpg: symmetric encryption of `secrets.txt' failed: Operation cancelled

A: Cypher Mode
OpenPGP enforces one given mode, a modified CBC mode as defined in RFC 4880. You cannot change it to something else.
GPG agent
As already noted by @grawity in the comments, more recent versions of GnuPG 2 extracted some cryptographic functions to the agent, so the passphrase and private key don't leave this smaller program with lower probability for vulnerabilities.
I guess that using gpg-preset-passphrase (documentation for GnuPG 2.1) to set the passphrase programatically is the way to go for batch operation in GnuPG 2. An alternative might be to use the `--passphrase[-fd, file] options which still seem to be available in GnuPG 2.1.

A: To get a list of supported ciphers you can use gpg2 --version. On my machine I get the following output:
Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,
        CAMELLIA128, CAMELLIA192, CAMELLIA256
I don't see a way to change to CTR or XTS, though.
I also don't see the option to specify passphrase in the command line but maybe you could try encrypting with a secret key instead of a passphrase.


text:
Q: common webservice interceptor and UsernameTokenValidation compatible with Spring-WS and CXF I have a scenario, where I want to configure a webservice security interceptor, and a UsernameTokenValidator and put this into say myws-security.jar. Which can be then be used by any webservice (be it CXF based or Spring-WS) that uses this jar. What would be the practice to deal with this scenario.
Would configuring an interceptor with org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor class , or org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor work for me in this case ?

A: In both Spring-WS and CXF, you typically do not provide your own WSS interceptor, you simply configure the provided interceptor with an appropriate callback handler. So in your case if you create an appropriate callback handler(based on the type of securement action), which needs to inherit from javax.security.auth.callback.CallbackHandler, this callback handler can be reused in Spring-WS and Apache CXF:
In Spring-WS you would do something along these lines:
<bean id="wss4jSecurityInterceptor" class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
    <property name="validationCallbackHandler" ref="callBackHandler" />
    <property name="validationActions" value="UsernameToken" />
</bean>

And in Apache CXF:
<jaxws:endpoint address=".." id=".." implementor="#memberendpoint">
    <jaxws:inInterceptors>
        <bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">
            <constructor-arg>
                <map>
                    <entry key="action" value="UsernameToken" />
                    <entry key="passwordType" value="PasswordDigest" />
                    <entry key="passwordCallbackRef">
                        <ref bean="callBackHandler" />
                    </entry>
                </map>
            </constructor-arg>
        </bean>
    </jaxws:inInterceptors>

And the common callbackhandler should work for you in both cases


text:
Q: How to trigger PHP function by a timer I'm making program what inserts data into a database. I have this button:
<form method='post'>

When it is pressed it inserts some data in the database.
I want to make a function that, when a button is pressed, waits for x time and then inserts data in the database.
I want to give a player the illusion that some building is under construction, and it will level up after some time.
sleep() doesn't work because it pauses the whole site, and doesn't allow to progress in other constructions.

A: Copy-paste next code in a PHP file and open it in your browser, it waits 5 seconds (5000 milliseconds) then submits the form (this javascript timer may help you) :
<html>
  <head>
    <script type="text/javascript">
var tmr;
function wait_before_submit ( seconds )
{ tmr = setTimeout( wait_seconds,seconds ); // TIMER START.
}
function wait_seconds ()
{ clearTimeout( tmr );           // TIMER END.
  document.getElementById("frm").submit(); // SUBMIT FORM.
}
    </script>
  </head>
  <body>
    <form id="frm" method="post" action="some_script.php">
      <input type="text" name="txt"/>
    </form>
    <!-- ▼ NOTICE THIS BUTTON IS OUTSIDE THE FORM ▼ -->
    <button onclick="wait_before_submit(5000)">Submit</button>
  </body>
</html>


text:
Q: How to use a 2fa code received in email with cypress.io? I am trying to automate login scenarios, but for the users once you log in, you will receive your 2fa code (6 digit) in your inbox and you have to copy and paste that number in order to access the site. So I am having some trouble with cypress since you cannot have multiple tabs...
I tried to use post, but I am pretty noob with it, solutions I am getting are more for 2fa with app not with a simple email
Any suggestion or ideal solution? Thank you!


text:
Q: Controller not deallocated when popping it dealloc is not called in controller B as it is popped from nav stack.
Ie this (very normal) setup:
Nav controller has controller A as root and a button tap pushes B on top. Then a back button in controller B unwinds to controller A. This is all made through the storyboard interface in IB (I do use a custom segue class that uses no animation on push). Normally (when using xibs only and non-arc) this would eventually call dealloc in controller B as it is popped. But it does not, in my case. Is this normal behaviour of storyboards? Or if not, I made some mistake somewhere, something is hanging onto controller B. FYI I'm using ARC and am not explicitly creating controller B anywhere in code.
It is alarming because I noticed that the constructor of controller B is called with each push of it from A (even after going back from B to A). It would mean the B controllers would leak.


text:
Q: Twitter Bootstrap Carousel slide to a specific index but passing through the intermediate ones? Currently I have made my carousel to slide through index boxes like this:
http://50.21.181.12:3000/

But I would like that if you are in slide 1 and click box 4, the two intermediate slides pass a lot faster to end in slide 4, like this slider:
http://www.hbs.edu/Pages/default.aspx
It is there any workaround for the carousel of twitter-bootstrap?
Any help will be highly appreciated!

A: I know this is an old post, but the chosen answer isn't correct. You can edit the speed at which it slides by setting the css with javascript.
var item = $('.carousel-inner .item')
$(item).css('-webkit-transition', '0.6s ease-in-out left');
$(item).css('-moz-transition', '0.6s ease-in-out left');
$(item).css('-o-transition', '0.6s ease-in-out left');
$(item).css('transition', '0.6s ease-in-out left');

The above is the actual css that the carousel is using by default simply change the values.
Edit:
In order to make it slide through the in between slides
slideTo(begin, end);

function slideTo(start_index, end_index){
    this.sliding = true;
    if(start_index != end_index) {

        var diff = start_index - end_index;
        var speed = 0.6/(Math.sqrt(Math.abs(diff))*1.5);

        var item = this.$('.carousel-inner .item')
        this.$(item).css('-webkit-transition', speed + 's linear left');
        this.$(item).css('-moz-transition'   , speed + 's linear left');
        this.$(item).css('-o-transition'     , speed + 's linear left');
        this.$(item).css('transition'        , speed + 's linear left');

        var that = this;

        if(diff < 0){
            this.$('.carousel').one('slid', function(){
                that.slideTo(start_index+1, end_index);
                return false;
            });
            this.$('.carousel').carousel(start_index+1);
        }
        else{
            this.$('.carousel').one('slid', function(){
                that.slideTo(start_index-1, end_index);
                return false;
            });
            this.$('.carousel').carousel(start_index-1);
        }
    }
    else{
        this.sliding = false;
        var item = this.$('.carousel-inner .item')
        this.$(item).css('-webkit-transition', '0.6s ease-in-out left');
        this.$(item).css('-moz-transition', '0.6s ease-in-out left');
        this.$(item).css('-o-transition', '0.6s ease-in-out left');
        this.$(item).css('transition', '0.6s ease-in-out left');
    }
}

This recursively calls itself and increments one slid closer. It currently bases the speed it slides based on the distance the current slide is from the target one.

A: No.
The Bootstrap Carousel visual presentation (including the animation) is CSS-based.  The JavaScript merely toggles CSS classes.  In order to achieve the type of sliding you're looking for, it would require a re-architecting of the core of the visual presentation, not merely a simple modification or workaround.
My recommendation would be to find a different jQuery carousel.


text:
Q: Cognos 8.4.1 / TFS Integration My team uses TFS 2010 for source control, build, etc. for all of our .NET and Java projects, and we would like to do the same for our Cognos reports.  Today we have to export the Cognos reports from the development environment into an XML file, which we can then store in the source code repository.  This is obviously not optimal and leaves the process open for mistakes.
Does anyone know if there is a better way to integrate Cognos reports into TFS?  I'm open to using the SDK and writing some minor integrations if necessary, but I'd like to know if it's even possible.
Thanks!

A: We also export reports to XML, and then manually maintain them in our version control system. You could if you wanted to, as you suggest, use the Cognos SDK to write a utility that handles this for you. The SDK gives you the ability to do this. Alternatively, you could use one of the existing third party tools that are available out there that put version control into Cognos Connection for you. Examples include:-

*

*MotioCI from Motio

*Integrated Control Suite from BSP

Obviously, the upside of using the SDK is you save yourself money, and you can integrate things into your existing VCS. On the downside, you have the time it takes you to do it, and the possibility of bugs.
The upside of using one of the products listed above is that you get a very mature solution which goes even beyond simple code control like you're thinking of. The downside is that you have to have the money for it.
Hope these thoughts help, and just to be clear, I have no connection with either of the companies linked to above.


text:
Q: Trouble using bootstrap_form gem - couldn't find file 'rails_bootstrap_forms' error I'm trying to use the bootstrap_form ~> 2.0.1 gem (see https://github.com/bootstrap-ruby/rails-bootstrap-forms) but it's giving me fits. I've installed is as per the instructions on their github page, adding it to my Gemfile:
gem 'bootstrap_form', '~> 2.0.1'

I ran bundle install. I then added it to my application.css.scss file:
 *= require_self
 *= require rails_bootstrap_forms
 *= require_tree .

But, when I try to run my app I get:

couldn't find file 'rails_bootstrap_forms' (in /path/to/my/app/assets/stylesheets/application.css.scss:12)

I'm obviously missing something. I checked lib/assets/ and vendor/assets/stylesheets/ but there's nothing there. Likewise, there's nothing in app/assets/stylesheets/.
What the fudge?

A: I had some trouble with this, partly (I think) because they renamed the gem. What seemed to make the difference for me was to have bundle grab the latest gem from github, by putting this into my Gemfile:
gem 'bootstrap_form', github: 'bootstrap-ruby/rails-bootstrap-forms'

I use bootstrap-sass, so I didn't want to mess around with application.css, so I made sure the following import statements were in application.css.scss, like this:
@import "bootstrap";
@import 'rails_bootstrap_forms';

It's also quite important to remember to restart the server after making these changes!

A: You have got to create the file rails_bootstrap_form.css in app/assets/stylesheets
.rails-bootstrap-forms-date-select,
.rails-bootstrap-forms-time-select,
.rails-bootstrap-forms-datetime-select {
  select {
    display: inline-block;
    width: auto;
  }
}
.rails-bootstrap-forms-error-summary {
  margin-top: 10px;
}

A: I had this problem and found that I'd mistyped the Gemfile entry as bootstrap-form. I corrected it to bootstrap_form and all was well.

A: Have you installed Bootstrap? Looks like that is a requirement of bootstrap_form, but it's not included as a dependency in the gem which means you need to manually install Bootstrap.
One popular way to do this is with the twitter-bootstrap-rails gem. The simplest way to install this is to include gem "twitter-bootstrap-rails" in your gemfile, and then run
$ bundle install
followed by
rails generate bootstrap:install static which should add the required CSS files to your assets folder.

A: I was getting the same error so I took out *= require rails_bootstrap_forms from application.css.scss and was able to compile and deploy without any errors.

A: Despite SO's admonishment not to respond to other answers I'm going to enhance Thomas Geider's answer above by explaining why you need to create a rails_bootstrap_forms.css file in app/assets/stylesheets.
If you look in the rails-bootstrap-forms Github you'll notice they have a rails_bootstrap_forms.css file. The README doesn't tell you this but it follows that this css file needs to be in /app/assets/stylesheets.
Here's the file:
https://github.com/bootstrap-ruby/rails-bootstrap-forms/blob/master/app/assets/stylesheets/rails_bootstrap_forms.css


text:
Q: JMapViewer centering I am trying to put a JMapViewer into a program I am doing and I want it to be centered in a specific area (Leicester, UK). Although I am not sure how the .setDisplayPosition function works and how I can use the co ordinates i have for it to do this task? Thanks.

A: Use JMapViewer#setDisplayPositionByLatLon() to zoom to a particular point.
Addendum: I don't have the method setDisplayPositionByLatLon().
Ah, the method was removed in r30244 in favor of setDisplayPosition().
Coordinate paris = new Coordinate(48.8567, 2.3508);
map.setDisplayPosition(paris, 8);

From the log:

$ svn log -r30244 src/org/openstreetmap/gui/jmapviewer/JMapViewer.java
------------------------------------------------------------------------
r30244 | glebius | 2014-01-31 07:51:51 -0500 (Fri, 31 Jan 2014) | 3 lines

To match getPosition() and simplify code rename setDisplayPositionByLatLon()
into setDisplayPosition(Coordinate to, ...).


text:
Q: Android implements Runnable didn't Terminate i am making a client server connection using the this Tutorial .
the problem i am facing that it doesn't stops, Log cat continue to show that client send data in an infinite loop. Also Server receives this data in an infinite loop
here is my code
Any Suggestion/changes will be appreciated, I am stucked in this problem to yesterday coud'nt fined a good working solution from google.
thanks
EDIT
the client side code
    public class ClientThread implements Runnable {

    public void run() {
        try {

            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            Log.d("ClientActivity", "C: Connecting...");
            socket = new Socket(serverAddr, 8080);
            connected = true;
            while (connected) {
                try {
                    Log.d("ClientActivity", "C: Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new
                     OutputStreamWriter(socket
                                .getOutputStream())), true);
                        // where you issue the commands

                        out.println(serverIpAddress);
                        //connected = false;
                        //socket.close();
                        Log.d("ClientActivity", "C: Sent.");

                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }

            }
            socket.close();
            Log.d("ClientActivity", "C: Closed.");
        } catch (Exception e) {
            Log.e("ClientActivity", "C: Error", e);
            connected = false;
        }
    }
}

Server Side
      public class ServerThread implements Runnable {
    private volatile boolean keepGoing = true;
    private volatile boolean firstLoop = true;

    public void requestStop() {
        keepGoing = false;
      }
    public void run() {
        try {
            if (SERVERIP != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Listening on IP: " + SERVERIP);
                    }
                });
                serverSocket = new ServerSocket(SERVERPORT);
                while (keepGoing) {
                    // listen for incoming clients
                    Socket client = serverSocket.accept();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            serverStatus.setText("Connected.");
                        }
                    });

                    try {
                        BufferedReader in = new BufferedReader(new
                       InputStreamReader(client.getInputStream()));
                        line = null;
                        while ((line = in.readLine()) != null) {
                            Log.d("ServerActivity", line);
                            handler.post(new Runnable() {
                                @Override
                                public void run() {

                                    serverStatus.setText(line);
                                    Log.d("IP recevied", line);
                                    requestStop();

                                }
                            });
                        }

                        break;
                    } catch (Exception e) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                serverStatus.setText("Oops. Connection interrupted.
                        Please reconnect your phones.");
                            }
                        });
                        e.printStackTrace();
                    }
                }
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        serverStatus.setText("Couldn't detect internet connection.");
                    }
                });
            }
        } catch (Exception e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    serverStatus.setText("Error");
                }
            });
            e.printStackTrace();
        }
    }
    }

A: to uncomment line //connected = false; should make it work .
after write stream operation you should exit from while instead of writing the same thing back .


text:
Q: Gradle plugin extension set a property of type Map I want to set a Map of attributes to my plugin extension. So basically I want to write something like
settings {
  envVars = {
    a = "abc"
    b = "dec"
    ...
    n = "sdf"
  }
}

When I use an attribute in my Extension class
private Map<?,?> envVars;

Gradle tells me that it can not set the property settings. So what I would like to achieve is to set a map of values in my extension class.
What I did achieve is to get the closure when i write the following:
settings {
  envVars {
    a = "abc"
    b = "dec"
    ...
    n = "sdf"
  }
}

public class extension {
....
    public envVars(Closure c){}
}

But then I have no clue what to do with the closure and how to access what is inside, so I would rather have a Map instead of the closure
Regards
Mathias

A: Ok, you just have to write the map properly :/
envVars = [test: 'test']

and everything is fine

A: I am using the following to read a map of values from build.gradle
reference: https://github.com/liquibase/liquibase-gradle-plugin
Container class:
class Database {
  def name
  def arguments = [logLevel: 'info']

  Database(String name) {
    this.name = name
  }

Extension Class:
class MyExtension {
  final NamedDomainObjectContainer<Database> databases
  def databases(Closure closure){
    databases.configure(closure)
  }

  def methodMissing(String name, args) {
    arguments[name] = args[0]
  }
}

Load Extensions
  def databases = project.container(Database) { name ->
      new Database(name)
    }
  project.configure(project) {
      extensions.create("extensionName", MyExtension, databases)
  }

Sample build.gradle:
dbDiff{
  databases{
    db1{
      url  'testUrl'
    }
   }
 }


text:
Q: Get distances using ST_Distance_Sphere & ST_GeomFromText I am trying to use postgis to calculate distances between points. I have the (from to coordinates) as Lat & Long in a table. I researched some code and it looks like this:
SELECT ST_Distance_Sphere(
(ST_GeomFromText('POINT(' || distance.sfg_long || ' ' ||  distance.sfg_lat || ')',4326)),
ST_GeomFromText('POINT(' || distance.plg_long || ' ' || distance.plg_lat || ')',4326))
FROM distance;

I get this message:
ERROR:  parse error - invalid geometry
HINT:  "POINT(SF" <-- parse error at position 8 within geometry
SQL state: XX000

All I want to do is get the distance and It looks like other people used a similar approach and it worked for them.
Any clues what is going on?

A: I suspect you have either a typo in your query, or an invalid value in your longitude column. Going by the error message, could it be that one of the values in sfg_long is text starting with "SF"?
Sharing your table design and some sample records would help us to help you. I am going to assume your columns are text.
I would try something like the following. The ST_POINT syntax is clearer.
SELECT ST_Distancesphere(
   st_setsrid(st_point(distance.sfg_long::numeric,distance.sfg_lat::numeric),4326),
   st_setsrid(st_point(distance.plg_long::numeric,distance.plg_lat::numeric),4326)
) FROM distance
    -- st_distance_sphere is deprecated since 2.2.0


text:
Q: Best practices for using `std::error_code` I am currently building an embedded system and use a modern C++ compiler.
While I could technically fit exception handling in the given resources (ARM7, more than 10M RAM), I don't think exceptions are the right tool for something like this and using exceptions requires RTTI, which in turn results in code bloat.
To stay C++-ish anyway I want to use std::error_code (or similar with more data) because I do like the concept.
However, there does not seem to be any consenus on how to actually use them. I have seen at least four different ways of passing them between function calls, two of them with multiple semantics.

*

*Passing by pointer as an argument
void somefunction(Args..., std::error_code* error);

This is the way I have not seen that often and the one I dislike the most. It leaves the return type fully available and (often, but not always) passing nullptr resulted in normal throwing behaviour.

*Passing by reference as an argument
void somefunction(Args..., std::error_code& error);

This is the one I prefer. It leaves returnvalue fully available and makes clear that the error_code is not optional.

*Returning it by value
std::error_code somefunction(Ret& out <= if used, Args...);

I have seen this one quite often but don't really like it that much, as it uses up your return value and I generally don't like "out parameters" unless there's no way around them.

*Returning a std::variant<Ret, std::error_code>
std::variant<Ret, std::error_code> somefunction(Args...);

This one allows for a return value, but makes accessing both value and error harder. Also, it makes code calling the function more verbose.
Semantics
I have seen both way 1 and 2 with different semantics, if the error_code is passed.

*

*Clear at start and set on error

*Only set on error

*Return right at start if the error_code is "set"

The last way is pretty good if you want to reduce error checking in the calling code. As you can just pass one error_code to multiple functions without checking in between and everything after the first error will not execute, similar to how exceptions would do it.
I personally do prefer way 2 with checking and returning, however I might be biased.
Is there some recommended / generally accepted way to do it?

A: Ok, this is no complete answer and actually not perfectly on topic because I am not aware of a standard way to do this. But I once saw a nifty little trick to make error codes harder to misuse. Consider the following code:
struct MyEC {
    MyEC() {}
    MyEC(MyEC && other) : parent(&other) {
        // Maybe log and or abort if other is not checked
        other.checked = false;
    }
    // Delete other constructors and assignment operators

    ~MyEC() {
        if(!checked && parent == nullptr) {
            // log and or abort
        }
     }

    [[nodiscard]] std::error_code check() {
        checked = true;
        return ec;
     }

     void set(std::error_code err) {
         if(parent == nullptr)  ec = err;
         else parent->set(err);
     }
private:
    MyEC* parent = nullptr;
    checked = true;
    std::error_code ec {};
};

int foo(MyEC&& err) {
    err.set(/* some error */);
    return 5;
}

int foo1(MyEC&&) {
    return 4;
}

void bar() {
    MyEC err;
    foo(std::move(err));
    // err has the error code and if its not checked, we will know

    foo1(std::move(err));
    // even though no error occurs, we will abort if err is not checked.
}

It will even then abort, when the error code is not set but also not checked, which is pretty nice. It has a lot of uses after move, which is a bit weird, but this is no problem here.


text:
Q: Unable to run the Hello World example of ReactJS I am a newbie of ReactJS and is learning it through a Hello World example as shown below:
abc.html
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Hello World</title>

index.js
const element =
Hello, world
;
ReactDOM.render(
   element,
   document.getElementById('root')
);

A: When using the Babel in-browser compiler you must include your code inline and set the script tag type to text/babel:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Hello World</title>

A: What you have seems to work - I just copy and pasted into a codepen. It's possible that your browser is blocking the react script or something
Maybe try it in a different browser?


text:
Q: Change git branch's root, retainig older commit as branch HEAD? Forgive me if I've phrased it incorrectly, but what I have is master and master-variant where the latter is a variant of the generic product that I'm working on. It contains additional files and some changed files.
The problem is that I'm creating this "in reverse", because I started out with the variant and am now in need of this new generic "root" because I will add other new variants branched from it.
So I started out with the original variant in master and created a branch master-variant for the current state, without any changes (i.e. it points to the same commit as master).
Then I modified the contents of master to make it "generic", i.e. removed everything variant-specific and commited it there. In this state, master has a new commit compared to the commit that master-variant points to.
But I want it to appear as if I started out with the generic master (the last commit there) and then branched master-variant off it, and added the variant-specific stuff, i.e. the state of the previous commit in master.
I'll try to illustrate. What I have is this (m = master, v = master-variant):
m0---m1---m2---m3 (changes to create generic variant)
           \
            v1 (just a new ref to m2)

Note that m0..m2 are in the master branch, but their contents are the original variant that I now want in a branch instead.
I want to change this so it would instead look like this:
m0---m1---m2---m3 (same as above, the generic variant)
                \
                 v1 (same content as "v1" above, which is also the same content as "m2" in both illustrations)

How can I achieve this?
My first thought was to use git rebase, but I fail to see how that would be possible, since what it does is to replay commits while I need to replay the reverse of a commit, i.e. the reverse of the m3 commit.
I guess I could stash the m2/v1 state, delete the master-variant branch, switch to master (i.e. commit m3), pop the stashed state and commit it to a new master-variant branch.
But is there a more direct approach?
I guess in short, what I really want is to create a branch that contains the state of a historic commit, but have that branch rooted at HEAD (not at the historic commit).

A: Reminder: commits are snapshots of the file state.  The commits themselves form the commit graph, while the branch names are simply labels that identify (point to) a specific commit.
You said that in your diagram, v1 is literally a reference to commit m2.  That is, it's not already a separate commit of its own.  So what you really have is:
C0--C1--C2   <-- v1
          \
           C3   <-- master

where v1 and master are labels (names) that point into the graph formed by the commits themselves, which are C0 through C3.  The graph you describe yourself as wanting adds a new commit C4 whose contents match those of C2 but whose parent (historic commit just behind itself) is C3:
C0--C1--C2    C4   <-- v1
          \  /
           C3   <-- master

Given that this is the case, you have two relatively easy options.  One is to go into Git's so-called plumbing commands and use a command that makes a new commit, giving it a specific saved snapshot and set of parents.  The new commit is your C4.  Then, having copied C2 to C4, you would move the name v1 to point to C4.  The two specific Git commands for this are:
hash=$(git commit-tree -p master v1^{tree} -F /tmp/message)

where /tmp/message contains the commit log message you'd like to use.  Note too that some shells may interpret the ^ or { characters; if so, quote them.  You can then run git log $hash to verify that the commit looks right.  Then, if you're currently "on" branch v1:
git reset $hash

will adjust the v1 label.  (Be sure your index and work-tree are clean, i.e., that there is nothing uncommitted to save.)  If not:
git branch -v v1 $hash

will adjust the v1 label.
Alternatively, consider that reverting the commit C3 would back out its changes and leave you with a new commit that matches C2.  So you could:
git checkout v1
git merge --ff-only master

which would produce:
C0--C1--C2
          \
           C3   <-- v1 (HEAD), master

Then you would just run:
git revert HEAD

to make a new commit that backs out the difference between C2 and C3, giving you a new commit C4:
C0--C1--C2    C4   <-- v1 (HEAD)
          \  /
           C3   <-- master

and again you're done.
If you had many commits to revert—i.e., if you wanted:
C0--C1--C2   <- v1
          \
           C3--C4--C5   <-- master

to become:
C0--C1--C2            C6   <- v1
          \          /
           C3--C4--C5   <-- master

then the git commit-tree method is less work (though you can still use git revert, you just need -n in this case while reverting C5, C4, and C3, or a subsequent git rebase -i where you squash together all the new commits).  In other words, git commit-tree is exactly the tool that achieves:

... what I really want is to create a branch that contains the state of a historic commit, but have that branch rooted at HEAD (not at the historic commit).


text:
Q: Agrupar en mongoDB (Agregate) tengo una duda y a la vez una consulta estoy trabajando con una colleción de datos, que es la siguiente
{
        "_id" : ObjectId("5d44bb2359f39d0ba947b6ea"),
        "actividad" : "V",
        "fechaInicial" : ISODate("2019-07-23T16:15:00.000Z"),
        "codVendedor" : "140",
}
{
        "_id" : ObjectId("5d44bb2359f39d0ba947b6oa"),
        "actividad" : "LL",
        "fechaInicial" : ISODate("2019-07-23T16:15:00.000Z"),
        "codVendedor" : "150",
}

{
        "_id" : ObjectId("5d44bb2359f39d0ba947b6ia"),
        "actividad" : "LL",
        "fechaInicial" : ISODate("2019-07-23T16:15:00.000Z"),
        "codVendedor" : "140",
}

quisiera agrupar en base a la fecha y el codigo , por dia de la fecha
adjunto mi código que he estado probando y aun no me sale
db.getCollection('actividad').aggregate(
[
    {
        $match : {
            $and : [
                {fechaInicial: { $gte : ISODate("2019-07-23T00:00:01")}},
                {fechaInicial: { $lte : ISODate("2019-07-23T23:59:59")}}
            ]
        }
    },
    {
        $project:
        {
            codVendedor: 1,
            sum_visitas : {$cond: [ { $eq: ["$actividad", "V"] }, 1, 0]},
            sum_llamadas :{$cond: [ { $eq: [ "$actividad", "LL"] }, 1, 0]}
        }
    },
    {
        $group:{
            _id: "$codVendedor",
            total_visitas: {$sum : "$sum_visitas"},
            total_llamadas : {$sum : "$sum_llamadas"},
        }
    }

])

como ven aplico condiciones para lo que es V o LL pero solo por codigoVendedor , pero ahora necesito por fecha , los registro.
agradecería su ayuda. Muchas Gracias

A: Según veo en tu código, creo que el problema esta en que no estas escribiendo bien el campo de codVendedor, ya que según creo entender en los documentos lo nombras código. Siendo esto cierto, si quieres agrupar por uno o mas campos deberías de añadirlo al $group, te muestro una posible solución:

*

*Query

db.getCollection('actividad').aggregate([
    {
        $match : {
            fechaInicial: { //Esto es lo mismo que tu código pero de otra manera
                $gte : ISODate("2019-07-23T00:00:01"),
                $lte : ISODate("2019-07-24T23:59:59")}
        }
    },
    {
        $group:{
            _id: {. // Campos para agrupar
                codigo: "$codigo",
                fechaInicial:"$fechaInicial"
            },
            total_visitas: {
                $sum:{ // El sumatorio lo puedes hacer aquí, eliminando la Etapa $project
                    $cond: [ { $eq: [ "$actividad", "V"] }, 1, 0]
                }
            },
            total_llamadas : {
                $sum:{
                    $cond: [ { $eq: [ "$actividad", "LL"] }, 1, 0]
                }
            }
        }
    }
])

*

*Resultado

[{
    "_id" : {
        "codigo" : "150",
        "fechaInicial" : ISODate("2019-07-23T16:15:00.000Z")
    },
    "total_visitas" : 0.0,
    "total_llamadas" : 1.0
},
{
    "_id" : {
        "codigo" : "140",
        "fechaInicial" : ISODate("2019-07-23T16:15:00.000Z")
    },
    "total_visitas" : 1.0,
    "total_llamadas" : 1.0
}]

Espero haber ayudado en tu problema.
Un saludo


text:
Q: Confluent JDBC Kafka Connect multiple tables from different schemas in "table.whitelist" I am trying to configure Confluents Kafka JDBC connect to stream data from two different tables in two different schemas to 1 topic.  I am having trouble getting my source command to execute when I add multiple tables in table.whitelist
I have two tables from different schemas:  db1.case & db2.case
When I run the curl command I set the table.whitelist like this
"table.whitelist": "case, db1.case, db2.case",

but I get an error saying
Update the connector's 'table.whitelist' config to include exactly one table in each of the tables listed below.
[["db1"."case", "db2"."case"]]

Does anyone know the right way to whitelist multiple tables from multiple schemas?


text:
Q: Ubuntu 22.04LTS GDM3 Troubleshooting (Not loading desktop, only showing"Unlock Login Keyring" After messing around on the Login screen, I found the little cogwheel that lets you change desktop environments. I clicked Kodi, logged in, and it worked fine, so then I decided to try Openbox and TWM and none of those launched, so I went to bed and called it a night. When i tried to log into Wayland again this morning I was greeted with a black screen and only "Unlock Login Keyring", and once I unlock it the screen freezes up. I'm pretty sure that using Openbox broke my GDM install since I don't think I had the dependencies, I'm not even sure what it is to be honest, any help will be appreciated and I will update with whatever information is required.
Additional info 1: When I do CTRL+ALT+f1 it opens the login screen, but I cannot change the environment and when I log in it takes me back to the same screen- I am able to open a new session on TTY3 though. and the cogwheel is missing.
Made a new User account in TTY and was able to load into wayland. Next step would be to compare config files?
Accessed the xsessions files and these are the contents of the options i selected.
For ubuntu.desktop:
Name=Ubuntu
Comment=This session logs you into Ubuntu
Exec=env GNOME_SHELL_SESSION_MODE=ubuntu /usr/bin/gnome-session --session=ubuntu
TryExec=/usr/bin/gnome-shell
Type=Application
DesktopNames=ubuntu:GNOME
X-GDM-SessionRegisters=true
X-Ubuntu-Gettext-Domain=gnome-session-42

For openbox.desktop
Name=Openbox
Comment=Log in using the Openbox window manager (without a session manager)
Exec=/usr/bin/openbox-session
TryExec=/usr/bin/openbox-session
Icon=openbox
Type=Application

For twm.desktop
Encoding=UTF-8
Type=XSession
Exec=twm
TryExec=twm
Name=TWM
Name[eo]=TFA
Name[hi]=टीडबल्यूएम
Name[te]=టి డబ్ల్యు ఎం
Comment=The Tab Window Manager
Comment[af]=Die Tab venster bestuurder
Comment[ar]=مدير النوافذ Tab
Comment[be]=Кіраўнік вокнаў з укладкамі Tab Window Manager
Comment[bn]=দি ট্যাব উইণ্ডো ম্যানেজার
Comment[bs]=Tab Window Manager
Comment[ca]=El gestor de finestres Tab
Comment[csb]=Tab Window Manager
Comment[cy]=Y Trefnydd Ffenestri Tab
Comment[da]=Tab-vindueshåndtering
Comment[de]=Der Tab-Fenstermanager
Comment[el]=Ο διαχειριστής παραθύρων Tab
Comment[eo]=Taba fenestroadministrilo
Comment[es]=El Tab Window Manager
Comment[et]=Kaartidega aknahaldur
Comment[eu]=Tab leiho kudeatzailea
Comment[fa]=مدیر پنجرۀ تب
Comment[fi]=Välilehtiä tukeva ikkunaohjelma
Comment[fy]=De Ljepper Finster Behearder
Comment[gl]=O Xestor de Fiestras Tab
Comment[hi]=टैब विंडो प्रबंधक
Comment[hr]=Tab upravitelj prozora
Comment[hu]=Tab Window Manager ablakkezelő
Comment[is]=Tab gluggastjórinn
Comment[it]=Il Tab Window Manager
Comment[ja]=Tab 化ウィンドウマネージャ
Comment[kk]=Tab терезе менеджері
Comment[km]=កម្មវិធីគ្រប់គ្រងបង្អួចជាផ្ទាំង
Comment[lt]=Kortelių langų tvarkyklė
Comment[lv]=Tabu logu menedžeris
Comment[mk]=Tab Window Manager
Comment[mn]=Tab Цонхны удирдагч
Comment[ms]=Pengurus Tetingkap Tab
Comment[mt]=Tab Window Manager
Comment[nb]=Tab Vindusbehandler
Comment[nds]=De Tab-Finsterpleger
Comment[ne]=ट्याब सञ्झ्याल प्रबन्धक
Comment[nl]=De Tab Window Manager
Comment[nn]=Tab Window Manager
Comment[pa]=ਟੈਬ ਝਰੋਖਾ ਮੈਨੇਜਰ
Comment[pl]=Tab Window Manager
Comment[pt]=O Tab Window Manager
Comment[pt_BR]=O Gerenciador de Janelas de Abas
Comment[ro]=Tab Window Manager
Comment[ru]=Традиционный оконный менеджер системы X11
Comment[rw]=Mugenga Dirishya Agafishi
Comment[se]=Tab-láse lásegieđahalli
Comment[sk]=Správca okien s kartami
Comment[sl]=Tab Window Manager, okenski upravitelj z zavihki
Comment[sv]=Flikfönsterhanteraren
Comment[ta]=டாப் சாளர மேலாளர்
Comment[te]=టాబ్ విండొ అభికర్త
Comment[tg]=Tab-и мудири тиреза
Comment[th]=Tab Window Manager
Comment[tr]=Tab Pencere Yöneticisi
Comment[tt]=X11 sistemendäge kebek tabaqlı täräzä-idäräçe
Comment[uk]=Tab Window Manager
Comment[vi]=Trình Quản lý Cửa sổ Thẻ
Comment[zh_CN]=标签式窗口管理器
Comment[zh_TW]=Tab 視窗管理程式

A: Found the answer! Ubuntu 20-04 won't boot up after modifying /etc/gdm3/custom.conf file - AskUbuntu
my etc/gdm3/custom.conf looked like this:
# GDM configuration storage
#
# See /usr/share/gdm/gdm.schemas for a list of available options.

[daemon]
# Uncomment the line below to force the login screen to use Xorg
#WaylandEnable=true

# Enabling automatic login
#  AutomaticLoginEnable = true
#  AutomaticLogin = user1

# Enabling timed login
#  TimedLoginEnable = true
#  TimedLogin = user1
#  TimedLoginDelay = 10

#AutomaticLoginEnable=True
AutomaticLogin=crith

Clearly the syntax is wrong, but commenting WaylandEnable=true and AutomaticLoginEnable gave me the cogwheel back, from where I was able to select Ubuntu.


text:
Q: ui-router move from nestedState to another parentState I can't seem to navigate directly from parentA.childState to parentB state.  How does one do this in one move?
$stateProvider.state(
    'parentA',
    {
        url: '/parentA',
        template: '
Parent A <ui-view />
',
        controller: function() {}
    }
).state(
    'parentA.childState',
    {
        url: '/childA',
        template: 'Child A',
        controller: function(){}
    }
).state(
    'parentB',
    {
        url: '/parentB',
        template: 'Parent B',
        controller: function(){}
    }
);

Assume my application currently at state parentA.childState and then I click the link below which SHOULD take me to parentB state.
Link only goes back to parentA state

How can I go directly to parentB state?
Thanks for help.

A: Answering my own question.  What I'm asking for here is default behavior.  It should work like this out of the box.  My problem was my own code interrupting this redirect.


text:
Q: Cloning Objects in Raku What is the best way to clone objects in raku? I know the clone method exists, but It does not seem to work with nested objects.
For example, in this script:
#!/usr/bin/env perl6

class Group {
    has Int @!group = Array[Int].new;

    method add-item(Int $int) {
        @!group.push($int);
    }

    method print {
        say @!group;
    }
}

class GroupOfGroups {
    has Group @!multi-group = Array[Group].new;

    method add-group(Group $group) {
        @!multi-group.push($group);
    }

    method print {
        for ^@!multi-group.elems -> $i {
            @!multi-group[$i].print;
        }
    }
}

my $group = Group.new;
$group.add-item(1);
$group.add-item(2);
$group.add-item(3);

my $group-of-groups = GroupOfGroups.new;
$group-of-groups.add-group($group.clone);
$group.add-item(4);
$group.add-item(5);
$group.add-item(6);

$group-of-groups.add-group($group.clone);

$group-of-groups.print;

The output is:
[1 2 3 4 5 6]
[1 2 3 4 5 6]

But I was expecting it to be:
[1 2 3]
[1 2 3 4 5 6]

A: I wouldn't use anything other than clone to clone objects. clone is a proto method defined by Mu, but it's up to its subtypes to implement its behaviour in this case, as cloning the object does clone the array attributes, but not in the way you want. As such, you can write your own clone multis that behave like you expect:
# Group
multi method clone(::?CLASS:D: --> ::?CLASS:D) {
    my ::?CLASS:D $clone .= new;
    $clone.add-item: .clone for @!group;
    $clone
}

# GroupOfGroups
multi method clone(::?CLASS:D: --> ::?CLASS:D) {
    my ::?CLASS:D $clone .= new;
    $clone.add-group: .clone for @!multi-group;
    $clone
}

::?CLASS here is a symbol that, when used in classes, is an alias for the class itself, with :D restricting the type to instances only.

A: Hi @julio a careful reading of the docs led me to this ... works like a charm:
method clone { nextwith :foo(@!foo.clone), :bar(%!bar.clone), |%_  }

(this also helped me to understand the rational behind "restricted" language help for deep cloning)


text:
Q: Set resize of XUL panel to auto I am developing an add on for Firefox on the Addon SDK (v.1.11).
My addon uses a toolbar button to display a XUL panel. This panel contains buttons that dynamically (using jQuery's slideToggle(500)) expand / collapse divs, modifying the overall dimensions of the panel.
Problem
The resizing is done smoothly, and the containing HTML elements are resized automatically since their height/width is set to 'auto'. However, the panel itself does not take height/width 'auto' values, only integers. This forces me to manually call a function to resize the panel when a collapse/expand motion has finished. This creates a very unpleasant effect. Is there a way to allow the panel to resize to its content automatically?

A: The system isn't ideal right now so I've been connecting the content and panel via a resize port event that handles the auto-resize of the panel.  Here's how it works.
In your Panel or main.js code listen for resize events.
Panel.port.on("resize", function (sizes) {
  Panel.resize(sizes.width, sizes.height);
});

Then in your Content Panel code use something like the following (when the DOM is ready):
$(window).bind('resize', function () {
   self.port.emit("resize", { "width" :  $("body").width(),
                              "height" : $("body").height() });
});

This will send a resize event through the panel ports system every time you content window size changes from an expand or collapse.
(update)
If you're not getting a $(window).resize() event from your DOM then you'll have to hook something up more manual to your slideToggle function.  Try hooking up a callback function to every slideToggle call you make.  Here's an example:
function emitResize() {
       self.port.emit("resize", { "width" :  $("body").width(),
                                  "height" : $("body").height() });

}

$('#yourid').slideToggle('fast', emitResize);

This will trigger the resize event after every slideToggle animation when the size of your page has finished changign.  You might want to alter the $("body").width() and $("body").height() calls to use a containing div if you've set a static width or height for your document.