text:
Q: How do I upgrade a Chef SQL Server Cookbook to use Enterprise Edition? I've got a Chef cookbook from GitHub.  It installs SQL Server 2012 Standard Edition.  Our DBA has upgraded our database code to utilize features that can only be found on SQL Server 2012 Enterprise Edition.  Since this cookbook is used to generate our test environments, we must now alter this cookbook to deploy SQL Server 2012 Enterprise.
Looking at the helper.rb file in the cookbook,
require 'chef/mixin/shell_out'

module SqlServer
  class Helper
    extend Chef::Mixin::ShellOut

    def self.firewall_rule_enabled?(rule_name=nil)
      cmd = shell_out("netsh advfirewall firewall show rule \"#{rule_name}\"")
      cmd.stderr.empty? && (cmd.stdout =~ /Enabled:\s*Yes/i)
    end

    def self.sql_server_url(version, x86_64)
      if x86_64
        case version
        when '2008R2'
          'http://download.microsoft.com/download/D/1/8/D1869DEC-2638-4854-81B7-0F37455F35EA/SQLEXPR_x64_ENU.exe'
        when '2012'
          'http://download.microsoft.com/download/8/D/D/8DD7BDBA-CEF7-4D8E-8C16-D9F69527F909/ENU/x64/SQLEXPR_x64_ENU.exe'
        end
      else
        case version
        when '2008R2'
          'http://download.microsoft.com/download/D/1/8/D1869DEC-2638-4854-81B7-0F37455F35EA/SQLEXPR32_x86_ENU.exe'
        when '2012'
          'http://download.microsoft.com/download/8/D/D/8DD7BDBA-CEF7-4D8E-8C16-D9F69527F909/ENU/x86/SQLEXPR_x86_ENU.exe'
        end
      end
    end

it seems that it gets the install media from

http://download.microsoft.com/download/8/D/D/8DD7BDBA-CEF7-4D8E-8C16-D9F69527F909/ENU/x64/SQLEXPR_x64_ENU.exe

When I look on MSDN (which we have access to) I don't see that the Enterprise Edition is available to download as a .EXE, only as an .ISO.
How can I alter this cookbook to deploy from an ISO instead of a EXE, assuming that I have full access to the ISO?

A: Re-write second half of the server.rb
Download the ISO from repo
remote_file 'C:\LocalPath' do
  source
end

Mount the ISO (you can also use Chef built-in mount resource)
powershell_script 'mount_it' do
  code <<-EOH
    Mount-DiskImage -ImagePath "C:\PATH\TO\ISO\FILE"
  EOH
end

