text:
Q: Paypal Adaptive Payments works in sandbox mode but not production I'm trying to use Paypal's adaptive payments API and having a tough time switching it to production. Everything works as expected on sandbox mode and I get a proper response, but when I switch to my live APP ID it doesn't work.
These are the configuration values I'm using for sandbox
PayPal URL : https://www.sandbox.paypal.com/webapps/adaptivepayment/flow/pay?paykey=[TOKEN_HERE]
Application ID : APP-80W284485P519543T

These values work for me in sandbox mode. But when I switch to the below production values, it stops working
PayPal URL : https://www.paypal.com/webapps/adaptivepayment/flow/pay?paykey=[TOKEN_HERE]
Application ID : [ACTUAL APP ID]

This is what I mean by stops working.

*

*In production mode, the application gets the paykey

*Appends it to the Paypal URL and then redirects it to their site

*On site load, I get the following message

This transaction has already been approved. Please visit your PayPal Account Overview to see the details

The final URL it ends up on - https://ic.paypal.com/webapps/adaptivepayment/flow/payinit?execution=e6s1
Screenshot - http://screencast.com/t/28qJZ9CIk
There is also a 'Return' button there, and when I click on it I get taken to a different site each time (Looks like I get sent to random failUrls)
I've included the code I use below
$payRequest = new PayRequest();
$payRequest->actionType     = "PAY";
$payRequest->cancelUrl      = $cancelURL; //my success and fail urls
$payRequest->returnUrl      = $returnURL;

$payRequest->clientDetails  = new ClientDetailsType();
$payRequest->clientDetails->applicationId   = $this->config['application_id'];
$payRequest->clientDetails->deviceId        = $this->config['device_id'];
$payRequest->clientDetails->ipAddress       = $this->CI->input->ip_address();

$payRequest->currencyCode = $currencyCode;

$payRequest->requestEnvelope = new RequestEnvelope();
$payRequest->requestEnvelope->errorLanguage = "en_US";

//I set the receiver and the amounts. I also define that these are digital goods payments
$receiver1 = new receiver();
$receiver1->email   = $opts['receiver_email'];
$receiver1->amount  = $opts['amount'];
$receiver1->paymentType = 'DIGITALGOODS';
$payRequest->receiverList = new ReceiverList();
$payRequest->receiverList = array($receiver1);

//Then I make the call
$ap          = new AdaptivePayments();
$response    = $ap->Pay($payRequest);

if(strtoupper($ap->isSuccess) == 'FAILURE') {
    log_message('error', "PAYMENT_FAIL : " . print_r($ap->getLastError(), true));
    return false;
} else {
    if($response->paymentExecStatus == "COMPLETED")  {
        header("Location: " . $this->config['success_url']);
        exit;
    } else {
        $token      = $response->payKey;
        $payPalURL  = $this->config['paypal_redirect_url'] . 'paykey='.$token;
        header("Location: ".$payPalURL);
        exit;
    }
}

This is code taken from their sample implementation, so not really sure what's going wrong here. Other information that might be relevant

*

*I'm using adaptive payments to make sure that the sender and receiver
actually did the transaction

*I have set the payment type as 'DIGITAL GOODS'
EDIT
I've included a sample URL with the pay key attached
https://www.paypal.com/webapps/adaptivepayment/flow/pay?paykey=AP-0H388650F08226841

A: I found the issue that was giving me all of this grief.
The Paypal SDK uses a couple of constants which are defined in /sdk/lib/Config/paypal_sdk_clientproperties
The constants contain the username, password, application_id the API url and a few others. These are used directly in the file /sdk/lib/CallerServices,php. So contrary to what you would expect in an API, these values are not injected in the setup phase so if you don't notice that file and change the values, the above code will not work.
To fix the issue, simply update the values defined in the file and you should be good to go.


text:
Q: Rails 3.1, RSpec - failing but page loads fine I am writing some specs and the following is failing but the page /menus/1 is loading fine in a browser. This is a port of a php app and is first time I've used RSpec. Any thoughts as to why it might not be working.
The error is:
1) MenusController GET 'show' should be succesful
  Failure/Error: get :show, :id => 1
  ActiveRecord::RecordNotFound:
  Couldn't find MenuHeader with id=1
  # ./app/controllers/menus_controller.rb:18:in `show'
  # ./spec/controllers/menus_controller_spec.rb:7:in `block (3 levels) in <top (required)>'

but that specific MenuHeader does exist based upon all normal criteria (console, mysql, browser). I'm 99% sure I have a mistake in my spec:
require 'spec_helper'

describe MenusController do
  describe "GET 'show'" do
     it "should be succesful" do
       get :show, :id => 1
       response.should be_success
     end
  end
end

here is the menus_controller.rb
def show
  @menu_header_data=MenuHeader.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    # format.json { render json: @menu } to do
  end
end

thx

A: When testing a controller with Rspec or TestUnit I would use a Factory or Fixture to pass the id rather than setting up a test database with data.  It's better to test with something like:
Using FactoryGirl (My Recommendation but everyone has their own tastes):
describe MenusController do
  describe "GET 'show'" do
     it "should be succesful" do
       get :show, :id => Factory(:menu).id
       response.should be_success
     end
  end
end

The test is mainly just to make sure the controller responds properly when provided valid data, and using Factories or Fixtures is much less brittle.  It will become a pain to maintain your test suite if it's based on hard data like fixtures or a db backup, and that could ultimately lead to you giving up on Test Driven Development rather than embracing it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: inner short circuit evaluation in c I know that Java and C/C++ have short circuit evaluation, i.e., in if (a && b), b will never evaluated if a is not true.
But what if I have expression like if ( (a && b) OP c ) (where OP is an arbitrary logical operator), will b evaluated if a = false? Thanks.

A: C Standards say that -

6.5.13 Logical AND operator

*The && operator guarantees left-to-right evaluation......
.If the first operand compares equal to 0, the second operand is not evaluated.

So in case a==flase b will not be evaluated.

A: You will always have if a = false : a && b == 0 whatever the value of b. Why would an operation done after the evaluation will change that ?
a b  |  a && b
0 0  |   0
0 1  |   0

A: If a=false then condition for b will not be checked so (a && b) is ALWAYS false
and the next condition depends upon the OP used if it is && it will not be evaluated. If it is || it will be evaluated.
So
((a && b) OP c)

here if a=false (a && b) will be always false.


text:
Q: Getting equation from differential equations I have:
$\dfrac {dx} {dt}$=$-x+y$
$\dfrac {dy}{dt}$=$-x-y$
and I am trying to find $x(t)$ and $y(t)$ given that $x(0)=0$ and $y(0)=1$
I know to do this I need to decouple the equations so that I only have to deal with one variable but the decoupling is what I am having trouble with
Do I set them equal to each other and then just move like terms to separate sides getting two different equations and then integrate?

A: Differentiate both w.r.t. t again, we end up with
$$
d^2x/dt^2 = -dx/dt+dy/dt
$$
$$
d^2y/dt^2 = -dx/dt-dy/dt
$$
Then add both of them. Remember that $y=dx/dt + x$
We get
$$
d^2(x+y)/dt^2 = -2dx/dt
$$
Substitute the value of $y = dx/dt +x $
You get,
$$
d^3x/dt^3 + 2d^2x/dt^2 + 2dx/dt = 0
$$
Mathematica(or setting $dx/dt = u$) will give the answer as
$$
x(t) = 1/2 exp(-t) ((c_2-c_1) sin(t)-(c_1+c_2) cos(t))+c_3
$$

A: If I understand your question correctly, you are seeking for a possiblity to separate the equations as common with some of the systems, by shifting the system parallel to the existing $x$ and $y$ coordinates. In simple words you want to find a way by addition or subtraction or multiplication or division. A fair answer is that this is not possible with this system, you can not just scale it. You need to rotate it.
You would see this from the solution of the equation with
$$x(t) = e^{-t} \sin t$$
$$y(t) = e^{-t} \cos t$$
you see there the trigonometric term and $\sin$ and $\cos$ depicting that $y$ and $x$ are shifted at a rotation of $\pi/2$ against each other.
But a priori you dont have of course the solution and the only way to know about the demand for a rotation is due to the fact that you feel by yourself intuitively the system has a resistence and you can not just stretch it. The positive and negative signs just make it impossible to manage a separation by only scaling - following your words.
There is no other way to solve the system by separation except via transformation in the eigenspace accepting a rotation.
You will see a way to caculation of the eigenvalues and solution of the system here>>>
It wont make sense to copy/paste all.
The solution path for such equations via transformation is standard straight forward and cares about all stretching/scaling and rotation required. You can find it also in other books/literature.
Hope this helps out of all confusion.

A: Suppose you change your variables from $(x,y)$ to $(u,v)$ according to the rule
$$\begin{cases}x=a u+bv \\y=cu+dv \end{cases}. $$
This can be written in a matrix form $\mathbf x=P \mathbf u$ where $P=\begin{pmatrix} a & b \\ c & d \end{pmatrix}$.
The ODE transforms accordingly, from
$$\frac{ \mathrm d \mathbf x}{\mathrm d t}=A \mathbf x $$ to
$$P\frac{ \mathrm d \mathbf u}{\mathrm d t}=AP \mathbf u,   $$ or
$$\frac{ \mathrm d \mathbf u}{\mathrm d t}=P^{-1}AP \mathbf u.  $$
If you choose the "right" matrix $P$ the equations for $u,v$ become uncoupled and you can solve them. Then it takes a simple multiplication by $P^{-1}$ to get back to $x,y$.


text:
Q: Restarting 1 Application server(java process) on GCP VM is resulting in bad performance across all Application VMs I have 3 java applications servers running on GCP VMs.  I am getting 2000 TPS.
The URL is a simple GET call to display the log level using actuator end point. I brought down one of the application servers and the load was distributed across other VMs with good TPS.   However, the minute I brought up the VM which was shutdown, the performance on all 3 VMs have degraded and my TPS drops to 1000.
Has anyone seen this issue on GCP VMs before?  Any information on how to debug further on this?


text:
Q: Matplotlib - Force plot display and then return to main code This is a MWE of what I'm after, adapted from this question:
from matplotlib.pyplot import plot, draw, show

def make_plot():
    plot([1,2,3])
    draw()
    print 'continue computation'

print('Do something before plotting.')
# Now display plot in a window
make_plot()

answer = raw_input('Back to main and window visible? ')
if answer == 'y':
    print('Excellent')
else:
    print('Nope')

show()

