Q: Istio 1.4.3 to 1.5.6 upgrade using istioctl and Istio operator Can I make an existing Istio open source installable compatible with the (Istioctl + Operator) ? I currently have Istio 1.4.3 installed via istioctl .. and need to make existing deployment Istio operator aware as well before I upgrade to Istio 1.5.6+ . Any specific steps to be followed here ?

A: There shouldn't be any problem with that, I have tried that on my test cluster and everything worked just fine.
I had a problem with upgrading immediately from 1.4.3 to 1.5.6, so with below steps you're first upgrading from 1.4.3 to 1.5.0, then from 1.5.0 to 1.5.6
Take a look at below steps to follow.

1.Follow istio documentation and install istioctl 1.4, 1.5 and 1.5.6 with:
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.4.0 sh -
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.5.0 sh -
curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.5.6 sh -

2.Add the istioctl 1.4 to your path
cd istio-1.4.0
export PATH=$PWD/bin:$PATH

3.Install istio 1.4
istioctl manifest apply --set profile=demo

4.Check if everything works correct.
kubectl get pod -n istio-system
kubectl get svc -n istio-system
istioctl version

5.Add the istioctl 1.5 to your path
cd istio-1.5.0
export PATH=$PWD/bin:$PATH

6.Install istio operator for future upgrade.
istioctl operator init

7.Prepare IstioOperator.yaml
nano IstioOperator.yaml

apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
metadata:
  namespace: istio-system
  name: example-istiocontrolplane
spec:
  profile: demo
  tag: 1.5.0

8.Before the upgrade use below commands
kubectl -n istio-system delete service/istio-galley deployment.apps/istio-galley
kubectl delete validatingwebhookconfiguration.admissionregistration.k8s.io/istio-galley

9.Upgrade from 1.4 to 1.5 with istioctl upgrade and prepared IstioOperator.yaml
istioctl upgrade -f IstioOperator.yaml

10.After the upgrade use below commands
kubectl -n istio-system delete deployment istio-citadel istio-galley istio-pilot istio-policy istio-sidecar-injector istio-telemetry
kubectl -n istio-system delete service istio-citadel istio-policy istio-sidecar-injector istio-telemetry
kubectl -n istio-system delete horizontalpodautoscaler.autoscaling/istio-pilot horizontalpodautoscaler.autoscaling/istio-telemetry
kubectl -n istio-system delete pdb istio-citadel istio-galley istio-pilot istio-policy istio-sidecar-injector istio-telemetry
kubectl -n istio-system delete deployment istiocoredns
kubectl -n istio-system delete service istiocoredns

11.Check if everything works correct.
kubectl get pod -n istio-system
kubectl get svc -n istio-system
istioctl version

12.Change istio IstioOperator.yaml tag value
nano IstioOperator.yaml

apiVersion: install.istio.io/v1alpha1
kind: IstioOperator
metadata:
  namespace: istio-system
  name: example-istiocontrolplane
spec:
  profile: demo
  tag: 1.5.6    <---

13.Upgrade from 1.5 to 1.5.6 with istioctl upgrade and prepared IstioOperator.yaml
istioctl upgrade -f IstioOperator.yaml

14.Add the istioctl 1.5.6 to your path
cd istio-1.5.6
export PATH=$PWD/bin:$PATH

15.I have deployed a bookinfo app to check if everything works correct.
kubectl label namespace default istio-injection=enabled
kubectl apply -f samples/bookinfo/platform/kube/bookinfo.yaml
kubectl apply -f samples/bookinfo/networking/bookinfo-gateway.yaml

16.Results
curl -v xx.xx.xxx.xxx/productpage | grep HTTP
HTTP/1.1 200 OK

istioctl version
client version: 1.5.6
control plane version: 1.5.6
data plane version: 1.5.6 (9 proxies)

Let me know if have any more questions.


Q: Mac: Installing app from Internet has an exception I want to install Firefox in my MacBook, downloaded from Internet.
After a series of clicking, I can use it with an exception.
It is not in the LaunchPad. Looks like it is installed on an other disk.
Here is image:

How to fix it?

A: Drag it to the Applications folder (as the green arrow suggests), and then run it from that folder rather than from the disk image.


Q: AWS dynamodb with Ruby SDK I have tables in dynamodb. I am new to 'AWS'.now my site is getting very slow. I couldn't find the solution. I suspect DynamoDB. So I need to know some details about DynamoDB. What is Read and write capacity, latency, CPU utilization? How to handle these all? to get DB gets fast?

A: When you create a table, you specify the provisioned capacity for read and write. This will limit the number of records you can read per second and number of records you can write per second. Your use-case will determine your actual needs. You can modify the provisioned capacity of a table after you have created, while it is being used and it will not affect access. This hot upgrade is a powerful feature of DynamoDB.
If you are exceeding your provisioned capacity, then DynamoDB will throttle your API calls. The aws-sdk gem will automatically retry throttled DynamoDB calls up to 10 times, using an exponential backoff strategy, sleeping between attempts.
To configure the retry limit for DynamoDB:
Aws.config[:dynamodb] = { retry_limit: 5 }

You can tell if your request is getting retried by inspecting the response object:
ddb = Aws::DynamoDB::Client.new
resp = ddb.get_item(table_name: 'aws-sdk', key: { id: '123' })
resp.context.retires
#=> 0

Also, you can enable logging:
require 'logger'
ddb = Aws::DynamoDB::Client.new(logger: Rails.logger)
ddb.get_item(table_name: 'aws-sdk', key: { id: '123' })

# sent to the rails logger
[Aws::DynamoDB::Client 200 0.008879 0 retries] get_item(table_name:"aws-sdk",key:{"id"=>{s:"123"}})

The log message contains the service client call, the HTTP status code (200), the time spent waiting on the call, the number of retires and the operation name and params called. You can of course configure the :log_level and a :log_formatter to modify when and what things are logged.


Q: Fresh install Ubuntu 14.04.03 boots every second time Fresh install. One boot is blank purple screen, second boot - normal, third - blank purple, forth - normal and so on. Can this be fixed?
I use entire disk encrytption LVM

A: I have the same issue, same configuration, but my screen goes blank instead of purple.
When that happens, if I press escape, I can see that it's prompting me for the drive encryption password, so the display isn't initialising properly for some reason.
To work around it, I edited /etc/default/grub and changed the line:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
To this:
GRUB_CMDLINE_LINUX_DEFAULT="nomodeset"
It now boots in text mode, asks for my encryption password, then proceeds via the normal GUI.


Q: Saving outputs from arcpy.da.Walk to the same folder I have a number of sub-directories within my "BP Tiles" directory. Each of these sub-directories represents a different year (2016, 2017, 2018, etc.) and within each of these sub-directories is a list of raster layers. I am attempting to use the Walk module to mosaic each list of Raster layers within the individual year directories.
See Code Source
import arcpy, os
from arcpy import env

# SET GEO_PROCESSING ENVIRONMENTS
arcpy.env.workspace = r"C:\Users\BP_Tiles"

walk = arcpy.da.Walk(env.workspace, topdown=True, datatype="RasterDataset")

for dirpath, dirnames, filenames in walk:
    print
    dirpath
    rasterList = []
    for file in filenames:
        raster = os.path.join(dirpath, file)
        rasterList.append(raster)
    try:
        arcpy.MosaicToNewRaster_management(rasterList, dirpath, + "Mosaic.tif", "", "", "", 1)
    except:
        pass

The code is set up to save the output "Mosaic.tif" within each sub-directory. I'd like to manipulate this code such that all of the Mosaics are saved to the same output folder. Id also like to append the sub-directory name (Ex. 2016) to each output such that I know how to differentiate the outputs.
Would anyone happen to know how to do this?

A: *

*All of the Mosaics are saved to the same output folder.

Instead of using dirpath when creating your new raster use the same path each time.
outPath  = r"C:\some\path"
for dirpath, dirnames, filenames in walk:
    .... #other code
    arcpy.MosaicToNewRaster_management(rasterList, outPath, "Mosaic.tif", "", "", "", 1)

*Append the sub-directory name (Ex. 2016) to each output such that I know how to differentiate the outputs

Update "Mosaic.tif" with the sub-directory name.
for dirpath, dirnames, filenames in walk:
    ....#other code
    dirName = os.path.basename (dirpath)
    arcpy.MosaicToNewRaster_management(rasterList, outPath, "Mosaic_{}.tif".format (dirName), "", "", "", 1)


Q: Is there a more straightforward way to search for a string while ignoring spaces? I am working on a function that searches a searches a string for one of a list of given words. The string being searched is generated by OCR software, that occasionally adds extra spaces between letters (depending on the font) which I need to ignore.
I currently have a function that looks like this:
function searchSomeText($searchTerms, $stringToBeSearched)
{
    $matches = array();
    for($i=0; $i < count($searchTerms); ++ $i)
    {
        $searchTerms[$i] = substr(chunk_split($searchTerms[$i],1,"\s*"), 0, -3);
    }
    $searchTermsString = implode("|", $searchTerms);

    if (preg_match("/\b($searchTermsString)\b/", $stringToBeSearched, $matches))
    {
        return $matches;
    }
    else { return false; }
}

*

*Is there any way to ignore spaces besides adding '\s*' between every character in the search terms?

*If there isn't, is there a more efficient method to add '\s*' after every character in the search terms but the last one other than using chunk_split() to add it after every character, and then chopping it off from the end?

Edit
I prefer not to just strip the spaces from the $stringToBeSearched because in the majority of cases, where the spacing is correct, I don't want a match where a search term is contained inside of another word (hence the '\b's)

A: Here is my recommended strategy for what I understand of your task:

*

*Do not mutate the haystack string.  Often the the string to be searched is much much longer than the needle(s) used in the search.  This potentially heavy lifting should be avoided when possible.

*Your search terms appear to be dynamic (and likely to be coming from user input), so the characters must be escaped to prevent regex pattern breakage.  Use preg_quote() for this process.

*Insert \s* between all non-whitespace characters in the escaped search terms (ignoring escaping slashes).

*Then convert all sequences of one or more whitespaces to \s+ in the search terms.

*Now that the terms are prepared, glue them together using pipes.  Wrap the piped expression in parentheses, then wrap that capture group in wordboundary markers (\b).

*Though not mentioned in your question, I recommend using case-insensitive matching.  If multibyte/unicode characters may be involved, add the u pattern modifier as well.

Recommended Code: (Demo)
function searchSomeText(array $searchTerms, string $stringToBeSearched): bool
{
    foreach ($searchTerms as &$searchTerm) {
        $searchTerm = preg_replace(
            ['/\\\\?\S\K(?=\S)/', '/\s+/'],
            ['\\s*', '\\s+'],
            preg_quote($searchTerm, '/')
        );
    }
    $pattern = '/\b(' . implode("|", $searchTerms) . ')\b/i';
    echo $pattern . "\n";
    return (bool)preg_match($pattern, $stringToBeSearched);
}