Use MixLib::ShellOut and get the Drive name (if you don't have it hardcoded mount with a drive letter), replace the part ##### with the volume name.
output = Mixlib::ShellOut.new('(gwmi -Class Win32_LogicalDisk | Where-Object {$_.VolumeName -eq "#####"}).DeviceID')
drive_name = output.run_command.stdout

Once you know the drive the ISO mounts on, then you will be able to find the local path to the installation .EXE file.
Install using windows_package or powershell_script block

A: Quoting the attributes file from your link

# Set these to specify the URL, checksum, and package name. Otherwise, the cookbook will
# use default values based on the value of node['sql_server']['version'] and the
# server architecture (x86 or x64).

default['sql_server']['server']['url'] = nil
default['sql_server']['server']['checksum'] = nil
default['sql_server']['server']['package_name'] = nil

So you just have to set those values to a local package (on a internal http server for example) in a wrapper cookbook for this cookbook to install the enterprise version.


text:
Q: With multiple background images defined in a CSS class; Do browsers download them all? body {
   background: url(image.png);
   background: -moz-linear-gradient(top, rgba(169,3,41,1) 0%, rgba(143,2,34,1) 44%, rgba(109,0,25,1) 100%);
}

I know the gradient will be shown and the .png overridden if I use Firefox. But will the browser still download the .png? What about other browsers, their vendor prefixes and behavior?

A: This really depends on what browser you're using. For the most part, up to date browsers, such as chrome, don't download the files until they've read all the CSS statements I believe. Because you stated two background "images", it's not actually going to download the PNG because the statement is overwritten.
However, I would advise against this, because there are still a lot of users out there using old versions of browsers, and I can't guarantee how those browsers will act in this situation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Showing that a function in a compact metric space $X$ has a unique fixed point. I am trying to prove the following result:
Let $(X,d)$ be a compact metric space, and suppose that $f:X\to X$ satisfies:
$$ d(f(x),f(y))<d(x,y)\,,\forall x,y\in X\,... (1)$$
Then, there is a unique $x^* \in X$ such that $f(x^*)=x^*$.
I am aware there are a couple proofs in here, but I tried a different approach, namely: a direct proof. And I would like some feedback about it.
Proof:
Let $x_{0}\in X$ arbitrary but fixed. Let us define the sequence $(x_{k})_{k=0}^{\infty}$ by
$$
x_{k}:=\begin{cases}x_{0}&\text{ if } k=0\\ f(x_{k-1})&\text{ if } k\geq1 \end{cases}
$$
That is: we are defining recursively the compostion of $f\circ f$.
Now, since $X$ is compact, there is a subsequence $(y_{l})_{l=0}^{\infty}:=(x_{k_{l}})_{l=0}^{\infty}$ of $(x_{k})_{k=0}^{\infty}$ such that:
$$
\lim_{l\to\infty}y_{l}\to y^*
$$
We claim that $y^*$ is a fixed point for the sequence $y_{l}$
This is because:
$$
f(y^*)=f(\lim_{l\to\infty}{y_{l}})=\lim_{l\to\infty}f(y_{l})=\lim_{l\to\infty}y_{l+1}=y^*
$$
Where the last two equalities are because:

*

*f is continuous (because $(1)$)

*The tail of the sequence has the same limit.

Now, we claim that $x^*:=y^*$ is a fixed point for $(x_{k})_{k=0}^{\infty}$.
Let $(z_{k})_{k=0}^{\infty}$ be defined as follows:
$$
z_{k}:=d(x_{k},x^*)
$$
Observe that, $d(x_{k},x^*)\geq d(x_{k+1},x^*)\geq0$ applying the function $f$ and $(1)$.
Then, $(z_{k})_{k=1}^{\infty}$ is a decreasing and bounded by $0$ sequence. Thus it converges to $0$. (I think this step requires a deeper treatment).
Then $x_{k}\to x^*$ and similarly to the sequence $y_{l}$ we show that $x^*$ is a fixed point for $f$.
To show that $x^*$ is unique, suppose that $w^*$ is a different fixed point for $f$. Then, since $w^*\neq x^*$:
$$
0\leq d(x^*,w^*)<d(x^*,w^*)
$$
But that is a contradiction. Then $x^*=w^*$.
$\square$

A: If $X\ne\emptyset$ there obviously cannot exist a function satisfying the hypothesis (considering $x=y$ leads to $0<0$). Hence strictly speaking the result is true, but only vacuously; it's also true that if $f$ is as above then I am the king of France.
A less silly version:

Exercise. If $(X,d)$ is a compact metric space and $f:X\to X$ is such that $d(f(x),f(y))<d(x,y)$ whenever $x\ne y$ then $f$ has a unique fixed point.

Proof. Define $D(x)=d(x, f(x))$. Since $D$ is continuous there exists $x_0$ with $D(x_0)\le D(x)$ for all $x$. Hence $f(x_0)=x_0$, because if not then $$D(f(x_0))=d(f(x_0),f(f(x_0))<d(x_0,f(x_0))=D(x_0).$$Uniqueness is still trivial.


text:
Q: Team Foundation Server Build Agent missing some capabilities - how to add? I have TFS2018 with VS2019 installed on my Build Server.  I have just added a default build agent but am getting a missing capabilities error when trying to queue a new build.
Checking the capabilities tab on the agent, I can see I am missing the VisualStudio capability.  The build one also references appears to be there (points to msbuild 14).
Can anyone tell me what the capabilities (and paths) should be for visual studio 2019.   I assume one is called VisualStudio and should point to a directory somewhere.  I also understand there should be one called VisualStudo_16 or something like that.
Regards

A: Please double check and make sure you have indeed installed the VS2019 on your build server.
Then try to restart the agent services (run services.msc to open the services console ), basically it will scan and identify the capabilities again.
If that still not work, then you can try to add user-defined capabilities manually:
Navigate to the Agent Pool and select the specific agent  (http://server:8080/tfs/DefaultCollection/_admin/_AgentPool) -> Capabilities -> Add Capability -> Add the following VS 2019 capabilities (community version for example):


text:
Q: Convergence and summation of power towers or Ackermann functions I deleted this at StackExchange as it seems advanced or not very relevant for there and I want to ask here.
Let z be a complex number, $Im(z)\neq 0$ or $Re(z)<4$, m be a natural number, let $f(z,m)$ be defined recursively;
$f(z, 0) = z$
$f(z, 1) = z^{z/2}$
$f(z,2)=\left(z^{z/2}\right)^{\frac{z^{z/2}}{2}}$
and so on,
$$f(z,n)=f(z,n-1)^{f(z,n-1)/2}$$
with
$$g(z,m)=\prod _{n=0}^m \left(1-f\left(\sqrt{z},n\right)\right)$$
then,
$$\sum _{m=0}^{\infty} f\left(\sqrt{z},m\right)g(z,m)=1-z-\sum _{m=0}^{\infty}(f\left(\sqrt{z},m+1\right)){}^{2}g(z,m)$$
with the first three terms of the sum on the left given by
$\left(1-\sqrt{z}\right) \sqrt{z}+\left(1-\sqrt{z}\right) z^{\frac{\sqrt{z}}{4}} \left(1-z^{\frac{\sqrt{z}}{4}}\right)+\left(1-\sqrt{z}\right) \left(z^{\frac{\sqrt{z}}
{4}}\right)^{\frac{z^{\frac{\sqrt{z}}{4}}}{2}} \left(1-z^{\frac{\sqrt{z}}{4}}\right) \left(1-\left(z^{\frac{\sqrt{z}}{4}}\right)^{\frac{z^{\frac{\sqrt{z}}{4}}}{2}}\right) etc$
and the values at zero by taking the appropriate limit of each term.
What are the usual/standard ways to approach a problem of this kind? Is there a known method to establish it?
What is known about the convergence of such series?
Is there any immediate way to prove, or analytically establish the convergence of either identity?


text:
Q: Need to use a nested cursor and getting "invalid object name" First, let me state right off that I'm well aware that cursors are generally evil and shouldn't be used - I'm all about using sets, but just couldn't come up with a set-based solution to this particular problem.  If you tell me to go do some set-based operations, well, I'm all for it, if you can tell me how you'd code this particular problem.
Basically, I've got a number of stock items for which I need to make purchases.  I want to make purchases based upon the cheapest available price, where I know the suppliers' prices and their stock levels.  There's also a pack-size issue in here, wherein I want to buy by pack-size if possible.
I've already pulled a list of the things I need to purchase into #needorders, and suppliers' stock levels and prices into #orderedprices.  Below I'm iterating through cursor CUR_NEEDED and creating a secondary cursor CUR_AVAILABLE:
    DECLARE CUR_NEEDED CURSOR LOCAL SCROLL_LOCKS
FOR
SELECT        GoodID
        , ConditionID
        , QuantityToShip
        , OrderStatusID
        , RetailerID
        , PackSize
FROM        #needorders
ORDER BY      GoodID
        , ConditionID
        , PurchaseDate DESC
FOR UPDATE

OPEN CUR_NEEDED
FETCH NEXT FROM CUR_NEEDED INTO @GoodID, @ConditionID, @QuantityToShip, @OrderStatusID, @RetailerID, @PackSize

WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE CUR_AVAILABLE CURSOR LOCAL SCROLL_LOCKS
        FOR
        SELECT        SupplierStocklistItemID
                , SupplierID
                , StockLevel
                , SupplierCurrencyID
                , CostPrice
        FROM        #orderedprices
        WHERE       #orderedprices.GoodID = @GoodID
        AND     #orderedprices.ConditionID = @ConditionID
        AND     #orderedprices.StockLevel > 0
        ORDER BY    #orderedprices.PriceRank
        FOR UPDATE

        OPEN CUR_AVAILABLE
        FETCH NEXT FROM CUR_AVAILABLE INTO @SupplierStocklistItemID, @SupplierID, @StockLevel, @SupplierCurrencyID, @CostPrice

        WHILE @@FETCH_STATUS = 0
            BEGIN
                /*
                Buy as many @PackSize as we need to cover how many we require, unless the supplier
                only has a certain number, in which case buy that number.
                E.g., need 14, pack size 5, 2 suppliers
                Supplier A has 11
                Supplier B has 40
                Buy 9 from Supplier A, with our remaining need being 3.
                Buy 5 from supplier B, with our remaining need being -2
                */
                --feed rows into #supplierpurchasesbase while @StockLevel > 0

                --Figure out how many we need to buy, based upon PackSize
                IF @QuantityToShip % @PackSize > 0
                    BEGIN
                        SET @Buy = @QuantityToShip - @QuantityToShip % @PackSize + @PackSize
                    END
                ELSE
                    BEGIN
                        SET @Buy = @QuantityToShip
                    END

                IF @StockLevel < @Buy
                    BEGIN
                        --PRINT 'Supplier only has ' + CAST(@StockLevel AS VARCHAR) + ' for us to buy.'
                        SET @Buy = @StockLevel
                    END

                INSERT INTO #supplierpurchasesbase (
                      GoodID
                    , ConditionID
                    , SupplierStocklistItemID
                    , Quantity
                    , SupplierID
                    , SupplierCurrencyID
                    , CostPrice
                    , RetailerID )
                SELECT    @GoodID
                    , @ConditionID
                    , @SupplierStocklistItemID
                    , @Buy
                    , @SupplierID
                    , @SupplierCurrencyID
                    , @CostPrice
                    , @RetailerID

                --update @QuantityToShip & the row in CUR_AVAILABLE
                IF @StockLevel <= @Buy
                    BEGIN
                        UPDATE  CUR_AVAILABLE
                        SET StockLevel = @StockLevel - @Buy
                        WHERE   CURRENT OF CUR_AVAILABLE

                        SET @QuantityToShip = 0
                    END
                ELSE
                    BEGIN
                        UPDATE  CUR_AVAILABLE
                        SET StockLevel = 0
                        WHERE   CURRENT OF CUR_AVAILABLE

                        SET @QuantityToShip = @QuantityToShip - @Buy
                    END

                --update the stocklevel so we don't see the thing again if we've used it up.

                IF @QuantityToShip = 0  --Don't need any more
                    BEGIN
                        UPDATE  CUR_NEEDED
                        SET OrderStatusID = @StatusPendingPO
                        WHERE   CURRENT OF CUR_NEEDED

                        BREAK
                    END
                ELSE    --Need more, move next, if we can
                    FETCH NEXT FROM CUR_AVAILABLE INTO @SupplierStocklistItemID, @SupplierID, @StockLevel, @SupplierCurrencyID, @CostPrice
            END
        CLOSE       CUR_AVAILABLE
        DEALLOCATE  CUR_AVAILABLE

        FETCH NEXT FROM CUR_NEEDED INTO @GoodID, @ConditionID, @QuantityToShip, @OrderStatusID, @RetailerID, @PackSize
    END
CLOSE       CUR_NEEDED
DEALLOCATE  CUR_NEEDED

The problem I'm running into is that I get I'm getting the error

Invalid object name 'CUR_AVAILABLE'.

when I'm attempting to update CURRENT OF CUR_AVAILABLE.
I've tried defining the CUR_AVAILABLE cursor as @CUR_AVAILABLE but get a different error.  I've tried defining the CUR_AVAILABLE cursor outside of the WHILE loop of CUR_NEEDED, I've tried not closing / deallocating the cursor, etc.  None of this seems to work.
Any ideas where I'm going wrong, here (other than not using sets, unless you've got a set-based solution)?

A: The following query uses a recursive CTE and, therefore, can't be considered a truly set-based solution. Nevertheless, I would still expect it to perform better than your two cursors (or to be worth trying, at the very least):
WITH buys (
  GoodID,
  ConditionID,
  SupplierStocklistItemID,
  Quantity,
  SupplierID,
  SupplierCurrencyID,
  CostPrice,
  RetailerID,
  PriceRank,
  RemainingNeed,
  PackSize
)
AS (
  SELECT
    GoodID,
    ConditionID,
    SupplierStocklistItemID = 0,
    Quantity                = 0,
    SupplierID              = 0,
    SupplierCurrencyID      = 0,
    CostPrice               = CAST(0.00 AS decimal(10,2)),
    RetailerID,
    PriceRank               = 0,
    RemainingNeed           = QuantityToShip,
    PackSize
  FROM #needorders
  UNION ALL
  SELECT
    p.GoodID,
    p.ConditionID,
    p.SupplierStockListItemID,
    Quantity = y.CurrentBuy,
    p.SupplierID,
    p.SupplierCurrencyID,
    p.CostPrice,
    b.RetailerID,
    p.PriceRank,
    RemainingNeed = b.RemainingNeed - y.CurrentBuy,
    b.PackSize
  FROM #orderedprices p
  INNER JOIN buys b ON p.GoodID = b.GoodID
    AND p.ConditionID = b.ConditionID
    AND p.PriceRank = b.PriceRank + 1
  CROSS APPLY (
    SELECT RemainingNeedAdjusted =
      (b.RemainingNeed + b.PackSize - 1) / b.PackSize * b.PackSize
  ) x
  CROSS APPLY (
    SELECT CurrentBuy = CASE
      WHEN x.RemainingNeedAdjusted > p.StockLevel
      THEN p.StockLevel
      ELSE x.RemainingNeedAdjusted
    END
  ) y
  WHERE p.StockLevel > 0
    AND b.RemainingNeed > 0
)
SELECT
  GoodID,
  ConditionID,
  SupplierStocklistItemID,
  Quantity,
  SupplierID,
  SupplierCurrencyID,
  CostPrice,
  RetailerID
FROM buys
WHERE PriceRank > 0
ORDER BY
  GoodID,
  ConditionID,
  PriceRank

Basically, the CTE forms the rows almost identical to those your query is inserting into #supplierpurchasesbase, except it additionally features auxiliary columns serving as kind of internal variables. (They are not pulled by the final SELECT, though.)
The anchor part forms a set of 0-quantity records based on the #needordered table, together with the initial values for the auxiliary columns. The recursive part contains all the logic: calculates the quantity to buy, updates the "remaining need" quantity for the next iteration, checks whether the next iteration is needed.
Certain assumptions have been made, and I hope you'll be able find your way around them if they do not match your real situation. For instance, quantities, pack sizes are assumed to be integer, and part of the logic relies on that, because it uses integral division. It is also assumed that PriceRank is a sequence of integers starting from 1, unique per (GoodID, ConditionID).
This script, as well as a minimal test setup, can be found, tested, modified, and tested on SQL Fiddle.

A: The problem was twofold: The update syntax should not be:
UPDATE  CUR_AVAILABLE
SET StockLevel = @StockLevel - @Buy
WHERE   CURRENT OF CUR_AVAILABLE

Rather, the syntax should be:
UPDATE  #orderedprices
SET StockLevel = @StockLevel - @Buy
WHERE   CURRENT OF CUR_AVAILABLE

Also, in order to be updatable, the temp table needed to have a primary key:
ALTER TABLE #orderedprices ADD CONSTRAINT PRIMARY KEY CLUSTERED (RowCtr)

Lesson learned, I guess, but it certainly took me a fair bit of grief to find the solution!


text:
Q: Laplace's equation in the first quadrant I am trying to find a non-constant harmonic function $\phi$ on $Q = \{z \mid \mathfrak{R}(z), \mathfrak{I}(z) > 0\}$, (i.e. the first quadrant) such that $\phi$ extends continuously to $\overline{Q} \setminus \{0\}$ with constant values on each the components of $\partial Q - \{0\}$ ($\phi$ need not be continuous at the origin). My method for doing this is to solve Laplace's equation in the strip $S = \{0 < \mathfrak{I}(z) < 1\}$ subject to appropriate boundary conditions, then carrying the solution forward under the conformal map $f(z) = e^{\pi z/2}$ which is a conformal equivalence between $S$ and $Q$ (I'm doing it this way because in an earlier part of the problem they ask us to find $f$).
Solving $\Delta u = 0$ on $S$ in general seems straightforward enough. Assume $u(x,y) = \alpha(x)\beta(y)$ then we get $\alpha''(x) = \lambda \alpha(x)$ and $\beta''(y) = -\lambda \beta(y)$ by simple algebra. This gives $\alpha(x) = Ae^{\sqrt \lambda x} + Be^{-\sqrt \lambda x}$ and $\beta(y) = Ce^{-\sqrt \lambda y} + De^{-i\sqrt \lambda y}$. Then we allow $u$ in general to be any linear combination of these solutions. My issue here is that I'm not sure how to carry the boundary conditions in $Q$ to boundary conditions on $S$. Intuitively it seems that it should just that $u$ must be constant on $\mathfrak{I}(z) = 0$ and $\mathfrak{I}(z) = 1$, but this forces $\alpha(x) = 0$ which gives $u = 0$, clearly not the desired result.My question is, how can I carry the boundary conditions over carefully (in general or in this case - I can probably figure out the general case if someone can work out this example)?

A: Your approach is too complicated. The principal value of the argument $\arg(z)$ is harmonic in the first quadrant  as the imaginary part of the complex logarithm, with constant values on both the positive real axis and positive imaginary axis.
Therefore an affine transform
$$
\phi (z) = a \arg(z) + b
$$
is the solution to your problem.
(The corresponding harmonic functions on the strip $S$ are of the form $u(z)= a' \operatorname{Im}(z) + b'$. )


text:
Q: Prove that $\frac{d^2x}{dt^2}=f(x, \frac{dx}{dt})$ can be written in the form $\frac{dv}{dx}=\frac{f(x,v)}{v}$: Prove that $\frac{d^2x}{dt^2}=f(x, \frac{dx}{dt})$ can be written in the form:
$\frac{dv}{dx}=\frac{f(x,v)}{v}$ where $v = \frac{dx}{dt}$
Any help would be greatly appreciated!

A: Hint: When $\frac{dx}{dt}(t_0)\neq 0$ then you may perform a change of variables so that $x$ becomes the variable (by the inverse function theorem).


text:
Q: Error al abrir una web desde google Chrome/Edge, pero si abre en IExplorer. ( window.parent.frames is not a function) cordial saludo. me podrian ayudar con el error que me sale Uncaught TypeError: window.parent.frames is not a function al intentar abrir un aplicativo web en Google Chrome/Edge. Este sitio si abre de forma correcta en IExplorer. donde quiero cargar una seccion html la referencia con href, pero donde requiero cargar un pdf me sale error. En internet explorer todo carga de forma correcta. De antemano gracias por sus aportes.

A: Solucionado.
Para mi caso solo tenia que cambiar ("") por [""].
window.parent.frames[""].location.replace(""). De esta forma funciona correctamente en Google y Edge. Tambien deberia servir para google  Mozilla.
Slds.


text:
Q: Deploying application with .NET framework without admin privileges Disclaimer: If this question does not belong on SO, please leave a hint where to move it.
Hello everyone,
the company I work for has developed an application that has accumulated a bunch of dependencies over time:

*

*.NET 3.5 with updates

*.NET 4.0 with updates

*VC++ Redist 2010

*VC++ Redist 2013

*VC++ Redist 2015

*Our proprietary device driver

Everything was then packaged into an Inno Setup executable and distributed to the clients. Recently, the need for an auto-update mechanism has been pointed out, which causes us to run into privilege problems. Here are some of the product demands I need to meet (and cannot figure out how):

*

*Installer (and product) must support legacy hardware and software (read as Windows XP and later)

*The installation (including auto update installations) may require an admin login exactly once (during first installation). This means that the auto-update installer must be able to run silently under a non-admin account.

*The installer should install to the {commonappdata} folder (locked) and the end application should behave the same

*The dependencies must be included in the application installer. They do not need to be included in the auto-update installers.

This may seem trivial at first glance, but every combination I try, I run into the "access denied" message either during installation or at update time. Does anyone know of a reliable way to do this?

A: You cannot update an application installed to Administrator-only folder without Administrator privileges.
The only way to implement an auto update of such application is to implement, what Windows Update, Mozilla Maintenance Service, Google Chrome Elevation Service, Adobe Acrobat Update Service and similar services do:

*

*On the first installation with Administrator privileges, install a service with Administrator privileges.

*Either have the service itself check regularly for updates and start the auto update;

*Or if you need to trigger the update otherwise, implement an API for the service that someone (e.g. the application itself running without Administrator privileges) can call to trigger the auto update.

Installing a service with Administrator privileges to a client system is a huge breach. So if you decide to do that, make sure you do it 200% right, not to introduce security holes into the client's system.

Related questions:

*

*Choose right Windows directory to install software and allow auto-updates

*How to automatically update an application installed with Inno Setup


text:
Q: Why does appending to a python list set its type to None I've looked through the rest of Stack Exchange and found questions that are similar, but not the same as mine and not helped.
My code is as follows:
class star:
    def __init__(self):
        # irrelevant other variables
        self.planets = []

    def genPlanets(self):
        self.planets.append(random.uniform(self.frostLine*0.98, self.frostLine*1.02))
        print ("There is a planet at " + str(self.planets[0]) + " AU away from the star.")

This part of the code outputs the following to the console:

[]
There is a planet at 2.916687900748318 AU away from the star.

However, in the next part of the code:
def genPlanets:
    # irrelevant, working code.

    planetSort = planets.sort()
    for p in planetSort:
        file.write("There is a planet at " + str(p) + " AU away from the star.")

It outputs:

Traceback (most recent call last):
File "C:\Users\Dominic\Documents\Coding\The Galaxy Maker\MAin.py", line 145, in
Star.outerHabitable, Star.innerPlanetary, Star.outerPlanetary, Star.frostLine, Star.planets)
File "C:\Users\Dominic\Documents\Coding\The Galaxy Maker\MAin.py", line 125, in writeData
for p in planetSort:
TypeError: 'NoneType' object is not iterable

I do not understand how this has happened and I don't see why the append function would return a None type! Please help!

A: Try this:
def genPlanets:
    # irrelevant, working code.

    planets.sort()
    for p in planets:
        file.write("There is a planet at " + str(p) + " AU away from the star.")

The .sort() method transforms the object you apply it to instead of returning the sorted list.

A:
def genPlanets:
      # irrelevant, working code.
planetSort = planets.sort()
for p in planetSort:
    file.write("There is a planet at " + str(p) + " AU away from the star."

Here, planetSort was nothing because you didn't specify values to planets for sorting, hence the error showed it was 'NoneType'.

A: list.sort() sorts the list in-place and returns None, while list.sorted() does what you expected.
Either call sort() and use the original, now sorted list:
planets.sort()
for p in planets:
    ...

Or use the sorted() function instead:
planetSort = planets.sorted()
for p in planetSort:
    ...


text:
Q: how to make Google Mapview change to fullscreen from a smaller mapview? I have a Google mapview in the corner of the screen. I want to add an event that makes it go fullscreen with a button on the map interface, and then small screen again with the same button. Any ideas??
Android v4.0.4
Google Map API V2

A: You could do this by 2 way:

*

*create a new Activity that on the press of a button will start of and will include a full screen map. in this activity create the same button that will bring you back to your original Activity.

*you can programaticly change the Layout width a length of you MapFragment in the same window.
second option will be better as you would avoid the screen flickering of new activity loading.
UPDATE:
regarding the second option here is a code i wrote to enlarge map onClick of the map see if this helps you:
 @Override
 public void onMapClick(LatLng point)
{
    LinearLayout mapFrameLayout = (LinearLayout)findViewById(R.id.mapFrameLayout);

    if (!isMapOpen)
    {
        LinearLayout.LayoutParams fullMapParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        if (!isDetailsOpen)
        {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.hide(closedDetailsFragment).commit();
            mapFrameLayout.setLayoutParams(fullMapParams);
            isMapOpen = true;
            isDetailsOpenWhenOpenedMap = false;
        }
        else
        {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.hide(openedDetailsFragment).commit();
            mapFrameLayout.setLayoutParams(fullMapParams);
            isMapOpen = true;
            isDetailsOpenWhenOpenedMap = true;
        }
    }
    else
    {
        LinearLayout.LayoutParams defaultMapparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 280);
        mapFrameLayout.setLayoutParams(defaultMapparams);
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (isDetailsOpenWhenOpenedMap)
        {
            fragmentTransaction.show(openedDetailsFragment).commit();
        }
        else
        {
            fragmentTransaction.show(closedDetailsFragment).commit();
        }
        isMapOpen = false;
    }
}

as you see i change the size of the FrameLayout where the map sits, you can put in the same layout your button and place it on the right|top corner for example. when your map will stretch the button will still be at the same right|top corner.

A: Start new activity on click with full screen map and all buttons/functions u need there.. Pass requered parameters using putExtra on starting intenet (location coordinates for example) and voila.. ;)


