text:
Q: Internal Server Error when trying to change upload file size parameters in htaccess I have edited a live WordPress site locally and am about to upload it to the live server. When doing this, I usually change (increase) the maximum file upload size since I am using a plugin to Export/Import the website, and this plugin only takes 100 MB of import file size (plugin: All in One WP Migration, free version).
When achieving this I add this code to the end of the .htaccess file located in the html folder:
php_value upload_max_filesize 1000M
php_value post_max_size 1000M
php_value memory_limit 1000M
php_value max_execution_time 0
php_value max_input_time 300

This typically works well, but this time this error message is shown in the browser (on page refresh):

Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.

*

*I have stripped the .htaccess file of code that is related to (and dynamically generated by) the Breeze cache plugin, and the site works as expected without this code (given that I have not added the "upload file size code" in the file).

*I have commented out the code related to GD-SSL (Godaddy SSL), and the site works as expected without this code (given that I have not added the "upload file size code" in the file). For reference, please see file content below.

This is what my .htaccess file looks like after these edits (edits made in order to solve the error, of course):
# BEGIN GD-SSL
# <IfModule mod_rewrite.c>
# Options +FollowSymLinks
# RewriteEngine On
# RewriteCond %{HTTPS} !=on
# RewriteCond %{HTTP_USER_AGENT} ^(.+)$
# RewriteCond %{SERVER_NAME} ^alloptik\.se$ [OR]
# RewriteCond %{SERVER_NAME} ^49l\.fd7\.myftpupload\.com$
# RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
# Header add Strict-Transport-Security "max-age=300"
# Header always set Content-Security-Policy "upgrade-insecure-requests"
# </IfModule>
# END GD-SSL

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

php_value upload_max_filesize 1000M
php_value post_max_size 1000M
php_value memory_limit 1000M
php_value max_execution_time 0
php_value max_input_time 300

A: Please use like below into wp-config.php file and remove your htaccess php_value. follow screenshoot below.
https://prnt.sc/7xitGHbSIFEn
@ini_set( 'upload_max_size' , '1000M' );
@ini_set( 'post_max_size', '1000M');
@ini_set( 'max_execution_time', '300' );

A: You can only use php_value (and related) directives in .htaccess if PHP is installed as an Apache module, which is probably not the case in your live server environment. The 500 Internal Server Error is likely due to the directive simply not being recognised.
You can try using a per-directory .user.ini file instead (on CGI/FastCGI) containing:
; Custom settings
upload_max_filesize = 1000M
post_max_size = 1000M
memory_limit = 1000M
max_execution_time = 0
max_input_time = 300

However, you'll also need to check the user_ini.filename and user_ini.cache_ttl PHP INI settings as the expected filename might be different on your server and this file is "cached" by default.
Also, your host (GoDaddy) might impose additional restrictions (on shared hosting plans) that cannot be circumvented.
Reference:

*

*https://www.php.net/manual/en/configuration.file.per-user.php


text:
Q: Shell script with wc -l, if statement ain't working The problem is with this code:
    words=`wc -l /home/tmp/logged.log | awk '{print $1}'`;
    if [ $words == 26 ]
    then
    echo $words
    echo Good
    else
    echo Not so good
    fi

it always returns the else statement. Even tho the result is 26.
I also tried
     words=`wc -l < /home/jonathan/tmp/logged.log`;

A: try to use [ $words -eq 26 ] instead of [ $words == 26 ]
or [ 26 == 26 ] to check that statement works properly

A: Because == is not valid. Use =
if [ $words = 26 ]

By the way you can use cut instead of awk.
wc -l /home/tmp/logged.log  | cut -f1 -d" "

A: Try this:
words=`wc -l /home/tmp/logged.log | awk '{print $1}'`;
if test $words -eq 26; then
    echo $words
    echo Good
else
    echo Not so good
fi

redpajama_set_name: RedPajamaStackExchange


text:
Q: Virtualbox 6.1 Memory Hogging I am on Ubuntu desktop 20.04 and I run a web server inside virtualbox box which on b/c I launch the VM via a custom systemd service file.
Problem:
For reasons unknown to me vboc is hogging all of my systems memory by launching multiple copies of the same process as seen here:

This is my systemd config for launching virtualbox:
/etc/systemd/system/VminRoot2.service
[Unit]
Description=Vmin-Vbox
After=network.target virtualbox.service
Before=runlevel2.target shutdown.target
[Service]
ExecStartPre=/bin/sleep 30
User=root
Group=vboxusers
Type=forking
Restart=no
TimeoutSec=5min
IgnoreSIGPIPE=no
KillMode=process
GuessMainPID=no
RemainAfterExit=yes
ExecStart=/usr/bin/VBoxManage startvm VminRoot2 --type headless
ExecStop=/usr/bin/VBoxManage controlvm VminRoot2 acpipowerbutton
[Install]
WantedBy=multi-user.target

These are the  settings for my machine:

Anyone see what I am doing wrong?  How can I get vbox to launch... once  ?

A: As it turns out it wasn't Vbox hogging memory (this time.)
For anyone, who wants an easy and straightforward way of knowing exactly what processes are running in your swap memory I suggest sudo apt-get install smem
That little clearly lists every process using swap which is how I was able to discover that a 6 month old docker experiment was still launching at boot and hiding in my swap memory, so I couldn't directly "see" its memory via top or htop.


text:
Q: Getting icon from external applications I am trying to prepare an application similar to 'Windows Start Menu Search'.
That's why I need each applications own icon.
From the C:\ProgramData\Start Menu\Programs\  file path, I add existing applications to a list (QListWidget) with their names and path.
And I get the icons like this:
https://forum.qt.io/topic/62866/getting-icon-from-external-applications
provider = QFileIconProvider()
info = QFileInfo("program_path")
icon = QIcon(provider.icon(info))

And naturally the result is this:

But I don't want this "shortcut icon" to appear.

Then, I am thinking and I came to this conclusion:
shell = win32com.client.Dispatch("WScript.Shell")
provider = QFileIconProvider()
shortcut = shell.CreateShortCut(programPath)
info = QFileInfo(shortcut.targetPath)
icon = QIcon(provider.icon(info))

This solution worked. But, It has created issue for some applications.
So I am looking for an alternative solution.

A: You were almost there.
Browsing the menu directory tree is actually the right path, but you also have to ensure that the icon of the link is actually the same of the target, as it might not.
The shortcut.iconlocation is a string representing a "tuple" (sort of) including the icon path and the index (as icon resources might contain more than one icon).
>>> shortcut = shell.createShortCut(linkPath)
>>> print(shortcut.iconlocation)
# most links will return this:
> ",0"
# some might return this:
> ",4"
# or this:
> "C:\SomePath\SomeProgram\SomeExe.exe,5"