var_export(
    searchSomeText(
        ['at', 'cat ', 'the'],
        'The catheter in the hat'
    )
);

Output: (dynamic regex pattern & return value)
/\b(a\s*t|c\s*a\s*t\s+|t\s*h\s*e)\b/i
true


Q: Вывести DataFrame в строку без индексов Имеется DataFrame df:
    1   2   3   4   5   6
0   45  55  65  75  85  95
1   43  53  63  73  83  93
2   47  57  67  77  87  97
3   41  51  61  71  81  91

При попытке получения строки:
row = df.iloc[0]

Выводит вместе с индексом:
1    45
2    55
3    65
4    75
5    85
6    95

Есть ли возможность вывести без индекса и в строчку, а не в стролбец?

A: df.iloc[0] возвращает нулевую строку в виде объекта Pandas.Series с именами столбцов в качестве нндексов. Series при выводе на печать показываются вертикально. Чтобы показать строку горизонтально можно "обрамить" номер строки квадратными скобками - в этом случае .iloc[[...]] вернет объект типа DataFrame:
In [6]: df.iloc[[0]]
Out[6]:
    1   2   3   4   5   6
0  45  55  65  75  85  95

Pandas всегда выводит индексы для Series и DataFrame's.
Также можно преобразовать Series в 1D Numpy vector:
In [7]: df.iloc[0].values
Out[7]: array([45, 55, 65, 75, 85, 95], dtype=int64)

или в обычный список:
In [8]: df.iloc[0].tolist()
Out[8]: [45, 55, 65, 75, 85, 95]


Q: deployment of persistence unit failed issue wHEN I AM DEPLOYING MY CRUDWEB web application it is throwing like below:
SEVERE:   Exception while deploying the app [CRUBWEB] : Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [CRUBWEBPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [SELECT e FROM custt e].
[14, 19] The abstract schema type 'custt' is unknown.

Please help Thanks.


Q: 2D wave equation solve using laplace transformation mathematica I'm trying to solve a wave equation using laplace and inverse laplace transformation .
But facing problem in inverse part.My problem and codes in the below:

eqn = D[T[x, t], {t, 2}] - D[T[x, t], {x, 2}] == 0
w[x_, t_] = D[T[x, t], t]

LaplaceTransform[eqn, t, s] /. {T[x, 0] -> Sin[\[Pi] x],w[x, 0] -> 3 x + 1}

eqn2 = -2 - 3 x + s^2 tT[x, s] - D[tT[x, s], {x, 2}] - s Sin[Pi*x] == 0

f = tT[x, s] /.DSolve[{eqn2, tT[0, s] == 0, tT[1, s] == 5}, tT[x, s], x]

InverseLaplaceTransform[f, s, t]

A: This gives same solution as Mathematica
ClearAll["Global`*"]
eqn = D[T[x, t], {t, 2}] - D[T[x, t], {x, 2}] == 0
ic = {T[x, 0] == Sin[Pi*x], (D[T[x, t], t] /. t -> 0) == 3*x + 1}
bc = {T[0, t] == 0, T[1, t] == 0}
lap = LaplaceTransform[eqn, t, s] /. (ic /. Equal -> Rule)
lap = lap /. {LaplaceTransform[T[x, t], t, s] -> Y[s, x],
   LaplaceTransform[Derivative[2, 0][T][x, t], t, s] ->
    D[Y[s, x], {x, 2}]}
solY = DSolveValue[lap, Y[s, x], x]
eq1 = (solY /. x -> 0) == 0
eq2 = (solY /. x -> 1) == 0 // Simplify
solC = Solve[{eq1, eq2}, {C[1], C[2]}]
solY = solY /. solC // First
mysol = Simplify[InverseLaplaceTransform[solY, s, t]]
mysol = FullSimplify[mysol /. HeavisideTheta[_] -> 1]

Note: In the above HeavisideTheta[_] -> 1 because it is 1 for all values, since $t>0$ and $0<x<1$.
Verify
sol = T -> Function[{x, t}, Evaluate@Activate@mysol];
eqn /. sol // Simplify
ic /. sol // Simplify
bc /. sol // Simplify

Which is the same as what Mathematica gives (but written different)
 mmaSol = DSolveValue[{eqn, ic, bc}, T[x, t], {x, t}]

sol = T -> Function[{x, t}, Evaluate@Activate@mmaSol];
eqn /. sol // Simplify
ic /. sol // Simplify
bc /. sol // Simplify


Q: Rails AASM does not rollback when validation returns false I have a model Booking that changes the status using AASM
models/booking.rb
before_validation :item_availability, if: -> { pending? || approved? }

enum status: [:pending, :approved, :rejected, :on_loan, :returned]

aasm column: :status, enum: true, whiny_transitions: true do
  state :pending, initial: true
  state :approved

  event :approve do
    transitions from: :pending, to: :approved
  end
end

private
 def item_availability
    if quantity.to_f > item.quantity.to_f
      errors.add(:base, "Not enough quantity for #{item.name} only #{item.quantity} left")
      false
    end
  end

and I have a service that triggers the approve! event
  def run
    booking.transaction do
      booking.approve!
      booking.item.decrement!(:quantity, booking.quantity)
      BookingsMailer.send_approval(booking).deliver_now
    end
  rescue ActiveRecord::RecordInvalid => e
    errors.add(:base, e.message)
    false
  end

The problem here is the validation is being hit because the quantity is greater than the booking's quantity but the transaction in my service does not rollback.
According to documentation

Saving includes running all validations on the Job class. If
  whiny_persistence flag is set to true, exception is raised in case of
  failure.

I already set whiny_transitions to true but


Q: IClassFactory failed due to the following error: 800a0153 I'm trying to reference a com component and it is throwing the below error.
Creating an instance of the COM component with CLSID {xxx} from the IClassFactory failed due to the following error: 800a0153.
Specifically the error gets thrown when I try to instantiate an object. I checked that

*

*The project being built for x86 processors which it is

*The com object is registered using regsvr32, and is available in the registry.

I can also see the methods in the object browser, so I know .net is finding it.
Any ideas on what I'm missing?

A: This is an error code that's specific to the component.  If you don't have documentation that explains what the code might mean then you'll need support from the vendor.

A: As noted in my comment to Hans' answer, this error code is FACILITY_CONTROL, which is supposed to relate to OLE/ActiveX controls, and has an error code which lies in the standard range (i.e. for Microsoft use) defined in OleCtl.h, but is not documented in the Win32 header files so is probably internal to a Microsoft product such as Visual Basic.
Can you tell us anything else about the COM component you are trying to use?
If the COM component was written using Visual Basic, I think it's probable that what you are seeing is equivalent to the Runtime Error 339 which users of Visual Basic see if they try to reference an OCX control which has some of its dependencies missing. You might look at the dependencies of the COM server's DLL/EXE using Depends.exe and see whether you have them all present on your machine.

A: Back when I had to do a lot of COM work, I used COM Explorer quite a bit from these guys:
http://download.cnet.com/COM-Explorer/3000-2206_4-10022464.html?tag=mncol;lst
I had to install it last year to debug a bizarre COM registration issue with Office plugins.
Also, I have no affiliation with these guys whatsoever (and it looks like the company might be toast anyway).


Q: Why MySQL InnoDB can handle concurrent updates and PostgreSQL can't? Let's imagine you have a table with this definition:
CREATE TABLE public.positions
(
   id serial,
   latitude numeric(18,12),
   longitude numeric(18,12),
   updated_at timestamp without time zone
)

And you have 50,000 rows in such table. now for testing purposes you will run an update like this:
update positions
set  updated_at = now()
where latitude between 234.12 and 235.00;

that statement will update 1,000 rows from the 50,000 (in this specific dataset)
if you run such query in 30 different threads, MySQL innodb will succeed and postgres will fail with lots of deadlocks.
why?

A: Plain old luck, I would say.
If thirty threads go ahead and want to update the same 1000 rows, they can either access these rows in the same order (in which case they will lock out each other and do it sequentially) or in different orders (in which case they will deadlock).
That's the same for InnoDB and PostgreSQL.
To analyze why things work out different in your case, you should start by comparing the execution plans. Maybe then you get a clue why PostgreSQL does not access all rows in the same order.
Lacking this information, I'd guess that you are experiencing a feature introduced in version 8.3 that speeds up concurrent sequential scans:

*

*Concurrent large sequential scans can now share disk reads (Jeff Davis)
This is accomplished by starting the new sequential scan in the middle of the table (where another sequential scan is already in-progress) and wrapping around to the beginning to finish. This can affect the order of returned rows in a query that does not specify ORDER BY. The synchronize_seqscans configuration parameter can be used to disable this if necessary.

Check if your PostgreSQL execution plan uses sequential scans and see if changing synchronize_seqscans avoids the deadlocks.


Q: Correct usage of $.ajaxComplete and $.ajaxError? I've been using the following snippet on my ajax form submits:
$.ajax({
url: "",
data: ilmoittautumisdata,
type: "POST",
success:function(){

});
error:function(){

});
});

However, I remember that I was told to stop using success and error within it, as they're deprecated (?) and instead use  $.ajaxComplete(); and  $.ajaxError();.
However, reading the docs isn't helping me as I want to use both of them, and this isn't working for me.
$('#ilmoittuminen').submit(function(){
            var ilmoittautumisdata = $('#ilmoittuminen').serialize();
            $.ajax({
                //url: "",
                data: ilmoittautumisdata,
                type: "POST"
                });
            $.ajaxComplete(
            function(){
            $('#ilmoittuminen').slideUp();
            });
            $.ajaxError(
            function(){

            });
    return false;
    });

How I should do it?
http://jsfiddle.net/D7qgd/

A: Firstly, the word you're looking for is "deprecated". As far as I'm aware, the success and error properties are definitely not deprecated. You can (and should, in your case) continue to use them.
The problem with your attempt to use ajaxError and ajaxComplete is that they are implemented as instance methods, rather than static methods on the jQuery object itself. For that reason, you need to select some element and call the methods on that collection. The element itself doesn't matter at all:
$("#someElement").ajaxComplete(function () {
    // Do stuff
});

The next problem, which you haven't come across yet, is that the ajaxError and related methods register global AJAX event handlers. Each time you call one of those methods, you add a new event handler to the global set, and every time an AJAX event is fired, all of your registered handlers will be executed.

Update (Thanks @DCoder)
Looks like the success and error properties are deprecated as of jQuery 1.8. Instead, you can use the fail, done and always methods of the jQuery modified XHR object. Any objects that inherit from the deferred object can use these methods (the jqXHR object is one of these):
$.ajax(ajaxSetupObject).done(function () {
    // Handle success
}).error(function () {
    // Handle error
});

A: This code handles a success and error inside the ajax method.if there is a success it prints out success, with the object you receive, and vica versa.
$.ajax({
   type: 'json',
   url: 'foobar.com',
   success: function(s) {
     console.log('success' + s);
   },
   error: function(e) {
     console.log('error' + e);
   }
});