text:
Q: Android setting one end folded corner i have taken a layout like this having the designed background image

i need a suggestion which is the best approach either using background image or rounded corner at one end XML
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:layout_weight="1"
    android:background="@drawable/test_back"
    android:padding="10dp">

   <TextView
       android:id="@+id/textView2"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="TextView" />
</LinearLayout>

A: Here i have attached some links, Please go through it, If you have any doubt let me know.
If you want to add rounded corner to any kind of android view like linear layout, relative layout, button etc., follow the below links which i have attached.
keep this drawable as background for the view to which you want to keep rounded corner border. Let's keep it for a LinearLayout.
Rounded Corner Reference1
Rounded Corner Reference2
Rounded Corner Reference3


text:
Q: Is there an issue with putting a longer input string to a hashing algorithm than the algorithm outputs? Currently I'm designing a hashing system for user emails, but what happens if the user email is longer than the hash output. I usually use sha1 sha256 or sha512 if it makes a difference based on algorithm... It just seems like at a point the algorithm wouldn't be able to keep on producing unique outputs.

A: Hash values usually have a fixed length from 13 (DES) to 86 (SHA2) characters. It's perfectly normal if you give longer input. Think of it like a "cross sum" that you can do with arbitrary long numbers as well.
Regarding the uniqueness, using the standard crypt(3) function with SHA-512 and characters in the set a-zA-Z./ you have 54 different characters and a 86 character long string so 54^86 different values. That's a lot :-)
(Don't use the 13 char long DES crypt though, that's bruteforceable with modern hardware and always use "salt" values so that the same input string gives different hash values and you can't use a "rainbow table" attack).


text:
Q: Apache CloudStack: No templates showing when adding instance I have setup the apache cloudstack on CentOS 6.8 machine following quick installation guide. The management server and KVM are setup on the same machine. The management server is running without problems. I was able to add zone, pod, cluster, primary and secondary storage from the web interface. But when I tried to add an instance it is not showing any templates in the second stage as you can see in the screenshot

However, I am able to see two templates under Templates link in web UI.

But when I select the template and navigate to Zone tab, I see Timeout waiting for response from storage host and Ready field shows no.

When I check the management server logs, it seems there is an error when cloudstack tries to mount secondary storage for use. The below segment from cloudstack-management.log file describes this error.
    2017-03-09 23:26:43,207 DEBUG [c.c.a.t.Request] (AgentManager-Handler-
14:null) (logid:) Seq 2-7686800138991304712: Processing:  { Ans: , MgmtId:
279278805450918, via: 2, Ver: v1, Flags: 10, [{"com.cloud.agent.api.Answer":
{"result":false,"details":"com.cloud.utils.exception.CloudRuntimeException:
GetRootDir for nfs://172.16.10.2/export/secondary failed due to
com.cloud.utils.exception.CloudRuntimeException: Unable to mount
172.16.10.2:/export/secondary at /mnt/SecStorage/6e26529d-c659-3053-8acb-
817a77b6cfc6 due to mount.nfs: Connection timed out\n\tat
org.apache.cloudstack.storage.resource.NfsSecondaryStorageResource.getRootDir(Nf
sSecondaryStorageResource.java:2080)\n\tat
org.apache.cloudstack.storage.resource.NfsSecondaryStorageResource.execute(NfsSe
condaryStorageResource.java:1829)\n\tat
org.apache.cloudstack.storage.resource.NfsSecondaryStorageResource.executeReques
t(NfsSecondaryStorageResource.java:265)\n\tat
com.cloud.agent.Agent.processRequest(Agent.java:525)\n\tat
com.cloud.agent.Agent$AgentRequestHandler.doTask(Agent.java:833)\n\tat
com.cloud.utils.nio.Task.call(Task.java:83)\n\tat
com.cloud.utils.nio.Task.call(Task.java:29)\n\tat
java.util.concurrent.FutureTask.run(FutureTask.java:262)\n\tat
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)\
n\tat
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)\
n\tat java.lang.Thread.run(Thread.java:745)\n","wait":0}}] }

Can anyone please guide me how to resolve this issue? I have been trying to figure it out for some hours now and don't know how to proceed further.
Edit 1: Please note that my LAN address was 10.103.72.50 which I assume is not /24 address. I tried to give CentOs a static IP by making the following settings in ifcg-eth0 file
DEVICE=eth0
HWADDR=52:54:00:B9:A6:C0
NM_CONTROLLED=no
ONBOOT=yes
BOOTPROTO=none
IPADDR=172.16.10.2
NETMASK=255.255.255.0
GATEWAY=172.16.10.1
DNS1=8.8.8.8
DNS2=8.8.4.4

But doing this would stop my internet. As a workaround, I reverted these changes and installed all the packages first. Then I changed the IP to static by the same configuration settings as above and ran the cloudstack management. Everything worked fine untill I bumped into this template thing. Please help me figure out what might have went wrong

A: I know I'm late, but for people trying out in the future, here it goes:
I hope you have successfully added a host as mentioned in Quick Install Guide before you changed your IP to static as it autoconfigures VLANs for different traffic and creates two bridges - generally with names 'cloud' or 'cloudbr'. Cloudstack uses the Secondary Storage System VM for doing all the storage-related operations in each Zone and Cluster. What seems to be the problem is that secondary storage system vm (SSVM) is not able to communicate with the management server at port 8250. If not, try manually mounting the NFS server's mount points in the SSVM shell. You can ssh into the SSVM using the below command:
ssh -i  /var/cloudstack/management/.ssh/id_rsa  -p 3922 root@<Private or Link local Ip address of SSVM>

I suggest you run the /usr/local/cloud/systemvm/ssvm-check.sh after doing ssh into the secondary storage system VM (assuming it is running) and has it's private, public and link local IP address. If that doesn't help you much, take a look at the secondary storage troubleshooting docs at Cloudstack.
I would further recommend, if anyone in future runs into similar issues, check if the SSVM is running and is in "Up" state in the System VMs section of Infrastructure tab and that you are able to open up a console session of it from the browser. If that is working go on to run the ssvm-check.sh script mentioned above which systematically checks each and every point of operation that SSVM executes. Even if console session cannot be opened up, you can still ssh using the link local IP address of SSVM which can be accessed by opening up details of SSVM and than execute the script. If it says, it cannot communicate with Management Server at port 8250, I recommend you check the iptables rules of management server and make sure all traffic is allowed at port 8250. A custom command to check the same is nc -v <mngmnt-server-ip> 8250. You can do a simple search and learn how to add port 8250 in your iptables rules if that is not opened. Next, you mentioned you used CentOS 6.8, so it probably uses older versions of nfs, so execute exportfs -a in your NFS server to make sure all the NFS shares are properly exported and there are no errors. I would recommend that you wait for the downloading status of CentOS 5.5 no GUI kvm template to be complete and its Ready status shown as 'Yes' before you start importing your own templates and ISOs to execute on VMs. Finally, if your ssvm-check.sh script shows everything is good and the download still does not start, you can run the command: service cloud restart and actually check if the service has gotten a PID using service cloud status as the older versions of system vm templates sometimes need us to manually start the cloud service using service cloud start even after the restart command. Restarting the cloud service in SSVM triggers the restart of downloading of all remaining templates and ISOs. Side note: the system VMs uses a Debian kernel if you want to do some more troubleshooting. Hope this helps.


text:
Q: Anonymous event handlers and disposing I have a rather short question about anonymous event handlers:
This is the code that I have:
public void AddTestControl(Control ctrl)
{
    ctrl.Disposed += (o, e) => { RemoveTestControl(ctrl); };
    ctrl.SomeEvent += _Control_SomeEvent;
}

public void RemoveTestControl(Control ctrl)
{
    ctrl.SomeEvent -= _Control_SomeEvent;
}

Is this code above fine, or should the code be rewritten in order to remove the Disposed Event Handler?
Something like this:
public void AddTestControl(Control ctrl)
{
    ctrl.Disposed += _Control_Disposed;
    ctrl.SomeEvent += _Control_SomeEvent;
}

public void RemoveTestControl(Control ctrl)
{
    ctrl.Disposed -= _Control_Disposed;
    ctrl.SomeEvent -= _Control_SomeEvent;
}

A: Generally, the only situation where you need to remove the event handlers from an object in order for it to be eligible for garbage collection is when the publisher object (the one defining the event) lives longer than the subscriber object (the one containing the event handlers). In such a situation the GC won't be able to release the subscriber when it goes out of scope since it's still being referenced by the publisher.
In this case, assuming this is WebForms or WinForms, the publisher (that is the Control object), is most likely a child object of the subscriber (probably a Page or a Form), which will be the first to go out of scope taking all its associated objects with it. Hence there's no need to remove the event handlers.

A: It always feels cleaner to me to unsubscribe from events, even in situations where I know the subscribers always outlive the publisher (the object raising the event): the event will never be raised again, the publisher is no longer reachable and can be collected.
Then again, how many people go to the trouble of unsubscribing every event handler in e.g. a WinForms application? The object references point from the publisher to the subscribers, not the other way around, so the publisher can be collected while the subscribers live on. It doesn't present the same danger as the opposite situation, where a long-lived publisher (e.g. a static event) can wastefully keep potentially large subscribers alive long after they could have been collected.
If you want/need to unsubscribe, then the requirement to unsubscribe the same delegate makes anonymous event handlers a bit of a pain. The Reactive Extensions solve this problem in a neat way: rather than having to remember the delegate you subscribed, subscribing returns an IDisposable which unsubscribes when disposed. Chucking all your subscriptions into a CompositeDisposable lets you unsubscribe everything with just one Dispose call.

A: Both codez are fine, but I like second as a matter of personal preference. It reads clearer than the first.
On top of it with the first code, there's anonymous lambda delegate and it gets a current reference to ctrl. That code may behave unexpectedly depending on situation and compile optimisation settings: whether or not the call is inlined or not.
Not to mention that there's architectural problem with the code: you have ControlOwner and a bunch of Child Controls. I take it you're adding child controls to ControlOwner at runtime, and then trying to react to their behavivour by subscribing ControlOwner to the childControl events. This is fine for events like _ButtonClicked etc. But not good for Dispose. Let the child control handle it's disposing on itself, the OwnerControl doesn't need to know about it. Not to mention that it may not exist at a time ChildControl[n].Dispose is called.
In short:
    * it is better to leave dispose event on ChildControl alone and do all clean up in ChildControl.Dispose
    * it is not necessary to unsubscribe from events. Event dispatcher will check if subscriber is alive.


text:
Q: Stored User Names and Passwords I'm writing an application which needs to store login data for multiple (XMPP) accounts on Windows.
Currently the application stores them in Windows' "Stored User Names and Passwords" using CredRead and CredWrite. And here is the problem: The login name for an XMPP account cannot be changed (it's the account's JID), but Windows only stores user name/password pairs under a given target name. I use something like "xmpp:account@server.tld" for the target name and don't use the user name at all during login. The user can't even set the user name from within the application (it will be set to "account@server.tld" automatically instead).
Now I would like to prevent the user name to be changed to something different by the user (using control panel or rundll32.exe keymgr.dll, KRShowKeyMgr) or an other application as this is currently possible and somehow confusing because the actual value is ignored anyway. If I open up the "Stored User Names and Passwords" dialog (using rundll32.exe keymgr.dll, KRShowKeyMgr), the entries which are created by my application are listed as "xmpp:account@server.tld (LegacyGeneric)" and can be edited using the "Edit..." button.
The list contains also an entry for Windows Live (listed as "live_account@hotmail.com (WindowsLive)"), whose user name cannot be changed (trying so will bring up a message box saying: "Windows cannot save the logon information. Make sure the information is correct and that all required fields are completed.".
And here is (finally) my question: Can I get this behavior for my application as well? How can I change the credential type to something different than "LegcyGeneric"? Or is there a better way to store only the password for a given login name (maybe using Windows Data Protection), while still using some "standard" Windows way of storing them?
Any hints and answers are appreciated.


text:
Q: Doing in line editing in VSCode using the Keyboard Only? In VSCode we can create multiple cursors inside a single word or sentence by select alt or option (Mac) and then clicking where we want the additional cursors.
Is there a way to use the keyboard only to create the additional cursors (Instead of having to click)?

A: I have added a few commands to the extension Select By v1.14.0 that allows to create and modify Multi Cursors with the keyboard.

*

*selectby.addNewSelection : Add a new selection at an offset (default: 1)

*selectby.moveLastSelectionActive : Modify (extend/reduce) the last selection by moving the Active position offset characters left/right (default: 1)

*selectby.moveLastSelection : Move the last selection number of characters left/right (default: 1)

*selectby.removeCursorBelow : remove the last selection

All 3 commands have 1 property, set in the args property of the key binding. If called from the Command Palette the value of offset is 1.
You can define a set of key bindings to use these commands.
By using a custom context variable (extension Extra Context v0.2.0) to set a mode, and use the when clause to determine if we use the default key binding for the arrow keys or our custom key bindings.
With the command extra-context.toggleVariable you can toggle the variable and thus the mode.
  {
    "key": "alt+F5", // or some other key combo
    "when": "editorTextFocus",
    "command": "extra-context.toggleVariable",
    "args": {"name": "multiCursorByKeyboard"}
  },
  {
    "key": "ctrl+alt+right",
    "when": "editorTextFocus && extraContext:multiCursorByKeyboard",
    "command": "selectby.addNewSelection",
    "args": {"offset": 1}
  },
  {
    "key": "shift+right",
    "when": "editorTextFocus && extraContext:multiCursorByKeyboard",
    "command": "selectby.moveLastSelectionActive",
    "args": {"offset": 1}
  },
  {
    "key": "shift+left",
    "when": "editorTextFocus && extraContext:multiCursorByKeyboard",
    "command": "selectby.moveLastSelectionActive",
    "args": {"offset": -1}
  },
  {
    "key": "right",
    "when": "editorTextFocus && extraContext:multiCursorByKeyboard",
    "command": "selectby.moveLastSelection",
    "args": {"offset": 1}
  },
  {
    "key": "left",
    "when": "editorTextFocus && extraContext:multiCursorByKeyboard",
    "command": "selectby.moveLastSelection",
    "args": {"offset": -1}
  }


text:
Q: prevent manual input on jquery-knob I am using Jquery-Knob as a control knob to choose values from an array, I use the input as the index of the array and I show other info as the label.
    $(".dial").knob({
        displayPrevious : true,
        'min':0,
        'max': this.arrayList.length -1,
        'format' : (knobText)=>{
            if( isNaN(knobText) ){
                return knobText;
            }
            return this.arrayList[knobText].name;
        },
        'change' : (knobValue)=>{
            // Get the new user index
            console.dir("currentKnobIndex: " + Math.floor(knobValue));
            this.currentKnobIndex = Math.floor(knobValue);
        }
    });

I works good except when I click on the knob label and it get focus to manually write a value. Is there a way to prevent this? The user should just be able to change the values with the mouse/touch. I tried adding "readonly" but it disables for complete the knob.

A: By adding "readonly" attribute to the input element you can prevent the editable option through the label. Check the below demo:
Demo


text:
Q: PHP extensions not loading in phpinfo So I'm running MAMP on Mountain Lion and I've installed gmagick and imagick using pecl, both are relase candidates (mainly because gmagick doesn't have a stable release and imagick 3.0.0 doesn't install, it gives a make error). The modules appear when I run php -i in the terminal but not in phpinfo(), I have checked the php.ini it is the same for both so that is not the issue.However I have installed bitset(which is a stable release) and it appears in phpinfo() and php -i. So my question is does PHP have any configuration option that does not load extensions if they are not stable? Btw, I did restart my server after the changes to the ini file.

A: You will probably now have two php installations on your machine. Mountain Lion ships with a preinstalled php version. Trylocate php.ini in Terminal to find out how many php.inis are installed.
In your phpinfo() page there is also noted which php.ini is in use. You might want to open the exact php.ini which is used for your phpinfo() and make sure the extentions are loaded.
There should be two lines like
extension=/path/to/gemagicext/gmagic.so
extension=/path/to/imagick/imagick.so

A: I faced a similar problem with php-fpm and nginx server. The problem was due to the fact that the updated php configuration was not reflected in the current active php-fpm worker processes. I have to manually kill the fpm process and restart it again to have the updated extensions info.
Steps that worked for me:
1) Look for active php-fpm process
 ps ax | grep "fpm"

mostly this will list more than one process
2) kill process manually
kill -9 [pid_got_from_previous_command]

3) restart php-fpm process
sudo service php5-fpm start

Note: Trying something like sudo service php-fpm reload or sudo service php-fpm restart didn't work since the old child processes retained the old configuration. Killing the active processes and restarting php fpm what updated the phpinfo for me.

A: I had the same problem CentOS 6.6 x64, php 5.5.27 and I followed the steps from
http://php.net/manual/en/imagick.installation.php
First of all download a tar image of the ImageMagick install from here:
sourceforge.net/projects/imagemagick/files/
Unpack it and then from terminal issue the following commands:
1.  "cd ImageMagick-6.9.1-10" - go where you placed the folder
2.  ./configure
3.  make
4.  make install
5. make check
6. install imagick extension from pecl.php.net/package/imagick/download 3.1.2
7. cd imagick-3.1.2
8. phpize
9. ./configure --with-imagick=/opt/local
10. make
11. make install
12. Copy imagick.so in your PHP extensions folder and add extension=imagick.so in php.ini

Restart apache: service httpd restart

A: I am sure this problem is related to your extension and PHP server compatibility. I encountered such problems when I created my own extensions. Your extension should compatible with your PHP server in three main attributes:
1- The Zend API number which your PHP server is configured with ( in phpinfo() you can find this number), this number should be the same with your extension header file at build time.
2- The compiler version on your PHP server and your extension must be the same.
3- Thread safety in your PHP server is important. If you use thread-safe server then your extension must be built with php thread-safe library and if you use non-thread safe server you should build your extension with PHP-nts library.


text:
Q: Why does math operation on large numbers sometimes need an intermediary variable to return a correct result? I have been using Excel 2013 here. For example,
Public Function RoundTest(ByVal flNumber As Double) As Double
  RoundTest = Round(flNumber)
End Function

Public Function Test( _
    ByVal flNumber As Double, _
    ByVal flDivisor As Double) _
    As Double

  Test = flNumber - (RoundTest(flNumber / flDivisor) * flDivisor)
End Function

Let flDivisor is passed as 10 by caller. Calling Test() with flNumber <= 10^22 yields a correct result, that is 0, but with flNumber > 10^22, Test() returns a wrong result, that is a negative number. However, if an intermediary variable is used to temporarily hold the partial result of the calculation, Test() returns a correct result, that is 0.
Public Function Test( _
    ByVal flNumber As Double, _
    ByVal flDivisor As Double) _
    As Double
  Dim flTemp As Double

  flTemp = RoundTest(flNumber / flDivisor) * flDivisor
  Test = flNumber - flTemp
End Function

Why does this happens? How can I avoid this peculiarity?

A: Here is more straightforward example:
Public Function RoundTest(ByVal flNumber As Double) As Double
    RoundTest = Round(flNumber)
End Function

Sub TestCDbl()
    Dim a As Double
    Dim b As Double
    a = 10 ^ 23
    b = 10
    w1 = a - RoundTest(a / b) * b ' -8388608
    w2 = a - Round(a / b) * b ' 0
    w3 = a - CDbl(RoundTest(a / b) * b) ' 0

End Sub

IMO intrinsic implementation of calculations works so that results of native Round() function and returned from RoundTest() function are processed in different ways. Also turns out it may process any part of expression and particularly subtrahend not as double type, and having explicit conversion to double with CDbl() might help in your case, instead of coercion by assigning to temp variable of double type.You have to bear in mind that this effort and suchlike do not guarantee to fix the issue. Each calculation can introduce floating point errors, as @Comintern commented.


text:
Q: Asynchronous Actionmailer in Rails I've noticed some of my actions (on a development environment) take a little while to load up as an email they require an email notification (through Google's servers).  Do I need to implement asynchronous handling of emails like - http://upstream-berlin.com/2008/05/19/new-rails-plugin-for-making-actionmailer-asynchronous/