As long as the icon index is 0, you can get the icon using QFileIconProvider with the targetPath or iconLocation (if there's something before the comma).
The problem comes when there's a value different from 0 for the icon index, as Qt doesn't handle that.
I've put together a simple function (based on some research here on StackOverflow).
def getIcon(self, shortcut):
    iconPath, iconId = shortcut.iconLocation.split(',')
    iconId = int(iconId)
    if not iconPath:
        iconPath = shortcut.targetPath
    iconPath = os.path.expandvars(iconPath)
    if not iconId:
        return QICon(self.iconProvider.icon(QFileInfo(iconPath)))

    iconRes = win32gui.ExtractIconEx(iconPath, iconId)
    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    # I think there's a way to find available icon sizes, I'll leave it up to you
    hbmp.CreateCompatibleBitmap(hdc, 32, 32)
    hdc = hdc.CreateCompatibleDC()
    hdc.SelectObject(hbmp)
    hdc.DrawIcon((0, 0), iconRes[0][0])
    hdc.DeleteDC()
    # the original QtGui.QPixmap.fromWinHBITMAP is now part of the
    # QtWin sub-module
    return QtGui.QIcon(QtWin.fromWinHBITMAP(hbmp.GetHandle(), 2))


text:
Q: How to point to one directory up (../) in PHP? When I'm on this file: /here/here.php I can require files from the same folder doing:
require_once(__DIR__."/here2.php");

However I can't figure out how to go up one directory to point to something such as this:
/there/there.php

How can I point to this other file with a relative path?

A: require_once __DIR__ . '/../there/there.php';

or
require_once dirname(__DIR__) . '/there/there.php';


text:
Q: asp.net razor web pages validation and using multiple forms i wanted to use two froms in my razor web pages(not mvc)
and my problem is working with more than one form
how do i say to my project that which form button is clicked and another problem is validation
because in web form project i was using validation group to separate validations but here
 i do not know how to deal with it both in client side validate and server side validation
here is my codes
:
@{
Page.Title = "";
Layout = "~/_layout.cshtml";

    Validation.Add("txt1", Validator.Required("can not leave empty"));
    Validation.Add("txt2", Validator.Required("can not leave empty"));

if (IsPost)
{

    if (!Validation.IsValid())
    {
    Validation.AddFormError("there are errors");
    }

}

}

<form name="f1" action="/" method="post">

    <input name="txt1" type="text"
        class="@Validation.ClassFor("txt1")"
         />

    @Html.ValidationMessage("txt1")

    <input type="submit" name="s1" value="Send 1" />

</form>

<form name="f2" action="/" method="post">

    <input name="txt2" type="text"
        class="@Validation.ClassFor("txt2")"
        />

    @Html.ValidationMessage("txt2")

    <input type="submit" name="s2" value="Send 2" />

 </form>

A: Check out this link for handling multiple form requests http://forums.asp.net/t/1678062.aspx/1
You can handle validation in each sub section. Hope that helps

A: You can determine which form was submitted by checking to see which submit button was clicked. Its name and value will be in the Request.Form collection. If the first form in your example code was submitted, Request["s1"] would have the value "Send 1". Request["s2"].IsEmpty() would be true.
The easiest way to get round the validation issue is to use the same name ("txt1") for both text boxes. Otherwise you will have to leave the Validation helpers and write your own conditional validation routines (client and server) based on which form is submitted.


text:
Q: AngularJS: return an array inside Object I'm trying to search inside JSON file by the _id, then only return the team_members array as you see below is an example of one object inside the file
    {
        "_id": "5769484bb3ef5c696c5686d0",
        "name": "XXXXX",
        "family": "XXXXX Products",
        "description": "XXXXXXXXXXXXXXXX",
        "image": "http://localhost/img/proudct6.png",
        "__v": 8,
        "team_members": [{
            "_id": "57694567b3ef5c696c5686c2",
            "name": "XXXXXXX",
            "description": "team member",
            "image": "http://localhost/img/1.png",
            "mobile_number": "XXXXXXXXXXXXXXX",
            "specialty": "Developer",
            "summary": "only for test"
        }, {
            "_id": "57694567b3ef5c678c5686c6",
            "name": "XXXXXXX",
            "description": "team member",
            "image": "http://localhost/img/1.png",
            "mobile_number": "XXXXXXXXXXXXXXX",
            "specialty": "Developer",
            "summary": "only for test"
        }]
    }

and here my code:
this.getProductReferences = function(productId){
var dfd = $q.defer();
$http.get('database.json').success(function(database) {
  var product = _.find(database.products, function(product){ return product._id == productId; });
  var references =product.references;

  dfd.resolve(references);
});
return dfd.promise;
};

A: Here's a working plunk. Since $http is promise based you can remove the dfd promise and return it directly.  Then handle the promise resolution from your calling func.
Controller
  var self = this;

  this.getProductReferences = function(productId) {
    return $http.get('database.json').success(function(database) {
      var product = _.find(database.products, function(product) {
        return product._id == productId;
      });
      return product.references;
    });
  };

  // this could be wrapped in a func that is called from your html
  this.getProductReferences("5769484bb3ef5c696c5686d0").then(function(result) {
    self.references = result.data.team_members;
  })

I chose to pass "5769484bb3ef5c696c5686d0" in as productId just for this example

A: You can use $filter service.
var object = $filter('filter')(database, {'_id': '5769484bb3ef5c696c5686d0'});
console.log(object.team_members) // here is your team members array

A: Thanks all, it's working with me know,
some one write the answer and then delete and i don't know why but i try before and it's work..
  this.getProductReferences = function(productId) {
   return $http.get('database.json').success(function(database) {
     var product = _.find(database.products, function(product) {
       return product._id == productId;
     });
     return product.team_members;
   });
 };

 this.getProductReferences(productId).then(function(references) {
  $scope.references = references.data.team_members;
 });


text:
Q: A compact space has the Bolzano-Weierstrass property. Proof Attempt:
Consider the open cover $\{N_{\epsilon_i}(x_i)\}_{x_i\in X}$ where $N_{\epsilon_i}(x_i)$ is the open $\epsilon$-neighborhood of $x_i \in X$. Assuming that $X$ is compact, $\{N_{\epsilon_i}(x_i)\}_{x_i\in X}$ would then have a finite subcollection, $\{N_{\epsilon_i}(x_i)\}_{i=1}^n$, such that $X \subseteq \bigcup_{i=1}^n N_{\epsilon_i}(x_i)$. So if $(x_k)$ is any sequence in $X$, then for all $k \in \Bbb{N}$, there exists $i=1,2,\cdots,n$ where $x_k\in N_{\epsilon_i}(x_i)$. Since $\epsilon$ is an arbitrary positive real number, then as $\epsilon \to 0$, the preceding argument would still hold; that is $\forall\epsilon\gt 0, \forall k\in\Bbb{N}, \exists i=1,\cdots n$, such that $x_k\in N_{\epsilon_i}(x_i)$. Therefore, $(x_n)$ has at least one cluster point.

A: No, it's not really correct and the notation you're using is very confusing.
Given a sequence $(z_k)_{k\in\mathbb{N}}$ you need to find $x$ such that, for every $\varepsilon>0$, infinitely many terms of the sequence belong to $N_\varepsilon(x)$.
Assume the contrary: for every $x\in X$, there is $\varepsilon_x>0$ such that $N_{\varepsilon_x}(x)$ contains only finitely many terms of the sequence: precisely, there exists $k_x$ such that $z_k\notin N_{\varepsilon_x}(x)$, for every $k>k_x$.
The family $(N_{\varepsilon_x}(x))_{x\in X}$ is an open cover of $X$, so it admits a finite subcover, say
$$
X=\bigcup_{i=1}^n N_{\varepsilon_i}(x_i)
$$
(where $\varepsilon_i=\varepsilon_{x_i}$ for readability).
Consider $\bar{k}=\max\{k_{x_1},k_{x_2},\dots,k_{x_n}\}$. For $k>\bar{k}$, we have by construction that $z_k\notin N_{\varepsilon_i}(x_i)$, which is a contradiction.

A comment. Such compactness arguments are highly non constructive, so you cannot hope to find a particular cluster point. At most you can prove, as done before, that assuming no cluster point exists leads to a contradiction.


text:
Q: How do I sort each string within a stream of strings? I am attempting to apply the map() function to a stream of strings right now such that the new stream contains a sorted version of each string.  That is, instead of "cat" it will have "act".  I am attempting to run the method as so:
Stream<String> sortedStream = validWordStream.map(s -> Arrays.sort(s.toString().toCharArray()));

However, it complains that the stream returned is a stream of Objects, not Strings:

Question
What intuitive changes do I have to make to the map() function such that I get a stream of sorted strings?

A: since Array.sort's return type is void, you can not use its value as map result.
Also, you won't have correct result if there are surrogate pairs.
So:
Stream<String> validWord = foo();
Stream<String> validSortedWord = validWord
    .map(s -> s.codePoints().sorted().toArray())
    .map(sortedCodepoints -> new String(sortedCodePoints, 0, sortedCodePoints.length))

(Edit: changed 3rd arguments of String constructor, see Sree Kumar's comment)

A: Sort each char array and then generate a new String:
Stream<String> sortedStream = validWordStream
      .map(s -> { char[] c = s.toCharArray();
                  Arrays.sort(c);
                  return new String(c);});


text:
Q: Why objects overlap although they are far from each other in A-Frame I have created some charts which are showing in front of another object (globe) as shown below:
how objects look like in the A-Frame inspector
but when I am using a camera and move in the scene the order of the objects change and the bar charts are not visible anymore (overlap). Not sure what causing this and how to resolve it.
Here are some screenshots from this issue:
overlay screenshot 1
overlay screenshot  2
overlay screenshot 3
and the code

const globeEntity = document.getElementById('globe');

const getAlt = d => d.MMS / 2500
//const catColor = d3.scaleOrdinal(d3.schemeCategory10.map(col => polished.transparentize(0.2, col)));
// const catColor = d3.scaleOrdinal(d3.schemeCategory10.map(col => polished.transparentize(0.2, col)));
const colorArray = ['#fb0511', '#fa4400', '#f56500', '#eb8100', '#dd9a00', '#cbb100', '#b4c700', '#97db00', '#6fed00', '#05ff34']
//https://colordesigner.io/gradient-generator
var assd = "sjdhdh"
globeEntity.setAttribute('globe', {
  pointLat: 'lat',
  pointLng: 'long',
  pointAltitude: getAlt,
  pointRadius: function(d) {
    return d.Population / 3000000
  },
  pointColor: function(d) {
    return colorArray[d.Dep]
  },
  labelLat: 'lat',
  labelLng: 'long',
  labelAltitude: d => getAlt(d),
  labelDotRadius: function(d) {
    return d.Population / 3000000
  },
  labelDotOrientation: () => 'bottom',
  labelColor: function(d) {
    return colorArray[d.Dep]
  },
  labelText: 'NAME',
  labelSize: 0.05,
  labelResolution: 0.15,
  onHover: hoverObj => {
    let label = '',
      desc = '';
    if (hoverObj) {
      const d = hoverObj.data;
      label = `${d.NAME}; Pop.:${new Intl.NumberFormat().format(d.Population)}; Dep:${d.Dep}`;
      desc = `Market Share: ${d.MMS}% `
    }
    document.querySelector('#globe-tooltip').setAttribute('value', label);
    document.querySelector('#globe-tooltip-details').setAttribute('value', desc);
    //  document.querySelector('#textentity').setAttribute('text', desc)
    //document.querySelector('#globe-tooltip-details').setAttribute('visible', 'true');
  },
  onClick: clickObj => {
    let label = '',
      desc = '';
    if (clickObj) {
      const d = clickObj.data;
      label = `${d.NAME}; Pop.:${new Intl.NumberFormat().format(d.Population)}; Dep:${d.Dep} clicked`;
      desc = `Market Share: ${d.MMS}% Clk`
    }

    document.querySelector('#globe-tooltip').setAttribute('value', label);
    document.querySelector('#globe-tooltip-details').setAttribute('value', desc);
  }
});

fetch('https://cdn.glitch.global/c153e3cf-7430-444d-9897-4e97f1ef8d35/TAJSON.json?v=1658396524027').then(res => res.json()).then(pt => {
  globeEntity.setAttribute('globe', {
    pointsData: pt,
    labelsData: pt
  });
});

// default alpha for bars
var alpha = 0.9

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

function colorPicker(v) {
  console.log(v)
  if (v <= 30) {
    return "#F96B4D";
  } else if (v < 50 & v > 30) {
    return "yellow"
  } else if (v > 50) {
    return "#73FA28 ";
  }
}

// d3.csv('https://drive.google.com/file/d/1PT6mwPM42mZvhrLYdC8WmwEjwusr0AfZ', function(data){

var X_x = -0.23865 - 10.379
var Y_y = 2.2
var Z_z = -2.21058

d3.csv('https://docs.google.com/spreadsheets/d/e/2PACX-1vS8opHDQ6I1QQbwtS3oxSk4ZNZr5MGsqJnmRMX9xGKcClEhbkCYWP_tsQKF2Y8JWaO6FXkTyqDVNIJt/pub?gid=0&single=true&output=csv', function(data) {
  let dataVariable = 'MMS'
  //   let dataVariable = 'Diff 2008-2012'
  data.forEach(function(d) {
    d[dataVariable] = +d[dataVariable];
    console.log("I am in ")
    console.log(d)
  });
  console.log(data)
  let yScale = d3.scale.linear()
    .range([3, 5]) //[0, 3]
    .domain([0, 70]);

  let xScale = d3.scale.linear()
    .range([-1, 2]) //[0, 3]
    .domain([0, 30]);
  console.log(yScale.domain())

  let scene = d3.select('a-scene')
  console.log(scene)
  let bars = scene.selectAll('a-box.bar')
    .data(data)
    .enter().append('a-box')
    .classed('bar', true);

  bars.attr({
    // src:"https://cdn.glitch.global/c153e3cf-7430-444d-9897-4e97f1ef8d35/Person.jpg",
    // normalmap:"#PersonAsset_NRM",
    // normalTextureRepeat:"2 2",
    position: function(d, i) {
      var x = xScale((i * 2) + X_x);
      var y = (yScale(d[dataVariable]) / 2) + Y_y - 1.5;
      var z = Z_z
      return x + " " + y + " " + z
    },
    width: function(d) {
      return 0.07
    },
    depth: function(d) {
      return 0.03
    },
    height: function(d) {
      return d3.max([yScale(d[dataVariable]) - 3, 0.01])
    },
    opacity: alpha,
    material: "shader: standard",
    roughness: 0.1,
    //repeat: function(d) {return (1,getRandomArbitrary(1,8))},
    //  scale:"1 1 1",
    color: function(d) {
      return colorPicker(d['MMS']); // call the color picker to get the fill.

    }
  });

  let text = scene.selectAll('a-text .desc')
    .data(data)
    .enter().append('a-text')
    .classed('desc', true);

  text.attr({
    position: function(d, i) {
      var x = xScale((i * 2) + X_x)
      var y = 2.2
      var z = Z_z
      return x + " " + y + " " + z
    },
    value: function(d) {
      return d['AREA_NAME'].replace(' ', '\n');
    },
    color: '#faf443',
    align: 'center',
    baseline: 'top',
    width: 1,
  })

  let numFormat = d3.format("s")
  let numText = scene.selectAll('a-text .num')
    .data(data)
    .enter().append('a-text')
    .classed('num', true);

  numText.attr({
    position: function(d, i) {
      var x = xScale((i * 2) + X_x)
      var y = yScale(d[dataVariable]) + Y_y - 2.8
      var z = Z_z
      return x + " " + y + " " + z
    },
    value: function(d) {
      return numFormat(d[dataVariable]);
    },
    color: 'red',
    align: 'center',
    width: 1.5,
  })

  scene.append('a-text')
    .attr({
      position: '5 5 0',
      value: 'MMS (each person is equal to 50k cutomers!)',
      color: 'green',
      align: 'center',
      width: 5,
    })

});
<meta charset="utf-8">
<title>A-Frame 3D Globe Component Example</title>
<meta name="description" content="Example for 3D Globe component."></meta>

and the order of objects in the scene,

A: You have two movement systems:

*

*the movement-controls at the rig which has the entire globe as a child object

*the wasd-controls attached to the camera which is also a child of the rig.

So when You try moving the camera, You also independantly move the globe with the movement controls, positioning the bar chart inside the globe.
Here's a glitch with the wasd-controls removed


text:
Q: How does `sqrt` behaves for negative values in GLSL? I have been wondering if sqrt(num) is equal to sqrt(abs(num)) in GLSL. This exactly how this function is behaving in this shader. I am not able to find any docs or references on this behaviour. In this shader a unit circle is formed and value inside sqrt is negative for outside pixels of circle, But results are as if abs has been takent before applying sqrt.

A: according to the spec

sqrt returns the square root of x. i.e., the value √x. Results are undefined if x<0.

Which means anything can happen, but some implementations would just ignore the sign bit on the argument and return a positive number.

A: Docs answer those types of question:

Results are undefined if x<0.


text:
Q: Cleaning `sort -nr` result to CSV format in terminal I have a file that is a result from sort -nr command
  10000 a, b, c, d
    110 c, d, e, f
     11 e, f, e, d

it's from a file that contains a lot of lines like below
a, b, c, d
a, b, c, d
a, b, c, d
a, b, c, d
a, b, c, d
c, d, e, f
e, f, e, d

and then applied with this command  cat file | sort | uniq -c | sort -nr. (I hope you get the picture).
I want to change the result to
10000, a, b, c, d
110, c, d, e, f
11, e, f, e, d

I'm looking for a one liner unix command to clean the space padding in the front and change the first space to comma.

A: What if you just use awk like this?
$ awk '{a[$0]++} END{for (i in a) print a[i], i}' a | sort -nr
5 a, b, c, d
1 e, f, e, d
1 c, d, e, f

This way you can indicate the separator between the counter and the lines itself:
$ awk '{a[$0]++} END{for (i in a) print a[i], i}' OFS="->" a | sort -nr
5->a, b, c, d                                     ^^^^^^^^
1->e, f, e, d
1->c, d, e, f

Explanation

*

*{a[$0]++} for every single line ($0), keep track of how many times it has appeared. This is done with the array a[] that contains a[line]=times.

*END{for (i in a) print a[i], i} once you are done of processing the file, print the counter + line.

*OFS="whatever" indicates what field separator applies. When using print, in this case.

In case you want to use sort anyway, do use sed to perform the change:
$ sort a | uniq -c | sort -nr | sed -r 's/^[ ]*([0-9]*) /\1 -> /'
5 -> a, b, c, d
1 -> e, f, e, d
1 -> c, d, e, f

This catches the first block of digits after the leading spaces and writes it back together with ->.


text:
Q: Moodle Web Services Function Moodle 2.0 has its web service function here, but is it possible for me to create something specific or create a function which has not yet been defined??

A: Yes. It is possible. Check this documentation: http://docs.moodle.org/dev/Creating_a_web_service_and_a_web_service_function This applies to Moodle-2.0 also.


text:
Q: Changing the Power query SQL Server database settings when moving an Excel workbook I'm working on creating an excel report that collects data from a local copy of a SQL Server database on my maschine, where I use Power Query to retrieve the data. These are then loaded into a PowerPivot data model. Now I'm finished with the development and on my way to put this into production on another server on the customer's server. The Excel workbook must change database settings using sql server database user Connection (not integrated). I had hoped that I could change the database Connection Properties at the Data tab, but there are not any easy way to change the connection string to the new server. Now I can't see any option that going through every Power Query query and change them manually. I have great hope that you Power Query experts have a Nice explaination and an example how I can solve this.
Hope to hear from you soon
Regards Geir F

A: There isn't a great solution for bulk server rename today, but we're very aware of the customer demand! (I can't promise anything about upcoming features, but at some point in the past I heard the dev team discuss this feature.) I'd recommend showing your support for this feature at https://excel.uservoice.com/
If you need to solve this soon, manually opening each query and editting the server string is what you need to do, sorry :\
(If you're building new reports again, Power BI Desktop lets you parameterize the server name to a top-level query, which would allow for quick rename operations!)

A: Do you only need to change the server name? If you go to the Data Source Settings window, you can select the SQL Server source you are using and click on the "Change Source..." button. If you change the server name in that dialog, it will change the server name in all of the queries that use that source (assuming it's the first step in the query).


text:
Q: Trying to get a hang of creating larger multiple source file programs, need help [Scala] So I'm fairly new to programming, right now I'm trying to get a better understanding of how to program across multiple files.
How better to do this, than to try.
I'm also using an IDE for pretty much the first time, so that might be what's tripping me up.
Onto the meat:
So I have one file while should be the main method. In my head, it takes args, and calls the window object (it can't do anything while the window is open, right?).
package CViewerMain

import CViewerMainWindow

/**
  * Created by Matt on 6/21/16.
  */
class CViewer {
  def main(args: Array[String]): Unit = {
    var coreWindow = new CViewerMainWindow
    coreWindow.main
    return
  }
}

That method calls CViewerMainWindow, which is in the second file. Also, the IDE (Intellij IDEA) is telling me that the second one's package name does not match the directory structure, but both the packages are in the same dir.
package CViewerWindow

import scala.swing._
import swing.event.UIElementResized

/**
  * Created by Matt on 6/21/16.
  */
package object CViewerMainWindow extends SimpleSwingApplication {
  def top = new MainFrame {
    title = "Hello, World!"
    preferredSize = new Dimension(320, 240)
    // maximize
    visible = true
    contents = new Label("Here is the contents!")
    listenTo(UI.this)
    reactions += {
      case UIElementResized(source) => println(source.size)
    }
  }
}

So What I assume is going wrong, is somewhere in the process I am not giving one of the files enough/correct information about the other.

A: Packages on in scala and java map pretty well onto your directory structure. If the two classes are in the same directory, they are in the same package.
So CViewerMain should be the package for the   CViewerMainWindow class.

A: Ok based on the project structure both CViewerMain and CViewerMainWindow classes are in same folder aka package. So you need to follow Robert's Answer.
Change the below
package CViewerWindow

to
package CViewerMain


text:
Q: proving that an element g is primitive How do I go about proving that an element g is primitive? If I let p be a prime. Is it then the same as proving that every non-zero element in $Z_p$  can be written as a power of g?

A: If you can factorize $p-1$, then it is enough to show that for all prime divisors $q$ of $p-1$, $g^{(p-1)/q}$ is not equal to $1$ mod $p$. This can be checked efficiently for $p$ in the thousands of digits.


text:
Q: Java - Fire an event to another thread on data reception I have to write a server that manages several Datagram sockets.
I know about the selector capabily of java.nio that allows async management of different sockets
However, after having parsed the message I need to fire an event to another thread (optionally with some parameters).
Is there a way to make other threads to "register" to the one that manages the sockets and make them aware that data is ready for them?
Thanks in advance

A: You can use have an ExecutorService that backs the async network call.  The Future returned at that point can act as the message passer upon completion.
public class SocketWork<T>{

    private final ExecutorService service = Executors.newSingleThreadExecutor();
    private final Future<T> future;

    public SocketWork(){
        future = service.submit(new SocketWorkCallable<T>());
    }

    public T register(){
        // all threads entering register will block until
        // the SocketWorkCallable is completed and returns.
       return future.get();
    }
}

An alternative is to use a CountdownLatch.
public class SocketWork<T>{

    private final CountdownLatch latch = new CountdownLatch(1);
    private T message;

    public void executeSocketWork(){
        //execute work and get message
        this.message = returnedMessage;
        latch.countDown();
    }

    public T register(){
        latch.await();
        return message;
    }
}

You could do something similar with a ReadWriteLock as well.
As you can imagine this will only work for a single task.  Per instance of SocketWork


text:
Q: Is there a more elegant way to search the station index? I work on a genetic algorithm for a robotic assembly line balancing problem (assigning assembly operations and robots to stations to minimize the cycle time for a given number of stations). The solution is represented by an ArrayList (configuration) which holds all the operations in the sequence assigned to different stations. Furthermore, I have two more ArrayLists (robotAssignment, operationPartition) which indicate where a new station starts and which robot is assigned to a station. For example, a solution candidate looks like this (configuration, robotAssignment, operationPartition from top to bottom):
Initial cycle time: 50.0
|2|7|3|9|1|5|4|6|8|10|
|2|1|3|2|
|0|2|5|7|

From this solution representation we know that operations 3, 9, and 1 are assigned to the second sation and robot 1 is used.
I need to keep track of the station an operation is assigned to. I tried a lot to store this in the Object Operation itself but I always ended up in problems and therefore I want to write a method that gives me the stations index of an operation.
Here is what I have coded so far:
// Get the station of an operation
public int getStation(Operation operation) {
    int stationIndex = 0;
    int position = configuration.indexOf(operation);

    for (int i = 0; i < GA_RALBP.numberOfStations ; i++ ) {
        if (i < GA_RALBP.numberOfStations - 1 &&    operationPartition.get(i) != null) {
            if (isBetween(position, (int) operationPartition.get(i), (int) operationPartition.get(i + 1))) {
                return stationIndex + 1;
            } else {
                stationIndex++;
            }
        }
        else if (i >= GA_RALBP.numberOfStations - 1 && operationPartition.get(i) != null) {
            if (isBetween(position, (int) operationPartition.get(i), configurationSize())) {
                return stationIndex + 1;
            }
        }
    }
    return -1;
}

// Check if value x is between values left and right including left
public static boolean isBetween(int x, int left, int right) {
    if (left <= x && x < right ) {
        return true;
    }
    else {
        return false;
    }
}

However, this does not seem to be (a) very elegant and (b) if I have to do this for a large number of operations the runtime could become a problem. Has anoyone an idea how to solve this more efficiently?

A: Why not make the partitioning explicit (replaces your operationPartition) - something like:
    Map<Integer, Integer> operationToStationMapping = new HashMap<>();
    operationToStationMapping.put(2,0);
    operationToStationMapping.put(7,0);
    operationToStationMapping.put(3,2);
    operationToStationMapping.put(9,2);
    operationToStationMapping.put(1,2);
    operationToStationMapping.put(5,5);
    operationToStationMapping.put(6,7);
    operationToStationMapping.put(8,-1);
    operationToStationMapping.put(10,-1);

Then getStation() becomes:
getStation(int operation) {return operationToStationMapping.get(operation);}


text:
Q: angularjs watch jquery directive value I'm running into a bit trouble with $scope.$watch. The situation is I'm using this nice plugin to create a dropdown:
http://wenzhixin.net.cn/p/multiple-select/docs/
in my view file, I have:
<select id="hid" multiple="multiple" name="hname">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>

in my js controller file:
$('#hid').change(function() { $scope.hvalue = $(this).val() }).multipleSelect({ width: '20%', selectAll:false })

$scope.testwatch = []
$scope.$watch(function() {
    return $scope.hvalue
  }, function(value) {
      if(value) {
        $scope.testwatch = $scope.hvalue
      }
     }, true)

The problem is that when the the user changed the dropdown, $scope.hvalue is modified. However, the $watch function is never executed. Any idea why this happens?
Thanks a lot!

A: If I were to hazard I guess I would say, your jquery change function isn't in the angular digest cycle.
To implement your functionality, I would recommend using ng-model on your select tag and keep a watch on that ng-model like this:
HTML:
<select id="hid" multiple="multiple" name="hname" ng-model="obj.hvalue">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>

Controller:
$scope.obj = {};
$scope.obj.hvalue = '';
$scope.$watch('obj.hvalue', function(newval, oldval) {
    console.log(newval);
})


text: Q: How to show specific Sentry alerts to specific users only? Development team uses Sentry to get technical alerts. Some technical failures need to be communicated to business team also. Business team is also tech savvy and can have sentry accounts. Is there an option in Sentry to send certain technical alerts to specific set of users?


text:
Q: How to limit the dimensions of a JDialog I'm working on a JDialog subclass (let's call it PendenciesDialog) which shows an arbitrary number of equally sized, vertically stacked JPanels to the user (minimally one) and a close button below them. No interaction involved besides building the JDialog and packing it, displaying it to the user and letting them close the dialog.
These JPanels show some info on invididual monthly payment pendencies, such as account name, the pendency status and a clickable link to the payment management system. I don't think we need to care about how they are constructed.
Now for my question. I want to keep the width of the JDialog fixed at half of the screen width and limit its maximum height to half of the screen height, or shorter if the number of pendencies is small or just one. If I'm unable to achieve that by adjusting the JDialog (e.g. by overriding the JDialog's getXXXSize() methods), I'm okay with adjusting its subcomponents. I'm not sure what I need to do though.
To construct the JDialog I have set its layout manager to BoxLayout with PAGE_AXIS alignment, then added a JScrollPane to it backed by a JPanel (let's call this JPanel's reference variable pendenciesPanel) and then added a close button. That JPanel also has a BoxLayout manager with PAGE_AXIS alignment and will contain the individual pendency JPanels (actually due to the equal sizes requirement I think it should actually be a GridLayout).
I intend the JScrollPane to show a view port of pendenciesPanel and to provide scrolling if the number of pendencies is too large to fit the JDialog's (or the JScrollPane's for that matter) maximum height.
So based in this description, how do I achieve the JDialog size adjustments? From what I've read about it it seems that the most appropriate approach would be to override its getXXXSize() methods, for instance:
private final Dimension SCREEN_DIMENSION = Toolkit.getDefaultToolkit().getScreenSize();

@Override
public Dimension getMaximumSize() {
    return new Dimension(SCREEN_DIMENSION.width / 2, SCREEN_DIMENSION.height / 2);
}

but my attempts to override getMinimumSize(), getPreferredSize(), getSize() etc. don't seem to work, or perhaps I'm implementing them wrong. Will I need to adjust its internal subcomponents? Or just adjusting the JDialog will be enough? If so, how?

A: I created a simple GUI to illustrate my comment.  Here's the JFrame.

Here's the JDialog.

Here's the complete example code.  You'll have to modify the createPendenciesPanel method to be more realistic.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class JDialogTest implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new JDialogTest());
    }

    private JFrame frame;

    @Override
    public void run() {
        frame = new JFrame("JDialog Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createMainPanel());

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(
                150, 100, 150, 100));
        panel.setPreferredSize(new Dimension(400, 600));

        JButton button = new JButton("Open JDialog");
        button.addActionListener(new ButtonListener());
        panel.add(button);

        return panel;
    }

    public class ButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            new PendenciesDialog(frame, "Pendencies Dialog");
        }

    }

    public class PendenciesDialog  extends JDialog {

        private static final long serialVersionUID = 1L;

        public PendenciesDialog(JFrame frame, String title) {
            super(frame, true);

            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            setTitle(title);

            add(createMainPanel(frame));
            pack();
            setLocationRelativeTo(frame);
            setVisible(true);
        }

        private JPanel createMainPanel(JFrame frame) {
            JPanel panel = new JPanel(new BorderLayout());

            JPanel displayPanel = createDisplayPanel();
            JScrollPane scrollPane = new JScrollPane(displayPanel);
            panel.add(scrollPane, BorderLayout.CENTER);

            Dimension d = frame.getSize();
            Dimension p = displayPanel.getPreferredSize();
            panel.setPreferredSize(new Dimension(p.width + 50, d.height / 2));

            return panel;
        }

        private JPanel createDisplayPanel() {
            JPanel panel = new JPanel(new GridLayout(0, 1, 10, 10));
            panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

            for (int i = 0; i < 6; i++) {
                panel.add(createPendenciesPanel());
            }

            return panel;
        }

        private JPanel createPendenciesPanel() {
            JPanel panel = new JPanel(new FlowLayout());
            panel.setBackground(Color.LIGHT_GRAY);
            panel.setPreferredSize(new Dimension(100, 200));

            return panel;
        }

    }

}