Q: Can c#/Razor work with DyGraph WITHOUT Javascript? In this question:
Previous DyGraph question
There is still the need to go to JavaScript to call DyGraph:
<script type="text/javascript">
g = new Dygraph(document.getElementById("readingGraph"), @data,{ labels: ["Sample Number", "Reading"] });
</script>

Is there anyway to remove JavaScript completely?
I would like a fully c# solution...

A: Ah, OBVIOUSSLY not. DyGraph is a javascript library. If you want to remove Javascript completely, you need to use a graph library that generates the graph on the server and sends the picture down to the client. Given that DyGraph is a javascript library - the obvious answer is no, it can not be used while at the same time totally disabling javascript.
Literally on the homepage it says: "dygraphs is a fast, flexible open source JavaScript charting library.".

A: If you want 100% C# and no Javascript, MudBlazor has some charting capabilities: https://mudblazor.com/components/barchart#api
As another answer states, "Given that DyGraph is a javascript library - the obvious answer is no, it can not be used while at the same time totally disabling javascript"


Q: localStorage.getItem retrieves 'null' I'm trying to get a counter for the number of times a button is pressed but when I try to retrieve it outside the function, it results in 'null' instead.
HTML:
<button class="signupbutton" onclick="counter()"> Yes I'm in!</button>

Number of people that have signed up for the newsletter:

0

Javascript:
function counter() {
    var elem = document.getElementById('counter1');
    var count = localStorage.getItem('count');
    if (count == null) {
        count = 0;
    }
    count++;
    localStorage.setItem('count', count);
    elem.innerHTML = count;
}
console.log(localStorage.getItem('count'));
var count1 = localStorage.getItem('count');
var elem = document.getElementById('counter1');
elem.innerHTML = count1;

A: Make your code a bit more DRY would save you a bit of time, in validating that your counter has a "real" value. For the rest, the onclick inside an html element is not encouraged anymore, you can just update your code like
// wait until the page has loaded
window.addEventListener('load', function() {
  // get your elements once
  const counterElement = document.querySelector('#counter1');
  const signupButton = document.querySelector('.signupbutton');

  // assign a click event to your button
  signupButton.addEventListener('click', updateCounter);

  // function to retrieve the counter from your localStorage
  function getKeyOrDefault( key, defaultValue = 0 ) {
    return localStorage.getItem( key ) || defaultValue;
  }

  function updateCounter( e ) {
    let counter = parseInt( getKeyOrDefault( 'counter' ) );
    counter++;
    counterElement.innerHTML = counter;
    localStorage.setItem( 'counter', counter );
    e.preventDefault();
  }
  // set the initial value
  counterElement.innerHTML = getKeyOrDefault( 'counter' );
} );

Ofcourse, don't forget to change your html, to remove the counter function from the html element like
<button class="signupbutton"> Yes I'm in!</button>

Number of people that have signed up for the newsletter:

0

A sample of this code can be found on this jsfiddle (it is not here, as stackoverflow doesn't support localstorage)
Now, the only thing I am really worried about, is the text of your HTML, note that the localStorage will be a personal storage for all clients, so, if this is a website run from the internet, all persons who arrive there once will start with null (or 0) and just increase by 1 each time they click the button, you will be none the wiser, as it is localStorage.
Ofcourse, if you handle it on 1 computer, where people have to input their data, then you have at least some data stored locally, but still, this isn't a real storage you can do something with ;)

A: The code does work. However, you have to make sure, that the counter function is interpreted before the page has loaded. Put the JS at the end of the document head, or rewrite the onlick using addEventListener.

A: You should convert to integer ..
function counter() {
var elem = document.getElementById('counter1');
var count = localStorage.getItem('count');
if (count == null) {
    count = 0;
}
count = parseInt(count);
count++;
localStorage.setItem('count', count);
elem.innerHTML = count;
}
console.log(localStorage.getItem('count'));
var count1 = localStorage.getItem('count');
var elem = document.getElementById('counter1');
elem.innerHTML = count1;

Please Try again

A: getItem/setItem are unavailable until didFinish will have executed unless
Read local storage data using WKWebView


Q: Can we create a custom wrapper for mock annotation of jmockit? Can we create a custom wrapper for mock annotation or MockUp class of jmockit ? If its possible can you explain how can we done it.

A: You can create a "custom wrapper" for JMockit's @Tested annotation (ie, use it as a meta-annotation), but not for any of the other annotations, @Mock included. So, the answer is no, it's not possible.


Q: Sync Azure AD users to SQL Server on vm or Sql Database Users Table How can we synchronize Azure AD users with a user table in the database?

A: To Sync Azure AD users to SQL make sure each property stored in the data source maps properly to an AD user's attribute.
This article by Adam Bertram has code and whole process to Sync Azure AD users to Sql Database.
As per official documentation
Azure role-based access control (Azure RBAC) applies only to the portal and is not propagated to SQL Server.

Note
Database users (with the exception of administrators) cannot be
created using the Azure portal. Azure roles are not propagated to the
database in SQL Database, the SQL Managed Instance, or Azure Synapse.
Azure roles are used for managing Azure Resources, and do not apply to
database permissions. For example, the SQL Server Contributor role
does not grant access to connect to the database in SQL Database, the
SQL Managed Instance, or Azure Synapse. The access permission must be
granted directly in the database using Transact-SQL statements.


Q: Show one post per author and limit query to 8 posts I want to show 8 recent products from multiple authors on the frontpage.
Need to show 1 recent product per author.
Currently i'm using basic wp query to show recent 8 products.
$args = array (
'post_type'              => array( 'product' ),
'posts_per_page'         => '8',
'order'                  => 'DESC',
'orderby'                => 'date',
);

// The Query
$query = new WP_Query( $args );

What's the best way to achieve this?

A: I believe that you can achieve this effect by grouping the query by author ID, which will require a filter(mostly cribbed from the Codex):
function my_posts_groupby($groupby) {
    global $wpdb;
    $groupby = "{$wpdb->posts}.post_author";
    return $groupby;
}
add_filter( 'posts_groupby', 'my_posts_groupby' );

If you have less than 8 authors, however, this won't work. (You will get a number of results equal to your number of authors.) If that is the case you will need much more complicated logic and a much more complicated code.

A: Anyone coming to this years after the fact and would like the code in full, rather than having to piece this together from comments and the accepted answer, here you go!
Declare the function that limits the post results to 1 per author. For me, this was in functions.php:
function one_per_author($groupby) {
    global $wpdb;
    $groupby = "{$wpdb->posts}.post_author";
    return $groupby;
}

Do NOT follow this with apply_filter as per the accepted answer - this would then apply to all loops.
Next run the loop you would like to filter, and call the apply and remove filters directly before and after it:
$args = array (
'post_type'              => array( 'product' ),
'posts_per_page'         => '8',
'order'                  => 'DESC',
'orderby'                => 'date',
);

add_filter( 'posts_groupby', 'one_per_author' );
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
   while ( $query->have_posts() ) : $query->the_post();
      // Do loop stuff
   endwhile;
endif;
remove_filter( 'posts_groupby', 'one_per_author' );


Q: How do you serve a static website using Google Cloud CDN, Google Cloud Storage, and a custom domain? I'd like to set up a static website with files stored in a Google Storage bucket.  I already own a custom domain and have, at a minimum, some barebone files to see if the site is setup successfully.
Ideally, I'd like to serve the content via SSL when accessing that custom domain and have the content cached from Google Storage utilizing Google Cloud CDN so that end users are served content from the CDN as opposed to being served from Cloud Storage directly.
I haven't been able to find the perfect setup for this yet or even solidify if Google enables/supports this scenario at this point (I've read that there may be a need to leverage a load balancer to support SSL, but nothing conclusive).
So far I have created a Google Storage bucket and uploaded the desired files.  I then made the bucket publicly readable to ensure there aren't any permissions issues.  From there I set up a load balancer to leverage my custom domain with the checkbox of Google Cloud CDN checked, the storage bucket just created, set as the backend, and the host file mapping set to the default settings.
UPDATE:
It turned out just a few more steps were required.  First, I needed to turn "Requestor Pays" off for the Storage bucket being utilized.  Secondly, I needed to add permissions of "Storage Object Viewer" for "allUsers" (the legacy permission won't work here).  Lastly, I had to both set the "A" and "AAAA" records to the IPV4 and IPV6 addresses of my Load Balancer for the DNS config on my domain name (and clear all previous values so that they were only referring to the new ones).  After all of this was completed, everything is working as it should be :)
Thanks to both Cloud Ace (for leading me in the right direction) and a Google Customer Engineer that I met last week (for referring me to this article for reference: https://medium.com/@marco_37432/create-a-custom-domain-cdn-with-google-beta-7ad9531dfbae)!

A: When you create HTTP(S) Load Balancer, there should be a Certificate section in Frontend configuration if you set the protocol to HTTPS, also preserve a static IP. Then you can configure the DNS to point the domain to this IP.


Q: Controling the look and feel of JButtons on Mac For my assignment I need a 2 dimensional array of JButtons in a grid JPanel in a JFrame. The JButtons must change color when clicked. I cannot get them to hold any color.
I implemented the solutions proposed in a previous thread and found that the work around only produced border color:
JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);

unpainting the border:
button.setBorderPainted(false);

simply causes the entire JFrame to be red.
This issue is only with MAC computers and not the intended problem of the assignment.
Any thoughts?

A: Remember : The Swing toolkit is pretty good at getting the system look and feel "almost right".  If you really need the system feel, however, there are other options like SWT that are a little better suited.
If you want consistency then Swing can always default to the old school applet look which, although a little boring, is pretty reliable .  The upside of this is that, when we roll back to this more simplistic looking gui toolkit, platform specific quirks magically seem to disappear .
I think you might find your problem solved quite easily if you simply set the look and feel to the standard swing style look and feel.
The Solution
I would suggest a call to
    UIManager.setLookAndFeel(
        UIManager.getCrossPlatformLookAndFeelClassName());

In the static code block where you initialize your application.


Q: Why was Dumbledore gone for hours when he went to the Ministry? In book 1, we came to know that Dumbledore had gone to the Ministry of Magic and was gone for hours. I mean enough time not just for Quirrell to get into the hole beneath the 3 headed dog and cross the hurdles to reach the Mirror of Erised but also the trio to imitate his actions and do the same - which I am sure must have take hours for combined both. Not to mention Harry even managed to fight with Quirrell and Voldemort before Dumbledore's arrival.
Dumbledore, one of the wisest and cleverest wizard of the age, was not able to comprehend that perhaps the letter from Ministry could be a plot to get him out of Hogwarts (when he very well knows that Quirrell is trying to steal the stone - detailed in Book 7).
While meeting Harry in the hospital ward, Dumbledore told him that when he realized that Ministry hadn't called him so perhaps he was needed more at Hogwarts than Ministry.
Why couldn't he just use one of the faster ways to talk directly to Fudge?

*

*Travelling thorough Floo Powder

*Talking through Fire (like in Goblet of Fire)

*Apparating outside Hogwarts Grounds and so on..

Why did it take him hours to realize that letter from the Ministry was a hoax and a planned attempt to get him out of the way while the thief try to steal the stone?

A: Just a theory.
Could Dumbledore be waiting for things to play out. There are a lot of chess analogies in the book, could he be making a slight sacrificial move in order to do a checkmate on Quirrell.
It certainly seems within his MO, to take such risks to get results. If he had stayed then nothing would have changed, the stone would still be at risk and nobody would be sure who was trying to steal it. By playing along with the ruse of a fake letter he moves the game forward, drawing out the potential theif.

A: Professor McGonagall says:

"Professor Dumbledore left ten minutes ago," she said coldly. "He received an urgent owl from the Ministry of Magic and flew off for London at once."

So that shows that Dumbledore flew to London, instead of Apparating. Its unlikely that he chose to travel by broomstick, since he's old and they're uncomfortable. He probably took a thestral (possibly in a carriage like how the Beauxbatons delegation arrives), which could easily have taken a few hours - plenty of time for Harry, Ron and Hermione to get through the challenges (I don't think they go at night in the book do they?).

A: Hogwarts is in Scotland and the Ministry of Magic is in London. While the UK is not a large country, it still takes time to travel that distance using more conventional means.
It's clear that Dumbledore didn't use one of the (near) instant forms of magical transportation - Apparition or Floo powder - for whatever reason. I believe it's stated in one of the later books that he sometimes uses the school Thestrals to travel. Even if he only got halfway before realising he needed to turn back it would take him a reasonable amount of time to do so using the same means; I can't see Dumbledore abandoning a Thestral in the middle of nowhere.
Why would he fall for the letter? We know that it's not uncommon at all for him to receive owls from the Minister, so it doesn't seem unreasonable that he would sometimes meet with him in person, and that he may not see the need to rush there under normal circumstances.
Even under these particular circumstances, he trusted Snape - who he had tasked with keeping an eye on Quirrell - completely, and also seemed rather taken with the brilliance of his own security measure for the Philosopher's Stone. He (I think rightly) believed that Quirrell could stand in front of the Mirror of Erised for days and never manage to obtain the Stone from it, so there wasn't any actual danger that he needed to rush back for (until Harry decided he had to stop Quirrell personally).
Out of universe, it's important to note that we've only been introduced to two forms of transport in the Wizarding world by that point: the Hogwarts Express (which barely counts) and brooms. While readers would likely accept "He's a wizard, he can travel anywhere he wants instantly" introducing that at the end would likely raise questions at a time when there are far more important things for the book to cover.


Q: Python selenium ошибка Код:
from selenium import webdriver
driver = webdriver.Chrome()

Ошибка:
C:/Users/user/PycharmProjects/learn_python/sel.py
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\common\service.py", line 74, in start
    stdout=self.log_file, stderr=self.log_file)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 947, in __init__
    restore_signals, start_new_session)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 1224, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] Не удается найти указанный файл

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/learn_python/sel.py", line 2, in <module>
    driver = webdriver.Chrome()
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__
    self.service.start()
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.chrome.service.Service object at 0x004FE1F0>>
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\common\service.py", line 173, in __del__
    self.stop()
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\common\service.py", line 145, in stop
    if self.process is None:
AttributeError: 'Service' object has no attribute 'process'

В чем дело?


Q: Getting the icon for an audio device In the Sound Control Panel in Windows, and in the Volume Mixer, all audio devices have a specific icon set.
Is it possible to get which icon is set for a device through the Windows API?
Sound Control Panel
Volume Mixer

A: As suggested by Simon Mourier in the comments above, there is a PKEY that can access that data.
You can follow along with most of this sample and just replace PKEY_Device_FriendlyNamewith PKEY_DeviceClass_IconPath.
In short, it's something like this:
    // [...]

    IMMDevice *pDevice; // the device you want to look up
    HRESULT hr = S_OK;
    IPropertyStore *pProps = NULL;
    PROPVARIANT varName;

    hr = pDevice->OpenPropertyStore(STGM_READ, &pProps);
    EXIT_ON_ERROR(hr);

    PropVariantInit(&varName);

    hr = pProps->GetValue(PKEY_DeviceClass_IconPath, &varName);
    EXIT_ON_ERROR(hr);

    // [...]


Q: How to display graph from database values using php? I want to create graph using php. I have tested jpgraph example. But it display error
like
> The image “http://localhost/test/jpgraphtest.php” cannot be displayed
> because it contains errors.

<?php
include('phpgraphlib.php');
$graph = new PHPGraphLib(500,350);
$data = array(12124, 5535, 43373, 22223, 90432, 23332, 15544, 24523,
 32778, 38878, 28787, 33243, 34832, 32302);
$graph->addData($data);
$graph->setTitle('Widgets Produced');
$graph->setGradient('red', 'maroon');
$graph->createGraph();
?>

A: check this link I think its perfect.
http://pchart.sourceforge.net/
(also you should configure php to enable image creating).
In Windows, you'll include the GD2 DLL php_gd2.dll as an extension in php.ini. The GD1 DLL php_gd.dll was removed in PHP 4.3.2. Also note that the preferred truecolor image functions, such as imagecreatetruecolor(), require GD2.
check these links.
http://www.php.net/manual/en/image.requirements.php
http://www.php.net/manual/en/image.installation.php
http://www.php.net/manual/en/image.configuration.php
examples:


Q: My Mouse is Too Fast on 12.04 I just installed 12.04 but the mouse is far too fast and it is almost
impossible to do a double click. I have checked the mouse speed settings with no success.

A: Checkout this link: http://patrickmylund.com/blog/lowering-gaming-mouse-sensitivity-in-ubuntu-9-10/
Have fun!

A: All settings concerning your mouse (speed, acceleration, double-click speed ...) can be found in Settings > Mouse. In this case, slide the bars under "Pointer speed" for acceleration and sensitivity.
Hope that helps!

A: Some mice have their own speed settings separate from the OS, for example, I had a mouse that had a button that would let you adjust the sensitivity there. Check and see if your mouse has any of those.


Q: Prevent spring boot resolving properties to scientific notation I have a Spring Boot v2.1.0.RELEASE application with the following application.yml properties file:
example:
  aws:
    account: 845216416540
  sqs:
    endpoint: https://sqs.us-west-2.amazonaws.com/${example.aws.account}

Then I use the property like this:
@Component public class Example {

   @Value("${example.aws.sqs.endpoint}")
   private String endpoint;

   public void test()
   {
      System.out.println(endpoint);
      // prints -> https://sqs.us-west-2.amazonaws.com/8.4521641654E10
   }
}

*

*No that is not my actual aws account (spare me the lecture)

Here is what I can't seem to figure out...
1) Why does spring by default interpolate the the value of the account as scientific notation?
2) How can I configure or prevent this from happening?

A: Spring is inferring the value to be a number. You can force the value to be treated as a string in YAML config by quoting it ie "845216416540"
This answer covers YAML convention in detail: https://stackoverflow.com/a/22235064/13172778


Q: How to fixed header with in table? Hi all I want to fix (or) freezthead header on top and want to scroll tbody values only in table, as of now in table while scroll the page everything gets scrolled, but expecting to scroll only the tbody values ... My Demo
HTML

        {{$index+1}}
             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{dyedyarnreferencenumber.shade}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{dyedyarnreferencenumber.buyers_reference}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{dyedyarnreferencenumber.approved_supplier_ref}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{dyedyarnreferencenumber.category}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{sryarnorder.order_quantity}} {{sryarnorder.order_quantity_unit}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{sryarnorder.price_per_kg_currency}} {{sryarnorder.price_per_kg}}

             <input type="text" ng-model="sryarnorder.color" style="display:none;">

{{sryarnorder.order_quantity * sryarnorder.price_per_kg}}

CSS
table tbody, table thead
{
    display: block!important;
}

table tbody
{
   overflow: auto!important;
   height: 100px!important;
}

table {
    width: 100%!important;
}
th
{
    width: auto!important;
}

Data
$scope.sryarnorders = [{"_id":"573d7fa0760ba711126d7de5","user":{"_id":"5721a378d33c0d6b0bb30416","displayName":"ms ms"},"__v":1,"colorshades":[{"_id":"573d7fc3760ba711126d7de6","price_per_kg_currency":"Inr","price_per_kg":"2","order_quantity_unit":"kg","order_quantity":"23","color":"56ffc46dab97a73d1066b792","quality":"Home Textiles","count":"yarn count"}],"created":"2016-05-19T08:56:00.997Z","remarks":"approved","actual_delivery_date":"2016-05-19","ex_india_date":"2016-05-19","ex_factory_date":"2016-05-19","lc_details_date":"2016-05-19","lc_details":"tooo much","po_delivery_date":"2016-05-19","sales_contract_date":"2016-05-19","sales_contract":"bioler","purchase_order_no_date":"2016-05-19","purchase_order_no":"1234","supplier_name":"Fsa","buyer_name":"e21"},{"_id":"56ffc6d5ab97a73d1066b798","user":{"_id":"56ff7bece2b9a1d10cd074a3","displayName":"saravana kumar"},"__v":1,"colorshades":[{"_id":"56ffc723ab97a73d1066b799","price_per_kg_currency":"Inr","price_per_kg":"120","order_quantity_unit":"kg","order_quantity":"25","color":"56ffc46dab97a73d1066b792","quality":"Home Textiles","count":"yarn count"}],"created":"2016-04-02T13:19:17.746Z","remarks":"pending","actual_delivery_date":"2016-04-02","ex_india_date":"2016-04-04","ex_factory_date":"2016-04-02","lc_details_date":"2016-04-02","lc_details":"lc","po_delivery_date":"2016-04-02","sales_contract_date":"2016-04-02","sales_contract":"required","purchase_order_no_date":"2016-04-02","purchase_order_no":"125","supplier_name":"Fsa","buyer_name":"Binary hand"},{"_id":"56ffc5e0ab97a73d1066b796","user":{"_id":"56ff7bece2b9a1d10cd074a3","displayName":"saravana kumar"},"__v":1,"colorshades":[{"_id":"56ffc608ab97a73d1066b797","price_per_kg_currency":"usd","price_per_kg":"5","order_quantity_unit":"kg","order_quantity":"20","color":"56ffc46dab97a73d1066b792","quality":"yarn quality","count":"yarn count"}],"created":"2016-04-02T13:15:12.876Z","remarks":"clear","actual_delivery_date":"2016-04-02","ex_india_date":"2016-04-02","ex_factory_date":"2016-04-02","lc_details_date":"2016-04-02","lc_details":"free","po_delivery_date":"2016-04-02","sales_contract_date":"2016-04-02","sales_contract":"required","purchase_order_no_date":"2016-04-02","purchase_order_no":"12345","supplier_name":"Fsa","buyer_name":"e21"}];
});