A: Offloading potentially long-running tasks such as sending emails in to the background is a good idea to improve the responsiveness of your application, albeit by sacrificing the simplicity of your application a little.
One popular way to do this (which I have used with great success) is using Delayed Job.  The README file contains examples of how simple it is to send email in the background -- basically you just use the send_later method.
Here's a link to another good tutorial:
http://railstips.org/2008/11/19/delayed-gratification-with-rails

A: I've just released a gem, Mailhopper, that queues email in your database for asynchronous sending plus optional archiving. A second gem, DelayedMailhopper, queues and sends these emails using DelayedJob.
I developed this approach to be more robust than DelayedJob alone, as explained here:
http://www.cerebris.com/blog/2011/09/07/tame-rails-email-dragons-with-mailhopper/


text:
Q: Value of a and P(x) when P(x) is a rational number when satisfies a certain equation This is the question as I still don't have permission to post picture, but it is basically when P(x) = x^3+x^2+ax+1, when a is a rational number, P(X) is also rational number for every x that satisfy x^2+2x-2=0

Consider the integral expression in $x$ $$ P= x^3 + x^2 + ax +1 $$ where $a$ is a rational number. At $a=a_0$ the value of $P$ is a rational number for any $x$ which satisfies the equation $x^2 + 2x -2 = 0$, and n this case the value of $P$ is $P_0$.
Find the values of $a_0$ and $P_0$