text:
Q: How can I connect Google App Engine to Elastic Cloud? I'm trying to connect to my cluster on Elastic Cloud using elasticsearch-py on GAE, but I'm running into the following error:

ConnectionError: ConnectionError('VerifiedHTTPSConnection' object has no attribute '_tunnel_host') caused by: AttributeError('VerifiedHTTPSConnection' object has no attribute '_tunnel_host')

I've tried this fix that I've seen in a number of places already that reference the '_tunnel_host' error, but it's not resolving my issue:
from requests_toolbelt.adapters import appengine
appengine.monkeypatch()

I've also tried a few variations that I've seen for the es declaration, but none of them have worked; for example:
es = Elasticsearch(["https://elastic:password@xxxxx.us-central1.gcp.cloud.es.io:9243"],
                   send_get_body_as='POST',
                   use_ssl=True,
                   verify_certs=True)

I'd like to be able to establish the connection and begin sending and consuming data from my cluster, but can't find a way to do this.  Any help would be much appreciated!

A: There is an article with example of real word app Elasticsearch on Google Cloud with Firebase functions.
On the other hand there is Google Cloud Marketplace with many available Elasticsearch solutions, for example:

1.You can deploy and configure Elasticsearch Cluster that works with kubernetes, using Google Click to Deploy containers.