A: Try this: https://codepen.io/tjvantoll/pen/JEKIu
(you need to set fixed column widths)
HTML:

            Name
            Color
            Description

            Apple
            Red
            These are red.

CSS:
.fixed_headers {
  width: 750px;
  table-layout: fixed;
  border-collapse: collapse;
}
.fixed_headers th {
  text-decoration: underline;
}
.fixed_headers th,
.fixed_headers td {
  padding: 5px;
  text-align: left;
}
.fixed_headers td:nth-child(1),
.fixed_headers th:nth-child(1) {
  min-width: 200px;
}
.fixed_headers td:nth-child(2),
.fixed_headers th:nth-child(2) {
  min-width: 200px;
}
.fixed_headers td:nth-child(3),
.fixed_headers th:nth-child(3) {
  width: 350px;
}
.fixed_headers thead {
  background-color: #333;
  color: #FDFDFD;
}
.fixed_headers thead tr {
  display: block;
  position: relative;
}
.fixed_headers tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 300px;
}
.fixed_headers tbody tr:nth-child(even) {
  background-color: #DDD;
}
.old_ie_wrapper {
  height: 300px;
  width: 750px;
  overflow-x: hidden;
  overflow-y: auto;
}
.old_ie_wrapper tbody {
  height: auto;
}


Q: Create Social Graph Dataset From Facebook I am doing a project at my college and I want to build a social graph from Facebook.
I want only the connections between users (friendship) so I can build a Graph.
I read the Facebook API documentation, from my understanding it doesn't allow to fetch my friends' friends, meaning that I'm stuck at first depth.
Does anyone have any suggestions on how to overcome this?

A: Without using a crawler, which is most likely against the TOS, this is not possible.
You could use the first depth to make only a first degree connection graph based on mutual friends within your friend network.
/userid1/friends/userid2

It would be easier to center your project around Twitter's data.


Q: What is a function signature? I was studying python and I ran into the concept of 'signature'. I looked things up but signature of a function seems to have different meaning for different languages. So, what does signature of a function refer to in python?

A: The signature indicates the names and types of the input arguments, and (with type annotations) the type of the returned result(s) of a function or method.
This is not particular to Python, though the concept is more central in some other languages (like C++, where the same method name can exist with multiple signatures, and the types of the input arguments determine which one will be called).

A: In general the signature of a function is defined by the number and type of input arguments the function takes and the type of the result the function returns.
As an example in C++ consider the following function:
int multiply(int x, int y){
    return x*y;
}

The signature of that function, described in an abstract way would be the set {int, int, int}.
As Python is a weakly typed language in general the signature is only given by the amount of parameters. But in newer Python versions type hints were introduced which clarify the signature:
def multiply(x: int, y: int) -> int:
    return x*y

A: A function signature is its declaration, parameters, and return type.
def func(params):
    #some stuff
    return modified_params

When you call it is an instance of that function.
var = func(parameters)


Q: T-SQL and MSBUILD - xml indents and line breaks i'm using msbuild for some automation. One of the task is sql query to get xml representation of table and write it to file. So i'm using
<MSBuild.ExtensionPack.SqlServer.SqlExecute
    ConnectionString="$(AdminConnectionString)"

    Sql="SELECT '%(ReaderResult.Identity)' as XmlFileName,
     (SELECT * FROM %(ReaderResult.Identity) FOR XML AUTO, TYPE, ELEMENTS,
      XMLSCHEMA('%(ReaderResult.Identity)'), ROOT('DataSet'))  as FileContent"
    ContinueOnError="false" TaskAction="ExecuteReader">

   <Output ItemName="ExportResult" TaskParameter="ReaderResult"/>

</MSBuild.ExtensionPack.SqlServer.SqlExecute>

<WriteLinesToFile File="%(ExportResult.XmlFileName).xml"
    Lines="<?xml version="1.0" standalone="yes"?>;
        %(ExportResult.FileContent)" Overwrite="true"/>

The problem is - i get the xml data in single line which is not readable, hard to edit etc.
How can i get the human readable xml with line breaks and indents?
Thanks.

A: Did the following, instead of WriteLinesToFile Task
<SaveFormattedXml XmlString="%(ExportResult.FileContent)" FilePath="%(ExportResult.XmlFileName).xml"/>

<UsingTask TaskName="SaveFormattedXml" TaskFactory="CodeTaskFactory" AssemblyFile="c:\Program Files (x86)\MSBuild\12.0\Bin\amd64\Microsoft.Build.Tasks.v12.0.dll">
<ParameterGroup>
  <XmlString ParameterType="System.String" Required="true" />
  <FilePath ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
  <Reference Include="System.Xml" />
  <Reference Include="System.Xml.Linq"/>
  <Using Namespace="System" />
  <Using Namespace="System.IO" />
  <Using Namespace="System.Xml" />
  <Using Namespace="System.Xml.Linq" />
  <Code Type="Fragment" Language="cs">
    <![CDATA[
       XDocument doc = XDocument.Parse(XmlString);
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.IndentChars = "  ";
        settings.NewLineChars = "\r\n";
        settings.NewLineHandling = NewLineHandling.Replace;
        using (Stream fileStream = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            using (XmlWriter writer = XmlWriter.Create(fileStream, settings))
            {
                doc.Save(writer);
            }
        }
    ]]>
  </Code>
</Task>


Q: Duplicate WiFi tag on Stack Overflow There are two tags which are synonymous to each-other and they have the same description: wifi and wi-fi. The wifi tag is used more often than wi-fi.

A: Good idea, I've merged and synonymized them so in the future this won't happen again.


Q: Create GString from String We're using groovy in a type-safe way. At some point I want to invoke a method with signature
void foo(GString baa)

As long the String I enter contains some ${baz} everything is fine, but when I use a pure String I get a compile error
foo("Hello, ${baz}") // fine
foo("Hello, world") // Cannot assign value of type java.lang.String to variable of type groovy.lang.GString
foo("Hello, world${""}") // fine but ugly

Is there a nice way to create a GString out of String?
EDIT
Guess I've oversimplicated my problem. I'm using named constructor parameters to initialize objects. Since some of the Strings are evaluated lazily, I need to store them as GString.
class SomeClass {
  GString foo
}

new SomeClass(
  foo: "Hello, world" // fails
)

So method-overloading is no option.
The solution is as mentioned by willyjoker to use CharSequence instead of String
class SomeClass {
  CharSequence foo
}

new SomeClass(
  foo: "Hello, world" // works
)

new SomeClass(
  foo: "Hello, ${baa}" // also works lazily
)

A: There is probably no good reason to have a method accepting only GString as input or output. GString is meant to be used interchangeably as a regular String, but with embedded values which are evaluated lazily.
Consider redefining the method as:
void foo (String baa)
void foo (CharSequence baa)  //more flexible

This way the method accepts both String and GString (GString parameter is automagically converted to String as needed). The second version even accepts StringBuffer/Builder/etc.