A: Hint: By a direct computation, $x^2+2x-2=0$ has two solutions, namely
$$
x=\pm \sqrt{3}-1.
$$
For $x=\sqrt{3}-1$ we have
$$
P=x^3+x^2+ax+1=(a+4)\sqrt{3}-a-5.
$$
Hence for $a=-4$, this is rational. For $x=-\sqrt{3}-1$ we have
$$
P=-(a+4)\sqrt{3}-a-5.
$$

A: Just another way without explicit root finding: $x^2=2-2x\implies x^3=2x-2x^2=2x-2(2-2x)=6x-4$, so in this case, $P(x)=(6x-4)+(2-2x)+ax+1=(a+4)x-1$.
As $x^2+2x-2$ has no rational roots ($\pm1,\pm2$ are not roots); to have $P$ rational, we must have $a_0=-4 \implies P_0=-1$


text:
Q: How to run JUnit test in Eclipse I have the following test class in Eclipse:
package org.drools.example;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.WorkingMemory;
import org.drools.compiler.DroolsError;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
import org.drools.compiler.PackageBuilderErrors;
import org.drools.rule.Package;

public class RuleTest {

    //@Test
    public void shouldFireHelloWorld() throws IOException, DroolsParserException {
        RuleBase ruleBase = initialiseDrools();
        WorkingMemory workingMemory = initializeMessageObjects(ruleBase);
        int expectedNumberOfRulesFired = 1;

        int actualNumberOfRulesFired = workingMemory.fireAllRules();

        assertThat(actualNumberOfRulesFired, is(expectedNumberOfRulesFired));
    }

    private RuleBase initialiseDrools() throws IOException, DroolsParserException {
        PackageBuilder packageBuilder = readRuleFiles();
        return addRulesToWorkingMemory(packageBuilder);
    }

    private PackageBuilder readRuleFiles() throws DroolsParserException, IOException {
        PackageBuilder packageBuilder = new PackageBuilder();

        String ruleFile = "/org/drools/example/helloWorld.drl";
        Reader reader = getRuleFileAsReader(ruleFile);
        packageBuilder.addPackageFromDrl(reader);

        assertNoRuleErrors(packageBuilder);

        return packageBuilder;
    }

    private Reader getRuleFileAsReader(String ruleFile) {
        InputStream resourceAsStream = getClass().getResourceAsStream(ruleFile);

        return new InputStreamReader(resourceAsStream);
    }

    private RuleBase addRulesToWorkingMemory(PackageBuilder packageBuilder) {
        RuleBase ruleBase = RuleBaseFactory.newRuleBase();
        Package rulesPackage = packageBuilder.getPackage();
        ruleBase.addPackage(rulesPackage);

        return ruleBase;
    }

    private void assertNoRuleErrors(PackageBuilder packageBuilder) {
        PackageBuilderErrors errors = packageBuilder.getErrors();

        if (errors.getErrors().length > 0) {
            StringBuilder errorMessages = new StringBuilder();
            errorMessages.append("Found errors in package builder\n");
            for (int i = 0; i < errors.getErrors().length; i++) {
                DroolsError errorMessage = errors.getErrors()[i];
                errorMessages.append(errorMessage);
                errorMessages.append("\n");
            }
            errorMessages.append("Could not parse knowledge");

            throw new IllegalArgumentException(errorMessages.toString());
        }
    }

    private WorkingMemory initializeMessageObjects(RuleBase ruleBase) {
        WorkingMemory workingMemory = ruleBase.newStatefulSession();

        createHelloWorld(workingMemory);

        return workingMemory;
    }

    private void createHelloWorld(WorkingMemory workingMemory) {
        Message helloMessage = new Message();
        helloMessage.setType("Hello");
        workingMemory.insert(helloMessage);
    }

}

When I right-click on the *.class, I can only see Run->Run configuration. Which settings should I select in Configuration to be able to execute this program?
If I run it as Java Application, the it says:
JUnit version 4.10

Time: 0.001

OK (0 tests)

A: This is because RuleTest  is not extending the Junit Base test class which you should do to let Eclipse know its a Junt class


text:
Q: How to apply chain rule to:$\frac{d}{dx} \Big( \frac{dy}{dx} \Big)$? How do I apply chain rule to the following:
$$\frac{d}{dx} \Big( \frac{dy}{dx} \Big)$$
Where $$\Big( \frac{dy}{dx} \Big) = \Bigg(\frac{\frac{dy}{dt}}{\frac{dx}{dt}} \Bigg)$$
I don't see the relationship between the bottom $dx$ and the $dy$ in the numerator. My textbook states that:
$$\frac{d}{dx} \Big( \frac{dy}{dx} \Big) = \frac{\frac{d}{dt} \times \big( \frac{dy}{dx} \big)}{\frac{dx}{dt}}$$
without explanation.
Any hints or help on  the details of this proccess will be greatly appreciated. Cheers!

A: The chain rule says
$$\frac{d\phi}{dx}\frac{dx}{dt}=\frac{d\phi}{dt}.$$
Divide both sides by $\frac{dx}{dt}$ and set $\phi=\frac{dy}{dx}$ to get the desired formula.
Better, just use the original formula
$$\frac{d}{dx}=\left(\frac{dx}{dt}\right)^{-1}\frac{d}{dt}$$
(as an equality of operators) on $\frac{dy}{dx}$ instead of $y$.

A: Let $y^{\prime}=\frac{dy}{dx}$.  By the Chain Rule,
$\displaystyle\frac{dy^{\prime}}{dx}=\frac{\frac{dy^{\prime}}{dt}}{\frac{dx}{dt}}=\frac{\frac{d}{dt}(\frac{dy/dt}{dx/dt})}{\frac{dx}{dt}}=\frac{\frac{dx}{dt}\cdot\frac{d^2y}{dt^2}-\frac{dy}{dt}\cdot\frac{d^2x}{dt^2}}{(\frac{dx}{dt})^3}$ (using the Quotient Rule to simplify the top).


text:
Q: How do I extract an exact word from text by using python? I want to calculate how many lines contain a word matched with keywords I chosen. So I coded like this.
  28         for each_keyword in keywords:
  29             if each_keyword in text:
  31                 related_tweet_count += 1
  32                 print "related_tweet_count", related_tweet_count
  33                 print text

It performed very well. But it has a problem. For example, I have a keyword "flu" then it gives not only "flu" but also "influence". To solve this problem, I searched match word examples and fixed the code like this.
  28         for each_keyword in keywords:
  30             if re.search('\beach_keyword\b', text, re.I):
  31                 related_tweet_count += 1
  32                 print "related_tweet_count", related_tweet_count
  33                 print text

But it doesn't work. Please help me out!

A: You need to actually substitute each_keyword into the regular expression.  At the moment it's literally trying to match "each_keyword".
28         for each_keyword in keywords:
30             if re.search('\\b' + each_keyword + '\\b', text, re.I):
31                 related_tweet_count += 1
32                 print "related_tweet_count", related_tweet_count
33                 print text