*Or Elasticsearch complete solution using virtual machines provided by Google.


text: Q: Titanium . identify current login facebook user? currently am working in a titanium. in which i stored facebook users login  and try to login with specified user. How to set the current user token in titanium.


text:
Q: Arithmetic operations using list I am trying to write a MATLAB code into python. The original MATLAB code is from this following vid: https://www.youtube.com/watch?v=T97ddyTMuro. Briefly, the MATLAB code is as follows:
v = 10;
theta = linspace(15, 75, 100);
g = 9.81;
t = 2*v*sin(theta)/g;
r = v*cos(theta).*t;
plot(r,theta)

I was trying to recreate this code in python, attached herewith is what I have tried and failed:
import numpy as np
import math as m
import matplotlib.pyplot as plt
theta = np.linspace(0,70,100)
v = 10 # velocity (m/s)
g = 9.81 # accel. due to grav.
t = []
r = []
a = []
multi =[]
for i in np.linspace(0,70,100):
    t.append(2*v*(m.sin(np.deg2rad(i)))/g)
    for j in np.linspace(0,70,100):
        r.append(v*(m.cos(np.deg2rad(i))))
        a.append(r[j]*t[j])

Unable to multiply two lists as they are not integers.

A: An easier approach is to directly use only numpy code:
import numpy as np
import matplotlib.pyplot as plt
theta = np.deg2rad(np.linspace(0,70,100))
v = 10 # velocity (m/s)
g = 9.81 # accel. due to grav.

t1 = 2*v*np.sin(theta)/g
r = v*np.cos(theta)*t1  # will compute elementwise multiplication

plt.plot(r, theta)
plt.show()


text:
Q: Push multiple array fields into separate arrays I have a requirement where I have data in this format. How can I or What is the best and easiest to get the output in the below format?
users = [
{
id: "1",
name: "Norah"
},
{
id: "2",
name: "Alyx"
}
];
accounts = [
{
account: "IRA-4679",
user: "1",
balance: "5175.36"
},
{
account: "AAA-3571",
user: "1",
balance: "3106701.85"
},
{
account: "AAA-4671",
user: "1",
balance: "138971.19"
},
{
account: "ROT-1687",
user: "2",
balance: "2686.00"
},
{
account: "AAA-7894",
user: "2",
balance: "68761.32"
},
{
account: "IRA-6818",
user: "2",
balance: "564.67"
},
{
account: "IRA-6819",
user: "2",
balance: "6564.67"
}
];

Output
["Norah | AAA-6818 | 564.67","Norah | AAA-4671 | 138971.19"]

Is it something related to splitting array and merging into one based on id or what should I do it here?

A:

const users=[{id:"1",name:"Norah"},{id:"2",name:"Alyx"}];
const accounts=[{account:"IRA-4679",user:"1",balance:"5175.36"},{account:"AAA-3571",user:"1",balance:"3106701.85"},{account:"AAA-4671",user:"1",balance:"138971.19"},{account:"ROT-1687",user:"2",balance:"2686.00"},{account:"AAA-7894",user:"2",balance:"68761.32"},{account:"IRA-6818",user:"2",balance:"564.67"},{account:"IRA-6819",user:"2",balance:"6564.67"}];

const res = accounts.map(e => [
  users.find(x => x.id === e.user).name,
  e.account,
  e.balance
].join(" | "))

console.log(res)

A:

users = [
  {
    id: "1",
    name: "Norah",
  },
  {
    id: "2",
    name: "Alyx",
  },
];

accounts = [
  {
    account: "IRA-4679",
    user: "1",
    balance: "5175.36",
  },
  {
    account: "AAA-3571",
    user: "1",
    balance: "3106701.85",
  },
  {
    account: "AAA-4671",
    user: "1",
    balance: "138971.19",
  },
  {
    account: "ROT-1687",
    user: "2",
    balance: "2686.00",
  },
  {
    account: "AAA-7894",
    user: "2",
    balance: "68761.32",
  },
  {
    account: "IRA-6818",
    user: "2",
    balance: "564.67",
  },
  {
    account: "IRA-6819",
    user: "2",
    balance: "6564.67",
  },
];