What I want is: I call the function to make the plot, the plot window appears, and then I get to go back to the prompt so I can input some value (based on that image that just displayed) and carry on with the code (the window can then close or remain there, I don't care).
What I get instead is that the window with the plot only appears after the code is completed, which is no good.

Add 1
I've tried the following with the same results, the plot window appears at the end of the code and not before:
from matplotlib.pyplot import plot, ion, draw

ion() # enables interactive mode
plot([1,2,3]) # result shows immediately (implicit draw())
# at the end call show to ensure window won't close.
draw()

answer = raw_input('Back to main and window visible? ')
if answer == 'y':
    print('Excellent')
else:
    print('Nope')

The same happens if I change draw() for show().

Add 2
I've tried the following approach:
from multiprocessing import Process
from matplotlib.pyplot import plot, show

def plot_graph(*args):
    for data in args:
        plot(data)
    show()

p = Process(target=plot_graph, args=([1, 2, 3],))
p.start()

print 'computation continues...'

print 'Now lets wait for the graph be closed to continue...:'
p.join()

which results in a Python kernel has crashed error in Canopy with the message:
The kernel (user Python environment) has terminated with error code -6. This may be due to a bug in your code or in the kernel itself.

Output captured from the kernel process is shown below.

[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing /tmp/tmp9cshhw.json
QGtkStyle could not resolve GTK. Make sure you have installed the proper libraries.
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python: ../../src/xcb_io.c:274: poll_for_event: La declaración `!xcb_xlib_threads_sequence_lost' no se cumple.

I should mention I'm running Canopy in elementary OS which is based in Ubuntu 12.04.

Add 3
Also tried solution posted in this question:
import numpy
from matplotlib import pyplot as plt

if __name__ == '__main__':
    x = [1, 2, 3]
    plt.ion() # turn on interactive mode
    for loop in range(0,3):
        y = numpy.dot(x, loop)
        plt.figure()
        plt.plot(x,y)
        plt.show()
        _ = raw_input("Press [enter] to continue.")

This displays empty plot windows as the code advances (ie: the user hits [enter]) and only displays the images after the code is finished.
This solution (also in the same question) doesn't even display the plot windows:
import numpy
from matplotlib import pyplot as plt
if __name__ == '__main__':
    x = [1, 2, 3]
    plt.ion() # turn on interactive mode, non-blocking `show`
    for loop in range(0,3):
        y = numpy.dot(x, loop)
        plt.figure()   # create a new figure
        plt.plot(x,y)  # plot the figure
        plt.show()     # show the figure, non-blocking
        _ = raw_input("Press [enter] to continue.") # wait for input from the user
        plt.close()    # close the figure to show the next one.

A: You may use plt.show(block=False), which gets rid of the blocking directly.
For your example, this could read
from matplotlib.pyplot import plot, show

def make_plot():
    plot([1,2,3])
    show(block=False)
    print('continue computation')

print('Do something before plotting.')
# Now display plot in a window
make_plot()

answer = input('Back to main and window visible? ')
if answer == 'y':
    print('Excellent')
else:
    print('Nope')

A: None of the presented solutions work for me. I tested them with three different IDEs PyCharm, Spyder and Pyzo, using the (currently) latest Matplotlib 2.1 under Python 3.6.
What works for me, although not optimal, is to use a plt.pause command:
import matplotlib.pyplot as plt

def make_plot():
    plt.plot([1, 2, 3])
#    plt.show(block=False)  # The plot does not appear.
#    plt.draw()             # The plot does not appear.
    plt.pause(0.1)          # The plot properly appears.
    print('continue computation')

print('Do something before plotting.')
# Now display plot in a window
make_plot()

answer = input('Back to main and window visible? ')
if answer == 'y':
    print('Excellent')
else:
    print('Nope')

A: I couldn't get this to work with Canopy (not yet at least) but I could get the code to run sort of like I wanted to using the Geany IDE. This is the code that works for me, it's a very minor modification to the first block of code in the question where the show() command is moved above from the end of the file to just below the make_plot() command:
from matplotlib.pyplot import plot, draw, show

def make_plot():
    plot([1,2,3])
    draw()
    print 'Plot displayed, waiting for it to be closed.'

print('Do something before plotting.')
# Now display plot in a window
make_plot()
# This line was moved up <----
show()

answer = raw_input('Back to main after plot window closed? ')
if answer == 'y':
    print('Move on')
else:
    print('Nope')

It doesn't do exactly what I want but it's close enough: it shows a plot to the user, waits till that plot window is closed and then moves on with the code. Ideally it shouldn't have to wait until the plot window is closed to move on with the code, but it's better than nothing I guess.
The code in the Add 2 section above also works in the same way and with no modifications needed in Geany, but I prefer this one because it's simpler. I'll update this answer If (when?) I get this to work with Canopy.


text:
Q: Webpacker::Manifest::MissingEntryError in Hello#index ( ruby on rails) I have downloaded the Honeybadger webpack example and run bundle install.
I don't have any errors in terminal, yet get the following when I start my server:
Webpacker can't find application.js in /Users/admin/Documents/sourcemap/honeybadger-rails-webpacker-example/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. Webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your Webpack configuration is not creating a manifest.
Your manifest contains:
{
}

It applies to the line <%= javascript_pack_tag 'application' %>
Where can be my problem?

A: Had the same problem.  Fix was:

*

*Run "bundle exec rails webpacker:install" in the console to upgrade to the latest version of webpacker

*Find out that my node version (8.6.0) was incompatible with the current version of webpack

*Use NVM to upgrade to Node 10.16.0

*Rerun "bundle exec rails webpacker:install" in the console (not sure if this was necessary)

At the end of this it started working!

A: in my case it was because i was setting extract_css: true but i didn't import any css


text:
Q: Scala/ Java, Summing up two arrays columns in a Dataset I have the following Dataset, currently using the UDF to sum up the arrays.
The performance is slow since I'm using an UDF.
Instead I'm looking to use High order functions or spark.sql.functions or any other effective way to sum up the array.
Id  Country State    Vector_1                   Vector_2
1     US     IL   [1.0,2.0,3.0,4.0,5.0]   [5.0,5.0,5.0,5.0,5.0]

1     US     IL   [5.0,3.0,3.0,2.0,1.0]   [5.0,5.0,5.0,5.0,5.0]

2     US     TX   [6.0,7.0,8.0,9.0,1.0]   [1.0,1.0,1.0,1.0,1.0]

The output should looks like this
Id  Country State    Vector_1                      Vector_2
1     US     IL   [6.0,5.0,6.0,6.0,6.0]    [10.0,10.0,10.0,10.0,10.0]
2     US     TX    [6.0,7.0,8.0,9.0,1.0]    [1.0,1.0,1.0,1.0,1.0]


text:
Q: SSRS - One tablix with 2 Datasets I am trying to build a report to show projects and subprojects status updates with data for projects and subprojects coming from 2 separate sharepoint lists i.e. datasets in the same data source.
The problem is

*

*That I do not know how to build a lookup function for tablix to pull data from different sharepoint lists.

*Tablix needs to have a rule for exceptions: 3 projects have subprojects but the other do not have subprojects.

The expected result is for tablix to display status report in the following way:
status update   next steps
project1
project2
project3
    subproject 3.1
    subproject 3.2
    subproject 3.3

I have linked the projects to subprojects using a key.
Advice much appreciated.

A: In current release of Reporting Services, each tablix can contains only one dataset. So in your scenario, the easiest way to achieve your requirement is combining the two datasets into one using Join in the query if it is possible. If the datasets cannot be combined, there are two ways you can give a try
a. Subreport - create a subreport to display in another report
1.Create another report as the subreport and insert the child row data.
2.Create a parameter named ID in the subreport.
3.In the main report, right-click to insert a subreport in the child row.
4.Right-click the subpeort to open the Subreport Properties, and select the
subreport name in the drop-down list.
5.In the left panel of the Subreport Properties dialog box, click Parameters.
6.Select Name in the drop-down list of ID, and select [ID] in the drop-down list
of Value.
b.  Use 'lookupset' function (more on lookupset function Lookupset Function


text:
Q: critical Z-statistic vs sample Z-statistic A hypothesis that the population mean is less or equal to $x$ should be rejected when the critical Z-statistic is greater than the sample Z-statistic. $x$ is any number.

*

*If $x=5$, the statement is true or false? The answer is false, but why?

*For what values of $x$ the statement is true or false?

I know this is a one-tail hypothesis, but how do I know which tail are we talking about? Or is there some general rule that can answer 2)?
UPDATE: I will post the question completely:

Which of the following statements about hypothesis testing is most
accurate?
A) A Type I error is rejecting the null hypothesis when it is true,
and a Type II error is rejecting the alternative hypothesis when it is
true.
B) A hypothesis that the population mean is less than or equal
to 5 should be rejected when the critical Z-statistic is greater than
the sample Z-statistic.
C) A hypothesized mean of 3, a sample mean of
6, and a standard error of the sampling means of 2 give a sample
Z-statistic of 1.5.

The answer is C. I'm trying to understand when B would be true (first understanding when B is true for $x=5$ as in my original question, then understanding when it's true for any value of $x$

A: To make it clear we can give it some context.  Let $X_1,...,X_n\sim N(\mu,\sigma^2)$ with $\sigma^2$ known.  To test $H_0: \mu \le 5$ at level $\alpha$ we would compare the observed sample test statistic
$$z=\frac{\bar{x}-5}{\sigma/\sqrt{n}}$$
to the critical value $z_{1-\alpha}$.  If $z>z_{1-\alpha}$ then $H_0$ is rejected.  Otherwise, $H_0$ is not rejected.
To generalize we would write $H_0: \mu \le \mu_0$ and examine $z=\frac{\bar{x}-\mu_0}{\sigma/\sqrt{n}}$.  Nevertheless, if $z>z_{1-\alpha}$ then $H_0$ is rejected.
Option B) above is incorrect because it states that $H_0$ is rejected if $z_{1-\alpha}>z$.  Let me know if I have understood your question correctly and if I have made any mistakes.


text:
Q: Save fb/google profile picture I'm using django cookie cutter which has pre-installed django-allauth. I've integrated fb and google to login successfully. But I need to save profile picture returned by fb/google in my user model.
But I can't find where django-allauth saves data in user model so that I can save profile pic as well.
Has somebody used it or know where can I edit this code?

A: From the sound of it (I don't use it) django-allauth is an authentication wrapper that provides some convenience functions to various APIs - what makes you think it is storing aspects like the profile picture at all? I think what you want is the ProviderAccount get_avatar_url() [1][2] then request and save it yourself. If you want it to be connected to the User model then a profile is probably the way to go. Avoid a custom user model unless it is absolutely necessary (which since you have started a project with cookiecutter, I can assume it is not).


text:
Q: change button image I have created a new custom button, can I set a different background image instead of 'circle' or 'triangle' ?
thanks
Chanan
        exporting: {
        enabled: true,
            buttons: {
                'realTimeButton': {
                id: 'realTimeButton',
                    symbol: 'diamond',
                    x: -88,
                    symbolFill: realTimeColor,
                    hoverSymbolFill: realTimeColor,
                    _titleKey: "realTimeButtonTitle",
                    onclick: function(event) {
                      // handle change to real time
                      if ( enable_lastRoundsChart_realtime )
                      {
                         // disable real time flag
                         enable_lastRoundsChart_realtime = 0;

                         // re-create detail in real time mode disabled
                         createDetail(cache_last_rounds.last_rounds_data, window.show_top_round_ids);

                         // enable plotBand
                         if ( pb_master_chart )
                         {
                            pb_master_chart.options.chart.events.selection.enabled = 'true';
                            pb_master_chart.options.chart.zoomType = 'x';
                          }
                    }
                    else
                    {
                        // enable real time flag
                        enable_lastRoundsChart_realtime = 1;

                        // re-create detail in real time mode enabled
                        createDetail(cache_last_rounds.last_rounds_data, window.show_top_round_ids);

                        // update title
                        this.setTitle({text:"Players/Drops Per Round"}, {text:"Real Time"});

                        // if master found, remove plotBand and disable master selection
                        if ( pb_master_chart )
                        {
                            // remove plotBand
                            pb_master_chart.xAxis[0].removePlotBand('mask-before');
                            pb_master_chart.xAxis[0].removePlotBand('mask-after');
                            pb_master_chart.xAxis[0].addPlotBand({
                                id: 'mask-before',
                                from: -1,
                                to: 99999,
                                color: 'rgba(0, 0, 0, 0.2)'
                            })

                            // disable selection
                            pb_master_chart.options.chart.events.selection.enabled = 'false';
                            pb_master_chart.options.chart.zoomType = null;
                        }
                    }
                }
            },

A: You have ability to set image as icon
http://jsfiddle.net/Udgb3/
 symbol: 'url(http://highcharts.com/demo/gfx/sun.png)',
                symbolX:5,
                symbolY:0

A: According to the docs, the shapes are defined in the Highcharts.Renderer.symbols collection.  Inspecting this object reveals the following available shapes:
Highcharts.Renderer.prototype.symbols:
  arc: function (a,b,c,d,e){var f=e.start,c=e.r||c||d,g=e.end-1.0E-6,d=e.innerR,h=e.open,i=W(f),j=Z(f),k=W(g),g=Z(g),e=e.end-f<Aa?0:1;return["M",a+c*i,b+c*j,"A",c,c,
  circle: function (a,b,c,d){var e=0.166*c;return["M",a+c/2,b,"C",a+c+e,b,a+c+e,b+d,
  diamond: function (a,b,c,d){return["M",a+c/2,b,"L",a+c,b+d/2,a+c/2,b+d,a,b+d/2,"Z"]}
  exportIcon: function (a,b,c,d){return y(["M",a,b+c,"L",a+c,b+d,a+c,b+d*0.8,a,b+d*0.8,"Z","M",a+c*0.5,b+d*0.8,"L",a+c*0.8,b+d*0.4,a+c*0.4,b+d*0.4,a+c*0.4,b,a+c*0.6,b,a+c*0.6,b+d*0.4,a+c*0.2,b+d*0.4,"Z"])}
  printIcon: function (a,b,c,d){return y(["M",a,b+d*0.7,"L",a+c,b+d*0.7,a+c,b+d*0.4,a,b+d*0.4,"Z","M",a+c*0.2,b+d*0.4,"L",a+c*0.2,b,a+c*0.8,b,a+c*0.8,b+d*0.4,"Z","M",a+c*0.2,b+d*0.7,"L",a,b+d,a+
  square: function (a,b,c,d){return["M",a,b,"L",a+c,b,a+c,b+d,a,b+d,"Z"]}
  triangle: function (a,b,c,d){return["M",a+c/2,b,"L",a+c,b+d,a,b+d,"Z"]}
  triangle-down: function (a,b,c,d){return["M",a,b,"L",a+c,b,a+c/2,b+d,"Z"]}

You can also add your own symbol by extending the collection.  For example, drawing a simple X:
$.extend(Highcharts.Renderer.prototype.symbols, {
    anX: function (a,b,c,d){return["M",a,b,"L",a+c,b+d,"M",a+c,b,"L",a,b+d]}
});

Produces:

Fiddle here.


text:
Q: How to enable CORS for asp.net mvc web site? I want to enable CORS for an action in my asp.net mvc 4 web site.
This is possible for web api
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Is there a similar solution for mvc web site?
I also want to be able to restrict this for origin web sites I want.
Thanks

A: i think you need to create your Custom authorization Like this:
/// <summary>
/// Referrer Url Custom Authorize
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class ReferrerUrlAuthorize : AuthorizeAttribute
{
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        IList<string> webSitesAllowed = new List<string>() { "http://mywebsite.com", "http://customersite.com" };
        string urlReferrer = System.Web.HttpContext.Current.Request.UrlReferrer.AbsoluteUri;

        //checking if the referrer url exists in your list of sites allowed
        if (!webSitesAllowed.Contains(urlReferrer))
            return false;  //access denied
        return true;
    }
}

and in your controller class must be set the ReferrerUrlAuthorize
   [ReferrerUrlAuthorize]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Title = "Home Page";

        return View();
    }
}


text:
Q: Insert values in specific position of array javascript First I am creating an array with an specific size.
$("#bntSize").one('click', function(e){
          var memoria = $("#memoria").val();
          console.log(memoria)

          html = "";

          for(var i = 0; i < memoria ; i++){
               html += "
"+i+"
";
               arrayMemoria.push('');
          }
          console.log(arrayMemoria)
          $("#contenedor").html(html);

        });

If memoria is equal to 7 I am getting this:
["", "", "", "", "", "", ""]

Now I am giving some values to the array:
var nada = 0;

function firstFit(){

          var cantidad = $("#ffinput").val();
          var value = $("#ffinput2").val();
          /*console.log(cantidad)*/

         if(nada == 0){
            for (nada ; nada < cantidad ; nada++) {
                arrayMemoria.splice(nada , 1 , value);
                nada = nada;
            }
         }
         else{

            for (nada; nada < arrayMemoria.length ; nada++) {
                arrayMemoria.splice(nada , 1 , value);
                nada = nada;
            }
         }

Here cantidad: how many spaces I am suppose to use in array & value: just a value.
So if I put => cantidad = 3 and value = A
["A", "A", "A", "", "", "", ""]

Then if I want to put => cantidad = 2 and value = B
["A", "A", "A", "B", "B", "B", "B"]

But I am trying to get this:
["A", "A", "A", "B", "B", "", ""]

and if I put => cantidad = 1 and value = C
["A", "A", "A", "B", "B", "C", ""]

And my second problem
If I do remove the values equals to A and I am inserting => cantidad = 2 AND VALUE = D
I am suppose to get this:
["D", "D", "", "B", "B", "C", ""]

How to count the available space in my array? cause if I want to insert
cantidad = 1 and value = E , I need to get the first available space
["D", "D", "E", "B", "B", "C", ""]

If someone can help me please!!

A: You can try the following code

 var arr = ["", "", "", "", "", "", ""];
    arr = insertValue(3, "A", arr);
    console.log(arr);
    arr = insertValue(2, "B", arr);
    console.log(arr);
    arr = insertValue(1, "C", arr);
    console.log(arr)
    arr = removeValue("A", arr);
    console.log(arr)
    arr = insertValue(2, "D", arr);
    console.log(arr)

 function insertValue(cantidad, value, arr){
  var arrLength = arr.length;
  var count = 0;
  for (var i = 0; i < arrLength; i++) {
   if(arr[i] == "" && count < cantidad){
    arr[i] = value;
    count ++;
   }
  };
      return arr;
 }

 function removeValue(value, arr){
  var arrLength = arr.length;
  for (var i = 0; i < arrLength; i++) {
   if(arr[i] == value){
    arr[i] = "";
   }
  };
      return arr;
 }

EDIT: To get the number of spaces in the array

var arr = ["A", "A", " " , " ", " " , "B" ,"C " , " "];
var  spaceCount = 0;

arr.forEach(function(i) { if(i == " ") spaceCount++;  });
console.log(spaceCount)

EDIT 2: To count consecutive spaces in an array

var arr = ["A", "A", " " , " ", " " , "B"," ", " " ,"C " , " "];
var count = 1;
var countArr = [];

for (var i = 0; i < arr.length; i++) {
 if(arr[i] == " "){
  if(arr[i+1] == arr[i]){
   count ++;
  }else {
   countArr.push(count);
   count = 1;
  }
 }
};

console.log(countArr)

EDIT 3: To get consecutive space count + starting position

var arr = [" ", "A", "A", " " , " ", " " , "B"," ", " " ,"C " , " "];
var count = 1;
var countArr = [];

var pos = 0;

for (var i = 0; i < arr.length; i++) {
 if(arr[i] == " "){
  if(arr[i] === arr[i+1]){
   count ++;
  }else {
   countArr.push({'pos': pos, 'count': count});
   count = 1;
  }
 }else{
  pos = i+1;
 }
};

console.log(countArr)

A:

  var array = ["A", "", "", "", "B", "B", "B"];

  var cantidad = 2;
  for (var x = 0; x < array.length; x++) {
    if (array[x] === "") {
      if (cantidad >0){
        array.splice(x, 1, "C");
        cantidad--;
      }
    }
  }

  function codeAddress() {
    alert(array);
  }

  window.onload = codeAddress;

Here's a solution, I realized you can solve this problem in a lot of different ways, mine is not necessarily the best approach.
Good luck.

A: EDIT: This is a working solution for both questions.

var array = ["","","","","","",""];

function addValues(num, value) {
    for(var i=0; i<num; i++) {
        for(var j=0; j<array.length; j++){
            if(array[j] ==="") {
                array[j] = value;
                break;
            }
        }
    }
}

function removeValues(value) {
    for(var i=0; i<array.length; i++) {
        if(array.indexOf(value) !== -1) {
            array[i] = "";
        }
    }

}
addValues(3, 'A');
addValues(2, 'B');
addValues(1, 'C');

removeValues('A');

addValues(2, 'D');
addValues(2, 'E');

console.log(array);


text:
Q: Averaging numbers in list Find 5 numbers
Find average of numbers
#import statistics
print("enter 5#s")
num1 = int(input())
num2 = int(input())
num3 = int(input())
num4 = int(input())
num5 = int(input())
numbers = [num1, num2, num3, num4, num5]
numsum = sum(numbers)
print("sum is:", numsum)
#Above list is working
#fix below
def Average(numbers):
    return sum(numbers) / len(numbers)
print("AVG = ", round(Average, 2))

error
traceback (most recent call last):
file "main.py", line 15 in
print("AVG = ", round(Average, 2))
TypeError: type function dosent define_round_method

A: You need to add an extra line at the end, which should be:
Average(numbers)

A: The last line (the call to print)
def Average(numbers):
    return sum(numbers) / len (numbers)
    print("AVG = ", round(Average, 2))

needs to be un-indented (moved to the left, outside of the function) and the function needs to be called with numbers as its argument, like this:
def Average(numbers):
    return sum(numbers) / len (numbers)
print("AVG = ", round(Average(numbers), 2))

Your code could be simplified and improved, maybe like this:
num_list = []
for i in range(5):
    s = input('Enter the {}. number: '.format(i+1))
    n = int(s)
    num_list.append(n)

the_sum = sum(num_list)
print('Sum:', the_sum)

the_avg = round(the_sum / len(num_list), 2)
print('Avg:', the_avg)

Sample run:
Enter the 1. number: 7
Enter the 2. number: 5
Enter the 3. number: 4
Enter the 4. number: 4
Enter the 5. number: 4
Sum: 24
Avg: 4.8


text:
Q: Finding the Möbius transformation when $z= \infty$ The following is available:
$ T(2i) = \infty $
$ T(0) = -i $
$ T(\infty) = i $
So I've got:
$ \frac{a(2i)+b}{c(2i)+d} = \infty \Rightarrow d=-2ic $
$ \frac{b}{d}=i \Rightarrow b = -2c $
$ \frac{a \cdot \infty -2c}{c \cdot \infty + -2ic} = i $
how do I continue when infinity is the argument?

A: Note that$$\lim_{z\to\infty}\frac{az+b}{cz+d}=\lim_{w\to0}\frac{a/w+b}{c/w+d}=\lim_{w\to0}\frac{bw+a}{dw+c}=\frac{a}{c}$$provided $c\ne0$. If $c=0\ne a$, the limit is $\lim_{z\to\infty}\frac{az+b}{d}=\infty$. We don't need to consider the case $a=c=0$, because Möbius transformations satisfy $ad-bc\ne0$.

A: We begin with the Ansatz
$$T(z)={az+b\over cz+d}\ ,$$
noting that the coefficients are only determined up to a common $\ne0$ factor, and that there are certain exception rules concerning $\infty$.
Since $T(2i)=\infty$ we conclude that $c\cdot2i+d=0$, hence $d=-2i c$. We  are now at
$$T(z)={az+b\over c(z-2i)}\ .$$
This shows that $c\ne0$, and that we may as well assume $c=1$. We are now at
$$T(z)={az+b\over z-2i}\ .$$
It follows that
$$a=\lim_{z\to\infty}{az+b\over z-2i}=T(\infty)=i\ ,$$
so that we arrive at
$$T(z)={iz+b\over z-2i}\ .$$
The condition $T(0)=-i$ then leads to $b=2$, so that we finally have
$$T(z)={iz+2\over z-2i}\ .$$


text:
Q: Is it true that $A \geq B$ implies $\|A\|_2 \geq \|B\|_2$ for $A,B \geq 0$? All matrices are real and not necessarily symmetric. Denote by $A \geq B$ the condition that $(A-B)$ has eigenvalues with non-negative real parts. Denote by $\| \cdot \|_2$ the $L_2$ matrix norm.
Is it true that $A \geq B$ implies $\|A\|_2 \geq \|B\|_2$ for $A,B \geq 0$?

Edit: Now I see it doesn't hold in general, I would also be grateful if someone could provide additional conditions on $A$ and $B$ for which $\|A\|_2 \geq \|B\|_2$ would hold.
I am particularly interested in whether the statement can still be rescued the following cases:

*

*$A,B$ symmetric.

*$A = \Xi$, $B = \Xi P$ where $P$ is a stochastic matrix (rows sum to 1) and $\Xi$ a diagonal matrix with the principal left eigenvector of $P$ (i.e. stationary distribution) on the diagonal.

A: Not necessarily.  For example, we can take
$$
A = \pmatrix{1&0\\0&1}, \quad B = \pmatrix{1&1\\0&1}
$$
the only eigenvalue of $A-B$ is $0$, so $A \geq B$.  However, $\|A\|_2 = 1 < \|B\|_2$.

Regarding your update: when $A,B$ are symmetric, this amounts to showing that if $A,B,$ and $A-B$ are positive semidefinite, then $\|A\|_2 \geq \|B\|_2$.
Note that
$$
\|B\|_2 = \sup_{\|x\| = 1}x^*Bx \leq
\sup_{\|x\| = 1}\left(x^*Bx + x^*(A-B)x\right) = \sup_{\|x\| = 1}x^*Ax = \|A\|_2
$$


text:
Q: How is the number of successful packets through a network calculated based on the probability of a successful transmission? Trying to intuitively understand this:
If I have $N$ packets flowing through a network, and the probability of a packet being successfully transmitted is $p$, how is the total number of packets that successfully went through $S$ equal $Np$ ?
The reason I have trouble understanding this is, assume $p=10\%$. If I send $10$ packets through a network, it doesn't necessarily mean I get only $Np=10×10\%=1$ packet to transmit successfully right? Couldn't I potentially get more than one packet to successfully transmit?
I came across this reasoning from Computer Networks 5th edition.
Here's an excerpt from the book:

Under all loads, the throughput, $S$, is just the offered
load, $G$, times the probability, $P_0$, of a transmission succeeding—that is, $S=GP_0$, where $P_0$ is the probability that a frame does not suffer a collision.

A: "Expected" is implied before "throughput" here – and I don't think this is a justified elision. There may be $2$ or $0$ or even $10$ packets that went through in a transmission of $10$ packets with $p=10\%$, but in the long run you would expect $1$ in $10$ packets to go through.

A: If you're carrying out $N$  transmissions, each of which is a bernoulli trial with success probability of $p$,
the distribution of number of successful transmissions is
the binomial $(N, p)$ distribution.
The "expected value" (i.e. the average) of this distribution is $Np$, which is what the textbook claims.


text:
Q: Determine what version of NDK was used to build library? Is there any way to determine what version of the NDK was used to compile an "aar" library?  Either decompiling, or via code would be fine, just need to know.
I am trying to determine what version of the ndk one of my third party libraries was built using.

A: An "aar" file is not compiled with NDK, you probably mean one of the c++ libraries inside that file. There is no simple way, but you can rule out new ndk versions according to the library date.
Also, you might be able to find out by getting the compiler version - see if something like this can help: How to retrieve the GCC version used to compile a given ELF executable


text:
Q: Storing Variables in ForEach Loop I have a large dataset of seasonal ratings for many pieces of equipment.  Each piece of equipment currently has 3 data objects, in order: Summer>Winter>(Spring & Fall).  I want to condense this so each piece of equipment only has one line of ratings.
$Equipment|%{if($_.C100_SP -match "Winter"){$aW=$_.A100_SU,$bW=$_.B100_SU,$cW=$_.C100_SU}elseif($_.C100_SP -match "Summer"){$aS=$_.A100_SU,$bS=$_.B100_SU,$cS=$_.C100_SU}elseif($_.C100_SP -match "Spring"){$_.A100_SP=$_.A100_F=$_.A100_SU;$_.B100_SP=$_.B100_F=$_.B100_SU;$_.C100_SP=$_.C100_F=$_.C100_SU;$_.A100_SU=$aS;$_.B100_SU=$bS;$_.C100_SU=$cS;$_.A100_W=$aW;$_.B100_W=$bW;$_.C100_W=$cW;$_.A='x'}}|Where-Object{$_.A -eq 'x'}

This code attempts to store the summer and winter ratings as variables ($aW, $bS, etc.), insert them into the spring record, then filter so only the filled out records are left.  However, the winter and fall variables keep passing $null to the output, along with 9999, a common placeholder in this dataset.
A100_SP    : 4219
B100_SP    : 4219
C100_SP    : 9999
A100_SU    : {9999, $null}
B100_SU    :
C100_SU    :
A100_F     : 4219
B100_F     : 4219
C100_F     : 9999
A100_W     : {9999, $null}
B100_W     :
C100_W     :

The Spring and fall values are working, which makes me think this is a problem with storing variables between iterations, but I can't find much help on the web.
Any ideas how to get those variables to stay put?

A: *

*The wrong statement separation in the first if clause: ,. It should be ;

*Nothing was pushed down the pipeline: there should be $_ at the end of Spring case.

*Instead of Where simply don't output anything to the pipeline in Winter and Summer .

$Equipment | %{
    switch -regex ($_.C100_SP) {
        "Winter" {
            $aW = $_.A100_SU
            $bW = $_.B100_SU
            $cW = $_.C100_SU
            break
        }
        "Summer" {
            $aS = $_.A100_SU
            $bS = $_.B100_SU
            $cS = $_.C100_SU
            break
        }
        "Spring" {
            $_.A100_SP = $_.A100_F = $_.A100_SU
            $_.B100_SP = $_.B100_F = $_.B100_SU
            $_.C100_SP = $_.C100_F = $_.C100_SU
            $_.A100_SU = $aS
            $_.B100_SU = $bS
            $_.C100_SU = $cS
            $_.A100_W = $aW
            $_.B100_W = $bW
            $_.C100_W = $cW
            $_
        }
    }
}

P.S. Don't use one-liners if you can't write them with your eyes closed :-)


text:
Q: handling for loop exceptions a = 6
item_list = [1,2,3,4,5]
for items in item_list:
    if items == a:
        print("match found")
    else:
        print ("no match")

In this code I want "no match" to be printed only once after completing all the iterations; not on every iteration. How can I modify the code?

A: Use instead:
a = 6
item_list = [1,2,3,4,5]
if a in item_list:
    print("match found")
else:
    print ("no match")

No need to iterate list by yourself, use built-in method.

A: As others have pointed out, the most efficient solution in this situation is to use an in test, and no explicit loop is needed.
However, in a more general situation where one is looping until a match is found (if more complex logic means that there is no simple equivalent of in available), it is worth remembering that a for loop can have an else block which is run after the loop completes if it is has not been exited using break.  Taking this code as an example (even though not necessary in this situation), you could do:
a = 6
item_list = [1,2,3,4,5]
for item in item_list:
    if item == a:
        print("match found")
        break
else:
    print ("no match")

Note that this is not exactly equivalent to the code in the question if more than one match is found, as here "match found" is only printed once and then the loop is exited via break.  If you were looking for potentially more than one match, for example saving these to a list, then you would not use break and else, but would instead test afterwards whether your output list was empty before printing "no match".

A: Instead of looping through, you can use index on list or using in operator
In [39]: a = 6
    ...: item_list = [1,2,3,4,5]

In [40]: try:
    ...:     index = item_list.index(a)
    ...:     print("match found")
    ...: except:
    ...:     print("no match")
    ...:
no match

In [41]: if a in item_list:
    ...:     print("match found")
    ...: else:
    ...:     print("no match")
    ...:
no match

A: a in b is generally a better solution, but if you want to loop through the entire list you could create a variable to store
matches in and check if the variable is populated when the for-loop expires.
a = 6
memory = []
item_list = [1,2,3,4,5]
for items in item_list:
    if items == a:
         memory.append(a)
         print("match found")
if len(memory) == 0:
    print("No matches")

a is never gonna show up in the loop since you're only looping over elements in item_list, fyi

A: a = 6
item_list = [1,2,3,4,5]
found_in_list_boolean = False

for items in item_list:
    if items == a:
        print("match found")
        '''Set the boolean to True as you reached the match found statement '''
        found_in_list_boolean = True

'''2 ways from here'''

'''First Way : If found_in_list_boolean is true print something and for false print not found'''
if (found_in_list_boolean):
    print("Found")
else:
    print("not found")

'''Second Way :If found_in_list_boolean is false and print'''
if (found_in_list_boolean==False):
    print("not Found")

A: You could use a while loop:
a = 6
item_list = [1, 2, 3, 4, 5]
i = 0
found = False
while True:
    i += 1
    if item_list[i] == 6:
        print("Found")
        found = True
    if i > len(item_list):
        break
if not found:
    print("Not found")

Note that 6 is not in the list, so it will print "Not found"


text:
Q: Flattening a list recursively - why doesn't my code return what I want? Question: Write a recursive function, flattenList, where flattenList([2, 9, [2, 1, 13, 2], 8, [2, 6]]), will return a list [2, 9, 2, 1, 13, 2, 8, 2, 6].
My code:
def flattenList(lis):
    a = []
    for i in lis:
        if not isinstance(i, list):
            a.append(i)
        else:
            flattenList(i)
    return a

print(flattenList([2, 9, [2, 1, 13, 2], 8, [2, 6]]))

While the desired output is [2, 9, 2, 1, 13, 2, 8, 2, 6], I'm getting [2, 9, 8] (numbers not in sublists).

A: You need to add a.extend(flattenList(i)). You're currently doing nothing with the recursive return.

A: Your recursive call doesn't add the data to the result list. So this:
flattenList(i)

should be:
a += flattenList(i)

A: You can make the function a generator and use the yield from syntax in python3:
def flattenList(lis):
    for i in lis:
        if not isinstance(i, list):
            yield i
        else:
            yield from flattenList(i)

print(list(flattenList([2, 9, [2, 1, 13, 2], 8, [2, 6]])))
[2, 9, 2, 1, 13, 2, 8, 2, 6]


text:
Q: Kill processes by name I have got python http server. OS - ubuntu server 12.04. Some time i need to kill all python http processes. I use this command
sudo killall python

But it kills all python processes. Is it possible to kill all processes with name 'python server.py'?

A: Use pkill -f instead:
pkill -f 'python server.py'

A: pkill -f 'python3 -m http.server 8000' if one is using the http.server module in python3, and the default port
pgrep -a python will list all python and the individual names required to distinguish.


text:
Q: C++ asynchronous network programming I have some simple questions, I have a client-server application and data sent on the wire.
I'd like to be able to recover the data and handle it properly.
struct T1
{
   int id;
   int foo;
};

struct T2
{
  int id;
  char foo;
  int bar;
};

Let's take these structures, they are sent on the network preceded by an int which will tell if either T1 or T2 follows.
If the client sends me T1, then sends me T2, do I have the assurance that I can read a full structure with asio::ip::tcp::socket.async_read() ?
I'd like to set up a handler which will handle a single struct, however what will happen if I'm unable to read everything in a single async_read() ?

The asynchronous operation will
  continue until one of the following
  conditions is true:

*

*The supplied buffers are full. That is, the bytes transferred is equal to the sum of the buffer sizes.

*An error occurred.

Will it discard the data that cannot be read ? will it trigger another async_read ?
And, am I assured that an async_read will only get one ID+structure if my client sends me sequentially the ID+structure ? Or may the OS optimize things and put them both in the same paquet ?
As you may have seen, I'm a little confused, I'd like to make the right decisions when designing a server/client application, any help will be appreciated.
Thank you.

A: EDIT: Thanks to @timo for pointing out a mistake. async_read won't complete until an entire struct is read, so you don't need to loop. Otherwise, my answer is the same. Nothing will be lost, regardless of how the TCP protocol breaks up or coalesces the data.
If there isn't enough data in the TCP buffers to fill your input buffer, the read will simply fetch whatever is available, and report the number of bytes fetched. What happens next is up to you. You might have enough data in the fetched bytes to decide you don't want to continue, so asio makes no assumptions. If you haven't read enough bytes to comprise a complete structure, then initiate a further async_read, repeating the process until you have enough bytes or something dies.
I'm not sure what you mean by, "unable to read everything." two possible meanings come to mind:

*

*The amount of data that's available to read doesn't fill a struct. In this case, you simply do another read_async to wait for more data to arrive.

*The struct doesn't absorb all that data that has arrived. The TCP stack will simply buffer unread data until you get around to reading it.


text:
Q: AWS EIP Unattached but still billed I have checked AWS Billing and I am being billed for an Idle EIP address.
I recently had a non-default VPC with NAT Gateway and VPC that I created.
However I deleted all the resources and the VPC.
When I check under the Elastic IP section in the VPC and EC2 services in the Management Console there are no EIPs showing.
Any advice on how I can resolve this please? There is no resource showing in the CSV file.
Service, Operation, UsageType, Resource, StartTime, EndTime, UsageValue
AmazonEC2,AssociateAddressVPC,EU-ElasticIP:IdleAddress,,05/01/20 00:00:00,05/01/20 01:00:00,1
Thanks

A: As per aws.
An Elastic IP address doesn't incur charges as long as the following conditions are true:

*

*The Elastic IP address is associated with an EC2 instance.

*The instance associated with the Elastic IP address is running.

*The instance has only one Elastic IP address attached to it.

You can check the Elastic IP resource under EC2 and release the EIP

A: As stated the EIP was not showing in the AWS Management Console. Using the CLI I could see the EIP and release it.
$ aws ec2 describe-addresses
{
    "Addresses": [
        {
            "PublicIp": "XX.XX.XXX.XXX",
            "AllocationId": "eipalloc-085acf12e1abb0847",
            "Domain": "vpc",
            "PublicIpv4Pool": "amazon",
            "NetworkBorderGroup": "eu-west-1"
        }
    ]
}

$ aws ec2 release-address --allocation-id eipalloc-085acf12e1abb0847


text:
Q: MS Access VBA - Custom Column is ListBox (using a value from another column coming from a table) Hello Stackoverflow community!
My question is in reguards to creating a custom column within a list box that is pulling from a table using SQL. Refering to the code and picture of the current list below, I want to create a custom column that is not stored in a table, that will be called "DaysActive" and will take todays date minus the StatusEffect Date for each individual record displayed and give the number of days in its own column, say between StatusEffect and Yr. Is this possible? Thank you in advance for taking the time to read through this.
Private Sub Form_Load()

DoCmd.RunCommand acCmdWindowHide

Dim rs As Recordset
Dim strSQL As String
Dim lstnum

strSQL = "SELECT LastName, FirstName, Status, StatusEffect, Yr, Make, Model, VIN, Deduction, USLicense, RegistrationState, Dependents,Notes, ID FROM InsuranceTable" & _
"WHERE SentRegistration = False And Status IN ('active','add') Order By StatusEffect Desc "

Set rs = CurrentDb.OpenRecordset(strSQL, dbOpenSnapshot)
Set Me.lstInfo.Recordset = rs

lstnum = [lstInfo].[ListCount]
Me.lstcount.Value = lstnum - 1
End Sub

Link to picture of my current list since I do not have enough rep points to embed it ;/

A: Use the DateDiff() function in your SQL.
DateDiff('d') returns the difference in days.
SELECT ..., StatusEffect, DateDiff('d',[StatusEffect],Date()) AS DaysActive, Yr, ...


text:
Q: Getting only sub in UserInfoEndpoint I am just following what is on the guide
I've already populated the user's profile information but so far I only get sub. I want to get something same like in the guide:
{
   "sub":"admin",
   "email":"admin@wso2.com",
   "website":"https://wso2.com",
   "name":"admin",
   "family_name":"admin",
   "preferred_username":"admin",
   "given_name":"admin",
   "profile":"https://wso2.com",
   "country":"Sri Lanka"
}

CONFIG
Identity Server - AWS Cloud with Domain and SSL + Nginx Proxy
Sample Web App - local machine

UPDATE:

*

*It is an open bug. What
is the workaround to get the other fields? Based on that jira, only
the password grant is not fix, where to get the fix for code and
impilict grant?

*I tried hosting the IS also locally, same results

A: To retrieve OIDC claim attributes to id_token or userinfo endpoint, the following steps needs to be done correctly(assuming you are working on IS 5.2.0).
1. Update relevant claims' Mapped Attribute with your underlying user store's matching attributes.
2. Update requested claims to Service provider [1].
3. Update missing attributes in '/_system/config/oidc' for scope 'openid' (Configuration changes in IS 5.2.0 [2]).


text:
Q: How to uninstall a software that has been installed using wine? I have installed Ms Office 7 using wine, I need to install office 10.
can someone tell me how can i uninstall office 7?

A: You can use Uninstaller.

Uninstaller is a GUI uninstaller for all setup programs that put an
  uninstall entry in the registry, e.g. InstallShield or the WISE
  installer. It's similar in function to "Add/Remove Programs" in
  Windows, except much simpler.
An actual Add/Remove Programs control panel applet (appwiz.cpl) was
  added to Wine 1.1.2, and the existing uninstaller was replaced with a
  stub to launch this control panel in Wine 1.1.3.
The uninstaller does not work with programs installed with an .msi
  file.
 wine uninstaller

For versions of Wine before 1.1.16 (which includes 1.0.x), you can
  also use the wrapper in /usr/bin/:
uninstaller1

1Source:WineHQ

A: I think there is uninstall.exe (or something like this of installed program). Open it via wine and run it. I think this will works.

A: Run below command:
wine uninstaller


text:
Q: PHP web site that restricted access to specific country Since IP can be spoofed, how can one build a PHP website that correctly identifies the visitor's country?

A: That's inherently a problem given the anonymity of the internet, but spoofing IP addresses to obtain content not legally available in your country is technically a crime in most places anyways.
It's up to you to make every reasonable effort to ensure your site follows distribution restrictions on media and information, but there are some things that are just impractical to guard against. The closest you could get is by doing an actual physical address verification such as a billing address on a credit card or physically mailing someone a pin number for registration, but both of those options incur expenses on behalf of either the user or yourself.

A: Joomla has been using below function to get IP addresses, it is very versatile good function, that can avoid possible cheats, you can use it:
function get_ip()
{
    $ip = false;

    if (!empty($_SERVER['HTTP_CLIENT_IP']))
    {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }

    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
         $ips = explode (', ', $_SERVER['HTTP_X_FORWARDED_FOR']);

         if ($ip != false)
         {
              array_unshift($ips,$ip);
              $ip = false;
         }

         $count = count($ips);

         # exclude IP addresses reserved for LANs
         for ($i = 0; $i < $count; $i++)
         {
              if (!preg_match("/^(10|172\.16|192\.168)\./i", $ips[$i]))
              {
                  $ip = $ips[$i];
                  break;
              }
         }
    }

    if (false == $ip AND isset($_SERVER['REMOTE_ADDR']))
    {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return $ip;
}


text:
Q: Updating properties of a class c# I have the following POCO in my project:
 public class FileTranslationData
{
    public string Id { get; set; }
    public string FileLocation { get; set; }
    public string FileJSONLocation { get; set; }
    public int TranslationRetries { get; set; }
    public string TranslationStatus { get; set; }
    public string TranslationId { get; set; }
    public string FileTranslationURL { get; set; }
    public string TranslatedFileURL { get; set; }
    public string ProcessStatus { get; set; }
    public int FileDownLoadRetries { get; set; }
    public int FileUploadRetries { get; set; }
    public int RetryDuration { get; set; }
    public string Errors { get; set; }
    public DateTime LastRetryTime { get; set; }
    public string StatusLog { get; set; }
}

Which I use to save data to and from a LiteDB to help maintain state of file progression through my process.  If I need to update certain properties of this class, I retrieve it from the database, make the changes and then resave to the database, no problem.  I use this class to detect changes in the object (pulled and modified from another answer):
 public static List<string> GetChangeProperties<T>(T a, T b) where T:class
    {
       if(a != null && b != null)
        {
            if(object.Equals(a,b))
            {
                return new List<string>();
            }
            var allProperties = a.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            return allProperties.Where(p => !object.Equals(p.GetValue(a), p.GetValue(b))).Select(p => p.Name).ToList();
        }
        else
        {
            var aText = $"{(a == null ? ("\"" + nameof(a) + "\"" + " was null") : "")}";
            var bText = $"{(b == null ? ("\"" + nameof(b) + "\"" + " was null") : "")}";
            var bothNull = !string.IsNullOrEmpty(aText) && !string.IsNullOrEmpty(bText);
            throw new ArgumentNullException(aText + (bothNull ? ", " : "") + bText);
        }
    }

This will return a list of properties that have changed between the objects. Once I have the list of changed properties, I only want to update the properties in the first object that have changed based on the 2nd object before re-saving the update back to the database.  I'm looking for help on a better way of changing the properties than using a switch statement and checking all the properties if they are different and only changing the properties that have changed.
Thanks.


text:
Q: python&unity3d: Websocket stability I'm creating an application in Unity3d that communicates with python's websockets library. My python script is as following:
from __future__ import division
import asyncio
import websockets
import time
import os
from threading import Thread
from random import randint
from read import CustOPCLib
import socket
from jsonsocket import Client,Server

class SubHandler(object):
    def data_change(self, handle, node, val, attr):
        print("Python: New data change event", handle, node, val, attr)

    def datachange_notification(self, node, val, data):
        print("Data received: ",val)

    def event(self, handle, event):
        print("Python: New event", handle, event)

p = CustOPCLib()
async def hello(websocket, path):
    p.connect() #my own custom library
    while True:
        datastring = p.opcjson()             #this is a jsonstring
        await websocket.send(datastring)
        #print("> {}".format(datastring))
        time.sleep(1)

if __name__ == '__main__':
    start_server = websockets.serve(hello, '127.0.0.1', 8765)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

my json string is as following:
{
    "Index": 709953575,
    "Moto": true,
    "Start": false,
    "StartWINCC": false,
    "Stop": false,
    "StopWINCC": false,
    "Tag1": true,
    "Tag2": false
}

This is the string i want to send to Unity. In Unity3d I've made the following script that used the Concurrentqueue from mono. The script works accordingly, the problem i have however, is that i get alot of null values from the websocket.
my Unity3d script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading;

public class ConcurrentQueue<T> : IEnumerable<T>, ICollection, ISerializable, IDeserializationCallback
{
    class Node
    {
        public T Value;
        public Node Next;
    }

    Node _head = new Node();
    Node _tail;
    int _count;

    /// <summary>
    /// </summary>
    public ConcurrentQueue()
    {
        _tail = _head;
    }

    public ConcurrentQueue(IEnumerable<T> enumerable)
        : this()
    {
        foreach (T item in enumerable)
            Enqueue(item);
    }

    public void Enqueue(T item)
    {
        var node = new Node { Value = item };

        Node oldTail = null;

        bool update = false;
        while (!update)
        {
            oldTail = _tail;
            var oldNext = oldTail.Next;

            // Did tail was already updated ?
            if (_tail == oldTail)
            {
                if (oldNext == null)
                {
                    // The place is for us
                    update = Interlocked.CompareExchange(ref _tail.Next, node, null) == null;
                }
                else
                {
                    // another Thread already used the place so give him a hand by putting tail where it should be
                    Interlocked.CompareExchange(ref _tail, oldNext, oldTail);
                }
            }
        }
        // At this point we added correctly our node, now we have to update tail. If it fails then it will be done by another thread
        Interlocked.CompareExchange(ref _tail, node, oldTail);

        Interlocked.Increment(ref _count);
    }

    /// <summary>
    /// </summary>
    /// <returns></returns>
    public bool TryDequeue(out T value)
    {
        value = default(T);
        bool advanced = false;
        while (!advanced)
        {
            Node oldHead = _head;
            Node oldTail = _tail;
            Node oldNext = oldHead.Next;

            if (oldHead == _head)
            {
                // Empty case ?
                if (oldHead == oldTail)
                {
                    // This should be false then
                    if (oldNext != null)
                    {
                        // If not then the linked list is mal formed, update tail
                        Interlocked.CompareExchange(ref _tail, oldNext, oldTail);
                    }
                    value = default(T);
                    return false;
                }
                else
                {
                    value = oldNext.Value;
                    advanced = Interlocked.CompareExchange(ref _head, oldNext, oldHead) == oldHead;
                }
            }
        }

        Interlocked.Decrement(ref _count);
        return true;
    }

    /// <summary>
    /// </summary>
    /// <returns></returns>
    public bool TryPeek(out T value)
    {
        if (IsEmpty)
        {
            value = default(T);
            return false;
        }

        Node first = _head.Next;
        value = first.Value;
        return true;
    }

    public void Clear()
    {
        _count = 0;
        _tail = _head = new Node();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return InternalGetEnumerator();
    }

    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return InternalGetEnumerator();
    }

    public IEnumerator<T> GetEnumerator()
    {
        return InternalGetEnumerator();
    }

    IEnumerator<T> InternalGetEnumerator()
    {
        Node myHead = _head;
        while ((myHead = myHead.Next) != null)
        {
            yield return myHead.Value;
        }
    }

    void ICollection.CopyTo(Array array, int index)
    {
        T[] dest = array as T[];
        if (dest == null)
            return;
        CopyTo(dest, index);
    }

    public void CopyTo(T[] dest, int index)
    {
        IEnumerator<T> e = InternalGetEnumerator();
        int i = index;
        while (e.MoveNext())
        {
            dest[i++] = e.Current;
        }
    }

    public T[] ToArray()
    {
        T[] dest = new T[_count];
        CopyTo(dest, 0);
        return dest;
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        throw new NotImplementedException();
    }

    bool ICollection.IsSynchronized
    {
        get { return true; }
    }

    public void OnDeserialization(object sender)
    {
        throw new NotImplementedException();
    }

    readonly object _syncRoot = new object();
    object ICollection.SyncRoot
    {
        get { return _syncRoot; }
    }

    public int Count
    {
        get
        {
            return _count;
        }
    }

    public bool IsEmpty
    {
        get
        {
            return _count == 0;
        }
    }
}

public class test : MonoBehaviour
{
    class OpcJson
    {
        public int Index { get; set; }
        public bool Moto { get; set; }
        public bool Start { get; set; }
        public bool StartWINCC { get; set; }
        public bool Stop { get; set; }
        public bool StopWINCC { get; set; }
        public bool Tag1 { get; set; }
        public bool Tag2 { get; set; }
    }
    //variables
    static readonly ConcurrentQueue<string> queue = new ConcurrentQueue<string>();
    public string receivedFromServer;
    WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:8765"));
    public Text testert;
    public Image moto;
    public Image start;
    public Image startwincc;
    public Image stop;
    public Image stopwincc;
    public Image tag1;
    public Image tag2;
    // Use this for initialization
    IEnumerator StartWebsocket()
    {
        yield return StartCoroutine(w.Connect());
        //w.SendString("Hi there");
        //int i = 0;
        while (true)
        {
            string reply = w.RecvString();
            if (reply != null)
            {
                //Debug.Log(reply);
                queue.Enqueue(reply);
                //receivedFromServer = reply;
                //Debug.Log("Received: " + reply);
                //w.SendString("Hi there" + i++);
            }
            if (w.error != null)
            {
                Debug.LogError("Error: " + w.error);
                break;
            }
            yield return 0;
        }
        w.Close();
    }
    private void OnApplicationQuit()
    {
        StopAllCoroutines();
        w.Close();
    }
    IEnumerator JsonObjectSetter(float waitforsecods)
    {
        while (true)
        {
            queue.TryDequeue(out receivedFromServer);
            //string s = receivedFromServer;
            //Debug.Log(s);
            if(receivedFromServer == null)
            {
                Debug.Log("I'm null");
            }
            else
            {
                var results = JsonConvert.DeserializeObject<OpcJson>(receivedFromServer);
                testert.text = results.Index.ToString();
                if (results.Moto == true)
                {
                    moto.GetComponent<Image>().color = Color.green;
                }
                else
                {
                    moto.GetComponent<Image>().color = Color.red;
                }

                if (results.Start == true)
                {
                    start.GetComponent<Image>().color = Color.green;
                }
                else
                {
                    start.GetComponent<Image>().color = Color.red;
                }

                if (results.StartWINCC == true)
                {
                    startwincc.GetComponent<Image>().color = Color.green;
                }
                else
                {
                    startwincc.GetComponent<Image>().color = Color.red;
                }

                if (results.Stop == true)
                {
                    stop.GetComponent<Image>().color = Color.green;
                }
                else
                {
                    stop.GetComponent<Image>().color = Color.red;
                }

                if (results.StopWINCC == true)
                {
                    stopwincc.GetComponent<Image>().color = Color.green;
                }
                else
                {
                    stopwincc.GetComponent<Image>().color = Color.red;
                }

                if (results.Tag1 == true)
                {
                    tag1.GetComponent<Image>().color = Color.green;
                }
                else
                {
                    tag1.GetComponent<Image>().color = Color.red;
                }

                if (results.Tag2 == true)
                {
                    tag2.GetComponent<Image>().color = Color.green;
                }
                else
                {
                    tag2.GetComponent<Image>().color = Color.red;
                }
            }
            yield return new WaitForSeconds(waitforsecods);
        }
    }
    private void Start()
    {
        StartCoroutine(StartWebsocket());
        StartCoroutine(JsonObjectSetter(1));
    }
}

as you can see, I've made an if/else statement in my JsonObjectSetter method. Everytime the string is null after a dequeue, it prints out "I'm null", and if its not null, it gets used to set an image to a color according to the value.
How can i make it so I won't get any nulls anymore?
Edit 1: during a 7-minute test I've counted 49 nulls. This is quite a big issue to be honest...

A: Fixed it!
The problem was that my python script had a time.sleep() which lasts 1 second, changed it to 0.1, and changed the WaitForSecods in the Unityscript to 0.25f. This totally fixed my problem. Kind of stupid that I didn't think of this before posting it on Stackoverflow.


text:
Q: Angular 8: page redirect to home when refresh base url In my angular project i have a menu dashboard , when login it redirects to dashboard but when i remove that dashboard from URL (i.e)before localhost:4200/dashboard, after removed localhost:4200, when refresh how to i navigate to dashboard again?
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent},
{ path: '**', redirectTo: 'login' ,pathMatch: 'full' }

A: https://angular.io/guide/router#the-default-route-to-heroes
You can change your router config something like below,
RouterConfig = [
  { path: '**', redirectTo: '/dashboard'},
  { path: '', component: HomeComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent }
];

Add this in your router config and it should work as expected.
Basic routing example => https://stackblitz.com/edit/angular-router-basic-example-11fgob

A: You can use redirectTo
According to the Angular documentation for the default routing
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent},
{ path: '**', redirectTo: 'login' ,pathMatch: 'full' }

This route redirects a URL that fully matches the empty path to the route whose path is '/dashboard'.
After the browser refreshes, the router loads the DashboardComponent and the browser address bar shows the /dashboard URL.

A: Change your router config as below.
  import { DashboardComponent} from '..path to your dashboard component';
  import { LoginComponent } from '..path to your login component';

  const routes: Routes = [
  { path: '', redirectTo: '/dashboard' ,pathMatch: 'full'}
  { path: 'dashboard', component: DashboardComponent}, canActivate:[AuthGuard]}
  { path: 'login', component: LoginComponent },
  ]


text:
Q: How to update state of a parent while using its another state without causing infinite updates? Let's have components A and B.
Component B only shows the parent's state in contentForB in a different format and doesn't manipulate with it. It takes A's state as a prop, applies a function transform(content) and shows it, so whenever A's contentForB changes, the new content get transformed and updated in B.
The problem comes when A wants to use B's transformed content and use it somewhere else. I tried to implemented in a standard way, using state-updating function and passed it from A to B like this:
class A extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            contentForB: "",
            transformedContent: ""
        };
        this.updateTransformedContent = this.updateTransformedContent.bind(this);
    }

    updateTransformedContent(newContent) {
        this.setState = { transformedContent: newContent };
    }

    render() {
        return (
            ...

            <ComponentUsingTransformedContent transformedContent = { this.state.transformedContent } />
        );
    }
}

class B extends React.Component {
    constructor(props) {
        super(props);
        this.transform = this.transform.bind(this);
    }

    transform(content) {
       let newContent = ...;
       this.props.updateTransformedContent(newContent);
       return newContent;
   }

   render() {
       <Something value={this.transform(this.props.content)} />
   }
}

However, when A's state changes, B gets reinitialized, it then changes A's state by calling the updateTransformedContent which again causes B to get reinitialized, thus causing an infinite loop even though the updateTransformedContent changes the state object which isn't directly passed into B.
Any ideas how to deal with such situation properly?

A: You can use componentDidUpdate lifecycle method.
[codesandbox.io]
https://codesandbox.io/s/cool-leaf-92nt8?file=/src/App.js:457-475
class TestB extends Component {
  constructor(props) {
    super(props);
    this.state = {
      transformed: ""
    };
    this.transform = this.transform.bind(this);
  }

  componentDidUpdate(prevProps) {
    if (this.props.content !== prevProps.content) {
      this.transform(this.props.content);
    }
  }

  transform(content) {
    const transformed = `<h4>${this.props.content}</h4>`;
    this.setState({ transformed: transformed });
    this.props.updateTransformedContent(transformed);
    return transformed;
  }

  render() {
    return (

B Componenet:

{this.state.transformed}

    );
  }
}


text:
Q: display a dialog after long click on list view android in my application I will fetch data from a cursor and put it in a ListActivity.
If a long click on a list item happens it should display a dialog.
Now I'll show you some code:
final ListView selectRoom = (ListView) findViewById(android.R.id.list);
        selectRoom.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> adapter, View view,
                    int position, long id) {

                Cursor unitCursor = (Cursor) getListView().getItemAtPosition(
                        position);
                int rid = unitCursor.getInt(0);
                DBAccessor dba = new DBAccessor(getApplicationContext());
                dba.alterUnitName(rid);
                callAdapter();
                final Dialog d = new Dialog(getApplicationContext());
                d.setContentView(R.layout.settings);
                d.setTitle("My Dialog");
                d.show();

                return true;

Here is the XML file with the List...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Spinner
        android:id="@+id/spinnerRooms"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </Spinner>

    <ListView
        android:id="@android:id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/spinnerRooms">
    </ListView>

</RelativeLayout>

the XML file with the columns of cursor is...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/unitId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"/>

    <TextView
        android:id="@+id/unitName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/unitRoomId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"/>

</LinearLayout>

Thank you for some answers and have a nice day.

A: Use the setOnItemLongClickListener as following..
 selectRoom.setOnItemLongClickListener(new OnItemLongClickListener(){
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            // TODO Auto-generated method stub
            Dialog();
  or
final MyDialog rDialog=new MyDialog(this,this);
            return false;
        }

    } );

public void Dialog()    {

        AlertDialog.Builder dialogAlert = new AlertDialog.Builder(getApplicationContext());
        dialogAlert.setTitle("Demo ?");

        dialogAlert.show();
}

 //Another way

 public class MyDialog extends Dialog {

Activity act;
public ReminderSettingDialog(Context context,Activity act) {
    super(context);
    this.act=act;
    // TODO Auto-generated constructor stub
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.settings);

}

}

A: Try this code:
selectRoom.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
            return onLongListItemClick(v,pos,id);
        }
        protected boolean onLongListItemClick(View v, final int pos, long id) {
            /////Display Dialog Here.......................

                    return true;

    });

A: dialog should be built using the dialg builder like that:
AlertDialog alertDialog = new AlertDialog.Builder(view.getContext()).create();
alertDialog.setTitle("Reset...");
alertDialog.setMessage("Are you sure?");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int which) {
      // here you can add functions
   }
});
alertDialog.setIcon(R.drawable.icon);
alertDialog.show();

hope it helps :)


text:
Q: Joomla installation fails on XAmpp Hi All when I am trying to install joomla on XAMPP server i am getting below error
[client ::1:51690] PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "file:/C:/xampp/htdocs/Joomla30/templates/protostar/templateDetails.xml" in C:\xampp\htdocs\Joomla30\libraries\cms\installer\installer.php on line 2195, referer: http://localhost/Joomla30/installation/index.php
Can any one help me to resolve this?

A: Hello I had a similar problem with easyphp, some research led me to two problems.
The first had to do with the premise between Mysql and joomla see the php configuration file.
The second and most likely thing you have is a problem in the paths you give to joomla error log. Checks the php configuration file.
Loking in to your erro it's related to path of instaled joomla. Solution install again the joomla but be sure to save it in your created site folder for exemple www.mysite in your apache htdocs it worked for me.


text:
Q: SSH allowing remote hosts to connect to local forwarded ports I'm currently facing an issue with a RHEL 7.0 regarding the ssh option -g (i.e remote hosts connection to local forwarded ports ).
I'm establishing a connection with port forwarding, from a server on  myserver_ip address , with the usual command line :
ssh -o StrictHostKeyChecking=no user@server_fqn -L9090:other_server_ip:9080 -g

When I point my browser (or try to fetch something with curl I get a connection refused exception ) :
curl -X GET "http://myserver_ip:9090"
curl: (7) Failed to connect to myserver_ip port 9090: No route to host

If I do the same on a Ubuntu server it works perfectly, however on RHEL it simply does not work.
I suspected the firewall, selinux, even network connectivity.
In order to solve/troubleshoot this I've tried the following :

*

*disabled the firewall (service firewalld stop)

*checked that selinux manages the 9090 as valid http port (semanage port -l  | grep 9090), it was ok

*checked that the port is open via netstat ( netstat -alptn  | grep 9090
 ) , seems ok , I've got an ssh process listening on 9090

*checked that the server recieves the packets on port 9090 of the ehternet interface ( tcpdump -i ens192 'port 9090' -v ) , and indeed packets are recieved ...

So basically it conformed that the system receives the requests on the interface, an ssh process is listening on all interfaces on the given port, however the ssh process does not forward packets to the other side ...
I'm really out of leads for troubleshooting, so If you have any suggestions, please do not hesitate, I'd really appreciate some help.
Thanks,

A: Curl has already told you the answer. It's not about SSH, its not about firewalls, it's not about selinux.
no route to host

The machine where you are running curl does not know where it should send packets intended for (the ip address it associates with) my server_ip


text:
Q: How can I get same result of date on browser from real data in mysql? (timezone) At first, I'm Korean and today is 2017-11-20.
I'm using CentOS7, Nodejs, express and mariadb(mysql).
I think I have a problem about timezone.
in my CentOS7,
#date
Mon Nov 20 19:30:16 KST 2017

in my mysql,
> SELECT now();
2017-11-20 19:34:05
> SELECT * FROM mytable
------------------
| ID | dodate    |
-----------------
| 1  | 2017-11-20|
------------------

in my app.js,
...
app.get('/', function(req, res){
    ...
    var sql = 'SELECT dodate FROM mytable';
    conn.query(sql, function(err, rows, fields){
    if(err){
        console.log(err);
    } else{
        res.send(rows);
    }
    ...
});
...

result is, (on browser)
[{"dodate":"2017-11-19T15:00:00:00.000z"}]

but I wanted the result of
2017-11-20

not
2017-11-19

How can I solve this problem?

A: I suspect your dodate column has the datatype of DATETIME. Datatypes of TIMESTAMP get translated.

A: try
var sql = 'SELECT dodate FROM date(mytable)';


text:
Q: How can I modify style from buttons in xctk xceed wizard? I'm trying to modify the style of the back, finish, cancel and next buttons at the bottom of the xctk:Wizard. I have tried to do it by modifying the style of the xctk:Wizard but nothing seems to work. I would like to make those buttons bigger. I'm using Xceed.Wpf.Toolkit.WizardPage.
Since I don't have direct access to those buttons (or at least I don't know how to access them) an easy task like this is making me sweat hard
This is an example of what I'm trying to do in order to accomplish my goal.
         <xctk:Wizard.Style>
            <Style TargetType="xctk:Wizard">
                <Setter Property="FontWeight"
                        Value="Bold"/>
            </Style>
        </xctk:Wizard.Style>

Any help is appreciated, thank you.

A: You could add an implicit Button style to the Wizard's Resources property:
<xctk:Wizard>
    <xctk:Wizard.Resources>
        <Style TargetType="Button">
            <Setter Property="FontWeight" Value="Bold"/>
            <Setter Property="FontSize" Value="40" />
        </Style>
    </xctk:Wizard.Resources>
    ...
</xctk:Wizard>


text:
Q: How can I simplify a recursive-descent parser? I have the following simple LL(1) grammar, which describes a language with only three valid sentences: "", "x y" and "z x y":
S -> A x y | ε .
A -> z | ε .

I have constructed the following parsing table, and from it a "naive" recursive-descent parser:
  | x          | y | z          | $
S | S -> A x y |   | S -> A x y | S -> ε
A | A -> ε     |   | A -> z     |

func S():
    if next() in ['x', 'z']:
        A()
        expect('x')
        expect('y')
        expect('$')
    elif next() == '$':
        pass
    else:
        error()

func A():
    if next() == 'x':
        pass
    elif next() == 'z':
        expect('z')
    else:
        error()

However, the function A seems to be more complicated than necessary. All of my tests still pass if it's simplified to:
func A():
    if next() == 'z':
        expect('z')

Is this a valid simplification of A? If so, are there any general rules regarding when it's valid to make simplifications like this one?

A: That simplification is certainly valid (and quite common).
The main difference is that there is no code associated with the production A→ε. If there are some semantics to implement, you will need to test for the condition. If you only need to ignore the nullable production, you can certainly just return.
Coalescing errors and epsilon productions has one other difference: the error (for example, in the input y) is detected later, after A() returns. Sometimes that makes it harder to produce good error messages (and sometimes it doesn't).


text:
Q: export to excel in c# where first row and 4 columns are in string & rest is in integer protected void ibtnExport_Click(object sender, ImageClickEventArgs e)
 {
   try
       {
            DataTable dt = new DataTable();
            dt = createDataTable();
            dt.Columns.RemoveAt(0);
            ClosedXML.Excel.XLWorkbook wbook = new ClosedXML.Excel.XLWorkbook();
            wbook.Worksheets.Add(dt,lblStartDate.Text+"to"+lblEndDate.Text);
            // Prepare the response
            HttpResponse httpResponse = Response;
            httpResponse.Clear();
            httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            //Provide you file name here
            httpResponse.AddHeader("content-disposition", "attachment;filename=\""+lblStartDate.Text+"to"+lblEndDate.Text+".xlsx\"");
            string style = @"<style> .integermode {mso-number-format:General} </style>";
            Response.Write(style);
            // Flush the workbook to the Response.OutputStream
            using (MemoryStream memoryStream = new MemoryStream())
            {
                wbook.SaveAs(memoryStream);
                memoryStream.WriteTo(httpResponse.OutputStream);
                memoryStream.Close();
            }
            httpResponse.End();

        }

        catch
        {
            Response.Write("<script>alert('Something went wrong..')</script>");
        }

    }

This is the code which i am using to export excel. Here the header is in string but the rest of the column is also in string, which I  will need to change into a number or integer for doing addition which is ha tic for the user to perform any action on it.
Please do help me to resolve this. If you need any other part of the code please ask.
Edit:
This is the createDataTable code:
    private DataTable createDataTable()
    {
        DataSet _ds = new DataSet();
        _ds = (DataSet)ViewState["DataSet"];
        DataTable dt = new DataTable();
        dt.Columns.Add("ProjectID");
        dt.Columns.Add("Projects");
        dt.Columns.Add("Network");
        dt.Columns.Add("Activity");
        dt.Columns.Add("SOP");
        for (int i = 0; i < _ds.Tables[1].Rows.Count; i++)
        {
            dt.Columns.Add(_ds.Tables[1].Rows[i]["Name"].ToString() + "(" + _ds.Tables[1].Rows[i]["SapCode"].ToString() + ")");
        }

        for (int i = 0; i < _ds.Tables[0].Rows.Count; i++)
        {
            dt.Rows.Add(_ds.Tables[0].Rows[i]["ProjectID"].ToString(), _ds.Tables[0].Rows[i]["BaseProject"].ToString(), _ds.Tables[0].Rows[i]["ProjectName"].ToString(), _ds.Tables[0].Rows[i]["Network"].ToString(), _ds.Tables[0].Rows[i]["Activity"].ToString(), _ds.Tables[0].Rows[i]["SOP"].ToString());
        }

        for (int j = 0; j < _ds.Tables[2].Rows.Count; j++)
        {
            for (int i = 0; i < _ds.Tables[0].Rows.Count; i++)
            {
                if(dt.Columns.Contains(_ds.Tables[2].Rows[j]["EmployeeData"].ToString()))
                //if (dt.Columns[_ds.Tables[2].Rows[j]["EmployeeData"].ToString()].ColumnName!= null && dt.Columns[_ds.Tables[2].Rows[j]["EmployeeData"].ToString()].ColumnName.ToString() != "")
                {
                    if (dt.Rows[i]["ProjectID"].ToString() == _ds.Tables[2].Rows[j]["ProjectID"].ToString() && dt.Columns[_ds.Tables[2].Rows[j]["EmployeeData"].ToString()].ColumnName.ToString() == _ds.Tables[2].Rows[j]["EmployeeData"].ToString())
                    {
                        dt.Rows[i][_ds.Tables[2].Rows[j]["EmployeeData"].ToString()] = Convert.ToDouble(_ds.Tables[2].Rows[j]["Hourspent"].ToString());
                    }
                }
            }
        }
        return dt;
    }


text:
Q: Extract all substrings that match a pattern in unix I have a string in a text file as below.
<sample:Recipients><sample:user name="11111111" guid="8fa4fbaabf904a16ad65449bd7adcba1"/><sample:user name="22222222" guid="f74ebd3310834601a2c22a5dde33c02a"/><sample:user name="33333333" guid="5fcd2e7775cb42ecbed5ac5dd85e1ca6"/></sample:Recipients>

The string is continuous and not formatted as proper xml
I have to extract all the values from  tags
I have used the below script
grep -o "<sample:Recipients>.*</sample:Recipients>" "sample.txt"|sed -n 's/.*\([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\).*/\1/p'

But I am getting only the last value 33333333. How can I extract the values from all user tags?

A: Following single awk may help you here.
awk '
{
  while(match($0,/sample:user name=\"[^"]*[0-9]+/)){
    print substr($0,RSTART+18,RLENGTH-18);
    $0=substr($0,RSTART+RLENGTH+1)}
}'  Input_file

A: You can use the following quick and dirty grep commands to reach your objective:
$ grep -E 'sample:Recipients>|<sample:user' file | grep -oP '(?<=name=")[^"]*'

INPUT:
$ cat file
abc
abc1
<sample:Recipients>
   <sample:user name="******1" guid="8fa4fbaabf904a16ad65449bd7adcba1"/>
   <sample:user name="*******2" guid="f74ebd3310834601a2c22a5dde33c02a"/>
   <sample:user name="*******3" guid="5fcd2e7775cb42ecbed5ac5dd85e1ca6"/>
</sample:Recipients>
abc2
abc

OUTPUT:
$ grep -E 'sample:Recipients>|<sample:user' file | grep -oP '(?<=name=")[^"]*'
******1
*******2
*******3

Explanations:
The first grep will fetch the lines that contains the XML you want to isolate from your input file, the second one will select the values from the attributes called name by using a perl regex (?<=name=")[^"]* with positive lookbehind.
Another quick and dirty solution using sed:
$ grep -E 'sample:Recipients>|<sample:user' file | sed -n '/name="/s/.*name="\([^"]*\)".*/\1/gp'
******1
*******2
*******3

Explanations:
You use sed and process lines only when matching the pattern name= then you replace the whole line by the backreference to the name value: \1 (the attribute value)
THE GOOD SOLUTION:
instead of grepping or using sed just use a xml parser to analyse your xml output:
$ cat extract_name.xsl
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" omit-xml-declation="yes" indent="no"/>
<xsl:template match="/">
  <xsl:for-each select="/*/*/@name">
        <xsl:value-of select="."/><xsl:text>
</xsl:text>
  </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

$ xsltproc extract_name.xsl <(grep -E 'sample:Recipients>|<sample:user' file) 2>/dev/null
******1
*******2
*******3

This is the safest way of working, note that the 2>/dev/null is used in order to ignore the namespace warning because the sample namespace is not properly defined.

A: You can try this awk script":
awk -v RS='<[a-z:]+|/>' -v FS='[a-z]+=' '{gsub("[\" ]",""); print $2,$3}'

THe record separator RS is set to get everything between <...\>. The field separtor is set to catch the left part of the sign =.
The gsub command gets rid of double quotes and extra spaces.
The print statement is displaying the name and guid. If you don't need guid, remove ,$3 in the print statement.


text:
Q: Using randomUUID() in Zapier to generate UUID I'm using Zapier's code module to write some Nodejs to generate a UUID.
I know that I can use node's crypto "library" because I've used it in the past to hash some text (MD5) to send to an API endpoint. I also know that I can use the crypto function randomInt.
For example, the following will correctly without errors return a number in the stated range:
const crypto = require('crypto');
let num = crypto.randomInt(1, 7);
output = [{id: num}];

When I try to use the randomUUID function (documentation), like the following, I get the error "TypeError: crypto.randomUUID is not a function" from Zapier:
const crypto = require('crypto');
let uuid = crypto.randomUUID();
output = [{id: uuid}];

I almost gave up there, but tried one last weird thing:
const crypto = require('crypto');
let uuid = crypto.randomUUID; //changed this
output = [{id: uuid}];

Note that I removed the () and this didn't throw an error and returned something like:
LT6TvivKgpFu5Yk3OvQmti1Hq1aNy5ZM
That looks a lot like a proper UUID since it has the right number of characters, but not the expected hyphens like (for example) 88368f2a-d5db-47d8-a05f-534fab0a0045
So, two questions:

*

*Why is Zapier saying that randomUUID() is not a function? Does it not support this or am I coding something weirdly wrong or not requiring something needed? Is there a different way to do this?

*When I use randomUUID (no ()) is this actually a reliable UUID?

EDIT: more info from Zapier, they are saying that their logs show that the code step cannot find module 'uuid'

A:
When I use randomUUID (no ()) is this actually a reliable UUID?

The value you're getting there is not a reliable UUID. UUIDs will contain only 0-9a-f characters, the example you have there doesn't match.
Sorry I can't help you with what's going wrong with the other part! You could maybe try something like this
let crypto;
try {
  crypto = require('crypto');
} catch (err) {
  console.log('crypto support is disabled!');
}

to make sure the crypto package is actually available and there's not some error being silently suppressed? You may also want to check the version, as randomUUID() appears to have been added in v14.17.0
Also nit but should probably be const uuid = crypto.randomUUID(); instead of let ;)


text:
Q: How to send SQL count data & array data together? I have a script designed to print out values of students who have accrued more than 3 tardies.  I want this script to print out both the student name, and the amount of times they've been tardy, but so far I've been only able to print out their names with the following script:
$sql = "select DISTINCT StudentID,classid,date from attendance_main where status = 'Tardy' AND classid like '%ADV%'";
$result = mysql_query($sql) or die (mysql_error());
while($row=mysql_fetch_array($result)) {
        $studentid = $row['StudentID'];
        $sql2 = "select distinct StudentID,classid,date from attendance_main where StudentID = '$studentid' AND status = 'Tardy' AND classid like '%ADV%'";
        $result2 = mysql_query($sql2) or die (mysql_error());
        while($row2=mysql_fetch_array($result2)) {
                $tardycount = mysql_num_rows($result2);
                $studentid = $row2['StudentID'];
                if($tardycount >= 3) {

                                $sql3 = "select * from students where rfid = '$studentid'";
                                $result3 = mysql_query($sql3) or die (mysql_error());
                                while($row3=mysql_fetch_array($result3)) {
                                        $fname[] = $row3['fname'];
                                }
                        }
                }
        }

$newdata = array_unique($fname);
foreach ($newdata as $value) {
        echo $value;
}

I can't think of how to intuitively do this.  Keeping it all in the while loop didn't work (I had multiple results coming up for the same students despite requesting unique entries) so using array_unique was the only method I could think of.
Thanks for any help!

A: Something like this:
SELECT
  attendance_main.StudentID,
  students.fname,
  COUNT(attendance_main.*) AS `times_tardy`
FROM
  attendance_main
INNER JOIN
  students
ON
  attendance_main.StudentID = students.rfid
WHERE
  attendance_main.status = 'Tardy'
AND
  attendance_main.classid like '%ADV%'
GROUP BY
  attendance_main.StudentID
HAVING
  `times_tardy` > 3

Joining the two tables gets you the tardy count and student's name in one query, and the GROUP BY and HAVING clause that get you only the students with more than 3 tardy entries.

A: You can (and should) do almost everything in SQL. It should look something like this.
select StudentID, classid, date count(*)
from attendance_main
where status = 'Tardy' AND classid like '%ADV%'"
left join student on student.rfid = attendance_main.StudentId
group by StudentId
having count(*) > 3;

Here's how it works.

*

*select the results you want to work with:
select StudentID, classid, date count(*)
from attendance_main
where status = 'Tardy' AND classid like '%ADV%'"

*Join the students to your result set on the common id
left join student on student.rfid = attendance_main.StudentId

*group everything by student.  We use count(*) to get the number of items. We know we're only dealing with tardies because of the where clause in the select.
group by StudentId

*limit the results to only tardies above 3 with the having claues (this is like a where clause for the group by)
having count(*) > 3;