A: Alternatively do it without regular expressions and use more kw variations,
for keyword in keywords:
    kw_list = [' '+keyword+',',' '+keyword+' ',' '+keyword+'.','. '+keyword]
    for kw in kw_list:
        if kw in text:
            related_tweet_count += 1


text:
Q: Create linked list of multiple objects I need help, if I have:
class gameObject{
    public: //get and set;
    private: int x;
    int y;
    string texture;
}

class gun:public gameObject{
    public: //get and set;
    private: int ammo;
}

class armor:public gameObject ... ,
class boots:public gameObject...

How I can create a linked list of multiple derived objects from base class gameObject ? For example user have a menu: [1. Add object 2.Delete object]. If user choose 1 another menu appear [Type: 1-Gun 2-Armor]. After 4 objects added the list will be: 1.Gun 2.Armor 3.Gun 4.Boots.
I need an example to understand the concept.
Thanks.

A:
How I can create a linked list of multiple derived objects from base class gameObject ?

You would use std::forward_list (singly linked list) or std::list (doubly linked list) in conjunction with a smart pointer like std::unique_ptr or std::shared_ptr (depending on owning semantic), as demonstrated below:
std::list<std::unique_ptr<gameObject>> list;

and then you would allocate objects using:
list.emplace_back(std::make_unique<gameObject>(...));

A: Other peoples answers were good, but in case they were answering the wrong question here:
A pointer to the base type (smart or otherwise) can point to any of the derived types too, so you need to make a list of pointers to the base type.
You can't make a list of the base type itself, because the derived types are probably bigger and wouldn't fit. The language won't even let you try.
std::list<GameObject *> is ok.
std::list<GameObject> is not.

A: You'll want to use auto pointers for this.
list<unique_ptr<gameObject>> foo;

foo.push_back(make_unique<gun>());
foo.push_back(make_unique<armor>());

for(auto& i : foo){
    if(dynamic_cast<gun*>(i.get())){
        cout << "gun" << endl;
    }else if(dynamic_cast<armor*>(i.get())){
        cout << "armor" << endl;
    }
}

This example adds a gun and then an armor to foo as unique_ptr<gameObject>s.
In the for-loop we use a dynamic_cast to discern the type. The code will output:

gun
  armor

You can see an example of this code here: http://ideone.com/trj9bn


text:
Q: Setting environmental variables for PlayonLinux So I just installed android studio for PlayOnLinux and it was fine.  When I try to start it, it is looking for JAVA_HOME environmental variable to be set to the jdk.
I have the jdk installed in my virtual windows directory as well as on linux.  How do I set an environmental variable in PlayOnLinux?
I tried adding export JAVA_HOME=/jdk-installation  to .bash.sh  and /home/myUser/playonlinux-bash.sh but neither did anything.  Is it somewhere in the GUI?

A: For future people trying to figure this out:
I don't think /etc/profile affects PlayOnLinux...  I finally found the correct file at
          /home/myUser/dosdevices/z:/usr/share/playonlinux/playonlinux

and added the
          export JAVA_HOME=/home/myUser/.PlayOnLinux/wineprefix/java/drive_c/ProgramFiles/Java/jdk1.8.0_201

I have other problems running android studio but this is for anyone that wants to set environmental variables in PlayOnLinux

A: Open file  /etc/profile in edit mode
vim /etc/profile

Add below path
export JAVA_HOME="jdk-installation"
export PATH=$JAVA_HOME/bin:$PATH

Source the file for applying the change
source /etc/profile


text:
Q: How to pass variable in bash for php command On bash funcion I need pass varible por a external command (php)
panel=$(php -r '$ini_array = parse_ini_file("/root/.name/name.ini");echo $ini_array['panel'];')

Work properly.
But I need pass path on variable and key of array also.
Try several form but all fails. '', "", ...
php -r '$ini_array = parse_ini_file(`$sPath`);echo $ini_array["$sKey"];'

It's possible?

A: Pass the variable through the environment, and retrieve it from the environment on the PHP side.
sPath=$sPath sKey=$sKey \
  php -r '$ini_array = parse_ini_file($_ENV["sPath"]);echo $ini_array[$_ENV["sKey"]];'

The initial sPath=$sPath and sKey=$sKey are not necessary if you have used export to put your shell variables in the environment already.


text:
Q: Query purchase products info returns Invalid Value use Google Play Developer API this problem may be similar here, but some different
1、I get client_id client_secret by this
2、I get authorization_code by:
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_type=code&access_type=offline&redirect_uri={REDIRECT_URIS}&client_id={CLIENT_ID}
3、get refresh_token by:
urls := "https://www.googleapis.com/oauth2/v4/token"

postData := "redirect_uri=%s&grant_type=authorization_code&client_id=%s&client_secret=%s&code=%s"
postData = fmt.Sprintf(postData, url.QueryEscape(REDIRECT_URL), url.QueryEscape(CLIENT_ID), url.QueryEscape(CLIENT_SECRET), url.QueryEscape(CODE))
beego.Debug("postData:", postData)

body, err := service.Post(urls, "application/x-www-form-urlencoded", bytes.NewReader([]byte(postData)))

4、I get access_token by:
urls := "https://www.googleapis.com/oauth2/v4/token"

postData := "grant_type=refresh_token&client_id=%s&client_secret=%s&refresh_token=%s"
postData = fmt.Sprintf(postData, url.QueryEscape(CLIENT_ID), url.QueryEscape(CLIENT_SECRET), url.QueryEscape(REFRESH_TOKEN))
beego.Debug("postData:", postData)

body, err := service.Post(urls, "application/x-www-form-urlencoded", bytes.NewReader([]byte(postData)))

and I want get products info:
urls := "https://www.googleapis.com/androidpublisher/v2/applications/%s/purchases/products/%s/tokens/%s"
urls = fmt.Sprintf(urls, url.QueryEscape("cn.wps.moffice_premium"), url.QueryEscape("premium_sub_m"), url.QueryEscape("fngalnikxxxxxxcncnbfa.AO-J1OxEoo9RnI-tFqxxxxxxB6u-xbsnp74QYZQYsw_yDyLxxxxxxxaAohBFeafRTZBIioiljUt_ZVbexxxxxxPV7jD_QPQTpmftxpoQGzGloApv9mJnxBe5thDxxxxxxxLhpRRRWlK"))
header := http.Header{}
header.Add("Authorization", "Bearer "+accessToken)
body, err := service.Get(urls, header)

and I get err:
 {
 "error": {
 "errors": [
  {
    "domain": "global",
    "reason": "invalid",
    "message": "Invalid Value"
   }
  ],
  "code": 400,
  "message": "Invalid Value"
 }
}

I try this url can return valid value:
"https://www.googleapis.com/androidpublisher/v2/applications/%s/purchases/subscriptions/%s/tokens/%s"

not sure what else to try.
Thanks for help and replies

A: I find the reason. My order item type is "subs", so can't use this Purchases.products
I use order item type "inapp", use Purchases.products return 200.


text:
Q: Stop Camera recording and save file when entering background I've been looking for the answer for 2 days, but I can't seem to get it right...
I have an example app that records audio and video from the device using a AVCaptureSession and a AVCaptureMovieFileOutput.
When I start recording I call:
[self.movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];

And it starts recording to the file. If I press the button again it stops recording
[self.movieFileOutput stopRecording];

Everything works well, but when I enter background (incoming call or HOME press) I get an error in the delegate method: didFinishRecordingToOutputFileAtURL
My desired action should be saving / completing the file on entering the background. If I call stopRecording on "applicationDidEnterBackground" it will enter background before the applicationDidEnterBackground is called. On entering the active state it is called.... and generates an error and leaves a corrupted movie file...
It seems that it hasn't got enough time to save the file.
What am I missing here?
This is my Error
Error Domain=AVFoundationErrorDomain Code=-11818 "Recording Stopped" UserInfo=0x17594e20 {NSLocalizedRecoverySuggestion=Stop any other actions using the recording device and try again., NSUnderlyingError=0x175d3500 "The operation couldn't be completed. (OSStatus error -16133.)", NSLocalizedDescription=Recording Stopped}
AVErrorSessionWasInterrupted = -11818

A: NSOperationQueue is the recommended way to perform multi-threaded tasks to avoid blocking the main thread. Background thread is used for tasks that you want to perform while your application is inactive, like GPS indications or Audio streaming.
If your application is running in foreground, you don't need background thread at all.
For simple tasks, you can add a operation to a queue using a block:
NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperationWithBlock:^{
    // Perform long-running tasks without blocking main thread
}];

More info about NSOperationQueue and how to use it.
- (void)applicationWillResignActive:(UIApplication *)application {
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{

      // Wait until the pending operations finish
      [operationQueue waitUntilAllOperationsAreFinished];

      [application endBackgroundTask: bgTask];
      bgTask = UIBackgroundTaskInvalid;
    }];
}

A: You can handle saving in applicationWillResignActive: and then you can continue your process in background.


text:
Q: Can anyone help me debug this? I'm fairy new at c++ and trying to make a simple program that returns the address of a char, here is the code
#include <iostream>
using namespace std;

char returnaddress(char* x){
char *t = &x;
return *t;
}
int main()
{
  char y = "a";
  returnaddress(&y);
  return 0;
}

A: There is no need to create a function to return the address of a variable.  That feature is already in the language.
int main()
{
  char y = 'a'; // single quotes for single characters.
  char * pointer_to_y = &y; // This replaces your function.
  std::cout << "Address is: " << static_cast<void *>(pointer_to_y) << "\n";
  return EXIT_SUCCESS;
}

The static_cast is required to force output of the address instead of calling the overload for printing C-Style strings.

A: the address of your char is &y. no need for the wrong function. the type of &x in your function is char** so the code cannot compile. also chars in c++ are delimited by ticks not quotes


text: Q: Studying the $F[x]/\langle p(x)\rangle$ when $p(x)$ is any degree. Let $F$ be a field, $p(x)\in F[x]$. If $p(x)=0$, then $F[x]/\langle p(x)\rangle=F[x]/\langle 0\rangle=\bigl\{\{a\}\mid a\in F[x]\bigr\}$, a set of sets of one element. If $\deg p(x)=0$, then $F[x]/\langle p(x)\rangle=\{F[x]\}$, a set with one element. Am I correct? And if $\deg p(x)\geq1$, under what circumstances will $F[x]/\langle p(x)\rangle$strictly larger than $F$ (view $F$ as the isomorphic copy in it)?


text:
Q: How to find out if a locale uses AM/PM? I have a label displaying only the minutes part of a certain hour of the day. I want it to read "PM" or "00", depending on time zone.
My current solution simply uses Joda's DateTimeFormat.shortTime().withLocale(myLocale) and takes the last 2 characters from the result. This works, but feels wrong.
Instead, I want to check if the given locale uses AM/PM notation, but I haven't found an API call to give me that information. Does it exist, either in JodaTime or the Java libraries themselves? For example, I would like to write something like usesAmPm(myLocale)) ? DateTimeFormat.forPattern("a") : DateTimeFormat.forPattern("mm")

A: Answer to the question how to check if a given locale uses AM/PM notation:
The only common source about such localized data is CLDR from Unicode consortium. Indirectly the JDK loads a small subset of CLDR which can be accessed as follows:
public static boolean usesAmPm(Locale locale) {
  DateFormat df = DateFormat.getTimeInstance(DateFormat.FULL, locale);
  if (df instanceof SimpleDateFormat) {
    return ((SimpleDateFormat) df).toPattern().contains("a");
  } else {
    return false; // unlikely to happen
  }
}