let finalOutput = users
  .sort((a, b) => (a.name > b.name ? 1 : -1))
  .map((user) =>
    accounts
      .filter((account) => account.user == user.id)
      .sort((a, b) => (parseFloat(a.balance) > parseFloat(b.balance) ? -1 : 1))
      .map(
        (filteredAccount) =>
          user.name +
          " | " +
          filteredAccount.account +
          " | " +
          filteredAccount.balance
      )
  );

console.log(finalOutput);

This should do the trick, for me running the above snippet turns your two inputs into an array of two arrays with the shape of this:
["Alyx | AAA-7894 | 68761.32", "Alyx | IRA-6819 | 6564.67", "Alyx | ROT-1687 | 2686.00", "Alyx | IRA-6818 | 564.67"]
and
["Norah | AAA-3571 | 3106701.85", "Norah | AAA-4671 | 138971.19", "Norah | IRA-4679 | 5175.36"]
EDIT: As requested I have now added sorting to first sort by name and then sort by account balance in descending order from largest to smallest.
Resulting in the updated outputs seen above.

A: Create a Map of the users, then map() over the accounts and use
destructuring and a template literal to return your string.

const
  users = [{ id: "1", name: "Norah" }, { id: "2", name: "Alyx" }],
  accounts = [{ account: "IRA-4679", user: "1", balance: "5175.36" }, { account: "AAA-3571", user: "1", balance: "3106701.85" }, { account: "AAA-4671", user: "1", balance: "138971.19" }, { account: "ROT-1687", user: "2", balance: "2686.00" }, { account: "AAA-7894", user: "2", balance: "68761.32" }, { account: "IRA-6818", user: "2", balance: "564.67" }, { account: "IRA-6819", user: "2", balance: "6564.67" }],

  userMap = new Map(users.map(({ id, name }) => [id, name])),
  result = accounts.map(({ user, account, balance }) =>
    `${userMap.get(user)} | ${account} | ${balance}`);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you need to maintain the ability to access individual properties of user/account elements it will be better to keep them as objects. You can merge the user name into the accounts array and define a toString() function to easily convert either a single userAccount object to a string, or to map the entire array to strings as needed.

const
  users = [{ id: "1", name: "Norah" }, { id: "2", name: "Alyx" }],
  accounts = [{ account: "IRA-4679", user: "1", balance: "5175.36" }, { account: "AAA-3571", user: "1", balance: "3106701.85" }, { account: "AAA-4671", user: "1", balance: "138971.19" }, { account: "ROT-1687", user: "2", balance: "2686.00" }, { account: "AAA-7894", user: "2", balance: "68761.32" }, { account: "IRA-6818", user: "2", balance: "564.67" }, { account: "IRA-6819", user: "2", balance: "6564.67" }],

  userAccountToString = (acct) => `${acct.user} | ${acct.account} | ${acct.balance}`,
  userMap = new Map(users.map(({ id, name }) => [id, name])),
  userAccounts = accounts.map(({ user, ...account }) =>
    ({ user: userMap.get(user), ...account }));

// accounts with user name merged
console.log(userAccounts);
console.log(userAccounts.map(userAccountToString));

// sort as needed
console.log('\nBy balance:')
userAccounts.sort((a, b) => a.balance - b.balance);
console.log(userAccounts);
// output array as account strings
console.log(userAccounts.map(userAccountToString));

// sort as needed
console.log('\nBy user:')
userAccounts.sort((a, b) => a.user.localeCompare(b.user));
console.log(userAccounts);
// output array as account strings
console.log(userAccounts.map(userAccountToString));
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Is it possible to load the contents of a generated bundle in another module in webpack? I'm looking to load a generated JS bundle as a string from another module (one that isn't included in the aforementioned bundle — i.e. no circular dependencies).
Something ideally like this:

webpack.config.js
module.exports = {
  entry: {
    foo: 'foo.js',
    bar: 'bar.js',
  }
  ...
}

bar.js
import fooContents from '<something that gets me foo>'

console.log(fooContents);

I was thinking I might need to write a custom loader (e.g. import fooContents from 'my-loader!?bundle=foo') or even a custom plugin, but I'm hoping something like that already exists. After looking through webpack-contrib and other places, I haven't found anything though :-/

A: For posterity, I indeed ended up forking worker-loader, which spins up a child compiler.


text:
Q: What is the opposite of a tail recursive solution? I'm solving problem 4 in the 99 problems of Ocaml and I'm still learning OCaml
Question 4 reads

OCaml standard library has List.length but we ask that you reimplement it. Bonus for a tail recursive solution.

So as per my understanding a recursive solution merits bonus points because it more efficient than a potentially easier more verbose solution
I came up with this for a tail recursive solution
let length in_list =
  let rec find_len cur_length = function
  | [] -> cur_length
  | hd::tl -> find_len (cur_length + 1) tl
  in find_len 0 in_list
;;

And as per my understanding of tail recursion this is valid because it operates recursively on the tail
My question is what is the opposite of this? What is a valid non tail recursive solution
I guess it would be something that operates recursively on the head of the list
I came up with
let hd_rec_length in_list =
  let rec pop_last saved_list= function
  | [] -> saved_list
  | [last] -> saved_list
  | hd::tl -> pop_last (saved_list@[hd]) tl
  in
    let rec hd_rec_find_len cur_length in_list =
    match in_list with
      | [] -> cur_length
      | hd::tl -> hd_rec_find_len (cur_length+1) (pop_last [] in_list)
      in hd_rec_find_len 0 in_list
;;

But my gut tells me I'm missing something more obvious than this and the second solution seems like too much work and the first seems more natural and easy, what am I missing?

A: A tail-recursive function is a recursive function where all recursive calls happen in a tail position. What that means is that the recursive call must be the last thing that happens in any given path through the function. All of the recursive functions in your question are tail recursive.
Tail recursion does not mean recursing on the tail of the list. In fact a tail recursive function doesn't have to involve lists at all.
So a non-tail recursive function would be any function where you do anything after the recursive call (or there are even multiple recursive calls that aren't mutually exclusive). Usually that means applying some other function to the result of the recursive function after the recursive function returns.
A non-tail recursive version of length would be:
let rec length = function
| [] -> 0
| _::tl -> 1 + length tl

This is not tail-recursive because the last thing that happens here is the addition, not the call to length. So after the recursive call returns, we add 1 to its result and then we return as well.


text:
Q: How do I install a bitnami LAMP module by SSH command line? This is a pretty straightforward question that I cannot seem to find an answer for. I already have a running Bitnami LAMP stack on an Amazon EC2 instance. Where do put the installer (bitnami-roundcube-1.0.1-0-module-linux-installer.run) and what commands do I need to do to run in?
I've tried:
sudo ./bitnami-*
And:
sudo ./bitnami-* --mode text
Both instances throw no errors but I also receive no messages nor a text mode installation process.
I also cannot find any files installed anywhere on the Ubuntu installation.
I downloaded this:
https://bitnami.com/stack/lamp/modules#roundcube
And I tried both 32-bit and 64-bit installers just in case I wasn't running 64-bit (which I'm pretty sure I am).


text:
Q: hyperbolic tangent vs tangent The tangent of an angle is the ratio of the length of the opposite side to the length of the adjacent side (in a right triangle). Is there a similar definition for the hyperbolic tangent?
The reason I ask this question is to get a geometrical intuition of the notion of rapidity in relativity: $$\phi = \mbox{tanh}^{-1}(v/c)$$

A: (just comments transfered to answer) s
$ \phi$ cannot be represented by an angle.
if only because it has a range $ − \infty < \phi < \infty $ , while angles have a range $ − \pi < x < \pi $ )
$ \phi$ can be represented by an area
see en.wikipedia.org/wiki/Hyperbolic_function and math.stackexchange.com/a/451372/88985 .
$ \phi$ is twice the area between:

*

*the x-axis,

*the line conecting the origin and the point (1,tanh) and

*the hyperbola,

I agree it is all not very intuitive, but then you could also see the normal trigonomic functions as functions of the area of the enclosed circle sector instead as function of the arc length.


text:
Q: NHibernate - Creating a proxy instance failed My data model looks like this.
public abstract class BasePivotField
    {
        public virtual int SystemId { get; set; }
        public virtual int Version { get; set; }
        public virtual string FieldName { get; set; }
        public virtual string FieldValuePrefix { get; set; }
        public virtual Field Field { get; set; }
        public abstract PivotFieldType FieldType { get; }
    }

public class PivotColumnField : BasePivotField
{
    public virtual CriteriaWithField FieldCriteria { get; set; }
    public virtual int Width { get; set; }

    public override PivotFieldType FieldType
    {
        get { return PivotFieldType.ColumnField; }
    }
}
public class PivotTableControl : BaseControl
{
        public virtual Criteria Criteria { get; set; }
        public virtual int Height { get; set; }
        public virtual PagingProperties PagingProperties { get; set; }
        public virtual IList<BasePivotField> PivotTableFields { get; set; }
}

I use Fluent NHibernate mapping and the mapping classes are below
public class PivotTableControlMap : SubclassMap<PivotTableControl>
    {
        public PivotTableControlMap()
        {
            References(x => x.Criteria).Cascade.All().Column("PivotTableCriteria");
            Map(x => x.Height);
            Component(x => x.PagingProperties);
            HasMany(x => x.PivotTableFields)
                .KeyColumn("PivotTableId")
                .Cascade.AllDeleteOrphan()
                .AsBag();
        }
    }

public class PivotTableFieldMap : ClassMap<BasePivotField>
    {
        public PivotTableFieldMap()
        {
            Table("PivotTableField");
            Id(x => x.SystemId);
            Version(x => x.Version);
            Map(x => x.FieldName);
            References(x => x.Field).Cascade.All().Column("FieldId");
            Map(x => x.FieldValuePrefix);
            DiscriminateSubClassesOnColumn("PivotFieldType");
        }
    }

public class PivotColumnFieldMap : SubclassMap<PivotColumnField>
{
    public PivotColumnFieldMap()
    {
        Component(x => x.FieldCriteria).ColumnPrefix("PivotTable");
        Map(x => x.Width);
    }
}

There are other classes that inherit from BasePivotField, but I have left them out for brevity.
The problem is that when I load the PivotTableControls from the database using NHibernate, the PivotTableFields collection does not get loaded.
The exception thrown says 'Creating a proxy instance failed'. Looking into the exception deeper, I can see that the PivotTableFields says 'illegal access to loading collection'.
I can confirm that the Session is not closed. If I don't use lazy load, the problem still persists.
I have used a similar kind of model and mapping in other places and they work fine. What am I doing wrong here?
Any clues will be highly appreciated!

A: I'm not sure if it resolve the issue but anyway you need add DiscriminatorValue(x => x.FieldType ) in PivotColumnFieldMap


text:
Q: Kotlin lazy initialization in subclass I'm trying to build a string with properties that are initialized in a subclass.
I read about lazy initialization but somehow this doesn't work as I expected.
abstract class SubProcessFullNameBuilder(technicalDomain: TechnicalDomainEnumeration) {