If you absolutely need to keep the GString signature (because it's a third party API, etc.), consider creating a wrapper method which accepts String and does the conversion internally. Something like this:
void fooWrapper (String baa) {
    foo(baa + "${''}")
}

A: You can create overloaded methods or you can use generics; something as below:

foo("Hello from foo GString ${X}")
foo("Hello from foo")

MyClass.foo("Hello from foo GString ${X}")
MyClass.foo("Hello from foo")

// method with GString as parameter
void foo(GString g) {
    println("GString: " + g)
}

// overloading method with String as parameter
void foo(String s) {
    println("String: " + s)
}

// using generics
class MyClass<T> {
    static void foo(T t) {
        println(t.class.name + ": " + t)
    }
}


Q: How they deduce that $\det A=1$ just from the first coefficient and minor

I found solution of exercise that said show that A is rotation to do that we have to compute det A=1 but they found it directly
Is there any relationship between the first coefficient and minor to say directly without complete computing that $\det A=1$

*

*how they deduce that det A=1 just from the first coeffcient and minor

A: I think the problem is having you try forming the product $A^TA$ and finding that it equals the identity. Therefore, $A^T = A^{-1}$.
Now you can use the equation given, where
$$ A^{-1} = \frac{1}{\det A} C^T = A^T $$
Consider the first element, so
$$ \frac{1}{\det A} C_{11} = A_{11} = \frac{8}{9}$$
Now, $C_{11} = 72/9^2$, so $\det A = \frac{8}{9} \frac{9^2}{72} = 1 $.

A: $DetA = 1$ is a necessary but not sufficient condition for a matrix being a rotation. To be a rotation $A^T = A^{-1}$ (and here we include reflections composed with rotations, ie $detA = \pm 1$).


Q: how can the bash script kill self if it received ctrl z pseudo code in my xxx.sh
a large loop {
    python xxx.py
}

when I run this script ./xxx.sh and some bugs in python, then exception info will be raised to stdout repeatedly.
if I press ctrl+c, the signal will be catched by python, and if I press ctrl+z, the xxx.sh will be sleep in the background.
So, I am trying to add some trap code to catch ctrl+z,
the trap code in my xxx.sh
function stop_ctrl_z() {
    echo $$
    pkill -9 $$
}
trap stop_ctrl_z SIGTSTP

But xxx.sh cannot stop itself when met ctrl+z as my expected.
It hangs up, sadly I must open another terminal and use pkill -9 xxx.sh to stop this script.
^Z^Z^Z^Z^Z^Z^Z^Z^Z^Z

Does someone has solution to solve my problem?

A: Just force an exit when the Python call fails:
python xxx.py || exit 1

You could use break instead of exit to just leave the loop. More advanced error handling can be achieved by evaluating $?; here's an example how to store the return value and reuse it:
python xxx.py
result=$?
if [ ${result} -ne 0 ]; then
    # Error
    echo "xxx.py exited with ${result}"
    ...
else
    # Success
    ...
fi

As a general rule, not only regarding Bash scripting but programming in general, always check return codes of commands for errors and handle them. It makes debugging and your working life in general easier in the long run.


Q: Does Perl 6 have an equivalent to Python's bytearray method? I can't find bytearray method or similar in Raku doc as in Python. In Python, the bytearray defined as this:
class bytearray([source[, encoding[, errors]]])

Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the str type has, see String Methods.

Does Raku should provide this method or some module?

A: brian d foy answer is essentially correct. You can pretty much translate this code into Perl6
 my $frame = Buf.new;
 $frame.append(0xA2);
 $frame.append(0x01);
 say $frame; # OUTPUT: «Buf:0x<a2 01>␤»

However, the declaration is not the same:
bu = bytearray( 'þor', encoding='utf8',errors='replace')

in Python would be equivalent to this in Perl 6
my $bú =  Buf.new('þor'.encode('utf-8'));
say $bú; # OUTPUT: «Buf:0x<c3 be 6f 72>␤»

And to use something equivalent to the error transformation, the approach is different due to the way Perl 6 approaches Unicode normalization; you would probably have to use UTF8 Clean 8 encoding.
For most uses, however, I guess Buf, as indicated by brian d foy, is correct.

A: I think you're looking for Buf - a mutable sequence of (usually unsigned) integers. Opening a file with :bin returns a Buf.


Q: Programmatically convert WAV I'm writing a file compressor utility in C++ that I want support for PCM WAV files, however I want to keep it in PCM encoding and just convert it to a lower sample rate and change it from stereo to mono if applicable to yield a lower file size.
I understand the WAV file header, however I have no experience or knowledge of how the actual sound data works. So my question is, would it be relatively easy to programmatically manipulate the "data" sub-chunk in a WAV file to convert it to another sample rate and change the channel number, or would I be much better off using an existing library for it? If it is, then how would it be done? Thanks in advance.

A: PCM merely means that the value of the original signal is sampled at equidistant points in time.
For stereo, there are two sequences of these values. To convert them to mono, you merely take piecewise average of the two sequences.
Resampling the signal at lower sampling rate is a little bit more tricky -- you have to filter out high frequencies from the signal so as to prevent alias (spurious low-frequency signal) from being created.

A: I agree with avakar and nico, but I'd like to add a little more explanation.  Lowering the sample rate of PCM audio is not trivial unless two things are true:

*

*Your signal only contains significant frequencies lower than 1/2 the new sampling rate (Nyquist rate).  In this case you do not need an anti-aliasing filter.

*You are downsampling by an integer value.  In this case, downampling by N just requires keeping every Nth sample and dropping the rest.
If these are true, you can just drop samples at a regular interval to downsample.  However, they are both probably not true if you're dealing with anything other than a synthetic signal.
To address problem one, you will have to filter the audio samples with a low-pass filter to make sure the resulting signal only contains frequency content up to 1/2 the new sampling rate.  If this is not done, high frequencies will not be accurately represented and will alias back into the frequencies that can be properly represented, causing major distortion.  Check out the critical frequency section of this wikipedia article for an explanation of aliasing.  Specifically, see figure 7 that shows  3 different signals that are indistinguishable by just the samples because the sampling rate is too low.
Addressing problem two can be done in multiple ways.  Sometimes it is performed in two steps: an upsample followed by a downsample, therefore achieving rational change in the sampling rate.  It may also be done using interpolation or other techniques.  Basically the problem that must be solved is that the samples of the new signal do not line up in time with samples of the original signal.
As you can see, resampling audio can be quite involved, so I would take nico's advice and use an existing library.  Getting the filter step right will require you to learn a lot about signal processing and frequency analysis.  You won't have to be an expert, but it will take some time.

A: I don't think there's really the need of reinventing the wheel (unless you want to do it for your personal learning).
For instance you can try to use libsnd


Q: Odd behavior with Ruby defined? I am a newbie at Ruby and have a question with the defined? keyword.
Here's a snippet of code that I've written to load a yaml file to initialize settings in my Ruby script:
# Read settings file
require 'YAML'
settingsFile = File.join(File.dirname(__FILE__), "settings.yml").tr('\\', '/')
Settings = YAML.load_file(settingsFile) unless defined? Settings
puts Settings

The yaml file looks like this:
Hello: World

This outputs correctly with:

{"Hello"=>"world"}

Now if I use a variable instead of a constant to store the settings, such as the following:
# Read settings file
require 'YAML'
settingsFile = File.join(File.dirname(__FILE__), "settings.yml").tr('\\', '/')
settings = YAML.load_file(settingsFile) unless defined? settings
puts settings

settings returns empty.
What gives? Why would using a constant make this work?

A: This is a quirk in the way Ruby handles trailing if/unless conditions and how variables come into existence and get "defined".
In the first case the constant is not "defined" until it's assigned a value. The only way to create a constant is to say:
CONSTANT = :value

Variables behave differently and some would argue a lot more strangely. They come into existence if they're used anywhere in a scope, even in blocks of code that get skipped by logical conditions.
In the case of your line of the form:
variable = :value unless defined?(variable)

The variable gets "defined" since it exists on the very line that's being executed, it's going to be conditionally assigned to. For that to happen it must be a local variable.
If you rework it like this:
unless defined?(variable)
  variable = :value
end

Then the behaviour goes away, the assignment proceeds because the variable was not defined prior to that line.
What's strange is this:
if defined?(variable)
  variable = :value
end

Now obviously it's not defined, it doesn't get assigned, but then this happens:
defined?(variable)
# => "local-variable"

Now it's defined anyway because Ruby's certain it's a variable. It doesn't have a value yet, it's nil, but it's "defined" as far as Ruby's concerned.
It gets even stranger:
defined?(variable)
# => false
if (false)
  variable = :value
end
defined?(variable)
# => "local-variable"

Where that block of code didn't even run, it can't even run, and yet, behold, variable is now defined. From that assignment line on forward that variable exists as far as Ruby is concerned.
Since you're doing an attempted assignment and defined? on the same line the variable exists and your assignment won't happen. It's like a tiny paradox.


Q: When is disk cache cleared on iOS? I'm using the cache to store a bunch of rendered thumbnails for my game. It can easily go up to 60MB if the user has all the content in the game.
I wonder if I need to clear this out myself? Does the OS do this for me, and if so when?
Thanks!

A: When I had an issue with the documents directory on IOS5 I found this article which discusses the cache amongst other subjects.
As I understand it; yes the OS handles the cache and it will clear it when disk space is low. What low actually means in size I do not know.


Q: How can I iterate through nested hash of hash without knowing its key? I have a hash of hashes, that is, hash and hash references in my data structure. Can I iterate through the deepest hash when I only have the main hash name and no key of the deepest hash?
my %gates_info=(
    'order' => {
        'nand' => {
            'nand2_1' =>2,
            'nand2_5' =>-1,
            'nand2_4' =>2,
            'nand2_6' =>-1,
            'nand2_2' =>2,
            'nand2_3' =>3
        },
        'and' => {
            'and2'=>1,
            'and3'=>2,
        },
    }
);

sub max_gate_order {
    print values (%{$gates_info{'order'}});
    my @arr = (sort {$a <=> $b} values %{$gates_info{'order'}});
    return $arr[-1];
}

I want to iterate over the whole hash when I have just its name %gates_info and no keys such as "nand" or "and". What I am trying to achieve is to get the highest numeric value in each of the gates by sorting. Such as 3 in nand case and 2 in and case. Sub max_gate_order is used for sorting and returning highest value. Thanks

A: keys will give you those keys.
sub max_gate_order {
   my ($gates_info) = @_;
   my $max_order;
   my @gates;
   for my $gate_type (keys %{ $gates_info->{order} }) {
      for my $gate_id (keys %{ $gates_info->{order}{$gate_type} }) {
         my $order = $gates_info->{order}{$gate_type}{$gate_id};
         $max_order //= $order;
         if ($order >= $max_order) {
            if ($order > $max_order) {
               $max_order = $order;
               @gates = ();
            }

            push @gates, $gate_id;
         }
      }
   }

   return @gates;
}

my @gates = max_gate_order(\%gates_info);

The above returns all the gates with the highest order.
If you want both the gate type and the gate id, replace
push @gates, $gate_id;

with
push @gates, [ $gate_type, $gate_id ];

or
push @gates, [ $gate_type, $gate_id, $order ];

A: This is a longer, more redundant solution, more of an exercise really. But you might find it interesting to examine the structure of the hash iteration this way. (I know I do!) This could be useful if you only have the main hash name (%gates_info), and none of the keys under that. Which is what your question implies is the case. This pulls out all the key and value names as deep as the hash goes, in case any of those might be useful. (Note this does require knowing how many levels deep your hash is.)
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my %gates_info=(
    'order' => {
        'nand' => {
            'nand2_1' =>2,
            'nand2_5' =>-1,
            'nand2_4' =>2,
            'nand2_6' =>-1,
            'nand2_2' =>2,
            'nand2_3' =>3
        },
        'and' => {
            'and2'=>1,
            'and3'=>2,
        },
    }
);
print Dumper %gates_info;
print "\n\n";

my @gate;
my $hival;

foreach my $gate (sort keys %gates_info) {
 foreach my $gatekey (sort keys %{$gates_info{$gate}}) {
   foreach my $deepkey (sort keys %{$gates_info{$gate}{$gatekey}}) {
   my $deepvalue = $gates_info{$gate}->{$gatekey}->{$deepkey};
push @gate, $deepvalue;
@gate = sort @gate;
$hival = $gate[@gate - 1];
print "Gate is $gate, gatekey is $gatekey, deepkey is $deepkey, deepvalue is $deepvalue\n";
  }
print "\nGatekey is $gatekey, highest value is $hival\n\n";
@gate = (); #empty gate array
 }
}

exit 0;

The output of the code is:
$VAR1 = 'order';
$VAR2 = {
          'and' => {
                     'and2' => 1,
                     'and3' => 2
                   },
          'nand' => {
                      'nand2_3' => 3,
                      'nand2_6' => -1,
                      'nand2_4' => 2,
                      'nand2_5' => -1,
                      'nand2_2' => 2,
                      'nand2_1' => 2
                    }
        };

Gate is order, gatekey is and, deepkey is and2, deepvalue is 1
Gate is order, gatekey is and, deepkey is and3, deepvalue is 2

Gatekey is and, highest value is 2

Gate is order, gatekey is nand, deepkey is nand2_1, deepvalue is 2
Gate is order, gatekey is nand, deepkey is nand2_2, deepvalue is 2
Gate is order, gatekey is nand, deepkey is nand2_3, deepvalue is 3
Gate is order, gatekey is nand, deepkey is nand2_4, deepvalue is 2
Gate is order, gatekey is nand, deepkey is nand2_5, deepvalue is -1
Gate is order, gatekey is nand, deepkey is nand2_6, deepvalue is -1

Gatekey is nand, highest value is 3

A: sub max_gate_order {

    my %hash =();
    foreach my $k (keys %{$gates_info{'order'}}) {
        my @arr = (sort {$a <=> $b} values %{$gates_info{'order'}->{$k}});
        $hash{$k} = $arr[-1];
    }
    return \%hash;

}


Q: Limit of an infinite sum (error function) I was playing with the error function:
$$\text{erf}(x)=\int_{0}^x e^{-t^2}dt$$
In that process I expanded the integrand $e^{-t^2}$ and integrated term by term and found out that you can express the $\text{erf}(x)$ function in terms of an infinite series:
$$\text{erf}(x)=\frac{2}{\sqrt{\pi}}\sum_{n=0}^{\infty}\frac{(-1)^{n}x^{2n+1}}{n!(2n+1)}$$
What really surprise me is the fact that this limit exists!(It seems unbounded, but it is not):
$$\lim_{x\rightarrow\infty}\text{erf}(x)= \lim_{x\rightarrow\infty}\ \frac{2}{\sqrt{\pi}}\sum_{n=0}^{\infty}\frac{(-1)^{n}x^{2n+1}}{n!(2n+1)}=1 \tag{1}$$
You can argue that the error series converges for all finite $x$.
$$\lim_{n\rightarrow\infty} \Bigg| \frac{\frac{(-1)^{n+1}x^{2(n+1)+1}}{(n+1)!(2(n+1)+1)}}{\frac{(-1)^{n}x^{2n+1}}{n!(2n+1)}} \Bigg|$$
$$=\lim_{n\rightarrow\infty} \Bigg| \frac{x^2(2n+1))}{(2n+3)(n+1)} \Bigg|=0$$
This also means that the radius of convergence $|x^2|$ is the whole complex plane
Update
I  want to know if  you can evaluate the limit (1) in a different way ?, than from getting the error integral and integrate.