A: This is very similar to Meno's answer, but I didn't like the instanceof usage (some form of OCD, I guess). Here's my version:
public static boolean usesAmPm(Locale locale)
{
    String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
        FormatStyle.MEDIUM, FormatStyle.MEDIUM, IsoChronology.INSTANCE, locale);
    return pattern.contains("a");
}

A: A shortened variant of Meno's solution:
public static boolean usesAmPm(Locale locale) {
        DateFormat df = DateFormat.getTimeInstance(DateFormat.FULL, locale);
        return df instanceof SimpleDateFormat && ((SimpleDateFormat) df).toPattern().contains("a");
}


text:
Q: iOS7: Navigation Bar and Tab Bar transparency looks different on a real iDevice I'm currently developing an app for iOS7, using XCode5.
Today was my first attempt to test the app on a real device (iPhone 4 with iOS7.0).
I've noticed there is a difference between what I see in the simulator and what I see on the real device.
The Navigation Bar and Tab Bar are defined as follows:
[self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
[self.navigationController.navigationBar setTranslucent:YES];

[self.tabBarController.tabBar setBarStyle:UIBarStyleBlack];
[self.tabBarController.tabBar setTranslucent:YES];

The level of transparency is very different between the simulator and the real device, as can be seen in the screenshots below:
1.Screenshot from Simulator:

2.Screenshot from a real iPhone:

I can't find anything about that online. Am I doing something wrong?
Thank you.

A: sorry for poor english .. I'm using google translator.
I was having this same problem, but in colors of the buttons in the tabbar and navigationBar. I found that this is a configuration of iOS. On your device go to Settings> General> Accessibility> Increase Contrast.
It remains now to discover how to predict whether the user is modified with these settings and make adjustments via code.


text:
Q: How to prevent socket io client (browser) from being overflowed with huge payload coming from server? I have a React.js client app and a Node.js server app and the Node.js app receives json data in real time via socket.io from another microservice. The JSON data is sent very often and this breaks the client app. For example:

*

*I stop the server but the client still receives data

*If I try refreshing the browser, it takes a lot of time to refresh

*It also used to disconnect and reconnect the sockets (I fixed this by increasing the pingTimeout but that did not solve the other problems)

I also used maxHttpBufferSize and updateTimeout by increasing them but that does not really help. Decreasing the maxHttpBufferSize stops the messages from being received but I want them to be received just in a manner which does not break my client application.
Any advices on what I can do to improve my situation?
EDIT:
It could also work if I do not send all messages but skip every second or so but I am not sure how to achieve this?

A: Backpressure can be implemented with acknowledgements:

*

*the client notifies the server when it has successfully handled the packet

socket.on("my-event", (data, cb) => {
  // do something with the data
  // then call the callback
  cb();
});

*

*the server must wait for the acknowledgement before sending more packets

io.on("connection", (socket) => {
  socket.emit("my-event", data, () => {
    // the client has acknowledged the packet, we can continue
  });
})

Reference: https://socket.io/docs/v4/emitting-events/#acknowledgements
Note: using volatile packets won't work here, because the amount of data buffered on the server is not taken in account
Reference: https://github.com/websockets/ws/blob/master/doc/ws.md#websocketbufferedamount


text:
Q: SOAP Client Request --> Bad Request I've been asked to look into syncing data using a SOAP service. I don't really know SOAP very well at all and I get a Bad Request Error.
The function I'm trying to call is a test echo function:
public string EchoAuthenticated(string text)
Each time I call it I get an error.
I have commented out the username / password setting as I don't know the username and password right now and my contact person is on leave :( Right now though I'd be perfectly happy just to get an authentication failed message rather than an error...
If anyone could point me in the right direction here please...
Thanks,
John
 <?php

 $apiUrl         = 'https://exdev.api.propctrl.co.za/v3/Integration.svc?wsdl';
 $options        = array( 'trace' => 1, 'exceptions' => 1,  'soap_version' => SOAP_1_2);

 try
 {
    $client     = new SoapClient($apiUrl, $options);

    //$data       = array(
    //  'Username'          => "test",
    //  'Password'          => "test"
    //);

    //$header = new SoapHeader('https://exdev.api.propctrl.co.za/v3/', 'CredentialsHeader', $data, false);
    //$client->__setSoapHeaders($header);

    var_dump($client->__getFunctions());

    print $client->EchoAuthenticated("Test String");
    var_dump($client->__getLastRequest());

 }
 catch(Exception $e)
 {
    echo $e->getMessage();
 }

 ?>

A: You might try something like:
...
$client     = new SoapClient($apiUrl, $options);

var_dump($client->__getFunctions());

$auth = array("Username" => "John", "Password" => "secret",
    "IsP24Credentials" => false);
$header = new SoapHeader("https://www.propctrl.com/", "CredentialsHeader",
    $auth, FALSE);
$client->__setSoapHeaders($header);

print $client->EchoAuthenticated(array(
    "text" => "My text to be echoed."
));
var_dump($client->__getLastRequest());
...

This should result in a request SOAP request like this:
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="https://www.propctrl.com/v3" xmlns:ns2="https://www.propctrl.com/">
   <env:Header>
      <ns2:CredentialsHeader>
         <ns2:IsP24Credentials>false</ns2:IsP24Credentials>
         <ns2:Password>secret</ns2:Password>
         <ns2:Username>John</ns2:Username>
      </ns2:CredentialsHeader>
   </env:Header>
   <env:Body>
      <ns1:EchoAuthenticated>
         <ns1:text>My text to be echoed.</ns1:text>
      </ns1:EchoAuthenticated>
   </env:Body>
</env:Envelope>

As a side note, you might have a look at http://www.soapui.org/. This tool helps greatly with web service development.


text:
Q: Where my log statement is printing on Mac? I have an firefox extension with the name myjavascriptfile.js,As I am new to this addon concepts,just I want to debug this script.So I am using the following statements in this file like
function LOG(text)
{
    var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
    consoleService.logStringMessage(text);
}

observe: function(subject, topic, data)
    {
      LOG("observe called ");
}

I know this observe is getting called but I dont know where to see my log message.can some one tell me Where it is printing?
Please help.

A: That text goes to the Error Console. You might need to go to about:config and change devtools.errorconsole.enabled preference to true - the Error Console was removed from the menus by default while ago (strangely enough, I could still see it even without this pref). I think that on OS X you can still open the Error Console via Tools / Web Developer menu, on Windows you have to click the Firefox button and choose Web Developer menu there. Alternatively, Command-Shift-J should do as well.


text:
Q: would this be possible is there anyway to run an cron job + use cURL to call a video ?
in other words is it possible to have server side scripts parse the cURL url video and increase the view count on it.
Is there some sort of server side "browser" or something of that nature?

A: Yes, use the libcurl PHP bindings, from a CRON job which executes your script with php5-cli.
You'd need to GET the URL of the video file directly, not the hosted page. That might force you to supply the 'referer' (sic) HTTP header.
Also, the site you're "inflating" the view count on might not appreciate it, or might simply not count your hits after a while.


text:
Q: Periodic job to find resource groups with tags corresponding to recently deleted users We have a tag policy in place such that each resource group has a Tech-Owner-Email and Tech-Owner-Name tag.
We want to be notified when people leaving the org have resource groups under their name.
What's a good way to find groups belonging to people who have recently left?
We will want this process to run periodically and to notify us with any results (email, teams, whatever works)

A: The graph API has an endpoint that lists recently deleted users (docs)
https://graph.microsoft.com/v1.0/directory/deletedItems/microsoft.graph.user
This can be polled via the Azure CLI to get the list of people, then az cli can also be used to get the list of tags from resource groups.
The script
#!/usr/bin/pwsh
Write-Host "Fetching deleted users"
$deletedUsers = az rest `
--method "GET" `
--url "https://graph.microsoft.com/v1.0/directory/deletedItems/microsoft.graph.user" `
--headers "Content-Type=application/json" | ConvertFrom-Json

if ($deletedUsers.value.count -eq 0)
{
    Write-Warning "No deleted users found"
    return
}

Write-Host "Gathering subscriptions"
$subs = az account list | ConvertFrom-Json
$found=0
foreach ($sub in $subs)
{
    Write-Host "Gathering resource group tags for subscription $($sub.name)"
    $groups = az group list --subscription $sub.id | ConvertFrom-Json
    foreach ($group in $groups)
    {
        if (
            $group.tags."Tech-Owner-Email" -in $deletedUsers.value.mail -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.businessPhones -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.displayName -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.givenName -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.id -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.jobTitle -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.mail -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.mobilePhone -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.officeLocation -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.preferredLanguage -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.surname -or
            $group.tags."Tech-Owner-Name" -in $deletedUsers.value.userPrincipalName
        )
        {
            Write-Host "Found group `"$($group.name)`" belonging to `"$($group.tags."Tech-Owner-Name")`" <$($group.tags."Tech-Owner-Email")>"
            $found++
        }
    }
}

if ($found -gt 0)
{
    throw "Found $found groups belonging to people who are no longer with us"
}

Note that $deletedUsers.value is a list of objects, but $deletedUsers.value.mail expands to a list of strings :D
The pipeline that runs every day
From there, you can use Azure DevOps pipelines to run this script periodically
trigger:
  branches:
    include:
      - main

schedules:
- cron: "0 12 * * *"
  displayName: Daily check
  branches:
    include:
    - main

variables:
  - group: deleted-owners-checker

steps:
- task: PowerShell@2
  displayName: az login
  inputs:
    pwsh: true
    targetType: inline
    script: az login --service-principal -u $Env:applicationId -p $Env:password --tenant $Env:tenantId
  env:
    applicationId: $(applicationId)
    objectId: $(objectId)
    password: $(password)
    tenantId: $(tenantId)
- task: PowerShell@2
  displayName: run script
  inputs:
    targetType: filePath
    filePath: scripts/listdeleted.ps1 # our repo has a folder called scripts containing the relevant script, update this based on your own
- task: PowerShell@2
  displayName: az logout
  inputs:
    pwsh: true
    targetType: inline
    script: az logout
    condition: always() # log out even if other tasks fail

This necessitates having a service principal that can be logged in during pipeline execution and has permissions to read your resource groups and has User.Read (Application) graph permissions. The credentials for the service principal can be passed to the pipeline using the Azure DevOps Library connected to an Azure KeyVault.
You can alternatively use a devops ARM service connection in a CLI task instead of manually logging in to the CLI, but I've had issues with this in the past so I prefer to manually log in.
The notification
Note that the scripts exits with an error if any groups belonging to gone-people are found, this lets you use pipeline-failed emails as your notification system. A better method would be Teams webhooks in the PowerShell script, but that's farther than I've gotten with this.
The infrastructure-as-code
I prefer to automate the creation of the service principal and key vault using Terraform.
This should take care of creating the key vault, creating the service principal, giving the service principal Reader perms on the resource groups (inherited), and giving the service principal the graph permission needed to query deleted users (might need admin consent).
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = ">= 3.23.0"
    }
    azuread = {
      source  = "hashicorp/azuread"
      version = ">= 2.21.0"
    }
  }
}

data "azurerm_resource_group" "main" {
  name = "my-rg-where-i-want-my-key-vault-to-go" # change me!
}

data "azurerm_client_config" "main" {}

resource "azuread_application" "main" {
  display_name = "deleted-owners-checker"
  owners = [
    data.azurerm_client_config.main.object_id
  ]
  required_resource_access {
    resource_app_id = "00000003-0000-0000-c000-000000000000" # microsoft graph

    resource_access {
      # User.Read.All
      id   = "df021288-bdef-4463-88db-98f22de89214"
      type = "Role"
    }
  }
}