    protected val moduleName = "td.${technicalDomain.value().toLowerCase()}.shared"

    private val packageName by lazy { packageName() }
    private val processName by lazy { processName() }

    val processFullName: String = "$moduleName/$packageName.$processName"

    protected abstract fun packageName(): String
    protected abstract fun processName(): String
}

class WorkerFullNameBuilder(
        private val jmsDirection: JmsDirectionEnumeration,
        technicalDomain: TechnicalDomainEnumeration,
        private val cdmCode: String) : SubProcessFullNameBuilder(technicalDomain) {

    override fun packageName() = "$moduleName.workers.${jmsDirection.value().toLowerCase()}.${cdmCode.toLowerCase()}"
    override fun processName() = "Worker"
}

Since I have overridden the packageName() and processName() properties, I would expect that on calling the packageName property it would use the implementation from the subclass.
But when I call the processFullName property, it throws a java.lang.NullPointerException.
val builder = WorkerFullNameBuilder(JmsDirectionEnumeration.ESB_IN, TechnicalDomainEnumeration.INFOR, "ccmd")
val name = builder.processFullName

How can I initialize the packageName and processName properties in a proper way?

A: This is a case of calling a non-final method in a constructor and thus accessing uninitialized variables.
This line is still evaluated eagerly, at the time when the base class is constructed:
val processFullName: String = "$moduleName/$packageName.$processName"

To get the values of the two lazy properties, this will make calls to the abstract methods, of which packageName() refers to jmsDirection and cdmCode to return its value - these properties are not initialized yet, because their values are set after the superclass constructor runs. Here's a simplified version of the subclass' constructor, decompiled back to Java:
public WorkerFullNameBuilder(@NotNull JmsDirectionEnumeration jmsDirection, @NotNull TechnicalDomainEnumeration technicalDomain, @NotNull String cdmCode) {
    super(technicalDomain);
    this.jmsDirection = jmsDirection;
    this.cdmCode = cdmCode;
}

As a demonstration, if you don't refer to these, for example, if you return constants in both of the subclass methods, your code will actually run fine:
override fun packageName() = "foo"
override fun processName() = "Worker"

However, the solution you need here is most likely to make the processFullName property itself lazy instead of the two values it uses (which you're evaluating at constructor time right now anyway, so you're not making use of them being lazy). This means you don't even need those two as separate properties:
abstract class SubProcessFullNameBuilder(technicalDomain: TechnicalDomainEnumeration) {

    protected val moduleName = "td.${technicalDomain.value().toLowerCase()}.shared"

    val processFullName by lazy { "$moduleName/${packageName()}.${processName()}" }

    protected abstract fun packageName(): String
    protected abstract fun processName(): String

}


text:
Q: Why the scaling is changing very slow? using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scale : MonoBehaviour
{
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;
    public bool scaleUp = false;
    public Coroutine scaleCoroutine;
    public bool scalingHasFinished = false;
    public DepthOfField depthOfField;

    private void Start()
    {
        transform.localScale = minSize;
    }

    private void Update()
    {
        if(depthOfField.depthOfFieldProcessEnded == true)
        {
            StartCoroutine(ScaleOverTime());
            depthOfField.depthOfFieldProcessEnded = false;
        }
    }

    public IEnumerator ScaleOverTime()
    {
        float counter = 0;
        Vector3 startScaleSize = transform.localScale;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            transform.localScale = Vector3.Lerp(startScaleSize, maxSize, counter / duration);

            yield return new WaitForSeconds(duration);
        }

        scalingHasFinished = true;
    }
}

I want it to scale from the minSize to maxSize over 1 second. But instead it's changing the scale each 1 second by  0.01 until it's getting to the maxSize.
It's making the whole scaling smooth by 1 second.


text:
Q: How to set parameter for customoid when run snmpset using net-snmp Q) I want to run the Snmpset command to set the parameter for custom oid but unable to set.
I have create a exec section but it only run on walk and get not on set. So how to take
parameter in backend from command.


text:
Q: Generating a regex from a function in PHP I need a function that could generate a regex.  For example if I write
$pat = "My {$var} is {$var2}"

to generate a regex that when I use
preg_match($pat,"My name is Kevin",$matches);

to return
$matches[1] = 'name';
$matches[2] = 'Kevin';

and the the string could be : "My $nameword is $name and i'm $age years old"
And the problem is:
FIG1
<?php
function gen_pattern($string)
{
<--- add code for generating pattern --->
}
?>

FIG2
$pat = gen_pattern('my name is {$X}');
ereg($pat,'my name is moo',$regs);
//$regs[1] == "moo"
([^\s]*)

$pat = gen_pattern('my {$YZ} is {$IJK}');
ereg($pat,'my name is moo',$regs);
//$regs[1] == "name", $regs[2] == "moo"

My homework's description is as follows:

Figure 1 shows a function which can generate a regular expression, usable for the ereg function.
Figure 2 shows how the pattern should work. In the given string, each item {$ABC} represents a placeholder, i.e. {$X} is the single place holder in "my name is {$X}", and there are two place holders in "my {$YZ} is {$IJK}". A place holder can be of any length above zero.
In the resulting pattern, each place holder represents one single word of the text, which has to be added to the result list. I.e. {$X} represents the next word after "my name is". As a result, $regs[1] becomes "moo" if the pattern is used on text "my name is moo". Assume that we have only texts of form [a-z ]* (note the white space).

My Task:

Fill in the green spot in Figure 1. Dont bother with error handling or checking the correct syntax of given string (i.e. "my name is {{}" or similar invalid input will not occur).

And I don't know where to begin.

A: this may work:
function gen_pattern($str){
    $str = preg_replace('/(\{[\$a-zA-Z]+\})/', '(\w+)', $str);
    return '/'.$str.'/';
}
$p = gen_pattern('my {$xx} is {$X}');

preg_match($p, 'my name is moo', $m);

$m will be:
array(3) {
  [0] =>
  string(14) "my name is moo"
  [1] =>
  string(4) "name"
  [2] =>
  string(3) "moo"
}

A: Something like this will help you..:
function gen_pattern($string)
{
    return "@".preg_replace("@(\{\$(.*?)\})@msi", "(?P<$2>.*?)", $string)."@";
}

so you will get a result with your variables as keys.


text:
Q: How can I render to an offscreen context to examine a section of a raster layer in mapbox-gl-js? I (and others) need to read the color value of the raster pixel in a layer at a particular point. I have an algorithm that works when there is only the subject layer, but this uses the main gl context and so it will interfere with other rendered layers. How can I render to a separate context so I get the raster piece I need without interfering with other layers?
    colorForLayerPoint(layerId: string, point: PointLike) {

    const layer = this.style._layers[layerId];
    if (layer.type !== 'raster') { return }

    const sourceCache = this.style._getLayerSourceCache(layer);

    sourceCache.prepare(this.context);

    const coordsAscending: Array<OverscaledTileID> = sourceCache.getVisibleCoordinates();
    const coordsDescending: Array<OverscaledTileID> = coordsAscending.slice().reverse();

    // Rebind the main framebuffer now that all offscreen layers have been rendered:
    // this.context.bindFramebuffer.set(null);
    this.context.viewport.set([0, 0, this.width, this.height]);

    this.context.clear({
        color: 'rgba(0,0,0,0)', //options.showOverdrawInspector ? Color.black : clearColor,
        depth: 1,
    });
    this.clearStencil();

    this._showOverdrawInspector = false; //options.showOverdrawInspector;

    this.renderPass = "translucent";

    // For symbol layers in the translucent pass, we add extra tiles to the renderable set
    // for cross-tile symbol fading. Symbol layers don't use tile clipping, so no need to render
    // separate clipping masks
    const coords = sourceCache
        ? coordsDescending
        : undefined;

    this._renderTileClippingMasks(
        layer,
        sourceCache,
        sourceCache ? coordsAscending : undefined
    );
    this.renderLayer(this, sourceCache, layer, coords);

    const gl = this.context.gl;
    var pixel = new Uint8Array(4);
    gl.readPixels(
        point.x * window.devicePixelRatio,
        this.height - point.y * window.devicePixelRatio,
        1,
        1,
        gl.RGBA,
        gl.UNSIGNED_BYTE,
        pixel
    );

    return pixel;
}


text:
Q: Is there a way to know when a script has finished running on a terminal? I ran a python script overnight, and it was already done when I checked the code in the morning.
Is there a time log stored somewhere of when the python script finished executing? Or maybe a log of the subprocesses running on the system that would give me the time when the script finished running? Or a terminal history? Is there a way to do this, without having to include a time logger in the script itself?
I am running my code on an Ubuntu 18.04 PC.

A: I don't know if Ubuntu automatically logs your script, but you can always use datetime with print, which is an easy way of knowing when it starts of finishes. Here's a link


text:
Q: Monkey patching a Pathname#gsub instance method If you look through the documentation for Pathname you won't find a Pathname#gsub instance method. But there is a Pathname#sub.
So you get a (NoMethodError) when you try to call it:
require 'pathname'

some_pathname = Pathname.new("path/with/two/path/occurances/")
p some_pathname.sub(/path/, 'foobar')
#=> #<Pathname:some/foobar/with/two/occurances/of/path>
p some_pathname.gsub(/path/, 'foobar')
# undefined method `gsub' (NoMethodError)

Why wouldn't Pathname have a gsub method? It seems like if you have a sub you might as well have a gsub.
Because ruby has open classes you can monkey patch the Pathname class and add a gsub instance method.
That's what I did below:
require 'pathname'

class Pathname
  def gsub(re, str)
    gsubbed_pn = self
    while gsubbed_pn.to_s =~ re
      gsubbed_pn = gsubbed_pn.sub(re, str)
    end
    gsubbed_pn
  end
end

monkey_pathname = Pathname.new("path/with/two/path/occurances")
p monkey_pathname.gsub(/path/, 'foobar')
#=> #<Pathname:foobar/with/two/foobar/occurances>
p monkey_pathname
#<Pathname:path/with/two/path/occurances>

But I've read that monkey patching should probably not be the first tool I reach for.
Is there a better alternative in this case? Is Pathname missing a gsub method by design?


text:
Q: Change View Title when Navigating Back from a (Sub) View I have a RootView with 5 buttons. When a button is pressed, I change the title of the current view (so the Back Button is brief) before displaying the selected view. When transitioning to the new (sub) view, I send the pushViewController message to the NavigationController through the AppDelegate.
When the Back Button is selected in the sub-view, I would like to change the title back to the verbose title.
Could anyone point out how I would accomplish the title change of the RootView when leaving a sub view?

A: Set the title in viewWillAppear of you RootView:
- (void)viewWillAppear:(BOOL)animated {
    self.title = @"RootView";
}

If you use the back button on a sub-view, the root view will get the right title.