A: You're trying to compute $\lim_{x\to\infty}\text{erf}(x)$ using the series expansion:
$$\text{erf}(x)=\frac{2}{\sqrt{\pi}}\sum_{n=0}^{\infty}\frac{(-1)^{n}x^{2n+1}}{n!(2n+1)}$$
and finding that the terms of the series don't converge as $x\to\infty$. This is not a contradiction, because you've simply established that
$$\lim_{x\to\infty}\lim_{m\to\infty}\sum_{n=0}^{m}\frac{(-1)^{n}x^{2n+1}}{n!(2n+1)}
\ne\lim_{m\to\infty}\lim_{x\to\infty}\sum_{n=0}^{m}\frac{(-1)^{n}x^{2n+1}}{n!(2n+1)}\ .
$$
In other words, interchanging the two limits doesn't yield the same result. The interchange of limits is not legal (i.e., the interchange won't give the same result) unless additional conditions are satisfied, such as uniform convergence.
See Proving $\int_{0}^{\infty} \mathrm{e}^{-x^2} dx = \dfrac{\sqrt \pi}{2}$ for alternative ways to evaluate this integral.


Q: Can't add std_logic to unsigned I'm making a program to count all the 1's from a std_logic_vector, the out from the program should be a std_logic_vector too. The vector size is based on a generic number. To do the count, i'm using a for generate and adding the 1's to an unsigned signal, but it's not working. Here is the error from the ide:
Line 27. unsigned can not have such operands with returned type UNSIGNED.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.std_logic_arith.all;
use IEEE.NUMERIC_STD.ALL;

entity proj2_1 is
     GENERIC (N: INTEGER := 8); -- SIZE OF THE VECTOR
    Port ( VTIN : in  STD_LOGIC_VECTOR (N-1 downto 0);
           VTOUT : out  STD_LOGIC_VECTOR (N-1 downto 0);
              cont: buffer unsigned  (N-1 downto 0) );
end proj2_1;
architecture Behavioral of proj2_1 is
begin
    gen: FOR i IN VTIN' RANGE GENERATE
    BEGIN
        cont <= cont + ( unsigned (VTIN(i)));
    END GENERATE;
    VTOUT <= std_logic_vector(cont);
end Behavioral;

A: First there should be no declaration of unsigned visible due to conflicts between packages std_logic_arith and numeric_std. Use one or the other (numeric_std is part of the VHDL standard).
Second the element type of VTIN is std_logic or std_ulogic depending on the VHDL revision which isn't compatible with the array type/subtype std_logic_vector. That means type conversion isn't legal.
Next a concurrent signal assignment is elaborated into a process which implies a driver for the longest static prefix (here cont). Having VTIN'LENGTH processes with generate 'X's, the values will be resolved, the driver outputs are shorted.
Instead of a generate statement use a process with a variable used to count '1's in a sequential loop statement with a for iteration scheme. The variable is used because the value of signal cont isn't updated until the process suspends. You assign the variable value to cont after the loop statement. After the process suspends, the value of cont will be available to use in the assignment to VTOUT. std_logic_arith can added a std_logic value to a std_logic_vector as can numeric_std in -2008 (otherwise unsigned(""& VTIN(i)) converts std_logic to unsigned. You could also implement a subprogram.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- use ieee.std_logic_arith.all;
use IEEE.NUMERIC_STD.ALL;

entity proj2_1 is
     GENERIC (N: INTEGER := 8); -- SIZE OF THE VECTOR
    Port ( VTIN : in  STD_LOGIC_VECTOR (N-1 downto 0);
           VTOUT : out  STD_LOGIC_VECTOR (N-1 downto 0);
              cont: buffer unsigned  (N-1 downto 0) );
end entity proj2_1;
architecture behavioral of proj2_1 is
begin
    -- gen: FOR i IN VTIN' RANGE GENERATE
    -- BEGIN
    --     cont <= cont + ( unsigned (VTIN(i)));
    -- END GENERATE;