resource "azuread_service_principal" "main" {
  application_id                = azuread_application.main.application_id
  owners                        = azuread_application.main.owners
}

resource "azuread_application_password" "main" {
  application_object_id = azuread_application.main.object_id
}

resource "azurerm_role_assignment" "main" {
  principal_id = azuread_service_principal.main.object_id
  scope = "/providers/Microsoft.Management/managementGroups/00000000-000000000-000000000-0000000" # management group that contains the resource groups you care about, change me!
  role_definition_name = "Reader"
}

resource "azurerm_key_vault" "main" {
  resource_group_name = data.azurerm_resource_group.main.name
  tenant_id = data.azurerm_client_config.main.tenant_id
  location = "canadacentral"
  sku_name = "standard"
  name = "deleted-owners-checker"
  lifecycle {
    ignore_changes = [
      tags
    ]
  }
}

resource "azurerm_key_vault_access_policy" "me" {
  secret_permissions      = ["Get", "List", "Set", "Delete", "Purge"]
  certificate_permissions = ["Get", "List", "Create", "Delete", "Import", "Purge"]
  key_permissions         = ["Get", "List", "Create", "Delete", "Import", "Purge"]
  key_vault_id            = azurerm_key_vault.main.id
  tenant_id               = azurerm_key_vault.main.tenant_id
  object_id               = data.azurerm_client_config.main.object_id
}

resource "azurerm_key_vault_access_policy" "devops" {
  secret_permissions      = ["Get", "List"]
  key_vault_id            = azurerm_key_vault.main.id
  tenant_id               = azurerm_key_vault.main.tenant_id
  object_id               = "0000-0000-0000-0000"
  # You would think this would be the object ID of the principal used by the service connection used when connecting the key vault to the Azure DevOps Library
  # In reality, you're better off creating the key vault access policy from the Azure DevOps web interface, since the object ID was different for us when we tried
  # The azure pipeline should let you know if the object ID is wrong. We got a pipeline error like this when we first tried. The error should give you the correct object ID to use
# objectId: "The user, group or application 'appid=***;oid=5555-55555-5555-5555;iss=https://sts.windows.net/zzzz-zzzz-zzzz-zzzz/' does not have secrets get permission on key vault 'deleted-owners-checker;location=canadacentral'. For help resolving this issue, please see https://go.microsoft.com/fwlink/?linkid=2125287. The specified Azure service connection needs to have Get, List secret management permissions on the selected key vault. To set these permissions, download the ProvisionKeyVaultPermissions.ps1 script from build/release logs and execute it, or set them from the Azure portal."
# applicationId: "The user, group or application 'appid=***;oid=5555-55555-5555-5555;iss=https://sts.windows.net/zzzz-zzzz-zzzz-zzzz/' does not have secrets get permission on key vault 'deleted-owners-checker;location=canadacentral'. For help resolving this issue, please see https://go.microsoft.com/fwlink/?linkid=2125287. The specified Azure service connection needs to have Get, List secret management permissions on the selected key vault. To set these permissions, download the ProvisionKeyVaultPermissions.ps1 script from build/release logs and execute it, or set them from the Azure portal."
# tenantId: "The user, group or application 'appid=***;oid=5555-55555-5555-5555;iss=https://sts.windows.net/zzzz-zzzz-zzzz-zzzz/' does not have secrets get permission on key vault 'deleted-owners-checker;location=canadacentral'. For help resolving this issue, please see https://go.microsoft.com/fwlink/?linkid=2125287. The specified Azure service connection needs to have Get, List secret management permissions on the selected key vault. To set these permissions, download the ProvisionKeyVaultPermissions.ps1 script from build/release logs and execute it, or set them from the Azure portal."
# password: "The user, group or application 'appid=***;oid=5555-55555-5555-5555;iss=https://sts.windows.net/zzzz-zzzz-zzzz-zzzz/' does not have secrets get permission on key vault 'deleted-owners-checker;location=canadacentral'. For help resolving this issue, please see https://go.microsoft.com/fwlink/?linkid=2125287. The specified Azure service connection needs to have Get, List secret management permissions on the selected key vault. To set these permissions, download the ProvisionKeyVaultPermissions.ps1 script from build/release logs and execute it, or set them from the Azure portal."

}

locals {
  kv_secrets = {
    objectId = azuread_application.main.object_id
    tenantId = azuread_service_principal.main.application_tenant_id
    applicationId = azuread_service_principal.main.application_id
    password = azuread_application_password.main.value
  }
}

resource "azurerm_key_vault_secret" "main" {
  for_each = local.kv_secrets
  name = each.key
  key_vault_id = azurerm_key_vault.main.id
  value = each.value
  depends_on = [
    azurerm_key_vault_access_policy.me
  ]
}


text:
Q: false value is ignored I have a registration form that checks onchange if a username already exists and displays a BS alert. The function to check this uses Ajax. Answers to my earlier question led me to improve my code to use callback in my Ajax function. So now I have the following code:
HTML:
onchange="callAjax('gebruikersnaam', document.getElementById('gebruikersnaam').value, checkBestaandeGebruikersnaam)"

JavaScript main function:
function callAjax(arg1, arg2, callback){
var request = new XMLHttpRequest();

request.onreadystatechange = function() {
  if(request.readyState === 4 && request.status === 200) {
        callback(request.responseText);
    } else {
        document.getElementById("message").innerHTML = 'An error occurred during your request: ' +  request.status + ' ' + request.statusText;
    }
  }
request.open("POST", "core/functions/checkBestaandeGebruikersnaam.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(arg1+"="+arg2);
}

JavaScript callback function:
function checkBestaandeGebruikersnaam(result) {
if(result == "1") {
    document.getElementById("message").innerHTML = '
×Let op! Die gebruikersnaam is al bezet, kies een andere gebruikersnaam.
';
    return false;
}
else {
    document.getElementById("message").innerHTML = '';
}
}

Now I have a generic Ajax request that I can re-use by feeding it different parameters. So thanks for that. Can someone confirm if I am using the callback functionality correctly?
Now, what I really want is to re-use the function checkBestaandeGebruikersnaam() when the form is submitted. I have the following code:
HTML:
 <form action="register.php" onsubmit="return validate()" name="registerForm" method="post" class="col-md-10 col-md-offset-1 col-xs-12 col-xs-offset-0">

JavaScript:
function validate() {
var errMsgHolder = document.getElementById("message");
if(checkPassword() === false ) {
    errMsgHolder.innerHTML =
            '
×Let op! Kies een wachtwoord van minimaal 3 en maximaal 30 tekens.
';
            return false;
} else if(checkPasswordsMatch() === false){
    errMsgHolder.innerHTML =
            '
×Let op! Wachtwoorden komen niet overeen.
';
            return false;
} else if(checkBestaandeGebruikersnaam() === false){
    errMsgHolder.innerHTML =
            '
×Let op! Die gebruikersnaam is al bezet, kies een andere gebruikersnaam.
';
            return false;
}

The functions checkPassword() and checkPasswordsMatch() don't use Ajax and they work as expected within the function validate(). But when I test the function validate() for checkBestaandeGebruikersnaam() it doesn't work. It ignores the false value and submits the form. I thought the use of a callback function should solve this, but apparently I am still doing something wrong.  Please enlighten me and thanks for your time.

A: Let's evaluate whats happening step by step:
The validate() function calls checkBestaandeGebruikersnaam()  without passing any parameter.
Inside checkBestaandeGebruikersnaam(), value of result is undefined, the else block gets executed that  does not return anything.
In validate() the check checkBestaandeGebruikersnaam() === false evaluates to false.
Since validate() does not return false, This makes javascript to submit the form.

A: Posting my solution, perhaps it will help some other novice.
I decided to evaluate validate() by a variable checkBG, that should get its value from 'result' inside checkBestaandeGebruikersnaam(). But since checkBG should be available to other functions, I made it a global variable by not using the var keyword, like this:
function checkBestaandeGebruikersnaam(result) {
checkBG = result;
if(checkBG == "1") {
    document.getElementById("message").innerHTML = '
×Let op! Die gebruikersnaam is al bezet, kies een andere gebruikersnaam.
';
}
else {
    document.getElementById("message").innerHTML = '';
}
}

Then I used that variable checkBG as the condition in my validate() function:
function validate() {
var errMsgHolder = document.getElementById("message");
if(checkPassword() === false ) {
    errMsgHolder.innerHTML =
            '
×Let op! Kies een wachtwoord van minimaal 3 en maximaal 30 tekens.
';
            return false;
} else if(checkPasswordsMatch() === false){
    errMsgHolder.innerHTML =
            '
×Let op! Wachtwoorden komen niet overeen.
';
            return false;
} else if(checkBG == "1"){
    errMsgHolder.innerHTML =
            '
×Let op! Die gebruikersnaam is al bezet, kies een andere gebruikersnaam.
';
            return false;
}
}

This actually worked and hours of torture have finally resulted in triomph! Thanks again to Kashif who helped me on my way.


text:
Q: C++ Delete "new"? Im learning about memory leak and I have a problem with how to delete "new".
I have a constructor like this:
Car(string nameOfCar) { carName = nameOfCar; }

and then I have a class that inherits Car, like this:
class Chrysler : public Car
{
public:
    Chrysler(string sound = "wroooom") : Car(sound) {}
};

Okay, I have more code than that, but I dont think I need to share more code than this, to ask my question. If Im wrong, I'll give you more code, of course.
Anyway, in main, I do like this:
car.setCar(new Chrysler());

Everything works just fine, but I have a memory leak because I dont know how to delete new Chrysler(). I guess I need a destructor in Car, but I cant seem to get it right. Anyone out there willing to help me? :)

A: A proper way to do this is to set delete operator inside the Destructor fucnction of every class created to avoid memory leak and crashed


text:
Q: Regex to get the string after @ sign I have a string like follows:
@78517700-1f01-11e3-a6b7-3c970e02b4ec, @68517700-1f01-11e3-a6b7-3c970e02b4ec, @98517700-1f01-11e3-a6b7-3c970e02b4ec, @38517700-1f01-11e3-a6b7-3c970e02b4ec ....
I want to extract the string after @.
I have the current code like follows:
private final static Pattern PATTERN_LOGIN = Pattern.compile("@[^\\s]+");
Matcher m = PATTERN_LOGIN.matcher("@78517700-1f01-11e3-a6b7-3c970e02b4ec , @68517700-1f01-11e3-a6b7-3c970e02b4ec, @98517700-1f01-11e3-a6b7-3c970e02b4ec, @38517700-1f01-11e3-a6b7-3c970e02b4ec");
while (m.find()) {
        String mentionedLogin = m.group();
        .......
   }

... but m.group() gives me @78517700-1f01-11e3-a6b7-3c970e02b4ec but I wanted 78517700-1f01-11e3-a6b7-3c970e02b4ec

A: I would modify the pattern to omit the at sign:
private final static Pattern PATTERN_LOGIN = Pattern.compile("@([^\\s]+)");

So the first group will be the GUID only

A: You should use the regex "@([^\\s]+)" and then m.group(1), which returns you what "captured" by the capturing parentheses ().
m.group() or m.group(0) return you the full matching string found by your regex.

A: Correct answers are mentioned in other responses. I will add some clarification. Your code is working correctly, as expected.
Your regex means: match string which starts with @ and after that follows one or more characters which isn't white space. So if you omit the parentheses you get you full string as expected.
The parentheses as mentioned in other responses are used for marking capturing groups. In layman terms - the regex engine does the matching multiple times for each parenthesis enclosed group, working it's way inside the nested structure.