text:
Q: One QuerySet for two tables (one to many related) I have created one to many relationship (two tables) such that every user has its own IP connections list. Every user has many connections.
My models are shown below:
class Conn(models.Model):
        src_ip = models.CharField(max_length=18, unique=False,default=None,blank=True,null=True)
        src_port = models.CharField(max_length=6, unique=False,default=None,blank=True,null=True)
        dst_ip = models.CharField(max_length=18, unique=False,default=None,blank=True,null=True)
        dst_port = models.CharField(max_length=6, unique=False,default=None,blank=True,null=True)
        proto = models.CharField(max_length=6, unique=False,default=None,blank=True,null=True)
        start_data = models.CharField(max_length=18, unique=False,default=None,blank=True,null=True)
        r_user = models.ForeignKey(User, on_delete=models.CASCADE)

class User(models.Model):
        e_user = models.CharField(max_length=15, unique=False,default=None,blank=True,null=True)
        e_dev = models.CharField(max_length=15, unique=False,default=None,blank=True,null=True)
        e_session = models.CharField(max_length=9, unique=False,default=None,blank=True,null=True)
        e_start = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True)
        e_stop = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True)
        e_summary = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True)
        e_ip = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True)

I'm trying to get all Users with their connections (Conn) in one QuerySet and then display everything in template. So far I can display every User without any problems with
q=Users.objects.all()

and passing the QuerySet to the template.
The question may be a bit not smart but how can I query all Users including related connections (Conn) as one QuerySet and then enumerate this connections in a form?

A: Use prefetch_related:
users = User.objects.all().prefetch_related('conn_set')

Now for each user you can look at its conn_set and see the Conn objects linked to it. Assuming you pass users to your template as a context variable users, something like this should work:
{% for user in users %}
    {{ user.e_user }}

    {% for connection in user.conn_set.all }}
        {{ connection.src_ip }}
    {% endfor %}
{% endfor %}

Adjust fields and add other markup to suit your needs.
From the documentation, prefetch_related

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

If this had been a one-to-one relationship or if you'd been trying to look things up in the other direction, finding all Conn objects along with the related User, you could have used select_related, which is even more efficient.
Note that you can also clean up some of your fields by choosing more appropriate field types. For example, consider GenericIPAddressField for src_ip and dst_ip.


text:
Q: Inputs are printed wrongly of template types in program here is the code snippet of my program with templates. It has no errors but when I print, it generates wrong result. Please tell me where I am wrong and how can I resolve this issue. Following is the C++ code having three functions and a main function with template T.
#include<iostream>
using namespace std;

template<typename T>
void input(T* &start, int size){
    start = new T[size];
    T* beyond = &start[size];

    while(start != beyond){
        cout<<"\nEnter: ";
        cin>>*start;
        start++;
    }
}

template<typename T>
void sort(T* start, int size){
    T hold;

    for(int j=0; j<size-1; j++){
        for(int i=0; i<size-1; i++){
            if(start[i]>start[i+1]){
                    hold=start[i];
                    start[i]=start[i+1];
                    start[i+1]=hold;
            }
        }
    }
}

template<typename T>
void display(T* start, int size){
    T* beyond = &start[size];
    cout<<"\nAfter Sorting: "<<endl;

    while(start != beyond){
        cout<<*start<<"\t";
        start++;
    }
}

int main(){
    int* x=NULL;
    float* y=NULL;
    char* z=NULL;
    int size;

    cout<<"Enter the number of elements: ";
    cin>>size;

    cout<<"\nEnter integer values:";
    input<int>(x, size);
    sort<int>(x, size);
    display<int>(x, size);

/**
    cout<<"\nEnter floating values:";
    input<float, int>(y, size);
    sort<float, int>(y, size);
    display<float, int>(y, size);

    cout<<"\nEnter character values:";
    input<char, int>(z, size);
    sort<char, int>(z, size);
    display<char, int>(z, size);
    */
    system("pause");
}

A: You can do this:
template<typename T>
void input(T* &start, int size){
    start = new T[size];
    //T* beyond = &start[size-1];

    //while(start <= beyond){
    for(int i=0;i<size;i++){
        cout<<"\nEnter: ";
        cin>>start[i];
        //start++;
    }
    //}
}

And:
template<typename T>
void display(T* start, int size){
    //T* beyond = &start[size-1];
    cout<<"\nAfter Sorting: "<<endl;

    for(int i=0;i<size;i++){
        cout<<start[i]<<"\t";
    }
}

This is a simpler form to do what you are trying to do, and works.

A: In your input function you allocate memory and put it to start. Then you move that pointer to the end and that end value will be returned to the calling function. Then you try to use that as the start to the other methods, which will lead to undefined behaviour.
template<typename T>
void input(T* &start, int size){
    start = new T[size]; // points to the start
    T* beyond = &start[size];

    while(start != beyond){
        cout<<"\nEnter: ";
        cin>>*start;
        start++; // Moving all the time...
    }
    // In the end start points to beyond and main gets that as a result
}

If you really want to play with pointers, you can fix it easily:
template<typename T>
void input(T* &start, int size){
    start = new T[size];
    T* beyond = &start[size];
    T* curr = start;

    while(curr != beyond){
        cout<<"\nEnter: ";
        cin>>*curr;
        curr++;
    }
}

This way the start pointer will always point to the beginning and is returned properly to the calling function.
Running step by step in debugger would show this problem easily. Also, please always describe the problem, we have no idea what "generates wrong result" means, if you don't explain what the right result would be or what you get as a result instead with certain input.


text:
Q: Executable files to MSI installer I have a folder that includes two EXE files and a lot of other files. How do I turn that into an MSI installer or some kind of self extracting installer so that it installs Main.exe to Programs in Windows. The second EXE file is because of communication between the two EXE files.
And I would prefer if it could include the "Shortcut to desktop" feature and doesn't require a license.
The EXE files aren't setup files already I think. They are Python scripts changed to EXE files.
This is the folder I want to turn into an MSI / Installer of some kind:

A: So I got what I was looking for and it was right in front of me the whole time. You an create a self-extracting (sfx) executable file in WinRAR which has ALL of the features I need.

A: This is a very common question. I'll just link to some existing answers:

*

*How to create windows installer - new and "short version" of deployment tools overview. I would recommend this one as a "quick read".

*What installation product to use? InstallShield, WiX, Wise, Advanced Installer, etc - older, more comprehensive summary of deployment tools and their different strengths and snags - no claim to be "right", but "best effort" to help people get their software to end users.

Advanced Installer (further info) and  Installshield (further info) are commercial options with nice GUIs for MSI creation - both with some free features / editions as well. And there is PACE Suite - another commercial product. WiX is free and XML-based, with a learning curve. Integration available in Visual Studio for all (most?) products.
And there are further tools as linked to by Phil above and also linked to in my answers above - some of which are not MSI-based, but create legacy setup.exe style setups (Inno, NSIS, etc...).

Some Further Links:

*

*Wrap C# application in .msi installer (brief section on VS Installer Projects - a Visual Studio feature that can't really be recommended - but it is free)

*Windows service NOT shown in add remove programs under control panel

*How do Installation Software Programs Extract Files?

*how to create a wix bootstrapper application that runs self extracting exe as an exepackage


text:
Q: 1 button 2 functions I've got a conflict issue with a form. The idea is that I need to store the datas in the form field in a table with a local storage in Javascript, and I need to send an email simultaneously with the same button with PHP. When I try it, either the button implement the table, either it send the mail. It depends of the position of the action inside the arrows. Here is my code :

<form action="mailer.php" method="post" class="onerow">

      First name:
      <input type="text" name="first_name" />

      Last name:
      <input type="text" name="last_name" />

      Company:
     <input type="text" name="company" />

      Address:
      <input type="text" name="address" />

      City:
      <input type="text" name="city" />

      Postal/zip code:
      <input type="text" name="zip" />

      State/province:
      <input type="text" name="state" />

      Country:
      <input type="text" name="country" />

      Phone number:
     <input type="text" name="phone" />

      Email:
      <input type="text" name="email" />

      Why are you looking for our solutions ?

        <SELECT name="nature_of_contact" size="1">
          <OPTION>I'm a distributor and I want to sell your products in my country.
          <OPTION>I'm a beautician I want to buy a product.
          <OPTION>I'm a doctor.
          <OPTION>I'm a distributor.
        </SELECT>

      <input type="button" id="contacts-op-discard" value="Discard" />
       <input type="submit" id="contacts-op-save" value="Save" />
    <input type="hidden" name="id_entry" value="0" />

  </form>

Contacts

      ID
      First name
      Last name
      Company
      Address
      City
      Postal/Zip
      State/province
      Country
      Phone number
      Email
      Kind of prospect
      Actions

See JSFIDDLE

A: One way would be:

*

*Change the submit button from type 'submit' to 'button' and add the event onClick()to it.

*Create a function -let's say readFromdata()- that reads the values from your form. Store the data into a container.

*Create a function -let's say sendFromdata()- that sends the data to your php script. Hint: Ajax would be your friend. Configure your Ajax so, that the data will be send asyncrosly.

*Create a function -let's say printFOverview()- that extends your html table, for the displaying the result.

*Call sendFromdata() and printFOverview() within the function readFromdata() and pass the data container to these methods.

*Add the call readFromdata() to the attribute onClick().

A: You could do the following:

*

*Add an event.preventDefault() to your handler

*Then store things in localStorage