SEQUENTIAL_LOOP_NOT_GENERATE_STATEMENT:
    process (VTIN)
    variable ones: unsigned(VTOUT'RANGE);
    begin
        ones := (others => '0'); -- zero
        for i in VTIN'RANGE loop
            ones := ones + unsigned'("" & VTIN(i));
        end loop;
        VTOUT <= std_logic_vector (cont + ones);
    end process;
end architecture behavioral;

A generate statement is a concurrent statement which elaborates to a block statement for every value of the generate parameter containing the concurrent statement which has a process statement equivalent. A process statement has a driver for each signal assigned in it's sequence of statements. One driver versus lots of drivers.
With package numeric std you could also declare the variable (here ones) as an integer (natural). numeric_std supports the addition of natural range integers to unsigned values.
Notice there's nothing that defines an initial value for port cont which has a mode of buffer, essentially an output that be read internally. The default initial value will be (others => 'U')from the left most value of the enumerated type std_ulogic. Either the original intent is wrong (count all the 1's from a std_logic_vector" or more likely you actually one the population count of '1's in VTIN.
The latter requires a change:
architecture behavioral of proj2_1 is
begin
SEQUENTIAL_LOOP_NOT_GENERATE_STATEMENT:
    process (VTIN)
    variable ones: unsigned(VTOUT'RANGE);
    begin
        ones := (others => '0'); -- zero
        for i in VTIN'RANGE loop
            ones := ones + unsigned'("" & VTIN(i));
        end loop;
        -- VTOUT <= std_logic_vector (cont + ones);
        VTOUT <= std_logic_vector (ones);
        cont <= ones;
    end process;
end architecture behavioral;

that doesn't reflect the original code but doesn't accumulate across new values of VTIN and is synthesis eligible.
The integer variable version of the population count of '1's could look like
architecture integer_variable of proj2_1 is
begin
SEQUENTIAL_LOOP_NOT_GENERATE_STATEMENT:
    process (VTIN)
    variable ones: natural;
    begin
        ones := 0;
        for i in VTIN'RANGE loop
            if TO_BIT(VTIN(i)) = '1' then
                ones := ones + 1;
            end if;
        end loop;
        VTOUT <= std_logic_vector (to_unsigned(ones, VTOUT'length));
        cont <= to_unsigned(ones, VTOUT'length); -- and both outputs don't make sense
    end process;
end architecture integer_variable;

where adding an integer value doesn't propagate meta values from VTIN during addition.


Q: Is this launchd plist broken or is it just me? I was reading a post about using Bittorrent Sync on OS X that includes a launchd plist that's supposed to keep the app running in the event that it crashes. It doesn't seem to work, though, since I've had the app crash and not relaunch. I'm looking for help fixing the plist.
The plist looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>KeepAlive</key>
    <dict>
        <key>Crashed</key>
        <true/>
        <key>SuccessfulExit</key>
        <false/>
    </dict>
    <key>Label</key>
    <string>sync.com.tjluoma.bittorrentsync</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/bin/open</string>
        <string>-W</string>
        <string>-a</string>
        <string>BitTorrent Sync</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

The "clever" bit is using /usr/bin/open to launch the app, with -W to make sure that open waits for the app to exit. But I think that's also why it doesn't actually work. If I'm reading this right, the app will only relaunch if /usr/bin/open crashes, not if Bittorrent Sync crashes. For the above approach to work, open would need to return error status if the app it opened had crashed (and this does not happen).
I know I could fix this by dropping open and instead hard coding the path to the executable as /Applications/BitTorrent Sync.app/Contents/MacOS/BitTorrent Sync. But is there an alternative that doesn't require hard-coding the full path? Using open would be elegant, if it worked.

A: It was as I expected. The version in the question doesn't re-launch the app, because /usr/bin/open doesn't return an error status when the app crashes. I wasn't able to find a better way than hard-coding the path to the executable, so I'm now using the following.
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>KeepAlive</key>
        <dict>
                <key>Crashed</key>
                <true/>
                <key>SuccessfulExit</key>
                <false/>
        </dict>
        <key>Label</key>
        <string>com.getsync.bittorrentsync</string>
        <key>Program</key>
        <string>/Applications/BitTorrent Sync.app/Contents/MacOS/BitTorrent Sync</string>
        <key>RunAtLoad</key>
        <true/>
</dict>
</plist>

I've verified that this does successfully re-launch the app if it crashes.
A more easily downloadable version of this can be found at https://gist.github.com/atomicbird/ff2de46a594cdb5c8e69


Q: Example OverlayFS Usage I'm running Ubuntu 14.04 with the 3.19 kernel which should have OpenFS supported (since kernel 3.18). I've been reading about OverlayFS but am confused as to how to actually implement using it. It looks like it could be a really useful alternative to LVM in enabling changes to be written somewhere else whilst taking a backup of the original filesystem that is being overlayed?
Can someone give me the example mount commands to use (if possible) for the following cases:

*

*With a raw disk image (created using dd if=/dev/zero of=$HOME/filestystem1.img bs=4096 count=1024000) to act as the overlaying filesystem, mount it over the top of my host's filesystem at $HOME/mount which should already contain some random files such as file1.txt and file2.txt. Once mounted I believe that I should still be able to see my already existing files and any files I now create will actually be stored inside the filesystem1.img file that I could possibly move to another system?

*Create another raw disk image and mount this one on top of the other one we just created. Do I do this as a second mount command that is executed after mount command we ran in the previous example, or can I possibly specify both mounts in one go?
I can't tell if OverlayFS is an actual filesystem I need to create on the disk images with mkfs -t xxx /path/to/raw/disk/image, or is a special mounting method and the raw disk images are actually using something like ext4, but they are mounted in a special way with mount -t OverlayFS? When I run:
cd /sbin
ls mkfs*

I get the following which do not show an option to make an overlay filesystem.
mkfs      mkfs.cramfs  mkfs.ext3  mkfs.ext4dev  mkfs.minix  mkfs.ntfs
mkfs.bfs  mkfs.ext2    mkfs.ext4  mkfs.fat      mkfs.msdos  mkfs.vfat

A:
I can't tell if OverlayFS is an actual filesystem I need to create on
  the disk images with mkfs -t xxx /path/to/raw/disk/image, or is a
  special mounting method and the raw disk images are actually using
  something like ext4, but they are mounted in a special way with mount
  -t OverlayFS?

One does not need to run any mkfs command for overlayFS, it is just a way of mounting.

Once mounted I believe that I should still be able to see my already
  existing files and any files I now create will actually be stored
  inside the filesystem1.img file that I could possibly move to another
  system?

Yes, for a more detailed explanation of how OverlayFS works, you may wish to refer to "Docker and OverlayFS in practice".
Examples
Creating an overlay mount can be done purely with directories if desired as demonstrated here:
cd /tmp
mkdir lower upper workdir overlay
sudo mount -t overlay -o \
lowerdir=/tmp/lower,\
upperdir=/tmp/upper,\
workdir=/tmp/workdir \
none /tmp/overlay

You can throw in [virtual] block devices with their own filesystems (of any kind) to act as the lower and upper filesystems if you desire. The only restriction is that the "workdir" needs to be an empty directory within the same filesystem as the upperdir. An example using a filesystem for both the upperdir and lowerdir can be shown below:
cd /tmp

# Create the necessary directories.
mkdir lower upper overlay

# Lets create a fake block device to hold our "lower" filesystem
dd if=/dev/zero of=lower-fs.img bs=4096 count=102400
dd if=/dev/zero of=upper-fs.img bs=4096 count=102400

# Give this block device an ext4 filesystem.
mkfs -t ext4 lower-fs.img
mkfs -t ext4 upper-fs.img

# Mount the filesystem we just created and give it a file
sudo mount lower-fs.img /tmp/lower
sudo chown $USER:$USER /tmp/lower
echo "hello world" >> /tmp/lower/lower-file.txt

# Remount the lower filesystem as read only just for giggles
sudo mount -o remount,ro lower-fs.img /tmp/lower

# Mount the upper filesystem
sudo mount upper-fs.img /tmp/upper
sudo chown $USER:$USER /tmp/upper

# Create the workdir in the upper filesystem and the
# directory in the upper filesystem that will act as the upper
# directory (they both have to be in the same filesystem)
mkdir /tmp/upper/upper
mkdir /tmp/upper/workdir

# Create our overlayfs mount
sudo mount -t overlay -o \
lowerdir=/tmp/lower,\
upperdir=/tmp/upper/upper,\
workdir=/tmp/upper/workdir \
none /tmp/overlay

The examples above are taken from my blog post on using overlayfs.
Nesting OverlayFS

... another raw disk image and mount this one on top of the other
  one we just created. Do I do this as a second mount command that is
  executed after mount command we ran in the previous example, or can I
  possibly specify both mounts in one go?

You can nest overlayFS. For example, you can nest the example above as the lowerdir to another overlayFS system by running:
mkdir -p /tmp/upperdir2/upper /tmp/upperdir2/workdir /tmp/overlay2
sudo mount -t overlay -o \
lowerdir=/tmp/overlay,\
upperdir=/tmp/upperdir2/upper,\
workdir=/tmp/upperdir2/workdir \
none /tmp/overlay2

When Ubuntu gets kernel 4.0+, we should be able to combine multiple lower directories in a single command by using the colon character as a separator like so:
sudo mount -t overlay -o \
lowerdir=/tmp/lower:/tmp/lowest,\
upperdir=/tmp/upper,\
workdir=/tmp/workdir \
none /tmp/overlay

In this case, you do not have two workdirs but one, and you keep the same merged path of /tmp/overlay. The lower directories will be stacked from right to left. You can also omit upperdir= entirely, which results in a readonly mount.


Q: Array to string in JavaScript I get an array of numbers as a response from remote command execution (using ssh2). How do I convert it to a string?
[97,112,112,46,106,115,10,110,111,100,101,46,106,115,10]

A: var result = String.fromCharCode.apply(null, arrayOfValues);

JSFiddle
Explanations:
String.fromCharCode can take a list of char codes as argument, each char code as a separate argument (for example: String.fromCharCode(97,98,99)).
apply allows to call a function with a custom this, and arguments provided as an array (in contrary to call which take arguments as is). So, as we don't care what this is, we set it to null (but anything could work).
In conclusion, String.fromCharCode.apply(null, [97,98,99]) is equivalent to String.fromCharCode(97,98,99) and returns 'abc', which is what we expect.

A: It depends on what you want and what you mean.
Option One: If you want to convert the text to ASCII, do this:
var theArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
theString = String.fromCharCode.apply(0, theArray);

(Edited based on helpful comments.)
Produces:
app.js
node.js

Option Two: If you just want a list separated by commas, you can do .join(','):
var theArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
var theString = theArray.join(',');

You can put whatever you want as a separator in .join(), like a comma and a space, hyphens, or even words.

A: In node.js it's usually done with buffers:
> new Buffer([97,112,112,46,106,115,10,110,111,100,101,46,106,115,10]).toString()
'app.js\nnode.js\n'

It'll be faster than fromCharCode, and what's most important, it'll preserve utf-8 sequences correctly.

A: just use the toString() function:

var yourArray = [97,112,112,46,106,115,10,110,111,100,101,46,106,115,10];
var strng = yourArray.toString();

A: The ssh2 module passes a Buffer (not an actual javascript array) to 'data' event handlers for streams you get from exec() or shell(). Unless of course you called setEncoding() on the stream, in which case you'd get a string with the encoding you specified.
If you want the string representation instead of the raw binary data, then call chunk.toString() for example.


Q: Google Sheet - Calculate a cost I'm trying to reproduce that lovely website that helps you calculate the cost of something you bought into my personnal google sheet so it's easier for me to use it.
I'm seeking here for help since I don't really know how to adapt the math when you change the value of year/month/day.
As you may see, it's able to calculate the cost by year, but when you change the value to month for example, I don't know how to make it adjust the results.
I've tried =SUMIF, =IF, but I can't seem to find a clear way to do it.
here is the doc
Thanks a lot!

A: I think what you are looking for is the SWITCH function:
You can in the cell D6 use the following formula:
=SWITCH(F2; I2; E1/E2; I3; E1*12/E2; I4; E1*52/E2; I5; E1*365/E2)
The logic is:

*

*check the cell F2 (where you have the dropdown)

*if the value of F2 equals I2 (Year) then, just divide the cost by the number of years

*if the value of F2 equals I3 (Month), then make E1*12 and divide it by the the E2 (same as (E1/E2)/12

*if the value of F2 equals I4 (Week), then calculate E1*52/E2 (same as above but with 52 weeks)

*if the value of F2 equals I5 (Day), then calculate E1*365/E2 (same as above but with 365 days)

And so on on the other cells, just change the differences between the formulas, between day, week, month and year.


Q: How to get number apps running in background I am working on an app which needs the information of how many application running in background at the system,
I want to get number of them.
Any idea please ?

A: This Below lines give the list of Apps which are in background,
ActivityManager actvityManager = (ActivityManager)
this.getSystemService( ACTIVITY_SERVICE );
List<RunningAppProcessInfo> procInfos = actvityManager.getRunningAppProcesses();

procInfos.size() gives you number of apps


Q: How do i fix this Nested if command in excel? I have a excel doc in which I record the crashes of a certain application.
Inside one of the rows is the following
3/27/2016 | (Cell B39)  |   null |  mins |  null |  secs |  (Command)

... the command is,
=IF(ERROR.TYPE(B39) =3,"Hasn't Crashed Yet",IF(B39 =0, "No Crash", "Crashed"))

*

*when B39 = 0, i want it to output "No Crash".

*when B39 is any number greater than 0, i want it to output "Crashed".

*when B39 has an error, i want it to output "Hasn't Crashed Yet".

The current command outputs "Hasn't Crashed Yet" when B39 is an error, but when B39 is 0 or higher, it outputs #N/A.

A: Try,
=if(isnumber(B39), if(b39>0, "crashed", "no crash"), if(iserror(b39), "hasn't crashed yet", "how'd I get here?"))


Q: How to upgrade multiple Macs to OS X 10.10.4? I own multiple Macs at home and, when I installed Yosemite (10.10) I downloaded the installer from the App Store on the main computer, then copied "/Applications/Install\ OS\ X\ Yosemite" to a safe location, and used the copy to upgrade the other computers skipping the long download time.
Now that the upgrade to 10.10.4 is available, I noticed that there is no "Install" executable in /Applications - so I had to repeat the long download for all my three computers.  How could I use a single download for all computers again?

A: For every OS X 'delta' release  - 10.10.1/2/3/ ...10.10.4 etc - which App Store will download to each Mac there is a simultaneous 'combo' update release which rolls up all the previous deltas into one single downloadable update.
It was for many years considered the 'pro' way to do the update, as it can also correct potential update issues that the delta can't.
You can always find updates related to OS X here.
As the combo update doesn't use the App Store "download, install, delete" structure, you can pass it from machine to machine at your leisure.
Maybe not as slick as using the server - but it's free ;-)
From comments -
The combo update can also be applied to machines which are already running the current version of the OS, unlike the App Store's delta "update" mechanism. This can sometimes correct issues that may linger after doing a series of incremental [delta] updates.
The combo updater is invariably larger than the incremental updates; but it is worth it, just for the peace of mind.

A: The OS X Server App allows you to cache data on your network as well as manage multiple devices and installations/updates on them. This would simplify things for you in the long run, but there might be a slight learning curve to start out. I haven't used the Yosemite version of the Server App yet so can't give you more specifics. It's something to look into anyway to streamline your process.


Q: Why is rust-analyzer not finding dependencies in workspace member? I have a cargo workspace with one library "./raytracing" and one binary "./cli". The two workspace members have different dependencies.
./raytracing/Cargo.toml:
[package]
name = "raytracer"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.8.5"

./cli/Cargo.toml:
[package]
name = "cli"
version = "0.1.0"
edition = "2021"

[dependencies]
raytracer = {path = "../raytracer"}
rand = "0.8.5"
rand_xorshift = "0.3.0"

Parent directory Cargo.toml (./Cargo.toml)
[package]
edition = "2021"
name = "raytracing"
version = "0.1.0"

[workspace]
members = [
    "raytracer",
    "cli",
]

[[bin]]
path = "cli/src/main.rs"
name = "cli"

Compiling both the raytracer and cli packages using cargo build -p works, however in VSCode rust-analyzer complains about my dependencies in the ./cli package when I import them in main.rs:
Error

A: With your current setup you actually have two binaries compiled from the same source file: cli and raytracing. raytracing doesn't declare any [dependencies] so of course you're getting an error when trying to compile that. You haven't explained what you're trying to achieve, so I can't tell you the correct way to fix this problem. Generally, there's two things you can do:

*

*Make the root package virtual by deleting everything from ./Cargo.toml except the [workspace] section. (normal)

*Ditch the ./cli/Cargo.toml and move its [dependencies] section to ./Cargo.toml. (bit weird)