*If things are stored submit the form with Contacts.$form.submit();
EDIT
Change the event handler from submit to click and remove it from the form to add it to the Contacts.$button_save button and add a preventDefault() just after.
As you changed the event handler from the form to the button you need to change the form values from this to Contacts.$form because this was in the scope of the form which is not the case anymore.
Contacts.$button_save.addEventListener("click", function(event) {
    event.preventDefault();
    var entry = {
        id: parseInt(Contacts.$form.id_entry.value),
        first_name: Contacts.$form.first_name.value,
        last_name: Contacts.$form.last_name.value,
   // and so on

Remove the input type="submit" and create a normal button instead:
<button id="contacts-op-save">Save</button>

Then you could submit the form after storing in storeAdd / storeEdit functions as said with Contacts.$form.submit();.
      storeAdd: function(entry) {
        entry.id = Contacts.index;
        window.localStorage.setItem("Contacts:index", ++Contacts.index);
        window.localStorage.setItem("Contacts:"+ entry.id, JSON.stringify(entry));
        Contacts.$form.submit();
      },
      storeEdit: function(entry) {
        window.localStorage.setItem("Contacts:"+ entry.id, JSON.stringify(entry));
        Contacts.$form.submit();
      },
      storeRemove: function(entry) {
        window.localStorage.removeItem("Contacts:"+ entry.id);
        // eventually here too?
        Contacts.$form.submit();

      },

Also you call the form element by its id , but the form has no id assigned.
$form: document.getElementById("contacts-form")

So give your form that ID:
<form id="contacts-form" action="mailer.php" method="post" class="onerow">


text:
Q: Why is my view file moving all my head content into the body section? I'm very confused by how the application.html.erb file and the view files combine.  I have in my application.html.erb file the following (minimized the content for brevity):
<!DOCTYPE html>
<html>
  <head>
    <!-- Bootstrap Css -->
    <link href="/bootstrap-assets/css/bootstrap.css" rel="stylesheet">
    <%= yield :head %>
  </head>
<body>
   <nav>
      <!--Long navbar section -->
   </nav>
  <%= yield %>
</body>
</html>

In my view file:
<html>
<head>
    <!-- View Specific Stylesheet -->
    <link href="/css/ViewSpecific.css" rel="stylesheet" />
</head>
<body>
    <!-- View Specific Body -->
</body>

What I would expect is that when these 2 files combine, the View specific stylesheet load in the <head> section, and the View Specific Body load in the <body> section.  The final result actually sends the view specific stylesheet to the <body> section, after the navbar from application.html.erb is already loaded.  This obviously produces the unwanted result that part of my body is loading before the stylsheet is loaded, and the first second the user views the page everything looks terrible.

A: You should make use of content_for if you want to render the view-specific head into the head section of application.html.erb. Use
<% content_for :head do %>
 <!-- View specific head section -->
  <link href="/css/ViewSpecific.css" rel="stylesheet" />
<% end %>

Since you yield :head in the application.html.erb, thats all to be done. And you don't need html tags in the views.
For more, see http://apidock.com/rails/v4.2.1/ActionView/Helpers/CaptureHelper/content_for


text:
Q: ms-coherence in matlab and python I'm analyzing ms-coherence between two signals, and I'm comparing the results of scipy.signal.coherence with Matlab's mscohere function. I'm not getting the same result when I use the same parameters in both functions:
Matlab
x = [1,3,5,7,4,6,7,8,9,3,5,6]
y = [3,4,7,8,9,1,2,3,4,1,5,6]

[cxy,w] = mscohere(x,y,hann(6),3,6,1)

cxy =
    0.7489
    0.6034
    0.2813
    0.3319

w =
         0
    0.1667
    0.3333
    0.5000

Python
from scipy.signal import coherence
x = [1,3,5,7,4,6,7,8,9,3,5,6]
y = [3,4,7,8,9,1,2,3,4,1,5,6]

coherence(x,y,'hann',noverlap=3,nperseg=6,fs=1,detrend=False)

(array([0.        , 0.16666667, 0.33333333, 0.5       ]),
 array([0.76762535, 0.53185638, 0.32743784, 0.07759385]))

What am I missing?

A: The inner algorithms boths are different's, i degug both codes and i could perceive differences.
Bellow you see difference using the same parameters in scipy.signal.coherence and Matlab's mscohere.
Follow some details dafault parameters matlab:
# %   When WINDOW and NOVERLAP are not specified, MSCOHERE divides X into
# %   eight sections with 50% overlap and windows each section with a Hamming
# %   window. MSCOHERE computes and averages the periodogram of each section
# %   to produce the estimate.
# L = fix(M./4.5);  noverlap = fix(0.5.*L); options.nfft = max(256,2^nextpow2(N));
#k = (M-noverlap)./(L-noverlap);
#m= n_sample L = int( n_sample // 4.5 ) noverlap= n/2

Follow example python using same parameters matlab
 L = int( n_sample // 4.5 )
 nfft = max( 256, 2 ** math.ceil( math.log2( L ) ) )
 frequences, coherence = signal.coherence(mean_zero_left, mean_zero_rigth, fs=self._fa, nfft=nfft, window=signal.get_window('hamming', L, fftbins=False), noverlap=int(L//2))

This manner you see the graph comparing both result
comparing Python x Matlab
I recomend to use matplotlib.mlab.cohere have the same algorithm matlab, but the number of point fft (nfft) have validation equals a niquist theorem.
coherence2 = mlab.cohere(mean_zero_left, mean_zero_rigth, window=np.hamming(L), NFFT=nfft, noverlap=int(L//2), Fs=self._fa)


text:
Q: Is passing an object from activity to fragment a reference or value? I am passing object from an activity to a fragment as explained in the accepted answer here:
Passing an Object from an Activity to a Fragment
However, my question is, when an object is passed to the fragment, is it a reference to the object? or a copy of the object?
Thanks.

A: Intent's extras contain values only. So it is a copy of your object not it reference.


text:
Q: Who would touch the ground of a see saw first? Imagine 2 perfectly balanced sea saws.
A heavy person sits on one side of the seasaw.
A light person sits on one side of the other seasaw.
If they both saw down at the same time, which seasaw would touch the ground first?

A: The seesaw itself has a moment of inertia and it could be ignored for a very heavy person, so the downward acceleration would be nearly $g$.
However for the light person the downward acceleration, and angular acceleration is less.
from $$T=I\alpha$$
(torque is moment of inertia times angular acceleration)
The torque from the light person's weight would cause only a small angular acceleration, so the heavier person would reach the ground first.

A: The seesaw upon which the heavier person sat will be the first to touch the ground.
A good way to approach questions like this one is to consider extreme cases. Suppose the heavier person weighed 100 tons and the lighter person weighed a microgram- would you have any doubt about which of them would hit the ground first?


text:
Q: Bondig two NIC slow upload I have two NIC in pc/nas:
eth0 (integrated motherboard):
Settings for eth0:
    Supported ports: [ TP MII ]
    Supported link modes:   10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Half 1000baseT/Full
    Supported pause frame use: No
    Supports auto-negotiation: Yes
    Advertised link modes:  10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Full
    Advertised pause frame use: Symmetric Receive-only
    Advertised auto-negotiation: Yes
    Link partner advertised link modes:  10baseT/Half 10baseT/Full
                                         100baseT/Half 100baseT/Full
                                         1000baseT/Full
    Link partner advertised pause frame use: Symmetric
    Link partner advertised auto-negotiation: Yes
    Speed: 1000Mb/s
    Duplex: Full
    Port: MII
    PHYAD: 0
    Transceiver: internal
    Auto-negotiation: on
    Supports Wake-on: pumbg
    Wake-on: g
    Current message level: 0x00000033 (51)
                           drv probe ifdown ifup
    Link detected: yes

eth1 (external PCIe)
Settings for eth1:
    Supported ports: [ TP MII ]
    Supported link modes:   10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Half 1000baseT/Full
    Supported pause frame use: No
    Supports auto-negotiation: Yes
    Advertised link modes:  10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Half 1000baseT/Full
    Advertised pause frame use: Symmetric Receive-only
    Advertised auto-negotiation: Yes
    Link partner advertised link modes:  10baseT/Half 10baseT/Full
                                         100baseT/Half 100baseT/Full
                                         1000baseT/Full
    Link partner advertised pause frame use: Symmetric
    Link partner advertised auto-negotiation: Yes
    Speed: 1000Mb/s
    Duplex: Full
    Port: MII
    PHYAD: 0
    Transceiver: internal
    Auto-negotiation: on
    Supports Wake-on: pumbg
    Wake-on: g
    Current message level: 0x00000033 (51)
                           drv probe ifdown ifup
    Link detected: yes

bond0
Settings for bond0:
    Supported ports: [ ]
    Supported link modes:   Not reported
    Supported pause frame use: No
    Supports auto-negotiation: No
    Advertised link modes:  Not reported
    Advertised pause frame use: No
    Advertised auto-negotiation: No
    Speed: 2000Mb/s
    Duplex: Full
    Port: Other
    PHYAD: 0
    Transceiver: internal
    Auto-negotiation: off
    Link detected: yes

/etc/network/interfaces
allow-hotplug bond0
iface bond0 inet static
        address 192.168.2.1
        netmask 255.255.255.0
        slaves eth0 eth1
        bond_mode 5
        bond-miimon 100
        bond_downdelay 200
        bond_updelay 200
        post-up arp -f

In download all work correctly (balanced load), but in upload there is no balancing. The two cards are 1Gbit ... so in download I can occupy a bandwidth of 2Gbit (server side) ... but in upload, the bonding does not perform any balancing (in fact if I try to make two uploads from my two pc lan on the pc/nas, i find myself the split band: 500Mbit on one side (pc1) and 500Mbit on the other side (pc2). Why??
I have tried 3 bonding modes (0,2,5) but the same problem is always present.
I am currently using mode 5.


text:
Q: Zeppelin and Spark Configuration I'm working with Zeppelin (0.7.1) on Spark (2.1.1) on my localhost, and trying to add some configuration values to the jobs I run.
Specifically, I'm trying to set the es.nodes value for elasticsearch-hadoop.
I tried adding the key and value to the interpreter configuration, but that didn't show up in sc.getConf. Adding to the interpreter's "args" configuration key the value of "--conf mykey:myvalue" didn't register as well.
Is that not what the spark interpreter configuration is supposed to do?

A: Apparently this is an intentional change in Zeppelin, implemented not long ago...
It only allows spark.* properties to be delegated to the SparkConf. I have submitted a comment to change this, as I believe it is problematic.
https://github.com/apache/zeppelin/pull/1970


text:
Q: How to replace a string use regular expression in maven? I tried to replace a string in a file when build from maven.
I did this:
<replace file="..." token="AssemblyVersion("${[0-9.]+}")"
     value="AssemblyVersion("${major}.${build}.${scmRevision}")"/>

The maven program just doesn't work on regular expression.

A: Try this plugin, seems to be doing exactly what you need. This answer can be helpful as well.


text:
Q: Experimenting with converting some jQuery to javascript So, I have been trying to, just for knowledge's sake, convert some of my jQuery into plain, vanilla javascript. I'd just like to get some comments on if there is a better way I could have re-written this. (It's also in coffeescript.)
The script itself listens for click events on the element  for example, finds the  with the same ID as the data-modal element and then attaches a class to that element, which makes a window pop up, basically. Then, the overlay class listens for a click event, which removes the previously attached class 'md-show' from any  that has it. It's just a simple script really, that adds and removes a class in order to show a popup window.
Thanks for any and all help.
Here is the original jQuery:
    overlay = $('.md-overlay')
$('.md-trigger').click (e) ->
    modal = $(@).data 'modal'
    modalID = '#' + modal
    $(modalID).addClass 'md-show'
    e.preventDefault()
$('.md-close').click ->
    $("div[id^='modal']").removeClass 'md-show'
overlay.click ->
    $("div[id^='modal']").removeClass 'md-show'

And here is the conversion to vanilla js:
    hasClass = (el, cl) ->
    regex = new RegExp('(?:\\s|^)' + cl + '(?:\\s|$)')
    !!el.className.match(regex)

overlay = document.getElementsByClassName('md-overlay')[0]
triggers = document.getElementsByClassName('md-trigger')
modals  = document.querySelectorAll("div[id^='modal']")

for i in [0...triggers.length]
    trigger = triggers[i]
    trigger.addEventListener 'click', (e) ->
        modal = this.getAttribute 'data-modal'
        modalID = document.getElementById(modal)
        modalID.classList.add 'md-show'
        return false

overlay.addEventListener 'click', ->
    for i in [0...modals.length]
        eachModal = modals[i]
        if hasClass(eachModal, 'md-show')
            eachModal.classList.remove 'md-show'

A: CoffeeScript takes care of proper iteration through an array for you. So
for i in [0...triggers.length]
    trigger = triggers[i]
    trigger.addEventListener 'click' ...

can be written more concisely as:
for t in triggers
    t.addEventListener 'click' ...